from __future__ import annotations

from players.age import sporting_age

from decimal import Decimal

from django.db import transaction
from django.utils import timezone

from clubs.models import Club, ClubSquadMembership
from game_statistics.models import AdvancedMatchPlayerStatistics, MatchAnalyticsRun
from matches.constants import LineupEntryRole, MatchResultType, MatchStatus
from matches.engine.serialization import payload_sha256
from matches.models import Match, MatchLineupEntry
from training.models import MatchExperienceDevelopmentResult, PlayerDevelopmentProgress

from .dynamics import (
    DYNAMICS_POLICY_KEY,
    DYNAMICS_POLICY_VERSION,
    PlayerDynamicInput,
    PlayerDynamicsPolicyV1,
    PlayerReadinessPolicyV1,
)
from .exceptions import (
    PlayerDynamicsIntegrityError,
    PlayerDynamicsOutOfOrderError,
    PlayerDynamicsUnavailableError,
)
from .models import (
    PLAYER_RATING_FIELDS,
    Player,
    PlayerDynamicState,
    PlayerMatchDynamicEffect,
    PlayerMatchReadinessSnapshot,
)


class PlayerDynamicsService:
    """Project one completed match into player form, morale and experience."""

    @classmethod
    @transaction.atomic
    def project_match(cls, *, match_id):
        try:
            match = (
                Match.objects.select_for_update(of=("self",))
                .select_related("fixture", "sporting_resolution")
                .get(pk=match_id)
            )
        except Match.DoesNotExist as exc:
            raise PlayerDynamicsUnavailableError("Match does not exist.") from exc
        if match.status != MatchStatus.COMPLETED or match.result_type != MatchResultType.PLAYED:
            raise PlayerDynamicsUnavailableError("Player dynamics require a completed played match.")
        if match.completed_at is None:
            raise PlayerDynamicsIntegrityError("Completed match has no completion timestamp.")

        try:
            analytics_run = MatchAnalyticsRun.objects.get(match_id=match.pk)
        except MatchAnalyticsRun.DoesNotExist as exc:
            raise PlayerDynamicsUnavailableError(
                "Player dynamics require advanced match analytics."
            ) from exc
        if payload_sha256(analytics_run.analytics_payload) != analytics_run.output_hash:
            raise PlayerDynamicsIntegrityError("Advanced analytics evidence hash is invalid.")

        entries = list(
            MatchLineupEntry.objects.filter(lineup__match_id=match.pk)
            .select_related("player", "lineup")
            .order_by("player_id")
        )
        if not entries:
            raise PlayerDynamicsIntegrityError("Completed match has no locked lineup entries.")

        existing = list(
            PlayerMatchDynamicEffect.objects.filter(match_id=match.pk)
            .order_by("player_id")
        )
        if existing:
            if len(existing) != len(entries):
                raise PlayerDynamicsIntegrityError("Match dynamics projection is partial.")
            cls._verify_effects(existing)
            cls._materialize_match_credit(match=match, effects=existing)
            return existing

        player_ids = [entry.player_id for entry in entries]
        players = {
            player.pk: player
            for player in Player.objects.select_for_update()
            .filter(pk__in=player_ids)
            .order_by("pk")
        }
        if len(players) != len(set(player_ids)):
            raise PlayerDynamicsIntegrityError("One or more lineup players no longer exist.")

        stats_by_player = {
            row.player_id: row
            for row in AdvancedMatchPlayerStatistics.objects.filter(
                analytics_run=analytics_run, player_id__in=player_ids
            ).order_by("player_id")
        }

        effects = []
        for entry in entries:
            player = players[entry.player_id]
            state, _ = PlayerDynamicState.objects.get_or_create(player=player)
            state = PlayerDynamicState.objects.select_for_update().get(pk=state.pk)
            if state.last_effect_at and state.last_effect_at > match.completed_at:
                raise PlayerDynamicsOutOfOrderError(
                    "An older match cannot be projected after a newer player dynamics effect. "
                    "Use chronological rebuild/backfill."
                )

            stats = stats_by_player.get(player.pk)
            started = entry.role == LineupEntryRole.STARTER
            appeared = bool(stats and stats.minutes_played > 0)
            if started and not appeared:
                raise PlayerDynamicsIntegrityError(
                    "Starting player is missing from advanced match participation statistics."
                )
            unused_substitute = entry.role == LineupEntryRole.SUBSTITUTE and not appeared
            club_id = entry.lineup.club_id
            result = cls._result_for_club(match=match, club_id=club_id)

            calculated = PlayerDynamicsPolicyV1.calculate(
                PlayerDynamicInput(
                    match_date=match.completed_at.date(),
                    date_of_birth=player.date_of_birth,
                    age_years=sporting_age(player, match.completed_at.date()),
                    overall=player.overall,
                    potential=player.potential,
                    position=player.position,
                    form_score=state.form_score,
                    morale_score=state.morale_score,
                    experience_points=state.experience_points,
                    last_effect_date=state.last_effect_at.date() if state.last_effect_at else None,
                    started=started,
                    appeared=appeared,
                    unused_substitute=unused_substitute,
                    minutes_played=int(stats.minutes_played) if stats else 0,
                    rating=stats.rating if stats else None,
                    result=result,
                    man_of_the_match=bool(stats and stats.is_man_of_the_match),
                    red_cards=int(stats.red_cards) if stats else 0,
                    injured=bool(stats and stats.injured),
                )
            )
            revision = state.revision + 1
            evidence_payload = {
                "schema_version": 1,
                "match_id": str(match.pk),
                "player_id": str(player.pk),
                "club_id": str(club_id),
                "analytics_run_id": str(analytics_run.pk),
                "analytics_output_hash": analytics_run.output_hash,
                "state_revision": revision,
                "lineup_role": entry.role,
                "started": started,
                "appeared": appeared,
                "unused_substitute": unused_substitute,
                "minutes_played": int(stats.minutes_played) if stats else 0,
                "performance_rating": str(stats.rating) if stats else None,
                "result": result,
                "man_of_the_match": bool(stats and stats.is_man_of_the_match),
                "red_cards": int(stats.red_cards) if stats else 0,
                "injured": bool(stats and stats.injured),
                "form_before": str(calculated.form_before),
                "form_after": str(calculated.form_after),
                "morale_before": str(calculated.morale_before),
                "morale_after": str(calculated.morale_after),
                "experience_before": str(calculated.experience_before),
                "experience_gained": str(calculated.experience_gained),
                "experience_after": str(calculated.experience_after),
                "development_credit": str(calculated.development_credit),
                "age_years": calculated.age_years,
                "development_allocations": [
                    {"attribute": name, "credit": str(credit)}
                    for name, credit in calculated.development_allocations
                ],
                "policy_key": calculated.policy_key,
                "policy_version": calculated.policy_version,
            }
            effect = PlayerMatchDynamicEffect.objects.create(
                match=match,
                player=player,
                club_id=club_id,
                state_revision=revision,
                lineup_role=entry.role,
                started=started,
                appeared=appeared,
                unused_substitute=unused_substitute,
                minutes_played=int(stats.minutes_played) if stats else 0,
                performance_rating=stats.rating if stats else None,
                result=result,
                man_of_the_match=bool(stats and stats.is_man_of_the_match),
                red_cards=int(stats.red_cards) if stats else 0,
                injured=bool(stats and stats.injured),
                form_before=calculated.form_before,
                form_after=calculated.form_after,
                morale_before=calculated.morale_before,
                morale_after=calculated.morale_after,
                experience_before=calculated.experience_before,
                experience_gained=calculated.experience_gained,
                experience_after=calculated.experience_after,
                development_credit=calculated.development_credit,
                evidence_payload=evidence_payload,
                evidence_hash=payload_sha256(evidence_payload),
                policy_key=calculated.policy_key,
                policy_version=calculated.policy_version,
            )
            cls._apply_development_credit(
                player=player,
                effect=effect,
                allocations=calculated.development_allocations,
            )

            state.form_score = calculated.form_after
            state.morale_score = calculated.morale_after
            state.experience_points = calculated.experience_after
            state.matches_selected += 1
            state.matches_appeared += int(appeared)
            state.starts += int(started)
            state.minutes_played += int(stats.minutes_played) if stats else 0
            state.unused_bench_count += int(unused_substitute)
            state.revision = revision
            state.last_match = match
            state.last_effect_at = match.completed_at
            state.policy_key = DYNAMICS_POLICY_KEY
            state.policy_version = DYNAMICS_POLICY_VERSION
            state.save(update_fields=[
                "form_score", "morale_score", "experience_points", "matches_selected",
                "matches_appeared", "starts", "minutes_played", "unused_bench_count",
                "revision", "last_match", "last_effect_at", "policy_key", "policy_version",
                "updated_at",
            ])
            effects.append(effect)
        cls._materialize_match_credit(match=match, effects=effects)
        return effects

    @staticmethod
    def _materialize_match_credit(*, match, effects):
        from training.models import PlayerRatingMaterializationTrigger
        from training.progression_services import PlayerProgressionMaterializationService

        for effect in sorted(effects, key=lambda row: str(row.player_id)):
            if effect.development_credit <= 0:
                continue
            PlayerProgressionMaterializationService.materialize_player(
                player_id=effect.player_id,
                trigger_type=PlayerRatingMaterializationTrigger.MATCH,
                source_reference=match.pk,
                observed_on=match.completed_at.date(),
            )

    @staticmethod
    def _apply_development_credit(*, player, effect, allocations):
        for attribute_name, credit in allocations:
            if credit <= 0:
                continue
            progress, _ = PlayerDevelopmentProgress.objects.get_or_create(
                player=player,
                attribute_name=attribute_name,
                defaults={"total_points": Decimal("0.000000")},
            )
            progress = PlayerDevelopmentProgress.objects.select_for_update().get(pk=progress.pk)
            before = progress.total_points
            after = before + credit
            progress.total_points = after
            progress.save(update_fields=["total_points", "updated_at"])
            MatchExperienceDevelopmentResult.objects.create(
                dynamic_effect=effect,
                player=player,
                attribute_name=attribute_name,
                credit=credit,
                progress_before=before,
                progress_after=after,
                policy_key=effect.policy_key,
                policy_version=effect.policy_version,
            )

    @staticmethod
    def _result_for_club(*, match, club_id):
        is_home = club_id == match.fixture.home_club_id
        if match.home_score == match.away_score:
            try:
                resolution = match.sporting_resolution
            except Exception:
                resolution = None
            if resolution is None or resolution.home_penalties is None or resolution.away_penalties is None:
                return "DRAW"
            home_won = resolution.home_penalties > resolution.away_penalties
            return "WIN" if home_won == is_home else "LOSS"
        home_won = match.home_score > match.away_score
        return "WIN" if home_won == is_home else "LOSS"

    @staticmethod
    def _verify_effects(effects):
        for effect in effects:
            if payload_sha256(effect.evidence_payload) != effect.evidence_hash:
                raise PlayerDynamicsIntegrityError(
                    f"Player dynamics evidence hash is invalid for player {effect.player_id}."
                )
            allocated = sum(
                (row.credit for row in effect.development_results.all()),
                Decimal("0.000000"),
            )
            if allocated != effect.development_credit:
                raise PlayerDynamicsIntegrityError(
                    f"Match-experience development credits do not reconcile for player {effect.player_id}."
                )
        return effects


class PlayerMatchReadinessSnapshotService:
    """Freeze form/morale and effective match ratings before kickoff."""

    @classmethod
    def snapshot_pair(cls, *, match, lineups):
        entries = list(
            MatchLineupEntry.objects.filter(lineup__in=lineups)
            .select_related("player", "lineup")
            .order_by("player_id")
        )
        existing = list(
            PlayerMatchReadinessSnapshot.objects.filter(match_id=match.pk).order_by("player_id")
        )
        if existing:
            if len(existing) != len(entries):
                raise PlayerDynamicsIntegrityError("Player readiness snapshot set is partial.")
            for row in existing:
                if payload_sha256(row.evidence_payload) != row.evidence_hash:
                    raise PlayerDynamicsIntegrityError("Player readiness evidence hash is invalid.")
            return {row.player_id: row for row in existing}

        observed_on = (match.scheduled_at or timezone.now()).date()
        rows = []
        for entry in entries:
            player = entry.player
            state = PlayerDynamicState.objects.filter(player_id=player.pk).first()
            form = state.form_score if state else Decimal("50.00")
            morale = state.morale_score if state else Decimal("50.00")
            experience = state.experience_points if state else Decimal("0.000")
            last_effect_at = state.last_effect_at if state else None
            days = max(0, (observed_on - last_effect_at.date()).days) if last_effect_at else 0
            base_ratings = {
                name: int(getattr(player, name))
                for name in PLAYER_RATING_FIELDS
            }
            calculated = PlayerReadinessPolicyV1.calculate(
                base_ratings=base_ratings,
                form_score=form,
                morale_score=morale,
                days_since_effect=days,
            )
            effective = {k: v for k, v in calculated.effective_ratings.items() if k != "potential"}
            payload = {
                "schema_version": 1,
                "match_id": str(match.pk),
                "player_id": str(player.pk),
                "club_id": str(entry.lineup.club_id),
                "observed_on": observed_on.isoformat(),
                "source_state_revision": state.revision if state else 0,
                "form_score": str(calculated.form_score),
                "morale_score": str(calculated.morale_score),
                "experience_points": str(experience),
                "readiness_multiplier": str(calculated.readiness_multiplier),
                "base_overall": player.overall,
                "base_ratings": base_ratings,
                "effective_overall": effective["overall"],
                "effective_ratings": effective,
                "policy_key": PlayerReadinessPolicyV1.key,
                "policy_version": PlayerReadinessPolicyV1.version,
            }
            rows.append(PlayerMatchReadinessSnapshot.objects.create(
                match=match,
                player=player,
                club_id=entry.lineup.club_id,
                form_score=calculated.form_score,
                morale_score=calculated.morale_score,
                experience_points=experience,
                readiness_multiplier=calculated.readiness_multiplier,
                base_overall=player.overall,
                effective_overall=effective["overall"],
                effective_ratings=effective,
                evidence_payload=payload,
                evidence_hash=payload_sha256(payload),
                policy_key=PlayerReadinessPolicyV1.key,
                policy_version=PlayerReadinessPolicyV1.version,
            ))
        return {row.player_id: row for row in rows}


class ClubLineupReadinessService:
    """Read-only ranking input for human/AI lineup selection."""

    @staticmethod
    def for_club(*, club_id, observed_on=None):
        observed_on = observed_on or timezone.localdate()
        try:
            club = Club.objects.get(pk=club_id)
        except Club.DoesNotExist as exc:
            raise PlayerDynamicsUnavailableError("Club does not exist.") from exc
        memberships = list(
            ClubSquadMembership.objects.filter(club=club)
            .select_related("player", "player__dynamic_state")
            .order_by("player_id")
        )
        from injuries.resolver import FatigueResolver, InjuryResolver

        rows = []
        for membership in memberships:
            player = membership.player
            state = getattr(player, "dynamic_state", None)
            form = state.form_score if state else Decimal("50.00")
            morale = state.morale_score if state else Decimal("50.00")
            exp = state.experience_points if state else Decimal("0.000")
            days = 0
            if state and state.last_effect_at:
                days = max(0, (observed_on - state.last_effect_at.date()).days)
            base_ratings = {name: int(getattr(player, name)) for name in PLAYER_RATING_FIELDS}
            readiness = PlayerReadinessPolicyV1.calculate(
                base_ratings=base_ratings,
                form_score=form,
                morale_score=morale,
                days_since_effect=days,
            )
            fatigue = FatigueResolver.for_player(player=player)
            injury = InjuryResolver.for_player(player=player)
            selection_score = Decimal(readiness.effective_ratings["overall"]) - (
                Decimal(fatigue.fatigue_index) * Decimal("0.08")
            )
            rows.append({
                "player_id": str(player.pk),
                "name": f"{player.first_name} {player.last_name}",
                "position": player.position,
                "base_overall": player.overall,
                "effective_overall": readiness.effective_ratings["overall"],
                "form_score": str(readiness.form_score),
                "morale_score": str(readiness.morale_score),
                "experience_points": str(exp),
                "readiness_multiplier": str(readiness.readiness_multiplier),
                "fatigue_index": str(fatigue.fatigue_index),
                "match_eligible": injury.match_eligible,
                "selection_score": str(selection_score.quantize(Decimal("0.01"))),
            })
        rows.sort(key=lambda row: (not row["match_eligible"], -Decimal(row["selection_score"]), row["player_id"]))
        return rows
