"""Pure match-environment contracts and deterministic football modifiers.

The environment belongs to the immutable kickoff snapshot.  No ORM or external
weather dependency is allowed here: historical replay must only depend on the
captured state.
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Mapping


WEATHER_CONDITIONS = frozenset({"CLEAR", "CLOUDY", "RAIN", "HEAVY_RAIN", "SNOW"})
SURFACE_TYPES = frozenset({"NATURAL_GRASS", "HYBRID_GRASS", "ARTIFICIAL"})
ROOF_TYPES = frozenset({"OPEN", "RETRACTABLE", "CLOSED"})


class MatchEnvironmentError(ValueError):
    pass


def _int(value: Any, name: str, low: int, high: int) -> int:
    if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
        raise MatchEnvironmentError(f"{name} must be an integer in [{low}, {high}].")
    return value


def _number(value: Any, name: str, low: float, high: float) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise MatchEnvironmentError(f"{name} must be numeric.")
    value = float(value)
    if not low <= value <= high:
        raise MatchEnvironmentError(f"{name} must be in [{low}, {high}].")
    return value


@dataclass(frozen=True, slots=True)
class MatchEnvironmentState:
    weather_condition: str = "CLEAR"
    temperature_c: int = 18
    humidity_pct: int = 55
    wind_kph: int = 8
    precipitation_intensity: int = 0
    pitch_quality: int = 75
    drainage_quality: int = 70
    pitch_length_m: int = 105
    pitch_width_m: int = 68
    surface_type: str = "NATURAL_GRASS"
    altitude_m: int = 0
    roof_type: str = "OPEN"
    roof_closed: bool = False
    venue_name: str = "Standard Venue"
    home_advantage_multiplier: float = 1.0
    source: str = "DEFAULT"

    def __post_init__(self):
        if self.weather_condition not in WEATHER_CONDITIONS:
            raise MatchEnvironmentError("Unsupported weather_condition.")
        _int(self.temperature_c, "temperature_c", -30, 55)
        _int(self.humidity_pct, "humidity_pct", 0, 100)
        _int(self.wind_kph, "wind_kph", 0, 140)
        _int(self.precipitation_intensity, "precipitation_intensity", 0, 100)
        _int(self.pitch_quality, "pitch_quality", 1, 100)
        _int(self.drainage_quality, "drainage_quality", 1, 100)
        _int(self.pitch_length_m, "pitch_length_m", 90, 120)
        _int(self.pitch_width_m, "pitch_width_m", 45, 90)
        if self.surface_type not in SURFACE_TYPES:
            raise MatchEnvironmentError("Unsupported surface_type.")
        _int(self.altitude_m, "altitude_m", 0, 4500)
        if self.roof_type not in ROOF_TYPES:
            raise MatchEnvironmentError("Unsupported roof_type.")
        if not isinstance(self.roof_closed, bool):
            raise MatchEnvironmentError("roof_closed must be boolean.")
        if not isinstance(self.venue_name, str) or not self.venue_name.strip():
            raise MatchEnvironmentError("venue_name must be non-empty.")
        _number(self.home_advantage_multiplier, "home_advantage_multiplier", 0.85, 1.25)
        if not isinstance(self.source, str) or not self.source.strip():
            raise MatchEnvironmentError("source must be non-empty.")

    def to_payload(self) -> dict[str, Any]:
        return {
            "weather_condition": self.weather_condition,
            "temperature_c": self.temperature_c,
            "humidity_pct": self.humidity_pct,
            "wind_kph": self.wind_kph,
            "precipitation_intensity": self.precipitation_intensity,
            "pitch_quality": self.pitch_quality,
            "drainage_quality": self.drainage_quality,
            "pitch_length_m": self.pitch_length_m,
            "pitch_width_m": self.pitch_width_m,
            "surface_type": self.surface_type,
            "altitude_m": self.altitude_m,
            "roof_type": self.roof_type,
            "roof_closed": self.roof_closed,
            "venue_name": self.venue_name,
            "home_advantage_multiplier": round(float(self.home_advantage_multiplier), 6),
            "source": self.source,
        }

    @classmethod
    def from_payload(cls, payload: Mapping[str, Any] | None) -> "MatchEnvironmentState":
        payload = payload or {}
        return cls(
            weather_condition=payload.get("weather_condition", "CLEAR"),
            temperature_c=payload.get("temperature_c", 18),
            humidity_pct=payload.get("humidity_pct", 55),
            wind_kph=payload.get("wind_kph", 8),
            precipitation_intensity=payload.get("precipitation_intensity", 0),
            pitch_quality=payload.get("pitch_quality", 75),
            drainage_quality=payload.get("drainage_quality", 70),
            pitch_length_m=payload.get("pitch_length_m", 105),
            pitch_width_m=payload.get("pitch_width_m", 68),
            surface_type=payload.get("surface_type", "NATURAL_GRASS"),
            altitude_m=payload.get("altitude_m", 0),
            roof_type=payload.get("roof_type", "OPEN"),
            roof_closed=payload.get("roof_closed", False),
            venue_name=payload.get("venue_name", "Standard Venue"),
            home_advantage_multiplier=payload.get("home_advantage_multiplier", 1.0),
            source=payload.get("source", "DEFAULT"),
        )


@dataclass(frozen=True, slots=True)
class EnvironmentEffects:
    pass_completion_delta: float
    dribble_success_delta: float
    chance_multiplier: float
    shot_quality_delta: float
    goal_conversion_multiplier: float
    goalkeeper_handling_multiplier: float
    set_piece_delivery_multiplier: float
    aerial_duel_variance: float
    fatigue_per_minute: float
    injury_risk_multiplier: float
    home_territorial_bonus: float
    wide_play_multiplier: float
    direct_play_multiplier: float

    def to_payload(self) -> dict[str, float]:
        return {name: round(float(getattr(self, name)), 6) for name in self.__dataclass_fields__}


def effects_for_environment(env: MatchEnvironmentState) -> EnvironmentEffects:
    """Translate captured conditions into bounded match-mechanics modifiers.

    Effects are deliberately modest.  Conditions shape football rather than
    overwhelming player quality/tactics.
    """
    # Closed roofs neutralize wind/precipitation for football mechanics.
    wind = 0 if env.roof_closed else env.wind_kph
    precip = 0 if env.roof_closed else env.precipitation_intensity
    pitch_penalty = max(0.0, (75.0 - env.pitch_quality) / 75.0)
    drainage_penalty = max(0.0, (65.0 - env.drainage_quality) / 65.0) * (precip / 100.0)
    wet = precip / 100.0
    wind_factor = min(1.0, wind / 70.0)

    pass_delta = -(0.055 * pitch_penalty + 0.035 * wet + 0.030 * wind_factor + 0.025 * drainage_penalty)
    dribble_delta = -(0.060 * pitch_penalty + 0.045 * wet + 0.030 * drainage_penalty)
    set_piece_mult = 1.0 - 0.08 * wind_factor - 0.05 * wet - 0.05 * pitch_penalty
    gk_handling = 1.0 - 0.075 * wet - 0.045 * drainage_penalty
    shot_quality_delta = -0.018 * pitch_penalty - 0.012 * wet - 0.012 * wind_factor
    goal_conversion = 1.0 + 0.035 * wet + 0.025 * drainage_penalty - 0.015 * wind_factor

    heat = max(0.0, env.temperature_c - 24) / 18.0
    cold = max(0.0, 5 - env.temperature_c) / 25.0
    humidity = max(0.0, env.humidity_pct - 65) / 35.0
    altitude = min(1.0, env.altitude_m / 3000.0)
    large_pitch = max(0.0, (env.pitch_length_m * env.pitch_width_m - 7140) / 1800.0)
    poor_surface = pitch_penalty * (1.15 if env.surface_type == "NATURAL_GRASS" else 0.85)
    fatigue_per_minute = 0.030 * heat + 0.012 * cold + 0.020 * humidity + 0.026 * altitude + 0.012 * large_pitch + 0.010 * poor_surface
    injury_risk = 1.0 + 0.45 * heat + 0.22 * cold + 0.38 * poor_surface + 0.28 * drainage_penalty + 0.22 * altitude
    if env.surface_type == "ARTIFICIAL":
        injury_risk += 0.08

    width_delta = (env.pitch_width_m - 68) / 20.0
    length_delta = (env.pitch_length_m - 105) / 30.0
    wide_mult = max(0.92, min(1.08, 1.0 + width_delta * 0.045))
    direct_mult = max(0.94, min(1.07, 1.0 + length_delta * 0.035 + wind_factor * 0.015))
    home_bonus = max(-0.006, min(0.018, (env.home_advantage_multiplier - 1.0) * 0.09 + altitude * 0.006))

    chance_mult = max(0.91, min(1.07, 1.0 - 0.025 * pitch_penalty - 0.018 * wet + 0.012 * large_pitch))
    aerial_variance = min(0.12, 0.03 * wind_factor + 0.025 * wet)

    return EnvironmentEffects(
        pass_completion_delta=max(-0.14, min(0.03, pass_delta)),
        dribble_success_delta=max(-0.13, min(0.02, dribble_delta)),
        chance_multiplier=chance_mult,
        shot_quality_delta=max(-0.06, min(0.02, shot_quality_delta)),
        goal_conversion_multiplier=max(0.90, min(1.10, goal_conversion)),
        goalkeeper_handling_multiplier=max(0.88, min(1.04, gk_handling)),
        set_piece_delivery_multiplier=max(0.84, min(1.05, set_piece_mult)),
        aerial_duel_variance=aerial_variance,
        fatigue_per_minute=max(0.0, min(0.10, fatigue_per_minute)),
        injury_risk_multiplier=max(0.80, min(2.20, injury_risk)),
        home_territorial_bonus=home_bonus,
        wide_play_multiplier=wide_mult,
        direct_play_multiplier=direct_mult,
    )
