"""Django adapter for immutable match weather/pitch/venue resolution.

The pure simulation contract lives in :mod:`matches.engine.environment`.
This module resolves the effective ratified venue + configurable country
climate exactly once at kickoff and returns a frozen pure state.
"""
from __future__ import annotations

import hashlib
import math
from dataclasses import dataclass
from typing import Any

from django.utils import timezone

from .engine.environment import MatchEnvironmentState, effects_for_environment


@dataclass(frozen=True, slots=True)
class ResolvedEnvironment:
    state: MatchEnvironmentState
    venue_source: str
    venue_reference: str
    climate_source: str

    @property
    def effects_payload(self):
        return effects_for_environment(self.state).to_payload()


def _unit(*parts: Any) -> float:
    digest = hashlib.sha256("|".join(str(p) for p in parts).encode("utf-8")).digest()
    return int.from_bytes(digest[:8], "big") / float(2**64 - 1)


def _bounded_int(value, low, high, default):
    try:
        value = int(value)
    except (TypeError, ValueError):
        return default
    return max(low, min(high, value))


def _bounded_float(value, low, high, default):
    try:
        value = float(value)
    except (TypeError, ValueError):
        return default
    return max(low, min(high, value))


class MatchEnvironmentResolver:
    """Resolve one authoritative environment from ratified match context."""

    DEFAULTS = {
        "pitch_quality": 75,
        "drainage_quality": 70,
        "pitch_length_m": 105,
        "pitch_width_m": 68,
        "surface_type": "NATURAL_GRASS",
        "altitude_m": 0,
        "roof_type": "OPEN",
        "home_advantage_multiplier": 1.0,
    }

    @classmethod
    def resolve(cls, *, match) -> ResolvedEnvironment:
        venue = cls._resolve_venue(match=match)
        country = str(venue.get("country") or getattr(match.fixture.home_club, "country", "") or "").strip()
        climate, climate_source = cls._resolve_climate(country=country)
        scheduled = match.scheduled_at or timezone.now()
        weather = cls._resolve_weather(
            match_id=str(match.pk), scheduled_at=scheduled, climate=climate,
            roof_type=venue["roof_type"],
        )
        state = MatchEnvironmentState(
            weather_condition=weather["weather_condition"],
            temperature_c=weather["temperature_c"],
            humidity_pct=weather["humidity_pct"],
            wind_kph=weather["wind_kph"],
            precipitation_intensity=weather["precipitation_intensity"],
            pitch_quality=venue["pitch_quality"],
            drainage_quality=venue["drainage_quality"],
            pitch_length_m=venue["pitch_length_m"],
            pitch_width_m=venue["pitch_width_m"],
            surface_type=venue["surface_type"],
            altitude_m=venue["altitude_m"],
            roof_type=venue["roof_type"],
            roof_closed=weather["roof_closed"],
            venue_name=venue["venue_name"],
            home_advantage_multiplier=venue["home_advantage_multiplier"],
            source=f"{venue['venue_source']}+{climate_source}",
        )
        return ResolvedEnvironment(
            state=state,
            venue_source=venue["venue_source"],
            venue_reference=venue["venue_reference"],
            climate_source=climate_source,
        )

    @classmethod
    def _resolve_venue(cls, *, match):
        # Calendar governance is authoritative when a ratified assignment exists.
        # Fail closed on database/integrity errors: silently falling back to a different
        # ground would corrupt the immutable sporting environment.
        from competition_calendar_governance.models import CalendarFixtureAssignment
        assignment = (
            CalendarFixtureAssignment.objects.filter(match=match)
            .select_related(
                "stadium_asset__stadium_profile",
                "stadium_asset__primary_for_club",
                "stadium_asset__owner_club",
                "home_stadium_profile",
            )
            .order_by("-created_at")
            .first()
        )

        if assignment is not None:
            if assignment.stadium_asset_id:
                stadium = getattr(assignment.stadium_asset, "stadium_profile", None)
                snapshot = dict(assignment.venue_snapshot or {})
                venue_club = assignment.stadium_asset.primary_for_club or assignment.stadium_asset.owner_club
                snapshot.setdefault("country", getattr(venue_club, "country", ""))
                return cls._venue_payload(
                    stadium=stadium,
                    venue_name=assignment.venue_name,
                    venue_source="CALENDAR_STADIUM_ASSET",
                    venue_reference=str(assignment.stadium_asset_id),
                    snapshot=snapshot,
                )
            return cls._venue_payload(
                stadium=None,
                venue_name=assignment.venue_name,
                venue_source=f"CALENDAR_{assignment.venue_source}",
                venue_reference=str(assignment.home_stadium_profile_id or assignment.pk),
                snapshot=assignment.venue_snapshot or {},
            )

        # Legacy/non-ratified fixtures use the current primary stadium asset.
        from club_assets.models import ClubAsset, ClubAssetStatus, ClubAssetType
        asset = (
            ClubAsset.objects.filter(
                primary_for_club=match.fixture.home_club,
                asset_type=ClubAssetType.STADIUM,
                status=ClubAssetStatus.ACTIVE,
            )
            .select_related("stadium_profile", "primary_for_club", "owner_club")
            .first()
        )
        if asset is not None:
            return cls._venue_payload(
                stadium=getattr(asset, "stadium_profile", None),
                venue_name=asset.name,
                venue_source="PRIMARY_STADIUM_ASSET",
                venue_reference=str(asset.pk),
                snapshot={"country": getattr(asset.primary_for_club or asset.owner_club, "country", "")},
            )

        legacy = getattr(match.fixture.home_club, "home_stadium_profile", None)
        if legacy is not None and getattr(legacy, "is_active", False):
            return cls._venue_payload(
                stadium=None,
                venue_name=legacy.name,
                venue_source="HOME_STADIUM_PROFILE",
                venue_reference=str(legacy.pk),
                snapshot={"country": getattr(match.fixture.home_club, "country", "")},
            )

        return cls._venue_payload(
            stadium=None,
            venue_name=f"{match.fixture.home_club.name} home venue",
            venue_source="FALLBACK_STANDARD",
            venue_reference=str(match.fixture.home_club_id),
            snapshot={"country": getattr(match.fixture.home_club, "country", "")},
        )

    @classmethod
    def _venue_payload(cls, *, stadium, venue_name, venue_source, venue_reference, snapshot):
        defaults = dict(cls.DEFAULTS)
        # Neutral/external venue governance may carry richer values without a local asset.
        pitch_quality = getattr(stadium, "pitch_quality", snapshot.get("pitch_quality", defaults["pitch_quality"]))
        drainage = getattr(stadium, "drainage_quality", snapshot.get("drainage_quality", defaults["drainage_quality"]))
        length = getattr(stadium, "pitch_length_m", snapshot.get("pitch_length_m", defaults["pitch_length_m"]))
        width = getattr(stadium, "pitch_width_m", snapshot.get("pitch_width_m", defaults["pitch_width_m"]))
        surface = getattr(stadium, "surface_type", snapshot.get("surface_type", defaults["surface_type"]))
        altitude = getattr(stadium, "altitude_m", snapshot.get("altitude_m", defaults["altitude_m"]))
        roof = getattr(stadium, "roof_type", snapshot.get("roof_type", defaults["roof_type"]))
        home_advantage = getattr(stadium, "home_advantage", snapshot.get("home_advantage", defaults["home_advantage_multiplier"]))
        if surface not in {"NATURAL_GRASS", "HYBRID_GRASS", "ARTIFICIAL"}:
            surface = defaults["surface_type"]
        if roof not in {"OPEN", "RETRACTABLE", "CLOSED"}:
            roof = defaults["roof_type"]
        return {
            "venue_name": str(venue_name or "Standard Venue")[:160],
            "country": str(snapshot.get("country") or "").strip(),
            "venue_source": venue_source,
            "venue_reference": venue_reference,
            "pitch_quality": _bounded_int(pitch_quality, 1, 100, defaults["pitch_quality"]),
            "drainage_quality": _bounded_int(drainage, 1, 100, defaults["drainage_quality"]),
            "pitch_length_m": _bounded_int(length, 90, 120, defaults["pitch_length_m"]),
            "pitch_width_m": _bounded_int(width, 45, 90, defaults["pitch_width_m"]),
            "surface_type": surface,
            "altitude_m": _bounded_int(altitude, 0, 4500, defaults["altitude_m"]),
            "roof_type": roof,
            "home_advantage_multiplier": _bounded_float(home_advantage, 0.85, 1.25, 1.0),
        }

    @staticmethod
    def _resolve_climate(*, country):
        from .models import CountryMatchEnvironmentProfile
        profile = CountryMatchEnvironmentProfile.objects.filter(
            country__iexact=country, is_active=True
        ).first()
        if profile is None:
            return {
                "climate_zone": "TEMPERATE",
                "mean_temperature_c": 14,
                "seasonal_amplitude_c": 11,
                "season_peak_month": 7,
                "humidity_index": 55,
                "rainfall_index": 45,
                "wind_index": 35,
                "snow_index": 10,
            }, "DEFAULT_CLIMATE"
        return {
            "climate_zone": profile.climate_zone,
            "mean_temperature_c": profile.mean_temperature_c,
            "seasonal_amplitude_c": profile.seasonal_amplitude_c,
            "season_peak_month": profile.season_peak_month,
            "humidity_index": profile.humidity_index,
            "rainfall_index": profile.rainfall_index,
            "wind_index": profile.wind_index,
            "snow_index": profile.snow_index,
        }, f"COUNTRY_PROFILE:{profile.pk}"

    @classmethod
    def _resolve_weather(cls, *, match_id, scheduled_at, climate, roof_type):
        month = scheduled_at.month
        peak = int(climate["season_peak_month"])
        seasonal = math.cos((month - peak) * math.tau / 12.0)
        jitter = (_unit(match_id, "temperature") - 0.5) * 7.0
        temperature = round(
            climate["mean_temperature_c"] + climate["seasonal_amplitude_c"] * seasonal + jitter
        )
        temperature = max(-30, min(55, temperature))
        humidity = round(climate["humidity_index"] + (_unit(match_id, "humidity") - 0.5) * 24)
        humidity = max(15, min(100, humidity))
        wind = round(2 + climate["wind_index"] * 0.20 + _unit(match_id, "wind") * 16)
        wind = max(0, min(120, wind))

        rain_probability = min(0.62, 0.05 + climate["rainfall_index"] * 0.0048)
        rain_roll = _unit(match_id, "rain")
        snow_probability = min(0.42, climate["snow_index"] * 0.0042)
        snow_roll = _unit(match_id, "snow")
        if temperature <= 2 and snow_roll < snow_probability:
            condition = "SNOW"
            precip = round(30 + _unit(match_id, "snow-intensity") * 55)
        elif rain_roll < rain_probability:
            heavy = _unit(match_id, "rain-heavy") < 0.22
            condition = "HEAVY_RAIN" if heavy else "RAIN"
            precip = round((58 if heavy else 18) + _unit(match_id, "rain-intensity") * (38 if heavy else 35))
        elif _unit(match_id, "cloud") < 0.42:
            condition = "CLOUDY"
            precip = 0
        else:
            condition = "CLEAR"
            precip = 0

        roof_closed = roof_type == "CLOSED" or (
            roof_type == "RETRACTABLE" and (condition in {"HEAVY_RAIN", "SNOW"} or wind >= 55)
        )
        if roof_closed:
            # Outside weather stays part of the evidence, but effective field exposure is protected.
            wind = min(wind, 3)
            precip = 0
            if condition in {"RAIN", "HEAVY_RAIN", "SNOW"}:
                condition = "CLOUDY"
        return {
            "weather_condition": condition,
            "temperature_c": int(temperature),
            "humidity_pct": int(humidity),
            "wind_kph": int(wind),
            "precipitation_intensity": max(0, min(100, int(precip))),
            "roof_closed": bool(roof_closed),
        }
