"""Deterministic causal football simulation for FTG Match Engine v3.

Unlike historical engines that sampled goals first and projected analytics later,
v3 simulates attacking possessions, pass chains, chance creation and shots. Goals
are therefore a consequence of authoritative shot outcomes. The same causal facts
feed xG, assists, keeper saves, player ratings and live checkpoint statistics.
"""
from __future__ import annotations

from collections import Counter, defaultdict
from typing import Any

from ..state import MatchState, SimulationResult, EngineStateError, PlayerState
from ..v1.engine import FTGMatchEngineV1
from ..v2.engine import FTGMatchEngineV2, _domain_rng, _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 TacticalDecisionV22
from ..reporting.v3 import MatchReportV3
from ..v21.policy import next_transition, opponent_defence_suppression, segment_multiplier
from ..v22.engine import FTGMatchEngineV22
from ..v22.commands import LiveCommandState, COMMAND_TACTICS
from ..v22.config import EXTRA_TIME_SEGMENTS, REGULATION_SEGMENTS
from .config import (
    ANALYTICS_POLICY_KEY,
    ANALYTICS_POLICY_VERSION,
    ANALYTICS_SCHEMA_VERSION,
    ATTACK_CHANCE_BONUS,
    ATTACK_POSSESSION_BONUS,
    ATTACK_SHOT_QUALITY,
    ATTACK_WORKLOAD,
    BASE_CHANCE_PROBABILITY,
    BIG_CHANCE_XG,
    DEFENCE_BLOCK_BONUS,
    DEFENCE_CHANCE_SUPPRESSION,
    DEFENCE_WORKLOAD,
    ENGINE_KEY,
    ENGINE_VERSION,
    EXTRA_TIME_POSSESSIONS_PER_SEGMENT,
    HOME_CHANCE_BONUS,
    MAX_CHANCE_PROBABILITY,
    MAX_GOAL_PROBABILITY,
    MAX_POSSESSION_SHARE,
    MAX_XG,
    MIN_CHANCE_PROBABILITY,
    MIN_GOAL_PROBABILITY,
    MIN_POSSESSION_SHARE,
    MIN_XG,
    REGULATION_POSSESSIONS_PER_SEGMENT,
)
from .contracts import MatchV3Outcome

DOMAIN_SEGMENT = 0x6A09E667F3BCC909
DOMAIN_SHOOTOUT_REPORT = 0xBB67AE8584CAA73B


def _clamp(value: float, low: float, high: float) -> float:
    return max(low, min(high, value))


def _phase(minute: int) -> str:
    return PHASE_REGULATION if minute <= 90 else PHASE_EXTRA_TIME


def _avg(players, attr: str, default=50) -> float:
    players = list(players)
    if not players:
        return float(default)
    return sum(_rating(player, attr, default) for player in players) / len(players)


class FTGMatchEngineV3(FTGMatchEngineV22):
    key = ENGINE_KEY
    version = ENGINE_VERSION

    def simulate(
        self,
        state: MatchState,
        *,
        seed: int,
        commands: tuple[LiveCommandState, ...] | list[LiveCommandState] = (),
    ) -> MatchV3Outcome:
        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 v3 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()

        # Reuse the proven score-independent card/injury/substitution generator.
        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,
        )
        non_goal_events = self._merge_non_goal_timeline(
            state=state,
            base_events=skeleton.events,
            commands=commands,
            max_substitutions=rules.max_substitutions,
            max_substitution_windows=rules.max_substitution_windows,
        )

        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)
        }
        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[str, Any]] = []

        # Causal ledgers accumulated during field play.
        shots: list[dict[str, Any]] = []
        goal_events: list[tuple[int, str, str, str | None, dict[str, Any]]] = []
        player_metrics: dict[str, Counter] = defaultdict(Counter)
        team_metrics: dict[str, Counter] = {
            state.home.club_id: Counter(),
            state.away.club_id: Counter(),
        }
        possession_units = Counter()
        segment_statistics: list[dict[str, Any]] = []
        score = {state.home.club_id: 0, state.away.club_id: 0}

        teams = {state.home.club_id: state.home, state.away.club_id: state.away}
        opponent = {
            state.home.club_id: state.away.club_id,
            state.away.club_id: state.home.club_id,
        }

        def reds_before(club_id: str, minute: int) -> int:
            return sum(
                row.club_id == club_id
                and row.event_type in {EVENT_RED, EVENT_SECOND_YELLOW}
                and row.minute < minute
                for row in non_goal_events
            )

        def process_segment(segment_index: int, start: int, end: int, *, extra_time=False):
            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": score[state.home.club_id],
                    "away_score": score[state.away.club_id],
                    "own_reds": own_reds,
                    "opp_reds": opp_reds,
                    "command_ref": command.command_ref,
                    "context": context,
                })

            for club_id, context, own_reds, opp_reds in (
                (state.home.club_id, state.home_tactics, home_reds, away_reds),
                (state.away.club_id, state.away_tactics, away_reds, home_reds),
            ):
                if club_id in manual_clubs:
                    continue
                own_score = score[club_id]
                opp_score = score[opponent[club_id]]
                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": score[state.home.club_id],
                        "away_score": score[state.away.club_id],
                        "own_reds": own_reds,
                        "opp_reds": opp_reds,
                        "command_ref": None,
                        "context": context,
                    })

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

            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

            rng = _domain_rng(seed, DOMAIN_SEGMENT ^ (segment_index * 0x9E3779B97F4A7C15))
            home_share = self._possession_share(
                state=state,
                evaluation=evaluation,
                current=current,
                minute=start,
                home_reds=home_reds,
                away_reds=away_reds,
            )
            possessions = (
                EXTRA_TIME_POSSESSIONS_PER_SEGMENT if extra_time else REGULATION_POSSESSIONS_PER_SEGMENT
            )

            for possession_index in range(possessions):
                minute = start + int(rng.random() * (end - start + 1))
                attacking_club = (
                    state.home.club_id if rng.random() < home_share else state.away.club_id
                )
                defending_club = opponent[attacking_club]
                possession_units[attacking_club] += 1
                attack_players = self._active_players_for_team(
                    team=teams[attacking_club],
                    events=non_goal_events,
                    minute=minute,
                    club_id=attacking_club,
                )
                defend_players = self._active_players_for_team(
                    team=teams[defending_club],
                    events=non_goal_events,
                    minute=minute,
                    club_id=defending_club,
                )
                if not attack_players or not defend_players:
                    continue

                attack_context = state.home_tactics if attacking_club == state.home.club_id else state.away_tactics
                defend_context = state.home_tactics if defending_club == state.home.club_id else state.away_tactics
                attack_strategy, attack_defence_strategy = current[attacking_club]
                _, defending_strategy = current[defending_club]
                own_factor = home_factor if attacking_club == state.home.club_id else away_factor
                own_suppression = home_suppression if attacking_club == state.home.club_id else away_suppression

                # Build-up: authoritative pass attempts happen before a chance can exist.
                chain_length = 1 + int(rng.random() * 4)
                chain_complete = True
                last_passer: PlayerState | None = None
                for pass_index in range(chain_length):
                    passer = _weighted_choice(
                        rng,
                        attack_players,
                        lambda p: self._pass_weight(
                            p,
                            minute=minute,
                            attacking_strategy=attack_strategy,
                            defensive_strategy=attack_defence_strategy,
                        ),
                    )
                    last_passer = passer
                    player_metrics[passer.player_id]["passes_attempted"] += 1
                    pass_skill = self._effective_rating(
                        passer,
                        "passing",
                        minute=minute,
                        attacking_strategy=attack_strategy,
                        defensive_strategy=attack_defence_strategy,
                    )
                    vision = self._effective_rating(
                        passer,
                        "vision",
                        minute=minute,
                        attacking_strategy=attack_strategy,
                        defensive_strategy=attack_defence_strategy,
                    )
                    pressure = self._defensive_pressure(
                        defend_players,
                        minute=minute,
                        defensive_strategy=defending_strategy,
                        attacking_strategy=current[defending_club][0],
                    )
                    completion = _clamp(
                        0.64
                        + (pass_skill - 50.0) * 0.0033
                        + (vision - 50.0) * 0.0012
                        - (pressure - 50.0) * 0.0020
                        + (0.035 if attack_strategy == "POSSESSION" else 0.0)
                        - pass_index * 0.006,
                        0.48,
                        0.94,
                    )
                    if rng.random() <= completion:
                        player_metrics[passer.player_id]["passes_completed"] += 1
                        continue
                    chain_complete = False
                    defender = _weighted_choice(
                        rng,
                        defend_players,
                        lambda p: self._defender_action_weight(
                            p,
                            minute=minute,
                            defensive_strategy=defending_strategy,
                            attacking_strategy=current[defending_club][0],
                        ),
                    )
                    if rng.random() < 0.54:
                        player_metrics[defender.player_id]["interceptions"] += 1
                    else:
                        player_metrics[defender.player_id]["tackles_attempted"] += 1
                        player_metrics[defender.player_id]["tackles_won"] += 1
                    if rng.random() < self._foul_probability(defender, defending_strategy):
                        team_metrics[defending_club]["fouls"] += 1
                    break

                if not chain_complete:
                    continue

                chance_prob = self._chance_probability(
                    attacking_club=attacking_club,
                    defending_club=defending_club,
                    state=state,
                    evaluation=evaluation,
                    attack_strategy=attack_strategy,
                    defending_strategy=defending_strategy,
                    own_factor=own_factor,
                    suppression=own_suppression,
                    attack_players=attack_players,
                    defend_players=defend_players,
                    minute=minute,
                )
                if rng.random() > chance_prob:
                    if rng.random() < 0.22:
                        dribbler = _weighted_choice(
                            rng,
                            attack_players,
                            lambda p: self._dribble_weight(p, minute, attack_strategy, attack_defence_strategy),
                        )
                        player_metrics[dribbler.player_id]["dribbles_attempted"] += 1
                        if rng.random() < self._dribble_success(dribbler, minute, attack_strategy, attack_defence_strategy):
                            player_metrics[dribbler.player_id]["dribbles_completed"] += 1
                    continue

                creator = self._choose_creator(
                    rng,
                    attack_players,
                    minute=minute,
                    attacking_strategy=attack_strategy,
                    defensive_strategy=attack_defence_strategy,
                    fallback=last_passer,
                )
                shooter = self._choose_shooter(
                    rng,
                    attack_players,
                    minute=minute,
                    attacking_strategy=attack_strategy,
                    defensive_strategy=attack_defence_strategy,
                )
                if creator is not None and creator.player_id == shooter.player_id:
                    creator = None

                xg = self._shot_xg(
                    rng,
                    shooter=shooter,
                    creator=creator,
                    attack_strategy=attack_strategy,
                    defend_strategy=defending_strategy,
                    minute=minute,
                    attack_players=attack_players,
                    defend_players=defend_players,
                )
                outcome, goalkeeper = self._shot_outcome(
                    rng,
                    xg=xg,
                    shooter=shooter,
                    defenders=defend_players,
                    defend_strategy=defending_strategy,
                    attack_strategy=attack_strategy,
                    minute=minute,
                )
                shot = {
                    "minute": minute,
                    "phase": _phase(minute),
                    "club_id": attacking_club,
                    "player_id": shooter.player_id,
                    "assisted_by_player_id": creator.player_id if creator else None,
                    "xg": round(xg, 3),
                    "outcome": outcome,
                    "chance_type": self._chance_type(attack_strategy, xg),
                }
                shots.append(shot)
                player_metrics[shooter.player_id]["shots"] += 1
                player_metrics[shooter.player_id]["xg_milli"] += int(round(xg * 1000))
                if xg >= BIG_CHANCE_XG:
                    player_metrics[shooter.player_id]["big_chances"] += 1
                if outcome in {"GOAL", "SAVED"}:
                    player_metrics[shooter.player_id]["shots_on_target"] += 1
                if creator is not None:
                    player_metrics[creator.player_id]["key_passes"] += 1
                    player_metrics[creator.player_id]["xa_milli"] += int(round(xg * 1000))
                if outcome == "SAVED" and goalkeeper is not None:
                    player_metrics[goalkeeper.player_id]["saves"] += 1
                elif outcome == "BLOCKED":
                    defender = _weighted_choice(
                        rng,
                        defend_players,
                        lambda p: self._defender_action_weight(
                            p,
                            minute=minute,
                            defensive_strategy=defending_strategy,
                            attacking_strategy=current[defending_club][0],
                        ),
                    )
                    player_metrics[defender.player_id]["blocks"] += 1
                    if rng.random() < 0.38:
                        team_metrics[attacking_club]["corners"] += 1
                elif outcome == "GOAL":
                    score[attacking_club] += 1
                    player_metrics[shooter.player_id]["goals"] += 1
                    if creator is not None:
                        player_metrics[creator.player_id]["assists"] += 1
                    goal_events.append((
                        minute,
                        attacking_club,
                        shooter.player_id,
                        creator.player_id if creator else None,
                        {
                            "xg": round(xg, 3),
                            "assist_player_id": creator.player_id if creator else None,
                            "chance_type": shot["chance_type"],
                        },
                    ))

                # Fouls arise from active defensive pressure, not from the score.
                if rng.random() < 0.045 + (0.025 if defending_strategy == "HIGH_PRESS" else 0.0):
                    defender = _weighted_choice(
                        rng,
                        defend_players,
                        lambda p: self._defender_action_weight(
                            p,
                            minute=minute,
                            defensive_strategy=defending_strategy,
                            attacking_strategy=current[defending_club][0],
                        ),
                    )
                    team_metrics[defending_club]["fouls"] += 1

            self._append_segment_statistics(
                segment_statistics=segment_statistics,
                segment=segment_index,
                start=start,
                end=end,
                state=state,
                score=score,
                shots=shots,
                possession_units=possession_units,
                player_metrics=player_metrics,
                team_metrics=team_metrics,
            )

        for index, (start, end) in enumerate(REGULATION_SEGMENTS, start=1):
            process_segment(index, start, end)
        regulation_home = score[state.home.club_id]
        regulation_away = score[state.away.club_id]

        decision_stage = RESOLUTION_REGULATION
        if rules.requires_winner and regulation_home == regulation_away:
            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.")

        final_home = score[state.home.club_id]
        final_away = score[state.away.club_id]
        extra_home = final_home - regulation_home
        extra_away = final_away - regulation_away
        penalties = None
        if rules.requires_winner and final_home == final_away:
            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=final_home, away_score=final_away)

        events, team_rows, player_rows = self._build_report_rows(
            state=state,
            seed=seed,
            non_goal_events=non_goal_events,
            goal_events=goal_events,
            result=result,
            resolution=resolution,
            player_metrics=player_metrics,
        )
        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["command_ref"],
                effect=tuple(sorted((row.get("effect") or {}).items())),
            )
            for index, row in enumerate(decisions)
        )

        advanced = self._build_advanced_analytics(
            state=state,
            events=events,
            team_rows=team_rows,
            player_rows=player_rows,
            shots=shots,
            possession_units=possession_units,
            player_metrics=player_metrics,
            team_metrics=team_metrics,
            segment_statistics=segment_statistics,
            result=result,
            match_minutes=120 if decision_stage in {RESOLUTION_EXTRA_TIME, RESOLUTION_PENALTIES} else 90,
            current=current,
        )
        report = MatchReportV3(
            events=events,
            team_statistics=team_rows,
            player_statistics=player_rows,
            tactical_decisions=tactical_rows,
            advanced_analytics=advanced,
        )
        return MatchV3Outcome(result=result, resolution=resolution, report=report)

    # ------------------------------------------------------------------
    # Causal football primitives
    # ------------------------------------------------------------------
    def _possession_share(self, *, state, evaluation, current, minute, home_reds, away_reds):
        diff = evaluation.home.midfield - evaluation.away.midfield
        share = 0.50 + diff * 0.0030
        share += ATTACK_POSSESSION_BONUS[current[state.home.club_id][0]]
        share -= ATTACK_POSSESSION_BONUS[current[state.away.club_id][0]]
        share -= home_reds * 0.055
        share += away_reds * 0.055
        # Home side gets a small territorial rather than direct-goal advantage.
        share += 0.012
        return _clamp(share, MIN_POSSESSION_SHARE, MAX_POSSESSION_SHARE)

    @staticmethod
    def _player_map(team):
        return {p.player_id: p for p in (*team.starters, *team.substitutes)}

    def _active_players_for_team(self, *, team, events, minute, club_id):
        active = {p.player_id: p for p in team.starters}
        bench = {p.player_id: p for p in team.substitutes}
        for event in sorted(events, key=lambda row: (row.minute, row.sequence)):
            if event.club_id != club_id or event.minute > minute:
                continue
            if event.event_type == EVENT_SUBSTITUTION:
                active.pop(event.player_id, None)
                incoming = bench.pop(event.secondary_player_id, None)
                if incoming is not None:
                    active[incoming.player_id] = incoming
            elif event.event_type in {EVENT_RED, EVENT_SECOND_YELLOW}:
                active.pop(event.player_id, None)
            elif event.event_type == EVENT_INJURY and event.detail_payload.get("match_availability") == "UNAVAILABLE":
                active.pop(event.player_id, None)
        return list(active.values())

    def _fatigue_load(self, player: PlayerState, minute: int, attacking_strategy: str, defensive_strategy: str) -> float:
        stamina = _rating(player, "stamina")
        natural = _rating(player, "natural_fitness")
        base = float(getattr(player, "fatigue_index", 0))
        minute_load = minute * (0.48 + max(0.0, 75 - stamina) * 0.006)
        fitness_relief = max(0.0, natural - 50) * 0.08
        workload = minute * (
            ATTACK_WORKLOAD.get(attacking_strategy, 0.0)
            + DEFENCE_WORKLOAD.get(defensive_strategy, 0.0)
        )
        return _clamp(base + minute_load + workload - fitness_relief, 0.0, 100.0)

    def _effective_rating(self, player, attr, *, minute, attacking_strategy, defensive_strategy):
        raw = float(_rating(player, attr))
        fatigue = self._fatigue_load(player, minute, attacking_strategy, defensive_strategy)
        # Fatigue can reduce execution by up to ~22%, but never erase quality.
        return raw * (1.0 - fatigue * 0.0022)

    def _pass_weight(self, player, *, minute, attacking_strategy, defensive_strategy):
        return (
            0.38 * self._effective_rating(player, "passing", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
            + 0.25 * self._effective_rating(player, "vision", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
            + 0.22 * self._effective_rating(player, "decision_making", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
            + 0.15 * self._effective_rating(player, "teamwork", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
        )

    def _defender_action_weight(self, player, *, minute, defensive_strategy, attacking_strategy):
        return (
            0.35 * self._effective_rating(player, "tackling", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
            + 0.30 * self._effective_rating(player, "positioning", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
            + 0.20 * self._effective_rating(player, "anticipation", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
            + 0.15 * self._effective_rating(player, "marking", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
        )

    def _defensive_pressure(self, players, *, minute, defensive_strategy, attacking_strategy):
        base = sum(
            self._defender_action_weight(
                p,
                minute=minute,
                defensive_strategy=defensive_strategy,
                attacking_strategy=attacking_strategy,
            )
            for p in players
        ) / max(1, len(players))
        tactical = {
            "BALANCED": 0.0,
            "HIGH_PRESS": 7.0,
            "MID_BLOCK": 3.0,
            "LOW_BLOCK": -1.0,
            "MAN_MARKING": 4.0,
            "ZONAL_COMPACT": 3.5,
        }.get(defensive_strategy, 0.0)
        return base + tactical

    def _foul_probability(self, defender, defensive_strategy):
        aggression = _rating(defender, "aggression")
        tackling = _rating(defender, "tackling")
        press = 0.025 if defensive_strategy == "HIGH_PRESS" else 0.0
        return _clamp(0.025 + max(0, aggression - tackling) * 0.002 + press, 0.02, 0.16)

    def _dribble_weight(self, player, minute, attack_strategy, defence_strategy):
        return (
            0.46 * self._effective_rating(player, "dribbling", minute=minute, attacking_strategy=attack_strategy, defensive_strategy=defence_strategy)
            + 0.28 * self._effective_rating(player, "agility", minute=minute, attacking_strategy=attack_strategy, defensive_strategy=defence_strategy)
            + 0.26 * self._effective_rating(player, "ball_control", minute=minute, attacking_strategy=attack_strategy, defensive_strategy=defence_strategy)
        )

    def _dribble_success(self, player, minute, attack_strategy, defence_strategy):
        skill = self._dribble_weight(player, minute, attack_strategy, defence_strategy)
        return _clamp(0.42 + (skill - 50) * 0.004, 0.30, 0.76)

    def _chance_probability(
        self, *, attacking_club, defending_club, state, evaluation,
        attack_strategy, defending_strategy, own_factor, suppression,
        attack_players, defend_players, minute,
    ):
        if attacking_club == state.home.club_id:
            attack = evaluation.home.attack
            defence = evaluation.away.defence
            home_bonus = HOME_CHANCE_BONUS
        else:
            attack = evaluation.away.attack
            defence = evaluation.home.defence
            home_bonus = 0.0
        attack_execution = _avg(attack_players, "decision_making") + _avg(attack_players, "off_ball")
        defence_execution = _avg(defend_players, "positioning") + _avg(defend_players, "concentration")
        chance = BASE_CHANCE_PROBABILITY + home_bonus
        chance += (attack - defence) * 0.0016
        chance += (attack_execution - defence_execution) * 0.00045
        chance += ATTACK_CHANCE_BONUS.get(attack_strategy, 0.0)
        chance -= DEFENCE_CHANCE_SUPPRESSION.get(defending_strategy, 0.0)
        chance *= float(own_factor.get("xg_factor", 1.0))
        chance *= float(own_factor.get("lineup_factor", 1.0))
        chance /= max(0.70, float(suppression))
        return _clamp(chance, MIN_CHANCE_PROBABILITY, MAX_CHANCE_PROBABILITY)

    def _choose_creator(self, rng, players, *, minute, attacking_strategy, defensive_strategy, fallback=None):
        candidates = [p for p in players if p.natural_position != "GK"]
        if not candidates:
            return fallback
        if rng.random() < 0.16:
            return None
        return _weighted_choice(
            rng,
            candidates,
            lambda p: (
                0.38 * self._effective_rating(p, "vision", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
                + 0.32 * self._effective_rating(p, "passing", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
                + 0.16 * self._effective_rating(p, "crossing", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
                + 0.14 * self._effective_rating(p, "dribbling", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
            ),
        )

    def _choose_shooter(self, rng, players, *, minute, attacking_strategy, defensive_strategy):
        candidates = [p for p in players if p.natural_position != "GK"] or list(players)
        positional = {
            "ST": 1.65, "CF": 1.55, "LW": 1.30, "RW": 1.30,
            "CAM": 1.18, "LM": 1.05, "RM": 1.05, "CM": 0.88,
            "CDM": 0.55, "LB": 0.48, "RB": 0.48, "CB": 0.34, "GK": 0.02,
        }
        return _weighted_choice(
            rng,
            candidates,
            lambda p: positional.get(p.natural_position, 0.8) * (
                0.40 * self._effective_rating(p, "finishing", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
                + 0.24 * self._effective_rating(p, "positioning", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
                + 0.20 * self._effective_rating(p, "off_ball", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
                + 0.16 * self._effective_rating(p, "composure", minute=minute, attacking_strategy=attacking_strategy, defensive_strategy=defensive_strategy)
            ),
        )

    def _shot_xg(self, rng, *, shooter, creator, attack_strategy, defend_strategy, minute, attack_players, defend_players):
        finishing = self._effective_rating(shooter, "finishing", minute=minute, attacking_strategy=attack_strategy, defensive_strategy="BALANCED")
        positioning = self._effective_rating(shooter, "positioning", minute=minute, attacking_strategy=attack_strategy, defensive_strategy="BALANCED")
        creation = 50.0
        if creator is not None:
            creation = (
                self._effective_rating(creator, "vision", minute=minute, attacking_strategy=attack_strategy, defensive_strategy="BALANCED")
                + self._effective_rating(creator, "passing", minute=minute, attacking_strategy=attack_strategy, defensive_strategy="BALANCED")
            ) / 2.0
        defensive_shape = (_avg(defend_players, "positioning") + _avg(defend_players, "marking")) / 2.0
        quality = 0.04 + (positioning - 50) * 0.0011 + (creation - 50) * 0.0008
        quality -= (defensive_shape - 50) * 0.0007
        quality += ATTACK_SHOT_QUALITY.get(attack_strategy, 0.0)
        # A bounded beta-like roll without depending on Python random implementation.
        roll = (rng.random() + rng.random() + rng.random()) / 3.0
        xg = quality + roll * 0.18 + (finishing - 50) * 0.00035
        if attack_strategy == "COUNTER_ATTACK" and rng.random() < 0.24:
            xg += 0.0505
        if attack_strategy == "WIDE_PLAY" and _rating(shooter, "heading") >= 65 and rng.random() < 0.20:
            xg += 0.050
        return _clamp(xg, MIN_XG, MAX_XG)

    def _shot_outcome(self, rng, *, xg, shooter, defenders, defend_strategy, attack_strategy, minute):
        goalkeeper = next((p for p in defenders if p.natural_position == "GK"), None)
        outfield = [p for p in defenders if p.natural_position != "GK"]
        gk_skill = 50.0
        if goalkeeper is not None:
            gk_skill = (
                self._effective_rating(goalkeeper, "gk_reflexes", minute=minute, attacking_strategy="BALANCED", defensive_strategy=defend_strategy)
                + self._effective_rating(goalkeeper, "gk_positioning", minute=minute, attacking_strategy="BALANCED", defensive_strategy=defend_strategy)
                + self._effective_rating(goalkeeper, "gk_one_on_one", minute=minute, attacking_strategy="BALANCED", defensive_strategy=defend_strategy)
            ) / 3.0
        finisher = (
            self._effective_rating(shooter, "finishing", minute=minute, attacking_strategy=attack_strategy, defensive_strategy="BALANCED")
            + self._effective_rating(shooter, "composure", minute=minute, attacking_strategy=attack_strategy, defensive_strategy="BALANCED")
        ) / 2.0
        # xG is the pre-shot chance quality. Finisher/GK quality changes actual
        # conversion around that baseline; goal is resolved before classifying misses.
        goal_prob = xg * (1.0 + (finisher - 50) * 0.0045 - (gk_skill - 50) * 0.0038)
        goal_prob = _clamp(goal_prob, MIN_GOAL_PROBABILITY, MAX_GOAL_PROBABILITY)
        if rng.random() < goal_prob:
            return "GOAL", goalkeeper

        defensive_block = (_avg(outfield, "positioning") + _avg(outfield, "marking")) / 2.0
        block_prob = _clamp(
            0.14 + (defensive_block - 50) * 0.0018 + DEFENCE_BLOCK_BONUS.get(defend_strategy, 0.0) - xg * 0.08,
            0.08,
            0.36,
        )
        shooting = self._effective_rating(shooter, "shooting", minute=minute, attacking_strategy=attack_strategy, defensive_strategy="BALANCED")
        composure = self._effective_rating(shooter, "composure", minute=minute, attacking_strategy=attack_strategy, defensive_strategy="BALANCED")
        saved_prob = _clamp(0.28 + (shooting - 50) * 0.002 + (composure - 50) * 0.001 + (gk_skill - 50) * 0.002, 0.18, 0.52)
        roll = rng.random()
        if roll < block_prob:
            return "BLOCKED", goalkeeper
        if roll < block_prob + saved_prob:
            return "SAVED", goalkeeper
        return "OFF_TARGET", goalkeeper

    @staticmethod
    def _chance_type(attack_strategy: str, xg: float) -> str:
        if xg >= 0.45:
            return "BIG_CHANCE"
        if attack_strategy == "COUNTER_ATTACK":
            return "TRANSITION"
        if attack_strategy == "WIDE_PLAY":
            return "WIDE_CREATION"
        if attack_strategy == "DIRECT":
            return "DIRECT_ATTACK"
        if attack_strategy == "POSSESSION":
            return "PATIENT_BUILDUP"
        return "OPEN_PLAY"

    # ------------------------------------------------------------------
    # Report / statistics construction
    # ------------------------------------------------------------------
    def _build_report_rows(self, *, state, seed, non_goal_events, goal_events, result, resolution, player_metrics):
        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
        raw = []
        for row in non_goal_events:
            if row.minute <= match_minutes:
                raw.append((
                    row.minute, row.event_type, row.club_id, row.player_id,
                    row.secondary_player_id, row.detail_payload,
                ))
        for minute, club, scorer, assister, detail in goal_events:
            if minute <= match_minutes:
                payload = dict(detail)
                if assister:
                    payload["assist_player_id"] = assister
                raw.append((minute, EVENT_GOAL, club, scorer, None, payload))

        if resolution.decision_stage == RESOLUTION_PENALTIES:
            raw.extend(self._shootout_report_events(state=state, seed=seed, resolution=resolution, non_goal_events=non_goal_events))

        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(minute)
        raw.sort(key=lambda row: (phase_order[event_phase(row[1], row[0])], row[0], 0 if row[1] != EVENT_GOAL else 1, row[2], row[3]))
        report_events = tuple(
            ReportEventV2(
                sequence=index + 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 or {}).items())),
            )
            for index, (minute, kind, club, pid, secondary, detail) in enumerate(raw)
        )

        entry_minute = {p.player_id: 0 for team in teams.values() for p in team.starters}
        exit_minute: dict[str, int] = {}
        started = set(entry_minute)
        subbed_in = set(); subbed_out = set(); injured = set()
        yellow = Counter(); red = Counter(); goals = Counter(); team_subs = Counter()
        active = {club: {p.player_id for p in team.starters} for club, team in teams.items()}
        for event in report_events:
            if event.phase == PHASE_SHOOTOUT:
                continue
            club = event.club_id
            pid = event.player_id
            if event.event_type == EVENT_SUBSTITUTION:
                active[club].discard(pid)
                if event.secondary_player_id:
                    active[club].add(event.secondary_player_id)
                    entry_minute[event.secondary_player_id] = event.minute
                    subbed_in.add(event.secondary_player_id)
                exit_minute.setdefault(pid, event.minute)
                subbed_out.add(pid)
                team_subs[club] += 1
            elif event.event_type == EVENT_YELLOW:
                yellow[pid] += 1
            elif event.event_type == EVENT_SECOND_YELLOW:
                yellow[pid] += 1; red[pid] = 1
                active[club].discard(pid); exit_minute.setdefault(pid, event.minute)
            elif event.event_type == EVENT_RED:
                red[pid] = 1
                active[club].discard(pid); exit_minute.setdefault(pid, event.minute)
            elif event.event_type == EVENT_INJURY:
                injured.add(pid)
                if event.detail_payload.get("match_availability") == "UNAVAILABLE":
                    active[club].discard(pid); exit_minute.setdefault(pid, event.minute)
            elif event.event_type == EVENT_GOAL:
                goals[pid] += 1

        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 = self._player_map(team)
            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=goals[pid],
                    clean_sheet=(result.away_score == 0 if club == state.home.club_id else result.home_score == 0),
                    yellow_cards=yellow[pid],
                    red_cards=red[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[p.player_id] for p in (*state.home.starters, *state.home.substitutes)),
                red_cards=sum(red[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[p.player_id] for p in (*state.away.starters, *state.away.substitutes)),
                red_cards=sum(red[p.player_id] for p in (*state.away.starters, *state.away.substitutes)),
                substitutions=team_subs[state.away.club_id],
            ),
        )
        return report_events, team_rows, tuple(player_rows)

    def _shootout_report_events(self, *, state, seed, resolution, non_goal_events):
        rng = _domain_rng(seed, DOMAIN_SHOOTOUT_REPORT)
        teams = {state.home.club_id: state.home, state.away.club_id: state.away}
        target = {
            state.home.club_id: int(resolution.home_penalties or 0),
            state.away.club_id: int(resolution.away_penalties or 0),
        }
        kickers = {}
        for club, team in teams.items():
            active = self._active_players_for_team(team=team, events=non_goal_events, minute=120, club_id=club)
            eligible = active or list(team.starters)
            kickers[club] = sorted(
                eligible,
                key=lambda p: (_rating(p, "composure") + _rating(p, "finishing") + _rating(p, "set_pieces")),
                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)
            for idx in range(len(pattern) - 1, 0, -1):
                swap = int(rng.random() * (idx + 1))
                pattern[idx], pattern[swap] = pattern[swap], pattern[idx]
            patterns[club] = pattern
        rows = []
        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])]
                rows.append((
                    120,
                    EVENT_PENALTY_SCORED if scored else EVENT_PENALTY_MISSED,
                    club,
                    taker.player_id,
                    None,
                    {"kick_number": index + 1},
                ))
        return rows

    def _append_segment_statistics(self, *, segment_statistics, segment, start, end, state, score, shots, possession_units, player_metrics, team_metrics):
        total_possessions = max(1, possession_units[state.home.club_id] + possession_units[state.away.club_id])
        row = {
            "segment": segment,
            "start_minute": start,
            "end_minute": end,
            "home": self._live_team_snapshot(
                club_id=state.home.club_id,
                opponent_id=state.away.club_id,
                player_ids=set(self._player_map(state.home)),
                score=score,
                shots=shots,
                possession_units=possession_units,
                total_possessions=total_possessions,
                player_metrics=player_metrics,
                team_metrics=team_metrics,
            ),
            "away": self._live_team_snapshot(
                club_id=state.away.club_id,
                opponent_id=state.home.club_id,
                player_ids=set(self._player_map(state.away)),
                score=score,
                shots=shots,
                possession_units=possession_units,
                total_possessions=total_possessions,
                player_metrics=player_metrics,
                team_metrics=team_metrics,
            ),
        }
        segment_statistics.append(row)

    @staticmethod
    def _live_team_snapshot(*, club_id, opponent_id, player_ids, score, shots, possession_units, total_possessions, player_metrics, team_metrics):
        club_shots = [row for row in shots if row["club_id"] == club_id]
        passes_attempted = sum(
            values["passes_attempted"] for pid, values in player_metrics.items() if pid in player_ids
        )
        passes_completed = sum(
            values["passes_completed"] for pid, values in player_metrics.items() if pid in player_ids
        )
        return {
            "score": score[club_id],
            "shots": len(club_shots),
            "shots_on_target": sum(row["outcome"] in {"GOAL", "SAVED"} for row in club_shots),
            "xg": round(sum(float(row["xg"]) for row in club_shots), 3),
            "possession_pct": round(100.0 * possession_units[club_id] / total_possessions, 1),
            "passes_attempted": passes_attempted,
            "passes_completed": passes_completed,
            "corners": team_metrics[club_id]["corners"],
            "fouls": team_metrics[club_id]["fouls"],
        }

    def _build_advanced_analytics(
        self, *, state, events, team_rows, player_rows, shots, possession_units,
        player_metrics, team_metrics, segment_statistics, result, match_minutes, current,
    ):
        club_players = {
            state.home.club_id: self._player_map(state.home),
            state.away.club_id: self._player_map(state.away),
        }
        # Match report is authoritative for cards/substitution/injury/minutes.
        basic_by_player = {row.player_id: row for row in player_rows}
        goal_shot_by_player = Counter(row["player_id"] for row in shots if row["outcome"] == "GOAL")
        assist_by_player = Counter(
            row["assisted_by_player_id"] for row in shots
            if row["outcome"] == "GOAL" and row["assisted_by_player_id"]
        )
        total_possessions = max(1, possession_units[state.home.club_id] + possession_units[state.away.club_id])

        advanced_players = []
        for club_id, players in club_players.items():
            for pid, player in players.items():
                basic = basic_by_player.get(pid)
                if basic is None:
                    continue
                metrics = player_metrics[pid]
                shots_for_player = [row for row in shots if row["player_id"] == pid]
                xg = round(sum(float(row["xg"]) for row in shots_for_player), 3)
                xa = round(metrics["xa_milli"] / 1000.0, 3)
                rating = self._performance_rating(
                    basic=basic,
                    metrics=metrics,
                    xg=xg,
                    xa=xa,
                    goals=goal_shot_by_player[pid],
                    assists=assist_by_player[pid],
                )
                attack_strategy, defence_strategy = current[club_id]
                end_condition = round(100.0 - self._fatigue_load(player, min(match_minutes, max(1, basic.minutes_played)), attack_strategy, defence_strategy), 1)
                advanced_players.append({
                    "player_id": pid,
                    "club_id": club_id,
                    "started": basic.started,
                    "minutes_played": basic.minutes_played,
                    "goals": int(goal_shot_by_player[pid]),
                    "assists": int(assist_by_player[pid]),
                    "clean_sheet": basic.clean_sheet,
                    "yellow_cards": basic.yellow_cards,
                    "red_cards": basic.red_cards,
                    "substituted_in": basic.substituted_in,
                    "substituted_out": basic.substituted_out,
                    "injured": basic.injured,
                    "xg": xg,
                    "xa": xa,
                    "shots": metrics["shots"],
                    "shots_on_target": metrics["shots_on_target"],
                    "big_chances": metrics["big_chances"],
                    "passes_attempted": metrics["passes_attempted"],
                    "passes_completed": metrics["passes_completed"],
                    "key_passes": metrics["key_passes"],
                    "tackles_attempted": metrics["tackles_attempted"],
                    "tackles_won": metrics["tackles_won"],
                    "interceptions": metrics["interceptions"],
                    "saves": metrics["saves"],
                    "dribbles_attempted": metrics["dribbles_attempted"],
                    "dribbles_completed": metrics["dribbles_completed"],
                    "rating": rating,
                    "is_man_of_the_match": False,
                    "condition_end_pct": max(0.0, end_condition),
                })

        if not advanced_players:
            raise EngineStateError("Causal analytics produced no player rows.")
        motm = sorted(
            advanced_players,
            key=lambda row: (-float(row["rating"]), -row["goals"], -row["assists"], -float(row["xg"]), row["player_id"]),
        )[0]
        for row in advanced_players:
            row["is_man_of_the_match"] = row["player_id"] == motm["player_id"]

        team_basic = {row.club_id: row for row in team_rows}
        advanced_teams = []
        for club_id, team in ((state.home.club_id, state.home), (state.away.club_id, state.away)):
            rows = [row for row in advanced_players if row["club_id"] == club_id]
            club_shots = [row for row in shots if row["club_id"] == club_id]
            passes_attempted = sum(row["passes_attempted"] for row in rows)
            passes_completed = sum(row["passes_completed"] for row in rows)
            tackles_attempted = sum(row["tackles_attempted"] for row in rows)
            tackles_won = sum(row["tackles_won"] for row in rows)
            base = team_basic[club_id]
            advanced_teams.append({
                "club_id": club_id,
                "goals_for": base.goals_for,
                "goals_against": base.goals_against,
                "yellow_cards": base.yellow_cards,
                "red_cards": base.red_cards,
                "substitutions": base.substitutions,
                "possession_pct": round(100.0 * possession_units[club_id] / total_possessions, 1),
                "xg": round(sum(float(row["xg"]) for row in club_shots), 3),
                "shots": len(club_shots),
                "shots_on_target": sum(row["outcome"] in {"GOAL", "SAVED"} for row in club_shots),
                "big_chances": sum(float(row["xg"]) >= BIG_CHANCE_XG for row in club_shots),
                "passes_attempted": passes_attempted,
                "passes_completed": passes_completed,
                "pass_accuracy_pct": round(100.0 * passes_completed / max(1, passes_attempted), 1),
                "tackles_attempted": tackles_attempted,
                "tackles_won": tackles_won,
                "interceptions": sum(row["interceptions"] for row in rows),
                "saves": sum(row["saves"] for row in rows),
                "corners": team_metrics[club_id]["corners"],
                "fouls": max(team_metrics[club_id]["fouls"], base.yellow_cards + base.red_cards),
            })

        shot_payload = []
        for index, row in enumerate(sorted(shots, key=lambda item: (item["minute"], item["club_id"], item["player_id"])), start=1):
            shot_payload.append({"sequence": index, **row})
        return {
            "schema_version": ANALYTICS_SCHEMA_VERSION,
            "policy_key": ANALYTICS_POLICY_KEY,
            "policy_version": ANALYTICS_POLICY_VERSION,
            "causal": True,
            "team_statistics": advanced_teams,
            "player_statistics": advanced_players,
            "shots": shot_payload,
            "segment_statistics": segment_statistics,
            "man_of_the_match": {
                "player_id": motm["player_id"],
                "club_id": motm["club_id"],
                "rating": motm["rating"],
            },
        }

    @staticmethod
    def _performance_rating(*, basic, metrics, xg, xa, goals, assists):
        rating = 6.0
        rating += goals * 1.05 + assists * 0.72
        rating += metrics["key_passes"] * 0.08 + metrics["tackles_won"] * 0.045 + metrics["interceptions"] * 0.05
        rating += metrics["saves"] * 0.11 + metrics["dribbles_completed"] * 0.035
        pass_accuracy = metrics["passes_completed"] / max(1, metrics["passes_attempted"])
        if metrics["passes_attempted"] >= 10:
            rating += (pass_accuracy - 0.76) * 1.25
        rating -= basic.yellow_cards * 0.18 + basic.red_cards * 1.10
        missed_big = max(0, metrics["big_chances"] - goals)
        rating -= missed_big * 0.12
        # Reward productive expected contribution without overpowering real goals.
        rating += min(0.35, max(0.0, xa * 0.18 + xg * 0.08))
        if basic.clean_sheet and metrics["saves"]:
            rating += 0.25
        if basic.minutes_played < 30:
            rating = 6.0 + (rating - 6.0) * max(0.25, basic.minutes_played / 30.0)
        return round(_clamp(rating, 3.0, 10.0), 2)
