"""Deterministic event-aware FTG Match Engine v2."""
from __future__ import annotations

import math
from collections import Counter

from ..randomness import SplitMix64
from ..state import MatchState, PlayerState, SimulationResult
from ..v1.engine import FTGMatchEngineV1
from ..reporting.v2 import (
    EVENT_GOAL, EVENT_INJURY, EVENT_PENALTY_MISSED, EVENT_PENALTY_SCORED,
    EVENT_RED, EVENT_SECOND_YELLOW, EVENT_SUBSTITUTION, EVENT_YELLOW,
    PHASE_EXTRA_TIME, PHASE_REGULATION, PHASE_SHOOTOUT,
    MatchReportV2, PlayerMatchStatisticsV2, ReportEventV2, TeamMatchStatisticsV2,
)
from .config import (
    BASE_TEAM_CARD_RATE, BASE_TEAM_INJURY_RATE, ENGINE_KEY, ENGINE_VERSION,
    FATIGUE_INJURY_RATE_FACTOR, TACTICAL_SUB_MINUTES,
)
from .contracts import (
    MatchV2Outcome, SportingResolutionV2, RESOLUTION_EXTRA_TIME,
    RESOLUTION_PENALTIES, RESOLUTION_REGULATION,
)

_MASK = (1 << 64) - 1
DOMAIN_SCORE = 0x9E3779B97F4A7C15
DOMAIN_EVENTS = 0xD1B54A32D192ED03
DOMAIN_SHOOTOUT = 0x94D049BB133111EB


def _domain_rng(seed: int, domain: int) -> SplitMix64:
    value = (seed ^ domain) & _MASK
    return SplitMix64(value or domain)


def _poisson(rng: SplitMix64, mean: float) -> int:
    threshold = math.exp(-max(0.01, mean))
    product = 1.0
    count = 0
    while product > threshold:
        count += 1
        product *= rng.random()
    return max(0, count - 1)


def _rating(player: PlayerState, name: str, default=50) -> int:
    return dict(player.ratings).get(name, default)


def _weighted_choice(rng, players, weight_fn):
    players = list(players)
    if not players:
        raise ValueError("Cannot choose from an empty player set.")
    weights = [max(0.001, float(weight_fn(player))) for player in players]
    total = sum(weights)
    marker = rng.random() * total
    upto = 0.0
    for player, weight in zip(players, weights):
        upto += weight
        if marker <= upto:
            return player
    return players[-1]


def _minute(rng, start, end):
    return start + int(rng.random() * (end - start + 1))


def _phase_for_minute(minute):
    return PHASE_REGULATION if minute <= 90 else PHASE_EXTRA_TIME


class FTGMatchEngineV2:
    key = ENGINE_KEY
    version = ENGINE_VERSION

    def simulate(self, state: MatchState, *, seed: int) -> MatchV2Outcome:
        if isinstance(seed, bool) or not isinstance(seed, int) or seed < 1:
            raise ValueError("seed must be a positive integer.")
        rules = getattr(state, "rules", None)
        requires_winner = bool(getattr(rules, "requires_winner", False))
        allows_extra_time = bool(getattr(rules, "allows_extra_time", False))
        allows_penalties = bool(getattr(rules, "allows_penalties", False))
        max_subs = int(getattr(rules, "max_substitutions", 5) or 0)
        max_sub_windows = int(getattr(rules, "max_substitution_windows", 3) or 0)

        evaluation = FTGMatchEngineV1().evaluate(state)
        score_rng = _domain_rng(seed, DOMAIN_SCORE)
        regulation_home = _poisson(score_rng, evaluation.home_expected_goals)
        regulation_away = _poisson(score_rng, evaluation.away_expected_goals)

        et_home = et_away = 0
        penalties = None
        decision_stage = RESOLUTION_REGULATION
        if requires_winner and regulation_home == regulation_away:
            if not allows_extra_time:
                if not allows_penalties:
                    raise ValueError("Winner-required match has no draw-resolution rule.")
            else:
                et_home = _poisson(score_rng, evaluation.home_expected_goals / 3.25)
                et_away = _poisson(score_rng, evaluation.away_expected_goals / 3.25)
                decision_stage = RESOLUTION_EXTRA_TIME
            if regulation_home + et_home == regulation_away + et_away:
                if not allows_penalties:
                    raise ValueError("Winner-required match remained drawn without penalties.")
                penalties = self._shootout(state=state, seed=seed)
                decision_stage = RESOLUTION_PENALTIES

        resolution = SportingResolutionV2(
            regulation_home_score=regulation_home,
            regulation_away_score=regulation_away,
            extra_time_home_goals=et_home,
            extra_time_away_goals=et_away,
            home_penalties=penalties[0] if penalties else None,
            away_penalties=penalties[1] if penalties else None,
            decision_stage=decision_stage,
        )
        result = SimulationResult(
            home_score=resolution.final_home_score,
            away_score=resolution.final_away_score,
        )
        report = self._build_report(
            state=state,
            result=result,
            resolution=resolution,
            seed=seed,
            max_substitutions=max_subs,
            max_substitution_windows=max_sub_windows,
        )
        return MatchV2Outcome(result=result, resolution=resolution, report=report)

    def _shootout(self, *, state, seed):
        rng = _domain_rng(seed, DOMAIN_SHOOTOUT)
        home = away = 0
        # Five initial kicks, then sudden death. Ability differences only make
        # modest probability changes so shootouts remain high variance.
        home_takers = sorted(
            (*state.home.starters,),
            key=lambda p: (_rating(p, "composure") + _rating(p, "finishing") + _rating(p, "set_pieces")),
            reverse=True,
        )
        away_takers = sorted(
            (*state.away.starters,),
            key=lambda p: (_rating(p, "composure") + _rating(p, "finishing") + _rating(p, "set_pieces")),
            reverse=True,
        )
        kick = 0
        while True:
            for team, takers in (("home", home_takers), ("away", away_takers)):
                taker = takers[kick % len(takers)]
                skill = (_rating(taker, "composure") + _rating(taker, "finishing") + _rating(taker, "set_pieces")) / 3
                scored = rng.random() < min(0.90, max(0.60, 0.69 + (skill - 50) * 0.0025))
                if scored:
                    if team == "home": home += 1
                    else: away += 1
            kick += 1
            if kick >= 5 and home != away:
                return home, away
            if kick >= 15:  # deterministic safety valve, never return a draw
                return (home + 1, away) if rng.random() < 0.5 else (home, away + 1)

    def _build_report(
        self, *, state, result, resolution, seed,
        max_substitutions, max_substitution_windows,
    ):
        rng = _domain_rng(seed, DOMAIN_EVENTS)
        match_minutes = 120 if resolution.decision_stage in {RESOLUTION_EXTRA_TIME, RESOLUTION_PENALTIES} else 90
        teams = {state.home.club_id: state.home, state.away.club_id: state.away}

        raw = []
        # Tactical substitution plans.  The chronological reducer below drops
        # any plan made invalid by a prior dismissal/injury.
        for club_id, team in teams.items():
            bench = list(team.substitutes)
            starters = list(team.starters)
            candidates = sorted(
                starters,
                key=lambda p: (_rating(p, "stamina") - getattr(p, "fatigue_index", 0), _rating(p, "overall")),
            )
            planned_count = min(len(bench), max_substitutions, len(candidates))
            window_count = min(max_substitution_windows, len(TACTICAL_SUB_MINUTES))
            if planned_count and window_count:
                # Use the substitution-window rule explicitly. Multiple changes
                # at the same minute consume one window, so 5 substitutions can
                # be represented truthfully across 3 stoppages (2 + 2 + 1).
                base, remainder = divmod(planned_count, window_count)
                player_index = 0
                for window_index in range(window_count):
                    changes_here = base + (1 if window_index < remainder else 0)
                    for _ in range(changes_here):
                        if player_index >= planned_count:
                            break
                        raw.append({
                            "minute": TACTICAL_SUB_MINUTES[window_index],
                            "club_id": club_id,
                            "kind": EVENT_SUBSTITUTION,
                            "player_out": candidates[player_index].player_id,
                            "player_in": bench[player_index].player_id,
                        })
                        player_index += 1

        # Goals are authoritative counts allocated to an eligible on-field
        # scorer when the chronological reducer reaches the goal minute.
        for club_id, count, start, end in (
            (state.home.club_id, resolution.regulation_home_score, 1, 90),
            (state.away.club_id, resolution.regulation_away_score, 1, 90),
            (state.home.club_id, resolution.extra_time_home_goals, 91, 120),
            (state.away.club_id, resolution.extra_time_away_goals, 91, 120),
        ):
            for _ in range(count):
                raw.append({"minute": _minute(rng, start, end), "club_id": club_id, "kind": EVENT_GOAL})

        # Cards. Aggressive players are more likely to be selected; a second
        # active yellow naturally becomes a SECOND_YELLOW dismissal.
        for club_id, team in teams.items():
            mean = BASE_TEAM_CARD_RATE + max(0.0, (sum(_rating(p, "aggression") for p in team.starters) / 11 - 50) * 0.012)
            card_count = min(5, _poisson(rng, mean))
            for _ in range(card_count):
                raw.append({"minute": _minute(rng, 8, min(88, match_minutes)), "club_id": club_id, "kind": "CARD"})

        # In-match injuries are intentionally conservative. Fatigue raises risk
        # without treating the engine as a medical model.
        for club_id, team in teams.items():
            avg_fatigue = sum(getattr(p, "fatigue_index", 0) for p in team.starters) / 11
            probability = min(0.38, BASE_TEAM_INJURY_RATE + avg_fatigue * FATIGUE_INJURY_RATE_FACTOR)
            if rng.random() < probability:
                minute = _minute(rng, 12, min(86, match_minutes))
                severe = rng.random() < 0.34
                raw.append({
                    "minute": minute, "club_id": club_id, "kind": EVENT_INJURY,
                    "severe": severe,
                })

        # Stable order at equal minute: cards/injury before substitution, then goals.
        priority = {"CARD": 0, EVENT_INJURY: 1, EVENT_SUBSTITUTION: 2, EVENT_GOAL: 3}
        raw.sort(key=lambda x: (x["minute"], priority[x["kind"]], x["club_id"]))

        active = {club: {p.player_id: p for p in team.starters} for club, team in teams.items()}
        bench = {club: {p.player_id: p for p in team.substitutes} for club, team in teams.items()}
        entry_minute = {p.player_id: 0 for t in teams.values() for p in t.starters}
        exit_minute = {}
        started = {p.player_id for t in teams.values() for p in t.starters}
        subbed_in = set(); subbed_out = set(); injured = set(); dismissed = set()
        yellow_count = Counter(); red_count = Counter(); goal_count = Counter(); team_subs = Counter()
        substitution_windows = {club: set() for club in teams}
        events = []

        def choose_active(club, weight):
            return _weighted_choice(rng, active[club].values(), weight)

        for item in raw:
            club = item["club_id"]
            minute = item["minute"]
            if not active[club]:
                continue
            if item["kind"] == EVENT_SUBSTITUTION:
                out_id, in_id = item["player_out"], item["player_in"]
                new_window = minute not in substitution_windows[club]
                if (
                    out_id not in active[club]
                    or in_id not in bench[club]
                    or team_subs[club] >= max_substitutions
                    or (new_window and len(substitution_windows[club]) >= max_substitution_windows)
                ):
                    continue
                active[club].pop(out_id); incoming = bench[club].pop(in_id); active[club][in_id] = incoming
                substitution_windows[club].add(minute)
                exit_minute.setdefault(out_id, minute); entry_minute[in_id] = minute
                subbed_out.add(out_id); subbed_in.add(in_id); team_subs[club] += 1
                events.append((minute, EVENT_SUBSTITUTION, club, out_id, in_id, {}))
            elif item["kind"] == "CARD":
                player = choose_active(club, lambda p: 0.45 * _rating(p, "aggression") + 0.35 * _rating(p, "tackling") + 10)
                pid = player.player_id
                direct_red = rng.random() < 0.07
                if direct_red:
                    kind = EVENT_RED; red_count[pid] = 1; dismissed.add(pid)
                    active[club].pop(pid, None); exit_minute.setdefault(pid, minute)
                elif yellow_count[pid] >= 1:
                    kind = EVENT_SECOND_YELLOW; yellow_count[pid] += 1; red_count[pid] = 1; dismissed.add(pid)
                    active[club].pop(pid, None); exit_minute.setdefault(pid, minute)
                else:
                    kind = EVENT_YELLOW; yellow_count[pid] += 1
                events.append((minute, kind, club, pid, None, {}))
            elif item["kind"] == EVENT_INJURY:
                player = choose_active(
                    club,
                    lambda p: 35 + getattr(p, "fatigue_index", 0) + max(0, 70 - _rating(p, "natural_fitness")),
                )
                pid = player.player_id; injured.add(pid)
                severe = bool(item["severe"])
                days = 14 if severe else 4
                detail = {
                    "injury_code": "MATCH_MODERATE" if severe else "MATCH_MINOR",
                    "expected_recovery_days": days,
                    "training_restriction": "PROHIBITED" if severe else "LIMITED",
                    "match_availability": "UNAVAILABLE" if severe else "AVAILABLE",
                }
                events.append((minute, EVENT_INJURY, club, pid, None, detail))
                # Severe injuries force the player off. Use an unused substitute
                # when available, otherwise the club continues a player down.
                if severe:
                    active[club].pop(pid, None); exit_minute.setdefault(pid, minute)
                    injury_window_available = (
                        minute in substitution_windows[club]
                        or len(substitution_windows[club]) < max_substitution_windows
                    )
                    if (
                        bench[club]
                        and team_subs[club] < max_substitutions
                        and injury_window_available
                    ):
                        incoming = max(bench[club].values(), key=lambda p: _rating(p, "overall"))
                        bench[club].pop(incoming.player_id); active[club][incoming.player_id] = incoming
                        substitution_windows[club].add(minute)
                        entry_minute[incoming.player_id] = minute
                        subbed_out.add(pid); subbed_in.add(incoming.player_id); team_subs[club] += 1
                        events.append((minute, EVENT_SUBSTITUTION, club, pid, incoming.player_id, {"reason": "INJURY"}))
            elif item["kind"] == EVENT_GOAL:
                scorer = choose_active(
                    club,
                    lambda p: 0.45 * _rating(p, "finishing") + 0.25 * _rating(p, "positioning") + 0.2 * _rating(p, "composure") + 0.1 * _rating(p, "heading"),
                )
                goal_count[scorer.player_id] += 1
                events.append((minute, EVENT_GOAL, club, scorer.player_id, None, {}))

        # Shootout events are report facts but never player/team goal statistics.
        if resolution.decision_stage == RESOLUTION_PENALTIES:
            srng = _domain_rng(seed, DOMAIN_SHOOTOUT)
            target = {
                state.home.club_id: int(resolution.home_penalties or 0),
                state.away.club_id: int(resolution.away_penalties or 0),
            }
            kickers = {}
            for club in teams:
                eligible = list(active[club].values())
                if not eligible:
                    eligible = list(teams[club].starters)
                kickers[club] = sorted(
                    eligible,
                    key=lambda p: (_rating(p, "composure") + _rating(p, "finishing")),
                    reverse=True,
                )
            total_kicks = max(5, max(target.values()))
            patterns = {}
            for club in teams:
                scored = target[club]
                pattern = [True] * scored + [False] * max(0, total_kicks - scored)
                # Deterministic in-place Fisher-Yates shuffle.
                for idx in range(len(pattern) - 1, 0, -1):
                    swap = int(srng.random() * (idx + 1))
                    pattern[idx], pattern[swap] = pattern[swap], pattern[idx]
                patterns[club] = pattern
            for index in range(total_kicks):
                for club in (state.home.club_id, state.away.club_id):
                    scored = patterns[club][index]
                    taker = kickers[club][index % len(kickers[club])]
                    events.append((
                        120,
                        EVENT_PENALTY_SCORED if scored else EVENT_PENALTY_MISSED,
                        club,
                        taker.player_id,
                        None,
                        {"kick_number": index + 1},
                    ))

        phase_order = {PHASE_REGULATION: 0, PHASE_EXTRA_TIME: 1, PHASE_SHOOTOUT: 2}
        def event_phase(kind, minute):
            if kind in {EVENT_PENALTY_SCORED, EVENT_PENALTY_MISSED}: return PHASE_SHOOTOUT
            return _phase_for_minute(minute)
        events.sort(key=lambda e: (phase_order[event_phase(e[1], e[0])], e[0], 0 if e[1] != EVENT_GOAL else 1, e[2], e[3]))
        report_events = tuple(
            ReportEventV2(
                sequence=i + 1, minute=minute, phase=event_phase(kind, minute),
                event_type=kind, club_id=club, player_id=pid,
                secondary_player_id=secondary,
                detail=tuple(sorted(detail.items())),
            )
            for i, (minute, kind, club, pid, secondary, detail) in enumerate(events)
        )

        for club in teams:
            for pid in active[club]:
                exit_minute.setdefault(pid, match_minutes)
        player_rows = []
        for club, team in teams.items():
            all_players = {p.player_id: p for p in (*team.starters, *team.substitutes)}
            participating = set(entry_minute) & set(all_players)
            for pid in sorted(participating):
                start = entry_minute[pid]; end = exit_minute.get(pid, match_minutes)
                minutes = max(0, min(match_minutes, end) - start)
                if minutes == 0 and pid in started:
                    minutes = 1
                player_rows.append(PlayerMatchStatisticsV2(
                    player_id=pid, club_id=club, started=pid in started,
                    minutes_played=minutes, goals=goal_count[pid],
                    clean_sheet=(result.away_score == 0 if club == state.home.club_id else result.home_score == 0),
                    yellow_cards=yellow_count[pid], red_cards=red_count[pid],
                    substituted_in=pid in subbed_in, substituted_out=pid in subbed_out,
                    injured=pid in injured,
                ))
        team_rows = (
            TeamMatchStatisticsV2(
                club_id=state.home.club_id, goals_for=result.home_score, goals_against=result.away_score,
                clean_sheet=result.away_score == 0,
                yellow_cards=sum(yellow_count[p.player_id] for p in (*state.home.starters, *state.home.substitutes)),
                red_cards=sum(red_count[p.player_id] for p in (*state.home.starters, *state.home.substitutes)),
                substitutions=team_subs[state.home.club_id],
            ),
            TeamMatchStatisticsV2(
                club_id=state.away.club_id, goals_for=result.away_score, goals_against=result.home_score,
                clean_sheet=result.home_score == 0,
                yellow_cards=sum(yellow_count[p.player_id] for p in (*state.away.starters, *state.away.substitutes)),
                red_cards=sum(red_count[p.player_id] for p in (*state.away.starters, *state.away.substitutes)),
                substitutions=team_subs[state.away.club_id],
            ),
        )
        return MatchReportV2(
            events=report_events,
            team_statistics=team_rows,
            player_statistics=tuple(player_rows),
        )
