"""Deterministic checkpoint-capable FTG Match Engine v2.2.

v2.2 preserves the v2.1 snapshot contract but accepts append-only live commands.
The engine remains pure: each checkpoint is reproducible from snapshot + seed +
accepted commands, so no PRNG cursor or hidden server memory is required.
"""
from __future__ import annotations

from collections import Counter
from dataclasses import replace

from ..state import MatchState, SimulationResult, EngineStateError
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.v22 import MatchReportV22, TacticalDecisionV22
from ..v21.policy import next_transition, opponent_defence_suppression, segment_multiplier
from .commands import LiveCommandState, COMMAND_SUBSTITUTION, COMMAND_TACTICS
from .config import ENGINE_KEY, ENGINE_VERSION, EXTRA_TIME_SEGMENTS, FIELD_SEGMENTS, REGULATION_SEGMENTS
from .contracts import MatchV22Outcome

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


def segment_window(segment: int) -> tuple[int, int]:
    if isinstance(segment, bool) or not isinstance(segment, int) or not 1 <= segment <= 8:
        raise EngineStateError("Interactive segment must be 1..8.")
    return FIELD_SEGMENTS[segment - 1]


class FTGMatchEngineV22:
    key = ENGINE_KEY
    version = ENGINE_VERSION

    def simulate(
        self,
        state: MatchState,
        *,
        seed: int,
        commands: tuple[LiveCommandState, ...] | list[LiveCommandState] = (),
    ) -> MatchV22Outcome:
        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.2 requires a schema-v3 tactical snapshot.")
        commands = tuple(sorted(commands, key=lambda row: row.sequence))
        self._validate_commands(state=state, commands=commands)

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

        # Freeze the score-independent event domain first. Interactive manual
        # substitutions are merged before cards/injuries are consumed so a
        # player removed by the manager cannot later receive an impossible card.
        zero_resolution = SportingResolutionV2(0, 0)
        zero_result = SimulationResult(home_score=0, away_score=0)
        base_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,
        )
        non_goal_events = self._merge_non_goal_timeline(
            state=state,
            base_events=base_skeleton.events,
            commands=commands,
            max_substitutions=rules.max_substitutions,
            max_substitution_windows=rules.max_substitution_windows,
        )
        red_events = tuple(
            row for row in non_goal_events
            if row.event_type in {EVENT_RED, EVENT_SECOND_YELLOW}
        )

        tactical_commands = {
            segment: [row for row in commands if row.command_type == COMMAND_TACTICS and row.effective_segment == segment]
            for segment in range(1, 9)
        }
        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: list[dict] = []

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

        def process_segment(segment_index: int, start: int, end: int, *, 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)

            manual_clubs: set[str] = set()
            for command in tactical_commands[segment_index]:
                club_id = command.club_id
                context = state.home_tactics if club_id == state.home.club_id else state.away_tactics
                own_reds = home_reds if club_id == state.home.club_id else away_reds
                opp_reds = away_reds if club_id == state.home.club_id else home_reds
                previous_attack, previous_defence = current[club_id]
                current[club_id] = [command.attacking_strategy, command.defensive_strategy]
                manual_clubs.add(club_id)
                decisions.append({
                    "minute": start,
                    "phase": phase,
                    "club_id": club_id,
                    "source": "LIVE_COMMAND",
                    "trigger_type": "LIVE_COMMAND",
                    "previous_attack": previous_attack,
                    "previous_defence": previous_defence,
                    "attack": command.attacking_strategy,
                    "defence": command.defensive_strategy,
                    "home_score": home_score,
                    "away_score": away_score,
                    "own_reds": own_reds,
                    "opp_reds": opp_reds,
                    "command_ref": command.command_ref,
                    "context": context,
                })

            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),
            ):
                # A manager command is authoritative for this checkpoint. The
                # automatic coach can react again at the next checkpoint.
                if club_id in manual_clubs:
                    continue
                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,
                        "command_ref": None,
                        "context": context,
                    })

            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],
            )
            home_lineup_factor = self._lineup_strength_factor(
                state=state, club_id=state.home.club_id, events=non_goal_events, minute=start
            )
            away_lineup_factor = self._lineup_strength_factor(
                state=state, club_id=state.away.club_id, events=non_goal_events, minute=start
            )
            home_factor = dict(home_factor); away_factor = dict(away_factor)
            home_factor["lineup_factor"] = home_lineup_factor
            away_factor["lineup_factor"] = away_lineup_factor

            fraction = (end - start + 1) / 90.0
            home_mean = evaluation.home_expected_goals * fraction * home_factor["xg_factor"] * home_lineup_factor / home_suppression
            away_mean = evaluation.away_expected_goals * fraction * away_factor["xg_factor"] * away_lineup_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))

            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 index, (start, end) in enumerate(REGULATION_SEGMENTS, start=1):
            process_segment(index, 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 index, (start, end) in enumerate(EXTRA_TIME_SEGMENTS, start=7):
                    process_segment(index, 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_interactive_report(
            state=state,
            seed=seed,
            non_goal_events=non_goal_events,
            goal_windows=goal_windows,
            result=result,
            resolution=resolution,
        )
        tactical_rows = tuple(
            TacticalDecisionV22(
                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"],
                command_ref=row.get("command_ref"),
                effect=tuple(sorted((row.get("effect") or {}).items())),
            )
            for index, row in enumerate(decisions)
        )
        return MatchV22Outcome(
            result=result,
            resolution=resolution,
            report=MatchReportV22(
                events=events,
                team_statistics=team_rows,
                player_statistics=player_rows,
                tactical_decisions=tactical_rows,
            ),
        )

    @staticmethod
    def _validate_commands(*, state: MatchState, commands: tuple[LiveCommandState, ...]):
        clubs = {state.home.club_id, state.away.club_id}
        players = {
            state.home.club_id: {p.player_id for p in (*state.home.starters, *state.home.substitutes)},
            state.away.club_id: {p.player_id for p in (*state.away.starters, *state.away.substitutes)},
        }
        sequences = [row.sequence for row in commands]
        if sequences != sorted(set(sequences)):
            raise EngineStateError("Live command sequences must be unique and increasing.")
        refs = [row.command_ref for row in commands]
        if len(refs) != len(set(refs)):
            raise EngineStateError("Live command references must be unique.")
        for row in commands:
            if row.club_id not in clubs:
                raise EngineStateError("Live command references a non-participating club.")
            if row.command_type == COMMAND_SUBSTITUTION:
                if row.player_out_id not in players[row.club_id] or row.player_in_id not in players[row.club_id]:
                    raise EngineStateError("Live substitution references a non-lineup player.")

    def _merge_non_goal_timeline(self, *, state, base_events, commands, max_substitutions, max_substitution_windows):
        teams = {state.home.club_id: state.home, state.away.club_id: state.away}
        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()}
        team_subs = Counter()
        windows = {club: set() for club in teams}

        timeline = []
        for event in base_events:
            if event.event_type in {EVENT_GOAL, EVENT_PENALTY_SCORED, EVENT_PENALTY_MISSED}:
                continue
            timeline.append((event.minute, 1, event.sequence, "BASE", event))
        for command in commands:
            if command.command_type != COMMAND_SUBSTITUTION:
                continue
            minute = segment_window(command.effective_segment)[0]
            timeline.append((minute, 0, command.sequence, "MANUAL", command))
        timeline.sort(key=lambda row: (row[0], row[1], row[2]))

        accepted = []
        for minute, _, _, source, payload in timeline:
            if source == "MANUAL":
                command = payload
                club = command.club_id
                out_id = command.player_out_id; in_id = command.player_in_id
                new_window = minute not in 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(windows[club]) >= max_substitution_windows)
                ):
                    raise EngineStateError(
                        f"Live substitution command {command.command_ref} is no longer valid at its checkpoint."
                    )
                active[club].pop(out_id)
                incoming = bench[club].pop(in_id)
                active[club][in_id] = incoming
                windows[club].add(minute); team_subs[club] += 1
                accepted.append(ReportEventV2(
                    sequence=1,
                    minute=minute,
                    phase=PHASE_REGULATION if minute <= 90 else PHASE_EXTRA_TIME,
                    event_type=EVENT_SUBSTITUTION,
                    club_id=club,
                    player_id=out_id,
                    secondary_player_id=in_id,
                    detail=(("command_ref", command.command_ref), ("source", "LIVE_COMMAND")),
                ))
                continue

            event = payload
            club = event.club_id; pid = event.player_id
            if event.event_type == EVENT_SUBSTITUTION:
                incoming_id = event.secondary_player_id
                detail = event.detail_payload
                injury_replacement = detail.get("reason") == "INJURY"
                new_window = minute not in windows[club]
                if (
                    incoming_id not in bench[club]
                    or team_subs[club] >= max_substitutions
                    or (new_window and len(windows[club]) >= max_substitution_windows)
                    or (not injury_replacement and pid not in active[club])
                ):
                    continue
                active[club].pop(pid, None)
                incoming = bench[club].pop(incoming_id)
                active[club][incoming_id] = incoming
                windows[club].add(minute); team_subs[club] += 1
                accepted.append(event)
                continue

            if pid not in active[club]:
                continue
            accepted.append(event)
            if event.event_type in {EVENT_RED, EVENT_SECOND_YELLOW}:
                active[club].pop(pid, None)
            elif event.event_type == EVENT_INJURY and event.detail_payload.get("match_availability") == "UNAVAILABLE":
                active[club].pop(pid, None)

        phase_order = {PHASE_REGULATION: 0, PHASE_EXTRA_TIME: 1}
        accepted.sort(key=lambda e: (phase_order.get(e.phase, 2), e.minute, e.sequence, e.club_id, e.player_id))
        return tuple(replace(event, sequence=index + 1) for index, event in enumerate(accepted))

    @staticmethod
    def _active_players_at(*, state, club_id, events, minute):
        team = state.home if club_id == state.home.club_id else state.away
        all_players = {p.player_id: p for p in (*team.starters, *team.substitutes)}
        active = {p.player_id for p in team.starters}
        for event in events:
            if event.club_id != club_id or event.minute > minute:
                continue
            if event.event_type == EVENT_SUBSTITUTION:
                active.discard(event.player_id)
                if event.secondary_player_id:
                    active.add(event.secondary_player_id)
            elif event.event_type in {EVENT_RED, EVENT_SECOND_YELLOW}:
                active.discard(event.player_id)
            elif event.event_type == EVENT_INJURY and event.detail_payload.get("match_availability") == "UNAVAILABLE":
                active.discard(event.player_id)
        return [all_players[pid] for pid in active if pid in all_players]

    def _lineup_strength_factor(self, *, state, club_id, events, minute):
        team = state.home if club_id == state.home.club_id else state.away
        active = self._active_players_at(state=state, club_id=club_id, events=events, minute=minute)
        if not active:
            return 0.72
        base = sum(_rating(p, "overall") for p in team.starters) / len(team.starters)
        current = sum(_rating(p, "overall") for p in active) / len(active)
        quality = ((current + 1.0) / (base + 1.0)) ** 0.35
        headcount = (len(active) / 11.0) ** 0.30
        return max(0.72, min(1.15, quality * headcount))

    def _build_interactive_report(self, *, state, seed, non_goal_events, goal_windows, result, resolution):
        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-minute randomness is isolated per club + field window.  A live
        # command effective in a future segment can change the number of goals
        # in that future window, but must never consume RNG values that move a
        # goal already published in an earlier checkpoint.  This prefix-stable
        # domain separation is a hard invariant of the interactive runner.
        goal_specs = []
        ordinal = 0
        for club_index, club_id in enumerate((state.home.club_id, state.away.club_id), start=1):
            for start, end, count in goal_windows[club_id]:
                window_domain = (
                    DOMAIN_TACTICAL_GOAL_MINUTES
                    ^ (club_index * 0x9E3779B97F4A7C15)
                    ^ (start << 17)
                    ^ (end << 33)
                )
                minute_rng = _domain_rng(seed, window_domain)
                for _ in range(count):
                    goal_specs.append((
                        start + int(minute_rng.random() * (end - start + 1)),
                        club_id,
                        ordinal,
                    ))
                    ordinal += 1

        timeline = [
            (row.minute, 0, row.sequence, "EVENT", row)
            for row in non_goal_events
            if row.minute <= match_minutes
        ]
        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,
            ))

        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)
