"""Deterministic FTG Match Engine v2.1 with live tactical intelligence."""
from __future__ import annotations

from collections import Counter
from dataclasses import replace

from ..randomness import SplitMix64
from ..state import MatchState, SimulationResult
from ..v1.engine import FTGMatchEngineV1
from ..v2.engine import FTGMatchEngineV2, _domain_rng, _poisson, _rating, _weighted_choice
from ..v2.contracts import (
    SportingResolutionV2, RESOLUTION_EXTRA_TIME, RESOLUTION_PENALTIES, RESOLUTION_REGULATION,
)
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,
    PlayerMatchStatisticsV2, ReportEventV2, TeamMatchStatisticsV2,
)
from ..reporting.v21 import MatchReportV21, TacticalDecisionV21
from .config import ENGINE_KEY, ENGINE_VERSION, EXTRA_TIME_SEGMENTS, REGULATION_SEGMENTS
from .contracts import MatchV21Outcome
from .policy import next_transition, opponent_defence_suppression, segment_multiplier

DOMAIN_TACTICAL_SCORE = 0xA24BAED4963EE407
DOMAIN_TACTICAL_GOAL_MINUTES = 0x9FB21C651E98DF25
DOMAIN_TACTICAL_SCORERS = 0xC6BC279692B5CC83
DOMAIN_TACTICAL_SHOOTOUT_REPORT = 0xDB4F0B9175AE2165


class FTGMatchEngineV21:
    key = ENGINE_KEY
    version = ENGINE_VERSION

    def simulate(self, state: MatchState, *, seed: int) -> MatchV21Outcome:
        if isinstance(seed, bool) or not isinstance(seed, int) or seed < 1:
            raise ValueError("seed must be a positive integer.")
        if state.schema_version < 3:
            raise ValueError("Match Engine v2.1 requires a schema-v3 tactical snapshot.")

        rules = state.rules
        evaluation = FTGMatchEngineV1().evaluate(state)
        base_engine = FTGMatchEngineV2()

        # Generate the v2 non-goal timeline first. Because its card/injury/sub
        # domains are independent from score, this is stable and can inform
        # tactical red-card reactions before we sample later scoring windows.
        zero_resolution = SportingResolutionV2(0, 0)
        zero_result = SimulationResult(home_score=0, away_score=0)
        skeleton = base_engine._build_report(
            state=state, result=zero_result, resolution=zero_resolution, seed=seed,
            max_substitutions=rules.max_substitutions,
            max_substitution_windows=rules.max_substitution_windows,
        )
        red_events = tuple(
            row for row in skeleton.events
            if row.event_type in {EVENT_RED, EVENT_SECOND_YELLOW}
        )

        score_rng = _domain_rng(seed, DOMAIN_TACTICAL_SCORE)
        goal_windows = {state.home.club_id: [], state.away.club_id: []}
        home_score = away_score = 0
        current = {
            state.home.club_id: [state.home_tactics.attacking_strategy, state.home_tactics.defensive_strategy],
            state.away.club_id: [state.away_tactics.attacking_strategy, state.away_tactics.defensive_strategy],
        }
        applied = {state.home.club_id: set(), state.away.club_id: set()}
        decisions = []

        def reds_before(club_id, minute):
            return sum(row.club_id == club_id and row.minute < minute for row in red_events)

        def process_segment(start, end, *, extra_time=False):
            nonlocal home_score, away_score
            phase = PHASE_EXTRA_TIME if extra_time else PHASE_REGULATION
            home_reds = reds_before(state.home.club_id, start)
            away_reds = reds_before(state.away.club_id, start)

            for club_id, context, own_score, opp_score, own_reds, opp_reds in (
                (state.home.club_id, state.home_tactics, home_score, away_score, home_reds, away_reds),
                (state.away.club_id, state.away_tactics, away_score, home_score, away_reds, home_reds),
            ):
                transition = next_transition(
                    context,
                    minute=start,
                    score_diff=own_score - opp_score,
                    own_reds=own_reds,
                    opponent_reds=opp_reds,
                    current_attack=current[club_id][0],
                    current_defence=current[club_id][1],
                    applied_keys=applied[club_id],
                )
                if transition is not None:
                    previous_attack, previous_defence = current[club_id]
                    current[club_id] = [transition.attacking_strategy, transition.defensive_strategy]
                    applied[club_id].add(transition.applied_key)
                    decisions.append({
                        "minute": start,
                        "phase": phase,
                        "club_id": club_id,
                        "source": transition.source,
                        "trigger_type": transition.trigger_type,
                        "previous_attack": previous_attack,
                        "previous_defence": previous_defence,
                        "attack": transition.attacking_strategy,
                        "defence": transition.defensive_strategy,
                        "home_score": home_score,
                        "away_score": away_score,
                        "own_reds": own_reds,
                        "opp_reds": opp_reds,
                    })

            home_factor = segment_multiplier(
                state.home_tactics,
                attack_strategy=current[state.home.club_id][0],
                defence_strategy=current[state.home.club_id][1],
                opponent_attack_strategy=current[state.away.club_id][0],
                opponent_defence_strategy=current[state.away.club_id][1],
                own_reds=home_reds, opponent_reds=away_reds,
            )
            away_factor = segment_multiplier(
                state.away_tactics,
                attack_strategy=current[state.away.club_id][0],
                defence_strategy=current[state.away.club_id][1],
                opponent_attack_strategy=current[state.home.club_id][0],
                opponent_defence_strategy=current[state.home.club_id][1],
                own_reds=away_reds, opponent_reds=home_reds,
            )
            home_suppression = opponent_defence_suppression(
                state.away_tactics, opponent_defence_strategy=current[state.away.club_id][1],
                attacking_strategy=current[state.home.club_id][0],
            )
            away_suppression = opponent_defence_suppression(
                state.home_tactics, opponent_defence_strategy=current[state.home.club_id][1],
                attacking_strategy=current[state.away.club_id][0],
            )
            fraction = (end - start + 1) / 90.0
            home_mean = evaluation.home_expected_goals * fraction * home_factor["xg_factor"] / home_suppression
            away_mean = evaluation.away_expected_goals * fraction * away_factor["xg_factor"] / away_suppression
            hg = _poisson(score_rng, max(0.01, home_mean))
            ag = _poisson(score_rng, max(0.01, away_mean))
            home_score += hg
            away_score += ag
            if hg:
                goal_windows[state.home.club_id].append((start, end, hg))
            if ag:
                goal_windows[state.away.club_id].append((start, end, ag))

            # Attach the effective factors to decisions taken at this checkpoint.
            for row in decisions:
                if row["minute"] == start and "effect" not in row:
                    row["effect"] = home_factor if row["club_id"] == state.home.club_id else away_factor

        for start, end in REGULATION_SEGMENTS:
            process_segment(start, end)
        regulation_home, regulation_away = home_score, away_score

        decision_stage = RESOLUTION_REGULATION
        if rules.requires_winner and home_score == away_score:
            if rules.allows_extra_time:
                for start, end in EXTRA_TIME_SEGMENTS:
                    process_segment(start, end, extra_time=True)
                decision_stage = RESOLUTION_EXTRA_TIME
            elif not rules.allows_penalties:
                raise ValueError("Winner-required match has no draw-resolution rule.")

        extra_home = home_score - regulation_home
        extra_away = away_score - regulation_away
        penalties = None
        if rules.requires_winner and home_score == away_score:
            if not rules.allows_penalties:
                raise ValueError("Winner-required match remained drawn without penalties.")
            penalties = base_engine._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=extra_home,
            extra_time_away_goals=extra_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=home_score, away_score=away_score)
        events, team_rows, player_rows = self._build_live_report(
            state=state, seed=seed, skeleton=skeleton, goal_windows=goal_windows,
            result=result, resolution=resolution,
        )
        tactical_rows = tuple(
            TacticalDecisionV21(
                sequence=index + 1,
                minute=row["minute"], phase=row["phase"], club_id=row["club_id"],
                source=row["source"], trigger_type=row["trigger_type"],
                previous_attacking_strategy=row["previous_attack"],
                previous_defensive_strategy=row["previous_defence"],
                attacking_strategy=row["attack"], defensive_strategy=row["defence"],
                home_score=row["home_score"], away_score=row["away_score"],
                own_red_cards=row["own_reds"], opponent_red_cards=row["opp_reds"],
                effect=tuple(sorted((row.get("effect") or {}).items())),
            )
            for index, row in enumerate(decisions)
        )
        report = MatchReportV21(
            events=events,
            team_statistics=team_rows,
            player_statistics=player_rows,
            tactical_decisions=tactical_rows,
        )
        return MatchV21Outcome(result=result, resolution=resolution, report=report)

    def _build_live_report(self, *, state, seed, skeleton, goal_windows, result, resolution):
        """Build v2.1 facts from one score-independent non-goal event domain.

        v2.0 intentionally used one event RNG. v2.1 freezes its non-goal
        timeline from a zero-goal pass, then adds tactical goals separately.
        This guarantees that a red card used by live tactics is the same red
        card later persisted in the authoritative report.
        """
        minute_rng = _domain_rng(seed, DOMAIN_TACTICAL_GOAL_MINUTES)
        scorer_rng = _domain_rng(seed, DOMAIN_TACTICAL_SCORERS)
        teams = {state.home.club_id: state.home, state.away.club_id: state.away}
        match_minutes = 120 if resolution.decision_stage in {RESOLUTION_EXTRA_TIME, RESOLUTION_PENALTIES} else 90

        goal_specs = []
        ordinal = 0
        for club_id in (state.home.club_id, state.away.club_id):
            for start, end, count in goal_windows[club_id]:
                for _ in range(count):
                    goal_specs.append((
                        start + int(minute_rng.random() * (end - start + 1)),
                        club_id,
                        ordinal,
                    ))
                    ordinal += 1

        # Skeleton contains zero GOAL events by construction. Preserve all
        # cards/substitutions/injuries exactly and interleave tactical goals.
        timeline = [
            (row.minute, 0, row.sequence, "EVENT", row)
            for row in skeleton.events
            if row.event_type != EVENT_GOAL
        ]
        timeline += [(minute, 1, order, "GOAL", club) for minute, club, order in goal_specs]
        timeline.sort(key=lambda item: (item[0], item[1], item[2]))

        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 team in teams.values() for p in team.starters}
        exit_minute = {}
        started = set(entry_minute)
        subbed_in = set(); subbed_out = set(); injured = set()
        yellow_count = Counter(); red_count = Counter(); goal_count = Counter(); team_subs = Counter()
        merged = []

        for minute, _, _, kind, payload in timeline:
            if kind == "EVENT":
                event = payload
                club = event.club_id
                if event.event_type == EVENT_SUBSTITUTION:
                    active[club].pop(event.player_id, None)
                    incoming = bench[club].pop(event.secondary_player_id, None)
                    if incoming is not None:
                        active[club][incoming.player_id] = incoming
                        entry_minute[incoming.player_id] = minute
                    exit_minute.setdefault(event.player_id, minute)
                    subbed_out.add(event.player_id)
                    if event.secondary_player_id:
                        subbed_in.add(event.secondary_player_id)
                    team_subs[club] += 1
                elif event.event_type == EVENT_YELLOW:
                    yellow_count[event.player_id] += 1
                elif event.event_type == EVENT_SECOND_YELLOW:
                    yellow_count[event.player_id] += 1
                    red_count[event.player_id] = 1
                    active[club].pop(event.player_id, None)
                    exit_minute.setdefault(event.player_id, minute)
                elif event.event_type == EVENT_RED:
                    red_count[event.player_id] = 1
                    active[club].pop(event.player_id, None)
                    exit_minute.setdefault(event.player_id, minute)
                elif event.event_type == EVENT_INJURY:
                    injured.add(event.player_id)
                    if event.detail_payload.get("match_availability") == "UNAVAILABLE":
                        active[club].pop(event.player_id, None)
                        exit_minute.setdefault(event.player_id, minute)
                merged.append(event)
                continue

            club = payload
            choices = list(active[club].values()) or list(teams[club].starters)
            scorer = _weighted_choice(
                scorer_rng, choices,
                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
            merged.append(ReportEventV2(
                sequence=1,
                minute=minute,
                phase=PHASE_REGULATION if minute <= 90 else PHASE_EXTRA_TIME,
                event_type=EVENT_GOAL,
                club_id=club,
                player_id=scorer.player_id,
            ))

        # Penalty-shootout facts are separate from field goals/statistics.
        if resolution.decision_stage == RESOLUTION_PENALTIES:
            srng = _domain_rng(seed, DOMAIN_TACTICAL_SHOOTOUT_REPORT)
            targets = {
                state.home.club_id: int(resolution.home_penalties or 0),
                state.away.club_id: int(resolution.away_penalties or 0),
            }
            total_kicks = max(5, max(targets.values()))
            for club in (state.home.club_id, state.away.club_id):
                eligible = list(active[club].values()) or list(teams[club].starters)
                eligible.sort(key=lambda p: (_rating(p, "composure") + _rating(p, "finishing")), reverse=True)
                pattern = [True] * targets[club] + [False] * max(0, total_kicks - targets[club])
                for idx in range(len(pattern) - 1, 0, -1):
                    swap = int(srng.random() * (idx + 1))
                    pattern[idx], pattern[swap] = pattern[swap], pattern[idx]
                for idx, scored in enumerate(pattern):
                    taker = eligible[idx % len(eligible)]
                    merged.append(ReportEventV2(
                        sequence=1, minute=120, phase=PHASE_SHOOTOUT,
                        event_type=EVENT_PENALTY_SCORED if scored else EVENT_PENALTY_MISSED,
                        club_id=club, player_id=taker.player_id,
                        detail=(("kick_number", idx + 1),),
                    ))

        phase_order = {PHASE_REGULATION: 0, PHASE_EXTRA_TIME: 1, PHASE_SHOOTOUT: 2}
        merged.sort(key=lambda e: (
            phase_order[e.phase], e.minute,
            1 if e.event_type == EVENT_GOAL else 0,
            e.sequence, e.club_id, e.player_id,
        ))
        events = tuple(replace(event, sequence=index + 1) for index, event in enumerate(merged))

        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 events, team_rows, tuple(player_rows)
