"""Deterministic report builder for score-only FTG Match Engine v1.

The score engine remains ftg.match.v1@1.0.0. This builder is separately
versioned and turns the immutable state + score into the smallest truthful
report the current simulation can support: goal events and derived appearance /
goal / clean-sheet statistics.
"""

from __future__ import annotations

from collections import Counter

from ..randomness import SplitMix64
from ..state import MatchState, PlayerState, SimulationResult
from .contracts import (
    GOAL_EVENT,
    MatchReport,
    PlayerMatchStatistics,
    ReportEvent,
    TeamMatchStatistics,
)

REPORT_BUILDER_KEY = "ftg.match.report.v1"
REPORT_BUILDER_VERSION = "1.0.0"
_REPORT_SEED_DOMAIN = 0xD1B54A32D192ED03
_MASK_64 = (1 << 64) - 1

# Tactical likelihood only allocates already-authoritative goals to scorers.
# It never changes the final score produced by the match engine.
_SLOT_GOAL_MULTIPLIER = {
    "GK": 0.02,
    "LB": 0.38,
    "LCB": 0.28,
    "RCB": 0.28,
    "RB": 0.38,
    "LCM": 0.72,
    "CM": 0.78,
    "RCM": 0.72,
    "LM": 0.92,
    "RM": 0.92,
    "LW": 1.30,
    "RW": 1.30,
    "ST": 1.65,
    "LST": 1.65,
    "RST": 1.65,
}

_SCORER_RATING_WEIGHTS = {
    "finishing": 0.34,
    "shooting": 0.20,
    "positioning": 0.16,
    "off_ball": 0.12,
    "composure": 0.10,
    "heading": 0.08,
}


class MatchReportBuilderV1:
    key = REPORT_BUILDER_KEY
    version = REPORT_BUILDER_VERSION

    def build(self, state: MatchState, result: SimulationResult, *, seed: int) -> MatchReport:
        if isinstance(seed, bool) or not isinstance(seed, int) or seed < 1:
            raise ValueError("seed must be a positive integer.")

        report_seed = (seed ^ _REPORT_SEED_DOMAIN) & _MASK_64
        if report_seed == 0:
            report_seed = _REPORT_SEED_DOMAIN
        rng = SplitMix64(report_seed)

        pending = []
        pending.extend(
            self._goal_events_for_team(
                rng=rng,
                club_id=state.home.club_id,
                starters=state.home.starters,
                goal_count=result.home_score,
            )
        )
        pending.extend(
            self._goal_events_for_team(
                rng=rng,
                club_id=state.away.club_id,
                starters=state.away.starters,
                goal_count=result.away_score,
            )
        )
        pending.sort(key=lambda item: (item[0], item[1], item[2]))

        events = tuple(
            ReportEvent(
                sequence=index,
                minute=minute,
                event_type=GOAL_EVENT,
                club_id=club_id,
                player_id=player_id,
            )
            for index, (minute, _stable_order, club_id, player_id) in enumerate(
                pending, start=1
            )
        )

        goal_counts = Counter(event.player_id for event in events)
        home_clean = result.away_score == 0
        away_clean = result.home_score == 0

        team_statistics = (
            TeamMatchStatistics(
                club_id=state.home.club_id,
                goals_for=result.home_score,
                goals_against=result.away_score,
                clean_sheet=home_clean,
            ),
            TeamMatchStatistics(
                club_id=state.away.club_id,
                goals_for=result.away_score,
                goals_against=result.home_score,
                clean_sheet=away_clean,
            ),
        )

        player_statistics = tuple(
            [
                PlayerMatchStatistics(
                    player_id=player.player_id,
                    club_id=state.home.club_id,
                    started=True,
                    minutes_played=90,
                    goals=goal_counts[player.player_id],
                    clean_sheet=home_clean,
                )
                for player in state.home.starters
            ]
            + [
                PlayerMatchStatistics(
                    player_id=player.player_id,
                    club_id=state.away.club_id,
                    started=True,
                    minutes_played=90,
                    goals=goal_counts[player.player_id],
                    clean_sheet=away_clean,
                )
                for player in state.away.starters
            ]
        )

        report = MatchReport(
            events=events,
            team_statistics=team_statistics,
            player_statistics=player_statistics,
        )
        self._validate_against_state_and_result(state=state, result=result, report=report)
        return report

    @staticmethod
    def _goal_events_for_team(*, rng, club_id, starters, goal_count):
        weighted_players = [
            (player, _scorer_weight(player)) for player in starters
        ]
        pending = []
        for stable_order in range(goal_count):
            minute = int(rng.random() * 90) + 1
            scorer = _weighted_choice(rng, weighted_players)
            pending.append((minute, stable_order, club_id, scorer.player_id))
        return pending

    @staticmethod
    def _validate_against_state_and_result(*, state, result, report):
        home_ids = {player.player_id for player in state.home.starters}
        away_ids = {player.player_id for player in state.away.starters}
        valid_clubs = {state.home.club_id, state.away.club_id}

        if len(report.events) != result.home_score + result.away_score:
            raise ValueError("Goal-event count must equal the authoritative final score.")
        home_goals = sum(event.club_id == state.home.club_id for event in report.events)
        away_goals = sum(event.club_id == state.away.club_id for event in report.events)
        if (home_goals, away_goals) != (result.home_score, result.away_score):
            raise ValueError("Goal events do not reconcile with the authoritative score.")

        for event in report.events:
            if event.club_id not in valid_clubs:
                raise ValueError("Report event references a non-participating club.")
            allowed = home_ids if event.club_id == state.home.club_id else away_ids
            if event.player_id not in allowed:
                raise ValueError("Goal scorer must be a starting player for the event club.")

        if len(report.player_statistics) != 22:
            raise ValueError("Report v1 must contain statistics for exactly 22 starters.")


def _scorer_weight(player: PlayerState) -> float:
    ratings = dict(player.ratings)
    missing = sorted(set(_SCORER_RATING_WEIGHTS) - set(ratings))
    if missing:
        raise ValueError(
            f"Player {player.player_id} is missing scorer ratings: " + ", ".join(missing)
        )
    weighted_rating = sum(
        ratings[name] * weight for name, weight in _SCORER_RATING_WEIGHTS.items()
    ) / sum(_SCORER_RATING_WEIGHTS.values())
    slot_multiplier = _SLOT_GOAL_MULTIPLIER.get(player.lineup_slot)
    if slot_multiplier is None:
        raise ValueError(f"Unsupported lineup slot for report v1: {player.lineup_slot}")
    return max(0.001, weighted_rating * slot_multiplier)


def _weighted_choice(rng: SplitMix64, weighted_players):
    total = sum(weight for _player, weight in weighted_players)
    if total <= 0:
        raise ValueError("Scorer weights must sum to a positive value.")
    target = rng.random() * total
    cursor = 0.0
    for player, weight in weighted_players:
        cursor += weight
        if target < cursor:
            return player
    return weighted_players[-1][0]
