"""Django/application boundary for pure match simulation.

The pure engine contracts live in ``matches.engine`` and never import Django.
This module owns ORM snapshot creation, integrity verification and exactly-once
persistence of a concrete engine result.
"""

from __future__ import annotations

import secrets

from django.db import transaction
from django.utils import timezone

from leagues.models import LeagueCompetition
from players.models import PLAYER_RATING_FIELDS, Player, Position

from .constants import FORMATION_SLOTS, LineupEntryRole, LineupStatus, MatchExecutionMode, MatchResultType, MatchStatus
from .competition_support import lock_competition_source_and_match
from .engine.state import MatchRules, MatchState, PlayerState, SimulationResult, TeamState, TeamTacticalContext
from .engine.environment import MatchEnvironmentState
from .engine.medical import MedicalRules, TeamMedicalContext
from .engine.officiating import OfficiatingRules
from .engine.setpieces import TeamSetPiecePlan
from .engine.roles import BASE_POSITION_FAMILIARITY, familiarity_from_map, resolve_tactical_role
from .engine.reporting.contracts import GOAL_EVENT, MatchReport
from .engine.serialization import payload_sha256
from .report_integrity import normalize_report_payload_for_jsonb
from .exceptions import (
    MatchNotFoundError,
    MatchNotSimulatableError,
    SimulationAlreadyResolvedError,
    SimulationEngineContractError,
    SimulationExecutionError,
    SimulationReportContractError,
    SimulationReportGenerationError,
    SimulationSnapshotIntegrityError,
    SimulationSnapshotNotFoundError,
)
from .models import (
    Match,
    MatchLineup,
    MatchLineupEntry,
    MatchEvent,
    MatchSimulationReport,
    MatchSimulationRun,
    MatchSimulationSnapshot,
    MatchSportingResolution,
    MatchEnvironmentEvidence,
    MatchMedicalEvidence,
    MatchDefensiveEvent,
    MatchPossessionEvent,
    MatchPressingEvent,
    MatchOffBallEvent,
    MatchGoalkeeperDistributionEvent,
)


SIMULATION_SCHEMA_VERSION = 8


def _schedule_advanced_analytics_projection(*, match_id):
    """Project analytics after the authoritative match transaction commits.

    Analytics is a derived projection: failure must never roll back a sporting
    result. Django's robust on_commit callback logs failures while the
    management backfill command can safely retry the idempotent projection.
    """
    def project():
        from game_statistics.services import AdvancedMatchAnalyticsService
        AdvancedMatchAnalyticsService.project(match_id=match_id)

    transaction.on_commit(project, robust=True)


def _finalize_discipline_if_ready(*, match_id):
    match = Match.objects.select_related("fixture__federation_competition").get(pk=match_id)
    if match.fixture.federation_competition_id:
        from match_officials_governance.services import OfficialMatchReportService
        if OfficialMatchReportService.should_defer_discipline(match=match):
            return None
    from .discipline import CompetitionDisciplineService
    return CompetitionDisciplineService.finalize_match(match_id=match_id)


# Potential is development ceiling rather than current match capability.  Keep
# current ratings in the kickoff snapshot without silently feeding potential to
# future match algorithms.
MATCH_STATE_RATING_FIELDS = tuple(
    field_name for field_name in PLAYER_RATING_FIELDS if field_name != "potential"
)


class MatchSimulationSnapshotService:
    @staticmethod
    def create_for_match_start(*, match: Match, lineups: list[MatchLineup]):
        """Capture immutable kickoff input inside MatchLifecycleService.start().

        Caller holds Competition/Match/Lineup/Player/Roster locks.  Snapshot
        creation is therefore part of the same transaction as locking lineups
        and moving the Match to IN_PROGRESS.
        """

        if match.status != MatchStatus.SCHEDULED:
            raise MatchNotSimulatableError(
                "A simulation snapshot can only be created for a SCHEDULED match."
            )
        if len(lineups) != 2 or any(
            lineup.status != LineupStatus.LOCKED for lineup in lineups
        ):
            raise SimulationSnapshotIntegrityError(
                "Both match lineups must be LOCKED before snapshot creation."
            )
        if MatchSimulationSnapshot.objects.filter(match=match).exists():
            raise SimulationSnapshotIntegrityError(
                "A simulation snapshot already exists before match start."
            )

        from .tactics import MatchTacticalContextService
        from players.dynamics_services import PlayerMatchReadinessSnapshotService
        tactical_contexts = MatchTacticalContextService.snapshot_pair(
            match=match, lineups=lineups
        )
        readiness_snapshots = PlayerMatchReadinessSnapshotService.snapshot_pair(
            match=match, lineups=lineups
        )
        from .environment import MatchEnvironmentResolver
        from .medical import MatchMedicalResolver
        resolved_environment = MatchEnvironmentResolver.resolve(match=match)
        resolved_medical = MatchMedicalResolver.resolve(match=match)
        state = MatchSimulationSnapshotService._build_state(
            match=match,
            lineups=lineups,
            tactical_contexts=tactical_contexts,
            readiness_snapshots=readiness_snapshots,
            environment=resolved_environment.state,
            medical_rules=resolved_medical.rules,
            home_medical=resolved_medical.home,
            away_medical=resolved_medical.away,
        )
        seed = secrets.randbelow((2**63) - 1) + 1
        state_payload = state.to_payload()
        state_hash = _snapshot_hash(
            schema_version=SIMULATION_SCHEMA_VERSION,
            seed=seed,
            state_payload=state_payload,
        )

        snapshot = MatchSimulationSnapshot.objects.create(
            match=match,
            schema_version=SIMULATION_SCHEMA_VERSION,
            seed=seed,
            state_payload=state_payload,
            state_hash=state_hash,
        )
        environment_payload = resolved_environment.state.to_payload()
        evidence_payload = {
            "match_id": str(match.pk),
            "snapshot_id": str(snapshot.pk),
            "venue_source": resolved_environment.venue_source,
            "venue_reference": resolved_environment.venue_reference,
            "climate_source": resolved_environment.climate_source,
            "environment": environment_payload,
            "effects": resolved_environment.effects_payload,
        }
        MatchEnvironmentEvidence.objects.create(
            match=match,
            snapshot=snapshot,
            venue_source=resolved_environment.venue_source,
            venue_reference=resolved_environment.venue_reference,
            climate_source=resolved_environment.climate_source,
            environment_payload=environment_payload,
            effects_payload=resolved_environment.effects_payload,
            evidence_hash=payload_sha256(evidence_payload),
        )
        medical_evidence_payload = {
            "match_id": str(match.pk),
            "snapshot_id": str(snapshot.pk),
            "rules": resolved_medical.rules.to_payload(),
            "home": resolved_medical.home.to_payload(),
            "away": resolved_medical.away.to_payload(),
        }
        MatchMedicalEvidence.objects.create(
            match=match,
            snapshot=snapshot,
            rules_payload=resolved_medical.rules.to_payload(),
            home_medical_payload=resolved_medical.home.to_payload(),
            away_medical_payload=resolved_medical.away.to_payload(),
            evidence_hash=payload_sha256(medical_evidence_payload),
        )
        return snapshot

    @staticmethod
    def _build_state(*, match: Match, lineups: list[MatchLineup], tactical_contexts=None, readiness_snapshots=None, environment=None, medical_rules=None, home_medical=None, away_medical=None) -> MatchState:
        by_club_id = {str(lineup.club_id): lineup for lineup in lineups}
        home_lineup = by_club_id.get(str(match.fixture.home_club_id))
        away_lineup = by_club_id.get(str(match.fixture.away_club_id))
        if home_lineup is None or away_lineup is None:
            raise SimulationSnapshotIntegrityError(
                "Locked lineups do not match the fixture clubs."
            )

        return MatchState(
            schema_version=SIMULATION_SCHEMA_VERSION,
            match_id=str(match.pk),
            fixture_id=str(match.fixture_id),
            competition_id=str(match.fixture.competition_source_id),
            season_id=str(match.fixture.season.id),
            home=MatchSimulationSnapshotService._build_team(home_lineup, readiness_snapshots=readiness_snapshots),
            away=MatchSimulationSnapshotService._build_team(away_lineup, readiness_snapshots=readiness_snapshots),
            rules=MatchSimulationSnapshotService._build_rules(match=match),
            home_tactics=(tactical_contexts or {}).get(str(home_lineup.club_id), (None, TeamTacticalContext()))[1],
            away_tactics=(tactical_contexts or {}).get(str(away_lineup.club_id), (None, TeamTacticalContext()))[1],
            environment=environment or MatchEnvironmentState(),
            home_medical=home_medical or TeamMedicalContext(),
            away_medical=away_medical or TeamMedicalContext(),
        )

    @staticmethod
    def _build_rules(*, match: Match) -> MatchRules:
        requires_winner = False
        if match.fixture.federation_competition_id:
            # Knockout fixtures own a FederationCompetitionTie. Group-stage
            # fixtures intentionally do not, so they remain draw-capable.
            from federations.models import FederationCompetitionTie
            requires_winner = FederationCompetitionTie.objects.filter(
                fixture_id=match.fixture_id
            ).exists()
        return MatchRules(
            requires_winner=requires_winner,
            allows_extra_time=requires_winner,
            allows_penalties=requires_winner,
            max_substitutions=5,
            max_substitution_windows=3,
            officiating=MatchSimulationSnapshotService._build_officiating_rules(match=match),
            medical=MatchSimulationSnapshotService._build_medical_rules(match=match),
        )

    @staticmethod
    def _build_medical_rules(*, match: Match) -> MedicalRules:
        from .medical import MatchMedicalResolver
        return MatchMedicalResolver.resolve(match=match).rules

    @staticmethod
    def _build_officiating_rules(*, match: Match) -> OfficiatingRules:
        """Freeze policy/referee mechanics into the immutable kickoff snapshot.

        Federation policy owns whether VAR is available.  Optional match-mechanics
        tuning can be supplied in policy ``rules`` and the appointed referee's
        metadata.  Missing governance data intentionally falls back to stable
        football defaults so ordinary league fixtures remain simulatable.
        """
        values = {
            "var_enabled": True,
            "advantage_enabled": True,
            "referee_strictness": 52,
            "referee_accuracy": 92,
            "assistant_accuracy": 94,
            "var_accuracy": 99,
        }
        competition = getattr(match.fixture, "federation_competition", None)
        if competition is None:
            return OfficiatingRules(**values)

        try:
            from match_officials_governance.constants import AppointmentPanelStatus, MatchOfficialRole
            from match_officials_governance.models import MatchOfficialsAppointmentPanel
            from match_officials_governance.services import MatchOfficialsPolicyService

            policy, payload, _ = MatchOfficialsPolicyService.resolve(competition=competition, at=match.scheduled_at)
            payload = payload or {}
            rules = payload.get("rules") or {}
            values["var_enabled"] = bool(payload.get("allow_var", True))
            for key in ("advantage_enabled", "referee_strictness", "referee_accuracy", "assistant_accuracy", "var_accuracy"):
                if key in rules:
                    values[key] = rules[key]

            panel = (
                MatchOfficialsAppointmentPanel.objects.filter(
                    match=match, status=AppointmentPanelStatus.CONFIRMED
                )
                .order_by("-sequence")
                .first()
            )
            if panel is not None:
                referee_appointment = panel.appointments.select_related("official").filter(
                    role=MatchOfficialRole.REFEREE
                ).first()
                if referee_appointment is not None:
                    metadata = referee_appointment.official.metadata or {}
                    mechanics = metadata.get("match_mechanics") or {}
                    for key in ("referee_strictness", "referee_accuracy"):
                        if key in mechanics:
                            values[key] = mechanics[key]
                var_appointment = panel.appointments.select_related("official").filter(
                    role=MatchOfficialRole.VAR
                ).first()
                if var_appointment is not None:
                    mechanics = (var_appointment.official.metadata or {}).get("match_mechanics") or {}
                    if "var_accuracy" in mechanics:
                        values["var_accuracy"] = mechanics["var_accuracy"]
                elif rules.get("require_var"):
                    values["var_enabled"] = False
        except Exception:
            # Kickoff snapshots must not depend on optional governance data being
            # present for legacy/non-federation fixtures. Integrity enforcement of
            # required panels remains the responsibility of matchday governance.
            pass
        return OfficiatingRules(**values)

    @staticmethod
    def _build_team(lineup: MatchLineup, *, readiness_snapshots=None) -> TeamState:
        entries = list(
            MatchLineupEntry.objects.filter(lineup=lineup)
            .select_related("player")
            .prefetch_related("player__position_familiarities")
            .order_by("role", "slot", "player_id")
        )
        starters = [entry for entry in entries if entry.role == LineupEntryRole.STARTER]
        substitutes = [
            entry for entry in entries if entry.role == LineupEntryRole.SUBSTITUTE
        ]

        slot_order = {
            slot: index for index, slot in enumerate(FORMATION_SLOTS[lineup.formation])
        }
        starters.sort(key=lambda entry: slot_order[entry.slot])
        substitutes.sort(key=lambda entry: str(entry.player_id))

        from staff.match_effects import for_match
        staff_effect = for_match(lineup.match_id, lineup.club_id)
        from training.drills import formation_identity
        from training.timed import formation_points
        training_key, _ = formation_identity(lineup.formation, [e.slot for e in starters])
        learning = formation_points(lineup.club_id, [e.player_id for e in entries], training_key)
        return TeamState(
            club_id=str(lineup.club_id),
            formation=lineup.formation,
            starters=tuple(_player_state(entry, readiness=(readiness_snapshots or {}).get(entry.player_id), staff_effect=staff_effect) for entry in starters),
            substitutes=tuple(_player_state(entry, readiness=(readiness_snapshots or {}).get(entry.player_id), staff_effect=staff_effect) for entry in substitutes),
            set_piece_plan=_set_piece_plan_state(lineup),
            formation_training=tuple(sorted(learning.items())),
        )


class MatchSimulationService:
    """Execute a pure engine outside DB locks, then persist exactly once."""

    @staticmethod
    def simulate_v1(*, match_id):
        """Run score engine v1 plus the separately-versioned detailed report."""

        from .engine.reporting.v1 import MatchReportBuilderV1
        from .engine.v1 import FTGMatchEngineV1

        return MatchSimulationService.simulate(
            match_id=match_id,
            engine=FTGMatchEngineV1(),
            report_builder=MatchReportBuilderV1(),
        )

    @staticmethod
    def simulate_v2(*, match_id, finalize_discipline=True, project_injuries=True):
        """Run event-aware Match Engine v2 and persist all authoritative facts.

        Score/report/resolution are one atomic write. Health and discipline
        projections are deterministic post-commit integrations so they do not
        invert the canonical Match -> Player locking order.
        """
        from .engine.v2 import FTGMatchEngineV2
        from .engine.v2.contracts import MatchV2Outcome

        snapshot = MatchSimulationService._load_snapshot(match_id=match_id)
        _assert_batch_simulation_allowed(snapshot)
        if snapshot.schema_version < 2:
            raise MatchNotSimulatableError(
                "Match Engine v2 requires a schema-v2 kickoff snapshot."
            )
        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        if existing is not None:
            if existing.engine_key == FTGMatchEngineV2.key and existing.engine_version == FTGMatchEngineV2.version:
                if project_injuries:
                    _project_v2_injuries(match_id=match_id)
                if finalize_discipline:
                    _finalize_discipline_if_ready(match_id=match_id)
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )
        if snapshot.match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError("Only an IN_PROGRESS unresolved match can be simulated.")
        state = MatchSimulationService._state_from_snapshot(snapshot)
        try:
            outcome = FTGMatchEngineV2().simulate(state, seed=snapshot.seed)
        except Exception as exc:
            raise SimulationExecutionError("The v2 simulation engine failed.") from exc
        if not isinstance(outcome, MatchV2Outcome):
            raise SimulationEngineContractError("Match Engine v2 returned an invalid outcome.")
        _validate_v2_outcome(state=state, outcome=outcome)

        run = MatchSimulationService._persist_v2_outcome(
            match_id=match_id,
            snapshot_id=snapshot.pk,
            expected_state_hash=snapshot.state_hash,
            outcome=outcome,
        )
        if project_injuries:
            _project_v2_injuries(match_id=match_id)
        if finalize_discipline:
            _finalize_discipline_if_ready(match_id=match_id)
        return run

    @staticmethod
    def simulate_v21(*, match_id, finalize_discipline=True, project_injuries=True):
        """Run live-tactics Match Engine v2.1 from a schema-v3 kickoff snapshot."""
        from .engine.v21 import FTGMatchEngineV21

        snapshot = MatchSimulationService._load_snapshot(match_id=match_id)
        _assert_batch_simulation_allowed(snapshot)
        if snapshot.schema_version < 3:
            raise MatchNotSimulatableError(
                "Match Engine v2.1 requires a schema-v3 tactical kickoff snapshot."
            )
        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        if existing is not None:
            if existing.engine_key == FTGMatchEngineV21.key and existing.engine_version == FTGMatchEngineV21.version:
                if project_injuries:
                    _project_v2_injuries(match_id=match_id)
                if finalize_discipline:
                    _finalize_discipline_if_ready(match_id=match_id)
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )
        if snapshot.match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError("Only an IN_PROGRESS unresolved match can be simulated.")
        state = MatchSimulationService._state_from_snapshot(snapshot)
        try:
            outcome = FTGMatchEngineV21().simulate(state, seed=snapshot.seed)
        except Exception as exc:
            raise SimulationExecutionError("The live-tactics v2.1 simulation engine failed.") from exc
        run = MatchSimulationService._persist_v21_outcome(
            match_id=match_id,
            snapshot_id=snapshot.pk,
            expected_state_hash=snapshot.state_hash,
            outcome=outcome,
        )
        if project_injuries:
            _project_v2_injuries(match_id=match_id)
        if finalize_discipline:
            _finalize_discipline_if_ready(match_id=match_id)
        return run

    @staticmethod
    def simulate_v3(*, match_id, finalize_discipline=True, project_injuries=True):
        """Run causal football Match Engine v3 for an AUTO match."""
        from .engine.registry import CurrentMatchEngine as FTGMatchEngineV3
        from .engine.v314 import FTGMatchEngineV314 as HistoricalV314
        from .engine.v3131 import FTGMatchEngineV3131 as HistoricalV3131
        from .engine.v313 import FTGMatchEngineV313 as HistoricalV3130
        from .engine.v3 import FTGMatchEngineV3 as HistoricalV312

        snapshot = MatchSimulationService._load_snapshot(match_id=match_id)
        _assert_batch_simulation_allowed(snapshot)
        if snapshot.schema_version < 3:
            raise MatchNotSimulatableError(
                "Match Engine v3 requires a schema-v3 tactical kickoff snapshot."
            )
        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        if existing is not None:
            if (existing.engine_key == FTGMatchEngineV3.key and
                    existing.engine_version in {FTGMatchEngineV3.version, HistoricalV314.version, HistoricalV3131.version, HistoricalV3130.version, HistoricalV312.version}):
                if project_injuries:
                    _project_v2_injuries(match_id=match_id)
                if finalize_discipline:
                    _finalize_discipline_if_ready(match_id=match_id)
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )
        if snapshot.match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError("Only an IN_PROGRESS unresolved match can be simulated.")
        state = MatchSimulationService._state_from_snapshot(snapshot)
        try:
            outcome = FTGMatchEngineV3().simulate(state, seed=snapshot.seed)
        except Exception as exc:
            raise SimulationExecutionError("The causal v3 simulation engine failed.") from exc
        run = MatchSimulationService._persist_v3_outcome(
            match_id=match_id,
            snapshot_id=snapshot.pk,
            expected_state_hash=snapshot.state_hash,
            outcome=outcome,
        )
        if project_injuries:
            _project_v2_injuries(match_id=match_id)
        if finalize_discipline:
            _finalize_discipline_if_ready(match_id=match_id)
        return run

    @staticmethod
    def simulate(*, match_id, engine, report_builder=None):
        snapshot = MatchSimulationService._load_snapshot(match_id=match_id)
        _assert_batch_simulation_allowed(snapshot)
        engine_key, engine_version = _validate_engine_identity(engine)

        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        state = MatchSimulationService._state_from_snapshot(snapshot)
        if existing is not None:
            if (
                existing.engine_key == engine_key
                and existing.engine_version == engine_version
            ):
                if report_builder is not None:
                    MatchSimulationService._ensure_report_for_existing_run(
                        snapshot=snapshot,
                        run=existing,
                        state=state,
                        report_builder=report_builder,
                    )
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )

        if snapshot.match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError(
                "Only an IN_PROGRESS unresolved match can be simulated."
            )

        # Deliberately outside transaction/row locks.  A future long-running
        # engine may run in Celery without holding database locks for minutes.
        try:
            result = engine.simulate(state, seed=snapshot.seed)
        except Exception as exc:  # engine implementation boundary
            raise SimulationExecutionError("The simulation engine failed.") from exc

        if not isinstance(result, SimulationResult):
            raise SimulationEngineContractError(
                "Engine simulate() must return SimulationResult."
            )

        report = None
        builder_key = builder_version = None
        if report_builder is not None:
            builder_key, builder_version = _validate_report_builder_identity(report_builder)
            try:
                report = report_builder.build(state, result, seed=snapshot.seed)
            except Exception as exc:
                raise SimulationReportGenerationError(
                    "The match report builder failed."
                ) from exc
            if not isinstance(report, MatchReport):
                raise SimulationReportContractError(
                    "Report builder must return MatchReport."
                )
            _validate_report_consistency(state=state, result=result, report=report)

        return MatchSimulationService._persist_result(
            match_id=match_id,
            snapshot_id=snapshot.pk,
            expected_state_hash=snapshot.state_hash,
            engine_key=engine_key,
            engine_version=engine_version,
            result=result,
            report=report,
            builder_key=builder_key,
            builder_version=builder_version,
        )

    @staticmethod
    def _ensure_report_for_existing_run(*, snapshot, run, state, report_builder):
        if MatchSimulationReport.objects.filter(run=run).exists():
            return
        builder_key, builder_version = _validate_report_builder_identity(report_builder)
        result = SimulationResult.from_payload(run.result_payload)
        try:
            report = report_builder.build(state, result, seed=snapshot.seed)
        except Exception as exc:
            raise SimulationReportGenerationError(
                "The match report builder failed while backfilling an existing run."
            ) from exc
        if not isinstance(report, MatchReport):
            raise SimulationReportContractError(
                "Report builder must return MatchReport."
            )
        _validate_report_consistency(state=state, result=result, report=report)
        MatchSimulationService._persist_report_only(
            match_id=snapshot.match_id,
            run_id=run.pk,
            report=report,
            builder_key=builder_key,
            builder_version=builder_version,
        )

    @staticmethod
    @transaction.atomic
    def _persist_report_only(*, match_id, run_id, report, builder_key, builder_version):
        source = lock_competition_source_and_match(match_id)
        match = source.match
        run = MatchSimulationRun.objects.select_for_update().select_related("snapshot").get(
            pk=run_id, snapshot__match_id=match_id
        )
        if MatchSimulationReport.objects.filter(run=run).exists():
            return
        _persist_report_rows(
            run=run,
            match=match,
            report=report,
            builder_key=builder_key,
            builder_version=builder_version,
        )
        _schedule_advanced_analytics_projection(match_id=match.pk)

    @staticmethod
    def get_input(*, match_id) -> tuple[MatchState, int]:
        """Read the immutable engine input for workers/debugging."""

        snapshot = MatchSimulationService._load_snapshot(match_id=match_id)
        return MatchSimulationService._state_from_snapshot(snapshot), snapshot.seed

    @staticmethod
    def _load_snapshot(*, match_id):
        try:
            snapshot = (
                MatchSimulationSnapshot.objects.select_related(
                    "match",
                    "match__fixture",
                    "match__fixture__competition",
                    "match__fixture__federation_competition",
                )
                .get(match_id=match_id)
            )
        except MatchSimulationSnapshot.DoesNotExist as exc:
            if not Match.objects.filter(pk=match_id).exists():
                raise MatchNotFoundError("Match does not exist.") from exc
            raise SimulationSnapshotNotFoundError(
                "Match has no kickoff simulation snapshot."
            ) from exc

        if snapshot.match.status not in {
            MatchStatus.IN_PROGRESS,
            MatchStatus.COMPLETED,
        }:
            raise MatchNotSimulatableError(
                "Only an IN_PROGRESS match can be simulated."
            )
        _verify_snapshot(snapshot)
        return snapshot

    @staticmethod
    def _state_from_snapshot(snapshot):
        try:
            return MatchState.from_payload(snapshot.state_payload)
        except (TypeError, ValueError) as exc:
            raise SimulationSnapshotIntegrityError(
                "Stored simulation state payload is invalid."
            ) from exc

    @staticmethod
    @transaction.atomic
    def _persist_v21_outcome(*, match_id, snapshot_id, expected_state_hash, outcome):
        from .engine.reporting.v21 import REPORT_BUILDER_KEY, REPORT_BUILDER_VERSION
        from .engine.v21 import FTGMatchEngineV21
        from .models import MatchTacticalDecision

        source = lock_competition_source_and_match(match_id)
        match = source.match
        snapshot = MatchSimulationSnapshot.objects.select_for_update().get(
            pk=snapshot_id, match_id=match_id
        )
        _verify_snapshot(snapshot)
        if snapshot.state_hash != expected_state_hash:
            raise SimulationSnapshotIntegrityError(
                "Simulation snapshot changed while Match Engine v2.1 was running."
            )
        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        if existing is not None:
            if existing.engine_key == FTGMatchEngineV21.key and existing.engine_version == FTGMatchEngineV21.version:
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )
        if match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError(
                "Match is no longer IN_PROGRESS when v2.1 outcome is persisted."
            )

        result_payload = outcome.result.to_payload()
        run = MatchSimulationRun.objects.create(
            snapshot=snapshot,
            engine_key=FTGMatchEngineV21.key,
            engine_version=FTGMatchEngineV21.version,
            result_payload=result_payload,
            result_hash=payload_sha256(result_payload),
        )
        report_model = _persist_report_v2_rows(
            run=run, match=match, report=outcome.report,
            builder_key=REPORT_BUILDER_KEY, builder_version=REPORT_BUILDER_VERSION,
        )
        decision_models = []
        for row in outcome.report.tactical_decisions:
            payload = {
                "match_id": str(match.pk),
                "run_id": str(run.pk),
                **row.to_payload(),
            }
            decision_models.append(MatchTacticalDecision(
                run=run,
                match=match,
                club_id=row.club_id,
                sequence=row.sequence,
                minute=row.minute,
                phase=row.phase,
                source=row.source,
                trigger_type=row.trigger_type,
                previous_attacking_strategy=row.previous_attacking_strategy,
                previous_defensive_strategy=row.previous_defensive_strategy,
                attacking_strategy=row.attacking_strategy,
                defensive_strategy=row.defensive_strategy,
                home_score=row.home_score,
                away_score=row.away_score,
                own_red_cards=row.own_red_cards,
                opponent_red_cards=row.opponent_red_cards,
                effect_payload=row.effect_payload,
                evidence_hash=payload_sha256(payload),
            ))
        if decision_models:
            MatchTacticalDecision.objects.bulk_create(decision_models)

        resolution_payload = {
            "match_id": str(match.pk),
            "run_id": str(run.pk),
            "report_id": str(report_model.pk),
            "engine_key": FTGMatchEngineV21.key,
            "engine_version": FTGMatchEngineV21.version,
            **outcome.resolution.to_payload(),
        }
        MatchSportingResolution.objects.create(
            match=match,
            decision_stage=outcome.resolution.decision_stage,
            regulation_home_score=outcome.resolution.regulation_home_score,
            regulation_away_score=outcome.resolution.regulation_away_score,
            extra_time_home_goals=outcome.resolution.extra_time_home_goals,
            extra_time_away_goals=outcome.resolution.extra_time_away_goals,
            home_penalties=outcome.resolution.home_penalties,
            away_penalties=outcome.resolution.away_penalties,
            engine_key=FTGMatchEngineV21.key,
            engine_version=FTGMatchEngineV21.version,
            evidence_hash=payload_sha256(resolution_payload),
        )
        match.home_score = outcome.result.home_score
        match.away_score = outcome.result.away_score
        match.completed_at = timezone.now()
        match.status = MatchStatus.COMPLETED
        match.result_type = MatchResultType.PLAYED
        match.save(update_fields=[
            "home_score", "away_score", "completed_at", "status",
            "result_type", "updated_at",
        ])
        if match.fixture.federation_competition_id:
            from federations.tournaments import FederationTournamentProgressionService
            FederationTournamentProgressionService.resolve_completed_match(
                match=match, competition=source.competition
            )
        _schedule_advanced_analytics_projection(match_id=match.pk)
        return run

    @staticmethod
    @transaction.atomic
    def _persist_v3_outcome(
        *, match_id, snapshot_id, expected_state_hash, outcome,
        engine_key=None, engine_version=None, report_builder_version=None,
    ):
        """Persist a causal v3-family outcome for AUTO or INTERACTIVE execution."""
        from .engine.reporting.v3 import REPORT_BUILDER_KEY, REPORT_BUILDER_VERSION
        from .engine.registry import CurrentMatchEngine as FTGMatchEngineV3
        engine_key = engine_key or FTGMatchEngineV3.key
        engine_version = engine_version or FTGMatchEngineV3.version
        report_builder_version = report_builder_version or REPORT_BUILDER_VERSION
        from .models import LiveMatchCommand, MatchTacticalDecision

        source = lock_competition_source_and_match(match_id)
        match = source.match
        snapshot = MatchSimulationSnapshot.objects.select_for_update().get(
            pk=snapshot_id, match_id=match_id
        )
        _verify_snapshot(snapshot)
        if snapshot.state_hash != expected_state_hash:
            raise SimulationSnapshotIntegrityError(
                "Simulation snapshot changed while Match Engine v3 was running."
            )
        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        if existing is not None:
            if existing.engine_key == engine_key and existing.engine_version == engine_version:
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )
        if match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError(
                "Match is no longer IN_PROGRESS when v3 outcome is persisted."
            )

        state = MatchSimulationService._state_from_snapshot(snapshot)
        _validate_v2_outcome(state=state, outcome=outcome)
        advanced = dict(outcome.report.advanced_analytics)
        team_advanced = {str(row["club_id"]): row for row in advanced.get("team_statistics") or []}
        if set(team_advanced) != {state.home.club_id, state.away.club_id}:
            raise SimulationReportContractError("v3 advanced analytics clubs do not match fixture.")
        goal_shots = {state.home.club_id: 0, state.away.club_id: 0}
        for shot in advanced.get("shots") or []:
            if shot.get("outcome") == "GOAL":
                goal_shots[str(shot.get("club_id"))] = goal_shots.get(str(shot.get("club_id")), 0) + 1
        if (goal_shots[state.home.club_id], goal_shots[state.away.club_id]) != (
            outcome.result.home_score, outcome.result.away_score
        ):
            raise SimulationReportContractError("v3 causal goal shots do not reconcile with score.")

        result_payload = outcome.result.to_payload()
        run = MatchSimulationRun.objects.create(
            snapshot=snapshot,
            engine_key=engine_key,
            engine_version=engine_version,
            result_payload=result_payload,
            result_hash=payload_sha256(result_payload),
        )
        report_model = _persist_report_v2_rows(
            run=run, match=match, report=outcome.report,
            builder_key=REPORT_BUILDER_KEY, builder_version=report_builder_version,
        )
        command_map = {
            str(row.pk): row
            for row in LiveMatchCommand.objects.filter(session__match=match)
        }
        decision_models = []
        for row in outcome.report.tactical_decisions:
            live_command = command_map.get(row.command_ref) if row.command_ref else None
            if row.source == "LIVE_COMMAND" and live_command is None:
                raise SimulationReportContractError(
                    "Causal tactical decision references missing live command evidence."
                )
            payload = {"match_id": str(match.pk), "run_id": str(run.pk), **row.to_payload()}
            decision_models.append(MatchTacticalDecision(
                run=run, match=match, club_id=row.club_id, live_command=live_command,
                sequence=row.sequence, minute=row.minute, phase=row.phase, source=row.source,
                trigger_type=row.trigger_type,
                previous_attacking_strategy=row.previous_attacking_strategy,
                previous_defensive_strategy=row.previous_defensive_strategy,
                attacking_strategy=row.attacking_strategy,
                defensive_strategy=row.defensive_strategy,
                home_score=row.home_score, away_score=row.away_score,
                own_red_cards=row.own_red_cards, opponent_red_cards=row.opponent_red_cards,
                effect_payload=row.effect_payload, evidence_hash=payload_sha256(payload),
            ))
        if decision_models:
            MatchTacticalDecision.objects.bulk_create(decision_models)

        defensive_rows = list(advanced.get("defensive_events") or [])
        if defensive_rows:
            expected_sequences = list(range(1, len(defensive_rows) + 1))
            actual_sequences = [int(row.get("sequence", 0)) for row in defensive_rows]
            if actual_sequences != expected_sequences:
                raise SimulationReportContractError(
                    "v3 defensive event sequences must be contiguous from 1."
                )
            valid_clubs = {state.home.club_id, state.away.club_id}
            defensive_models = []
            for row in defensive_rows:
                defending_club_id = str(row.get("defending_club_id") or "")
                attacking_club_id = str(row.get("attacking_club_id") or "")
                if {defending_club_id, attacking_club_id} != valid_clubs:
                    raise SimulationReportContractError(
                        "v3 defensive event clubs do not match the fixture."
                    )
                payload = {
                    "match_id": str(match.pk),
                    "run_id": str(run.pk),
                    **row,
                }
                defensive_models.append(MatchDefensiveEvent(
                    run=run, match=match, sequence=row["sequence"], minute=row["minute"],
                    phase=row["phase"], event_type=row["type"],
                    defending_club_id=defending_club_id, attacking_club_id=attacking_club_id,
                    player_id=row.get("player_id") or None,
                    opponent_player_id=row.get("opponent_player_id") or None,
                    outcome=row.get("outcome") or "", zone=row.get("zone") or "",
                    detail_payload=row.get("detail") or {}, evidence_hash=payload_sha256(payload),
                ))
            MatchDefensiveEvent.objects.bulk_create(defensive_models)

        possession_rows = list(advanced.get("possession_events") or [])
        if possession_rows:
            expected_sequences = list(range(1, len(possession_rows) + 1))
            actual_sequences = [int(row.get("sequence", 0)) for row in possession_rows]
            if actual_sequences != expected_sequences:
                raise SimulationReportContractError(
                    "v3 possession event sequences must be contiguous from 1."
                )
            valid_clubs = {state.home.club_id, state.away.club_id}
            action_cursor = {}
            possession_models = []
            for row in possession_rows:
                club_id = str(row.get("club_id") or "")
                opponent_club_id = str(row.get("opponent_club_id") or "")
                if {club_id, opponent_club_id} != valid_clubs:
                    raise SimulationReportContractError(
                        "v3 possession event clubs do not match the fixture."
                    )
                possession_sequence = int(row.get("possession_sequence", 0))
                action_sequence = int(row.get("action_sequence", 0))
                if possession_sequence < 1 or action_sequence < 1:
                    raise SimulationReportContractError(
                        "v3 possession/action sequence must be positive."
                    )
                expected_action = action_cursor.get(possession_sequence, 0) + 1
                if action_sequence != expected_action:
                    raise SimulationReportContractError(
                        "v3 possession action sequences must be contiguous within each possession."
                    )
                action_cursor[possession_sequence] = action_sequence
                payload = {"match_id": str(match.pk), "run_id": str(run.pk), **row}
                possession_models.append(MatchPossessionEvent(
                    run=run, match=match, sequence=row["sequence"],
                    possession_sequence=possession_sequence, action_sequence=action_sequence,
                    minute=row["minute"], phase=row["phase"], event_type=row["type"],
                    club_id=club_id, opponent_club_id=opponent_club_id,
                    player_id=row.get("player_id") or None,
                    target_player_id=row.get("target_player_id") or None,
                    origin_zone=row.get("origin_zone") or "DEFENSIVE_THIRD",
                    destination_zone=row.get("destination_zone") or row.get("origin_zone") or "DEFENSIVE_THIRD",
                    channel=row.get("channel") or "CENTRE", outcome=row.get("outcome") or "",
                    transition_state=row.get("transition_state") or "SETTLED",
                    detail_payload=row.get("detail") or {}, evidence_hash=payload_sha256(payload),
                ))
            MatchPossessionEvent.objects.bulk_create(possession_models)

        pressing_rows = list(advanced.get("pressing_events") or [])
        if pressing_rows:
            expected_sequences = list(range(1, len(pressing_rows) + 1))
            actual_sequences = [int(row.get("sequence", 0)) for row in pressing_rows]
            if actual_sequences != expected_sequences:
                raise SimulationReportContractError("v3 pressing event sequences must be contiguous from 1.")
            valid_clubs = {state.home.club_id, state.away.club_id}
            pressing_models = []
            for row in pressing_rows:
                pressing_club_id = str(row.get("pressing_club_id") or "")
                opponent_club_id = str(row.get("opponent_club_id") or "")
                if {pressing_club_id, opponent_club_id} != valid_clubs:
                    raise SimulationReportContractError("v3 pressing event clubs do not match the fixture.")
                payload = {"match_id": str(match.pk), "run_id": str(run.pk), **row}
                pressing_models.append(MatchPressingEvent(
                    run=run, match=match, sequence=row["sequence"],
                    possession_sequence=row["possession_sequence"], minute=row["minute"], phase=row["phase"],
                    event_type=row["type"], pressing_club_id=pressing_club_id, opponent_club_id=opponent_club_id,
                    player_id=row.get("player_id") or None, target_player_id=row.get("target_player_id") or None,
                    zone=row.get("zone") or "MIDDLE_THIRD", channel=row.get("channel") or "CENTRE",
                    defensive_strategy=row.get("defensive_strategy") or "BALANCED", trigger=row.get("trigger") or "",
                    line_height=int(row.get("line_height") or 0), compactness=int(row.get("compactness") or 0),
                    width=int(row.get("width") or 0), press_intensity=row.get("press_intensity") or 0,
                    outcome=row.get("outcome") or "", detail_payload=row.get("detail") or {},
                    evidence_hash=payload_sha256(payload),
                ))
            MatchPressingEvent.objects.bulk_create(pressing_models)

        off_ball_rows = list(advanced.get("off_ball_events") or [])
        if off_ball_rows:
            expected_sequences = list(range(1, len(off_ball_rows) + 1))
            actual_sequences = [int(row.get("sequence", 0)) for row in off_ball_rows]
            if actual_sequences != expected_sequences:
                raise SimulationReportContractError("v3 off-ball event sequences must be contiguous from 1.")
            valid_clubs = {state.home.club_id, state.away.club_id}
            off_ball_models = []
            for row in off_ball_rows:
                club_id = str(row.get("club_id") or "")
                opponent_club_id = str(row.get("opponent_club_id") or "")
                if {club_id, opponent_club_id} != valid_clubs:
                    raise SimulationReportContractError("v3 off-ball event clubs do not match the fixture.")
                payload = {"match_id": str(match.pk), "run_id": str(run.pk), **row}
                off_ball_models.append(MatchOffBallEvent(
                    run=run, match=match, sequence=row["sequence"],
                    possession_sequence=row["possession_sequence"], minute=row["minute"], phase=row["phase"],
                    event_type=row["type"], club_id=club_id, opponent_club_id=opponent_club_id,
                    player_id=row.get("player_id") or None, related_player_id=row.get("related_player_id") or None,
                    origin_zone=row.get("origin_zone") or "MIDDLE_THIRD",
                    destination_zone=row.get("destination_zone") or row.get("origin_zone") or "MIDDLE_THIRD",
                    origin_lane=row.get("origin_lane") or "CENTRE",
                    destination_lane=row.get("destination_lane") or "CENTRE",
                    tactical_role=row.get("tactical_role") or "", outcome=row.get("outcome") or "",
                    detail_payload=row.get("detail") or {}, evidence_hash=payload_sha256(payload),
                ))
            MatchOffBallEvent.objects.bulk_create(off_ball_models)

        distribution_rows = list(advanced.get("goalkeeper_distribution_events") or [])
        if distribution_rows:
            expected_sequences = list(range(1, len(distribution_rows) + 1))
            actual_sequences = [int(row.get("sequence", 0)) for row in distribution_rows]
            if actual_sequences != expected_sequences:
                raise SimulationReportContractError("v3 goalkeeper distribution sequences must be contiguous from 1.")
            valid_clubs = {state.home.club_id, state.away.club_id}
            distribution_models = []
            for row in distribution_rows:
                club_id = str(row.get("club_id") or "")
                opponent_club_id = str(row.get("opponent_club_id") or "")
                if {club_id, opponent_club_id} != valid_clubs:
                    raise SimulationReportContractError("v3 goalkeeper distribution clubs do not match the fixture.")
                payload = {"match_id": str(match.pk), "run_id": str(run.pk), **row}
                distribution_models.append(MatchGoalkeeperDistributionEvent(
                    run=run, match=match, sequence=row["sequence"], possession_sequence=row["possession_sequence"],
                    minute=row["minute"], phase=row["phase"], club_id=club_id, opponent_club_id=opponent_club_id,
                    goalkeeper_id=row["goalkeeper_player_id"], receiver_id=row.get("receiver_player_id") or None,
                    distribution_type=row["distribution_type"], source=row.get("source") or "GOAL_KICK",
                    origin_zone=row.get("origin_zone") or "DEFENSIVE_THIRD",
                    destination_zone=row.get("destination_zone") or "MIDDLE_THIRD", channel=row.get("channel") or "CENTRE",
                    under_pressure=bool(row.get("under_pressure")), success_probability=row.get("success_probability") or 0,
                    outcome=row.get("outcome") or "", detail_payload=row.get("detail") or {},
                    evidence_hash=payload_sha256(payload),
                ))
            MatchGoalkeeperDistributionEvent.objects.bulk_create(distribution_models)

        resolution_payload = {
            "match_id": str(match.pk), "run_id": str(run.pk),
            "report_id": str(report_model.pk),
            "engine_key": engine_key, "engine_version": engine_version,
            **outcome.resolution.to_payload(),
        }
        MatchSportingResolution.objects.create(
            match=match, decision_stage=outcome.resolution.decision_stage,
            regulation_home_score=outcome.resolution.regulation_home_score,
            regulation_away_score=outcome.resolution.regulation_away_score,
            extra_time_home_goals=outcome.resolution.extra_time_home_goals,
            extra_time_away_goals=outcome.resolution.extra_time_away_goals,
            home_penalties=outcome.resolution.home_penalties,
            away_penalties=outcome.resolution.away_penalties,
            engine_key=engine_key, engine_version=engine_version,
            evidence_hash=payload_sha256(resolution_payload),
        )
        match.home_score = outcome.result.home_score
        match.away_score = outcome.result.away_score
        match.completed_at = timezone.now()
        match.status = MatchStatus.COMPLETED
        match.result_type = MatchResultType.PLAYED
        match.save(update_fields=[
            "home_score", "away_score", "completed_at", "status",
            "result_type", "updated_at",
        ])
        if match.fixture.federation_competition_id:
            from federations.tournaments import FederationTournamentProgressionService
            FederationTournamentProgressionService.resolve_completed_match(
                match=match, competition=source.competition
            )
        _schedule_advanced_analytics_projection(match_id=match.pk)
        return run

    @staticmethod
    @transaction.atomic
    def _persist_v22_outcome(*, match_id, snapshot_id, expected_state_hash, outcome):
        """Persist the final interactive v2.2 outcome exactly once."""
        from .engine.reporting.v22 import REPORT_BUILDER_KEY, REPORT_BUILDER_VERSION
        from .engine.v22 import FTGMatchEngineV22
        from .models import LiveMatchCommand, MatchTacticalDecision

        source = lock_competition_source_and_match(match_id)
        match = source.match
        snapshot = MatchSimulationSnapshot.objects.select_for_update().get(
            pk=snapshot_id, match_id=match_id
        )
        _verify_snapshot(snapshot)
        if snapshot.state_hash != expected_state_hash:
            raise SimulationSnapshotIntegrityError(
                "Simulation snapshot changed while Match Engine v2.2 was running."
            )
        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        if existing is not None:
            if existing.engine_key == FTGMatchEngineV22.key and existing.engine_version == FTGMatchEngineV22.version:
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )
        if match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError(
                "Match is no longer IN_PROGRESS when v2.2 outcome is persisted."
            )

        state = MatchSimulationService._state_from_snapshot(snapshot)
        _validate_v2_outcome(state=state, outcome=outcome)
        result_payload = outcome.result.to_payload()
        run = MatchSimulationRun.objects.create(
            snapshot=snapshot,
            engine_key=FTGMatchEngineV22.key,
            engine_version=FTGMatchEngineV22.version,
            result_payload=result_payload,
            result_hash=payload_sha256(result_payload),
        )
        report_model = _persist_report_v2_rows(
            run=run, match=match, report=outcome.report,
            builder_key=REPORT_BUILDER_KEY, builder_version=REPORT_BUILDER_VERSION,
        )
        command_map = {
            str(row.pk): row
            for row in LiveMatchCommand.objects.filter(session__match=match)
        }
        decision_models = []
        for row in outcome.report.tactical_decisions:
            live_command = command_map.get(row.command_ref) if row.command_ref else None
            if row.source == "LIVE_COMMAND" and live_command is None:
                raise SimulationReportContractError(
                    "Interactive tactical decision references missing live command evidence."
                )
            payload = {
                "match_id": str(match.pk),
                "run_id": str(run.pk),
                **row.to_payload(),
            }
            decision_models.append(MatchTacticalDecision(
                run=run,
                match=match,
                club_id=row.club_id,
                live_command=live_command,
                sequence=row.sequence,
                minute=row.minute,
                phase=row.phase,
                source=row.source,
                trigger_type=row.trigger_type,
                previous_attacking_strategy=row.previous_attacking_strategy,
                previous_defensive_strategy=row.previous_defensive_strategy,
                attacking_strategy=row.attacking_strategy,
                defensive_strategy=row.defensive_strategy,
                home_score=row.home_score,
                away_score=row.away_score,
                own_red_cards=row.own_red_cards,
                opponent_red_cards=row.opponent_red_cards,
                effect_payload=row.effect_payload,
                evidence_hash=payload_sha256(payload),
            ))
        if decision_models:
            MatchTacticalDecision.objects.bulk_create(decision_models)

        resolution_payload = {
            "match_id": str(match.pk),
            "run_id": str(run.pk),
            "report_id": str(report_model.pk),
            "engine_key": FTGMatchEngineV22.key,
            "engine_version": FTGMatchEngineV22.version,
            **outcome.resolution.to_payload(),
        }
        MatchSportingResolution.objects.create(
            match=match,
            decision_stage=outcome.resolution.decision_stage,
            regulation_home_score=outcome.resolution.regulation_home_score,
            regulation_away_score=outcome.resolution.regulation_away_score,
            extra_time_home_goals=outcome.resolution.extra_time_home_goals,
            extra_time_away_goals=outcome.resolution.extra_time_away_goals,
            home_penalties=outcome.resolution.home_penalties,
            away_penalties=outcome.resolution.away_penalties,
            engine_key=FTGMatchEngineV22.key,
            engine_version=FTGMatchEngineV22.version,
            evidence_hash=payload_sha256(resolution_payload),
        )
        match.home_score = outcome.result.home_score
        match.away_score = outcome.result.away_score
        match.completed_at = timezone.now()
        match.status = MatchStatus.COMPLETED
        match.result_type = MatchResultType.PLAYED
        match.save(update_fields=[
            "home_score", "away_score", "completed_at", "status",
            "result_type", "updated_at",
        ])
        if match.fixture.federation_competition_id:
            from federations.tournaments import FederationTournamentProgressionService
            FederationTournamentProgressionService.resolve_completed_match(
                match=match, competition=source.competition
            )
        _schedule_advanced_analytics_projection(match_id=match.pk)
        return run

    @staticmethod
    @transaction.atomic
    def _persist_v2_outcome(*, match_id, snapshot_id, expected_state_hash, outcome):
        from .engine.reporting.v2 import REPORT_BUILDER_KEY, REPORT_BUILDER_VERSION
        from .engine.v2 import FTGMatchEngineV2

        source = lock_competition_source_and_match(match_id)
        match = source.match
        snapshot = MatchSimulationSnapshot.objects.select_for_update().get(
            pk=snapshot_id, match_id=match_id
        )
        _verify_snapshot(snapshot)
        if snapshot.state_hash != expected_state_hash:
            raise SimulationSnapshotIntegrityError(
                "Simulation snapshot changed while Match Engine v2 was running."
            )
        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        if existing is not None:
            if existing.engine_key == FTGMatchEngineV2.key and existing.engine_version == FTGMatchEngineV2.version:
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )
        if match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError(
                "Match is no longer IN_PROGRESS when v2 outcome is persisted."
            )

        result_payload = outcome.result.to_payload()
        run = MatchSimulationRun.objects.create(
            snapshot=snapshot,
            engine_key=FTGMatchEngineV2.key,
            engine_version=FTGMatchEngineV2.version,
            result_payload=result_payload,
            result_hash=payload_sha256(result_payload),
        )
        report_model = _persist_report_v2_rows(
            run=run, match=match, report=outcome.report,
            builder_key=REPORT_BUILDER_KEY, builder_version=REPORT_BUILDER_VERSION,
        )
        resolution_payload = {
            "match_id": str(match.pk),
            "run_id": str(run.pk),
            "report_id": str(report_model.pk),
            "engine_key": FTGMatchEngineV2.key,
            "engine_version": FTGMatchEngineV2.version,
            **outcome.resolution.to_payload(),
        }
        MatchSportingResolution.objects.create(
            match=match,
            decision_stage=outcome.resolution.decision_stage,
            regulation_home_score=outcome.resolution.regulation_home_score,
            regulation_away_score=outcome.resolution.regulation_away_score,
            extra_time_home_goals=outcome.resolution.extra_time_home_goals,
            extra_time_away_goals=outcome.resolution.extra_time_away_goals,
            home_penalties=outcome.resolution.home_penalties,
            away_penalties=outcome.resolution.away_penalties,
            engine_key=FTGMatchEngineV2.key,
            engine_version=FTGMatchEngineV2.version,
            evidence_hash=payload_sha256(resolution_payload),
        )

        match.home_score = outcome.result.home_score
        match.away_score = outcome.result.away_score
        match.completed_at = timezone.now()
        match.status = MatchStatus.COMPLETED
        match.result_type = MatchResultType.PLAYED
        match.save(update_fields=[
            "home_score", "away_score", "completed_at", "status",
            "result_type", "updated_at",
        ])
        if match.fixture.federation_competition_id:
            from federations.tournaments import FederationTournamentProgressionService
            FederationTournamentProgressionService.resolve_completed_match(
                match=match, competition=source.competition
            )
        _schedule_advanced_analytics_projection(match_id=match.pk)
        return run

    @staticmethod
    @transaction.atomic
    def _persist_result(
        *,
        match_id,
        snapshot_id,
        expected_state_hash,
        engine_key,
        engine_version,
        result,
        report=None,
        builder_key=None,
        builder_version=None,
    ):
        # Preserve the established match lock order: Competition -> Match ->
        # Snapshot. Engine execution already happened outside this block.
        source = lock_competition_source_and_match(match_id)
        match = source.match

        try:
            snapshot = MatchSimulationSnapshot.objects.select_for_update().get(
                pk=snapshot_id,
                match_id=match_id,
            )
        except MatchSimulationSnapshot.DoesNotExist as exc:
            raise SimulationSnapshotNotFoundError(
                "Kickoff simulation snapshot no longer exists."
            ) from exc

        _verify_snapshot(snapshot)
        if snapshot.state_hash != expected_state_hash:
            raise SimulationSnapshotIntegrityError(
                "Simulation snapshot changed while the engine was running."
            )

        existing = MatchSimulationRun.objects.filter(snapshot=snapshot).first()
        if existing is not None:
            if (
                existing.engine_key == engine_key
                and existing.engine_version == engine_version
            ):
                if report is not None and not MatchSimulationReport.objects.filter(run=existing).exists():
                    _persist_report_rows(
                        run=existing,
                        match=match,
                        report=report,
                        builder_key=builder_key,
                        builder_version=builder_version,
                    )
                return existing
            raise SimulationAlreadyResolvedError(
                "This match was already resolved by another engine/version."
            )

        if match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotSimulatableError(
                "Match is no longer IN_PROGRESS when simulation result is persisted."
            )

        result_payload = result.to_payload()
        run = MatchSimulationRun.objects.create(
            snapshot=snapshot,
            engine_key=engine_key,
            engine_version=engine_version,
            result_payload=result_payload,
            result_hash=payload_sha256(result_payload),
        )

        if report is not None:
            _persist_report_rows(
                run=run,
                match=match,
                report=report,
                builder_key=builder_key,
                builder_version=builder_version,
            )

        match.home_score = result.home_score
        match.away_score = result.away_score
        match.completed_at = timezone.now()
        match.status = MatchStatus.COMPLETED
        match.result_type = MatchResultType.PLAYED
        match.save(
            update_fields=[
                "home_score",
                "away_score",
                "completed_at",
                "status",
                "result_type",
                "updated_at",
            ]
        )

        if match.fixture.federation_competition_id:
            from federations.tournaments import FederationTournamentProgressionService

            FederationTournamentProgressionService.resolve_completed_match(
                match=match, competition=source.competition
            )
        if report is not None:
            _schedule_advanced_analytics_projection(match_id=match.pk)
        return run



def _persist_report_rows(*, run, match, report, builder_key, builder_version):
    if report is None:
        return None
    if not builder_key or not builder_version:
        raise SimulationReportContractError(
            "A persisted report requires builder identity/version."
        )

    from game_statistics.models import MatchPlayerStatistics, MatchTeamStatistics

    report_payload = normalize_report_payload_for_jsonb(report.to_payload())
    report_model = MatchSimulationReport.objects.create(
        run=run,
        schema_version=report.schema_version,
        builder_key=builder_key,
        builder_version=builder_version,
        report_payload=report_payload,
        report_hash=payload_sha256(report_payload),
    )

    MatchEvent.objects.bulk_create(
        [
            MatchEvent(
                report=report_model,
                match=match,
                sequence=event.sequence,
                minute=event.minute,
                event_type=event.event_type,
                club_id=event.club_id,
                player_id=event.player_id,
            )
            for event in report.events
        ]
    )
    MatchTeamStatistics.objects.bulk_create(
        [
            MatchTeamStatistics(
                report=report_model,
                match=match,
                club_id=item.club_id,
                goals_for=item.goals_for,
                goals_against=item.goals_against,
                clean_sheet=item.clean_sheet,
            )
            for item in report.team_statistics
        ]
    )
    MatchPlayerStatistics.objects.bulk_create(
        [
            MatchPlayerStatistics(
                report=report_model,
                match=match,
                player_id=item.player_id,
                club_id=item.club_id,
                started=item.started,
                minutes_played=item.minutes_played,
                goals=item.goals,
                clean_sheet=item.clean_sheet,
            )
            for item in report.player_statistics
        ]
    )
    return report_model


def _validate_v2_outcome(*, state, outcome):
    from .engine.reporting.v2 import (
        EVENT_GOAL, EVENT_PENALTY_SCORED, PHASE_SHOOTOUT,
    )

    clubs = {state.home.club_id, state.away.club_id}
    lineup_by_club = {
        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)},
    }
    goal_counts = {state.home.club_id: 0, state.away.club_id: 0}
    penalty_counts = {state.home.club_id: 0, state.away.club_id: 0}
    for event in outcome.report.events:
        if event.club_id not in clubs or event.player_id not in lineup_by_club[event.club_id]:
            raise SimulationReportContractError("v2 event references a non-participating identity.")
        if event.secondary_player_id is not None and event.secondary_player_id not in lineup_by_club[event.club_id]:
            raise SimulationReportContractError("v2 substitution references a non-lineup player.")
        if event.event_type == EVENT_GOAL:
            goal_counts[event.club_id] += 1
        if event.event_type == EVENT_PENALTY_SCORED:
            if event.phase != PHASE_SHOOTOUT:
                raise SimulationReportContractError("Penalty event has invalid phase.")
            penalty_counts[event.club_id] += 1
    if (goal_counts[state.home.club_id], goal_counts[state.away.club_id]) != (
        outcome.result.home_score, outcome.result.away_score
    ):
        raise SimulationReportContractError("v2 goal timeline does not reconcile with field score.")
    if outcome.resolution.decision_stage == "PENALTIES":
        if (penalty_counts[state.home.club_id], penalty_counts[state.away.club_id]) != (
            outcome.resolution.home_penalties, outcome.resolution.away_penalties
        ):
            raise SimulationReportContractError("v2 shootout timeline does not reconcile with resolution.")
    elif any(penalty_counts.values()):
        raise SimulationReportContractError("Non-shootout match contains penalty-shootout events.")

    team_rows = {row.club_id: row for row in outcome.report.team_statistics}
    if set(team_rows) != clubs:
        raise SimulationReportContractError("v2 report must contain exactly the fixture clubs.")
    if (team_rows[state.home.club_id].goals_for, team_rows[state.home.club_id].goals_against) != (outcome.result.home_score, outcome.result.away_score):
        raise SimulationReportContractError("v2 home statistics do not reconcile with score.")
    if (team_rows[state.away.club_id].goals_for, team_rows[state.away.club_id].goals_against) != (outcome.result.away_score, outcome.result.home_score):
        raise SimulationReportContractError("v2 away statistics do not reconcile with score.")


def _persist_report_v2_rows(*, run, match, report, builder_key, builder_version):
    from game_statistics.models import MatchPlayerStatistics, MatchTeamStatistics
    from .discipline import DisciplineCardService
    from .constants import DisciplinaryCardSource, DisciplinaryCardType

    report_payload = normalize_report_payload_for_jsonb(report.to_payload())
    report_model = MatchSimulationReport.objects.create(
        run=run,
        schema_version=report.schema_version,
        builder_key=builder_key,
        builder_version=builder_version,
        report_payload=report_payload,
        report_hash=payload_sha256(report_payload),
    )
    event_models = []
    for event in report.events:
        event_models.append(
            MatchEvent(
                report=report_model,
                match=match,
                sequence=event.sequence,
                minute=event.minute,
                phase=event.phase,
                event_type=event.event_type,
                club_id=event.club_id,
                player_id=event.player_id,
                secondary_player_id=event.secondary_player_id,
                detail_payload=event.detail_payload,
            )
        )
    MatchEvent.objects.bulk_create(event_models)

    MatchTeamStatistics.objects.bulk_create([
        MatchTeamStatistics(
            report=report_model, match=match, club_id=row.club_id,
            goals_for=row.goals_for, goals_against=row.goals_against,
            clean_sheet=row.clean_sheet, yellow_cards=row.yellow_cards,
            red_cards=row.red_cards, substitutions=row.substitutions,
        )
        for row in report.team_statistics
    ])
    MatchPlayerStatistics.objects.bulk_create([
        MatchPlayerStatistics(
            report=report_model, match=match, player_id=row.player_id,
            club_id=row.club_id, started=row.started,
            minutes_played=row.minutes_played, goals=row.goals,
            clean_sheet=row.clean_sheet, yellow_cards=row.yellow_cards,
            red_cards=row.red_cards, substituted_in=row.substituted_in,
            substituted_out=row.substituted_out, injured=row.injured,
        )
        for row in report.player_statistics
    ])

    card_type_by_event = {
        "YELLOW_CARD": DisciplinaryCardType.YELLOW,
        "SECOND_YELLOW": DisciplinaryCardType.SECOND_YELLOW,
        "RED_CARD": DisciplinaryCardType.DIRECT_RED,
    }
    for event_model in event_models:
        card_type = card_type_by_event.get(event_model.event_type)
        if card_type is not None:
            DisciplineCardService.record(
                match_id=match.pk, club_id=event_model.club_id,
                player_id=event_model.player_id, minute=event_model.minute,
                card_type=card_type, source=DisciplinaryCardSource.MATCH_ENGINE,
                source_match_event_id=event_model.pk,
            )
    return report_model


def _project_v2_injuries(*, match_id):
    """Idempotently project authoritative v2 INJURY events to Health."""
    from datetime import timedelta
    from injuries.models import InjuryIncident
    from injuries.services import InjuryService
    from .constants import MatchEventType

    match = Match.objects.get(pk=match_id)
    occurred_on = timezone.localdate(match.scheduled_at) if match.scheduled_at else timezone.localdate()
    events = MatchEvent.objects.filter(
        match_id=match_id, event_type=MatchEventType.INJURY
    ).order_by("sequence")
    for event in events:
        source_id = str(event.pk)
        if InjuryIncident.objects.filter(source_type="MATCH_EVENT", source_id=source_id).exists():
            continue
        detail = event.detail_payload or {}
        days = int(detail.get("expected_recovery_days") or 4)
        InjuryService.record_injury(
            player_id=event.player_id,
            injury_code=str(detail.get("injury_code") or "MATCH_MINOR"),
            training_restriction=str(detail.get("training_restriction") or "LIMITED"),
            match_availability=str(detail.get("match_availability") or "AVAILABLE"),
            occurred_on=occurred_on,
            expected_recovery_on=occurred_on + timedelta(days=max(1, days)),
            source_type="MATCH_EVENT",
            source_id=source_id,
            notes=f"Authoritative in-match injury from Match {match_id} event #{event.sequence}.",
        )


def _validate_report_consistency(*, state, result, report):
    home_ids = {player.player_id for player in state.home.starters}
    away_ids = {player.player_id for player in state.away.starters}
    all_starters = home_ids | away_ids
    club_players = {
        state.home.club_id: home_ids,
        state.away.club_id: away_ids,
    }

    events = tuple(report.events)
    if any(event.event_type != GOAL_EVENT for event in events):
        raise SimulationReportContractError(
            "Foundation report supports GOAL events only."
        )
    home_event_goals = sum(event.club_id == state.home.club_id for event in events)
    away_event_goals = sum(event.club_id == state.away.club_id for event in events)
    if (home_event_goals, away_event_goals) != (result.home_score, result.away_score):
        raise SimulationReportContractError(
            "Goal timeline must exactly reconcile with the authoritative score."
        )
    for event in events:
        if event.club_id not in club_players:
            raise SimulationReportContractError(
                "Report event references a non-participating club."
            )
        if event.player_id not in club_players[event.club_id]:
            raise SimulationReportContractError(
                "Goal scorer must be a starter for the event club."
            )

    team_rows = {item.club_id: item for item in report.team_statistics}
    if set(team_rows) != set(club_players):
        raise SimulationReportContractError(
            "Team statistics must contain exactly the two fixture clubs."
        )
    expected_team = {
        state.home.club_id: (result.home_score, result.away_score),
        state.away.club_id: (result.away_score, result.home_score),
    }
    for club_id, (goals_for, goals_against) in expected_team.items():
        row = team_rows[club_id]
        if (row.goals_for, row.goals_against) != (goals_for, goals_against):
            raise SimulationReportContractError(
                "Team statistics do not reconcile with the authoritative score."
            )

    player_rows = {item.player_id: item for item in report.player_statistics}
    if set(player_rows) != all_starters or len(player_rows) != 22:
        raise SimulationReportContractError(
            "Player statistics must contain exactly the 22 starting players."
        )
    goal_counts = {}
    for event in events:
        goal_counts[event.player_id] = goal_counts.get(event.player_id, 0) + 1
    for player_id, row in player_rows.items():
        expected_club = (
            state.home.club_id if player_id in home_ids else state.away.club_id
        )
        if row.club_id != expected_club:
            raise SimulationReportContractError(
                "Player statistics row references the wrong club."
            )
        if not row.started or row.minutes_played != 90:
            raise SimulationReportContractError(
                "Report v1 records exactly 90 minutes for the 22 starters."
            )
        if row.goals != goal_counts.get(player_id, 0):
            raise SimulationReportContractError(
                "Player goal statistics do not reconcile with goal events."
            )
        opponent_score = (
            result.away_score if expected_club == state.home.club_id else result.home_score
        )
        if row.clean_sheet != (opponent_score == 0):
            raise SimulationReportContractError(
                "Player clean-sheet statistic is inconsistent with the score."
            )


def _validate_report_builder_identity(builder):
    builder_key = getattr(builder, "key", None)
    builder_version = getattr(builder, "version", None)
    for value, field_name in (
        (builder_key, "report_builder.key"),
        (builder_version, "report_builder.version"),
    ):
        if not isinstance(value, str) or not value.strip() or len(value) > 64:
            raise SimulationReportContractError(
                f"{field_name} must be a non-empty string up to 64 characters."
            )
    if not callable(getattr(builder, "build", None)):
        raise SimulationReportContractError(
            "Report builder must implement build(state, result, *, seed)."
        )
    return builder_key, builder_version

def _set_piece_plan_state(lineup):
    from .models import MatchSetPiecePlan
    try:
        plan = lineup.set_piece_plan
    except MatchSetPiecePlan.DoesNotExist:
        return TeamSetPiecePlan()
    return TeamSetPiecePlan(
        penalty_taker_id=str(plan.penalty_taker_id) if plan.penalty_taker_id else None,
        direct_free_kick_taker_id=str(plan.direct_free_kick_taker_id) if plan.direct_free_kick_taker_id else None,
        left_corner_taker_id=str(plan.left_corner_taker_id) if plan.left_corner_taker_id else None,
        right_corner_taker_id=str(plan.right_corner_taker_id) if plan.right_corner_taker_id else None,
        aerial_target_player_id=str(plan.aerial_target_player_id) if plan.aerial_target_player_id else None,
        penalty_order=tuple(str(value) for value in (plan.penalty_order or [])),
        corner_routine=plan.corner_routine,
        free_kick_routine=plan.free_kick_routine,
    )


def _player_state(entry: MatchLineupEntry, readiness=None, staff_effect=None) -> PlayerState:
    player: Player = entry.player
    if readiness is not None:
        effective = readiness.effective_ratings
        ratings = tuple(
            (field_name, int(effective.get(field_name, getattr(player, field_name))))
            for field_name in MATCH_STATE_RATING_FIELDS
        )
    else:
        ratings = tuple(
            (field_name, int(getattr(player, field_name)))
            for field_name in MATCH_STATE_RATING_FIELDS
        )
    from decimal import Decimal, ROUND_HALF_UP
    effect = staff_effect or {}
    multiplier = Decimal("1") + Decimal(effect.get("team_bonus", "0"))
    ratings = tuple((name, min(100, max(1, int((Decimal(value) * multiplier).quantize(Decimal("1"), rounding=ROUND_HALF_UP))))) for name, value in ratings)
    from injuries.resolver import FatigueResolver
    fatigue = FatigueResolver.for_player(player=player)
    familiarity_map = dict(BASE_POSITION_FAMILIARITY.get(player.position, {}))
    familiarity_map[player.position] = 100
    for row in player.position_familiarities.all():
        familiarity_map[row.position] = max(int(row.familiarity), int(familiarity_map.get(row.position, 0)))
    current_familiarity = 100
    tactical_role = "AUTO"
    if entry.role == LineupEntryRole.STARTER:
        current_familiarity = familiarity_from_map(player.position, familiarity_map.items(), entry.slot)
        tactical_role = resolve_tactical_role(entry.tactical_role, entry.slot)
    return PlayerState(
        player_id=str(player.pk),
        natural_position=player.position,
        lineup_slot=entry.slot,
        role=entry.role,
        is_captain=entry.is_captain,
        ratings=ratings,
        fatigue_index=int(round(float(fatigue.fatigue_index) * (1 - float(effect.get("fatigue_reduction", "0"))))),
        tactical_role=tactical_role,
        position_familiarity=current_familiarity,
        position_familiarities=tuple(sorted((str(k), int(v)) for k, v in familiarity_map.items())),
    )


def _snapshot_hash(*, schema_version, seed, state_payload):
    return payload_sha256(
        {
            "schema_version": schema_version,
            "seed": seed,
            "state": state_payload,
        }
    )


def _assert_batch_simulation_allowed(snapshot):
    if snapshot.match.execution_mode == MatchExecutionMode.INTERACTIVE:
        raise MatchNotSimulatableError(
            "INTERACTIVE matches must be resolved through InteractiveMatchRunnerService."
        )


def _verify_snapshot(snapshot):
    expected = _snapshot_hash(
        schema_version=snapshot.schema_version,
        seed=snapshot.seed,
        state_payload=snapshot.state_payload,
    )
    if expected != snapshot.state_hash:
        raise SimulationSnapshotIntegrityError(
            "Simulation snapshot integrity hash does not match stored input."
        )
    if snapshot.schema_version not in {1, 2, 3, 4, 5, 6, 7, SIMULATION_SCHEMA_VERSION}:
        raise SimulationSnapshotIntegrityError(
            "Unsupported simulation state schema version."
        )


def _validate_engine_identity(engine):
    engine_key = getattr(engine, "key", None)
    engine_version = getattr(engine, "version", None)
    for value, field_name in (
        (engine_key, "engine.key"),
        (engine_version, "engine.version"),
    ):
        if not isinstance(value, str) or not value.strip() or len(value) > 64:
            raise SimulationEngineContractError(
                f"{field_name} must be a non-empty string up to 64 characters."
            )
    if not callable(getattr(engine, "simulate", None)):
        raise SimulationEngineContractError(
            "Engine must implement simulate(state, *, seed)."
        )
    return engine_key, engine_version
