import uuid
from .friendly_models import FriendlyGame, FriendlyAudit  # noqa: F401

from django.db import models
from django.db.models import F, Q

from leagues.constants import LeagueCompetitionType

from .constants import (
    ALL_FORMATION_SLOTS,
    LEAGUE_ROUNDS_PER_LEG,
    LEAGUE_TOTAL_ROUNDS,
    FormationCode,
    LineupEntryRole,
    TacticalPlayerRole,
    CornerRoutine,
    FreeKickRoutine,
    LineupStatus,
    MatchEventType,
    MatchEventPhase,
    DefensiveEventType,
    PossessionEventType,
    PressingEventType,
    OffBallEventType,
    GoalkeeperDistributionType,
    SportingDecisionStage,
    MatchStatus,
    MatchResultType,
    DisciplinaryCardType,
    DisciplinaryCardSource,
    DisciplinarySanctionType,
    DisciplinaryAppealDecisionOutcome,
    AdministrativeDecisionReason,
    AdministrativeDecisionOutcome,
    AttackingStrategy,
    DefensiveStrategy,
    TacticalAdaptationMode,
    TacticalTriggerType,
    TacticalDecisionSource,
    LIVE_TACTICS_POLICY_KEY,
    LIVE_TACTICS_POLICY_VERSION,
    MatchExecutionMode,
    InteractiveMatchSessionStatus,
    LiveMatchCommandType,
    INTERACTIVE_MATCH_POLICY_KEY,
    INTERACTIVE_MATCH_POLICY_VERSION,
    LiveStreamEventType,
    LiveStreamVisibility,
    LIVE_STREAM_POLICY_KEY,
    LIVE_STREAM_POLICY_VERSION,
    LIVE_STREAM_SCHEMA_VERSION,
)


class Fixture(models.Model):
    """Authoritative pairing/round slot for one seasonal league competition.

    A Fixture is schedule structure, not a simulated result. Match owns the
    execution lifecycle and score. The pairing remains stable so historical
    competition structure does not depend on mutable Match state.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    competition = models.ForeignKey(
        "leagues.LeagueCompetition",
        on_delete=models.PROTECT,
        related_name="fixtures",
        null=True,
        blank=True,
    )
    federation_competition = models.ForeignKey(
        "federations.FederationCompetition",
        on_delete=models.PROTECT,
        related_name="fixtures",
        null=True,
        blank=True,
    )
    draw_generation = models.PositiveIntegerField(default=1, editable=False)
    replay_of_fixture = models.ForeignKey(
        "self", null=True, blank=True, on_delete=models.PROTECT,
        related_name="replay_fixtures", editable=False,
    )
    replay_sequence = models.PositiveSmallIntegerField(default=0, editable=False)
    round_number = models.PositiveSmallIntegerField()
    leg = models.PositiveSmallIntegerField()
    home_club = models.ForeignKey(
        "clubs.Club",
        on_delete=models.PROTECT,
        related_name="home_fixtures",
    )
    away_club = models.ForeignKey(
        "clubs.Club",
        on_delete=models.PROTECT,
        related_name="away_fixtures",
    )
    competition_type = models.CharField(
        max_length=10,
        choices=LeagueCompetitionType.choices,
        default=LeagueCompetitionType.ADULT,
        editable=False,
    )
    home_youth_team = models.ForeignKey(
        "academy.ClubYouthTeam",
        on_delete=models.PROTECT,
        related_name="home_fixtures",
        null=True,
        blank=True,
    )
    away_youth_team = models.ForeignKey(
        "academy.ClubYouthTeam",
        on_delete=models.PROTECT,
        related_name="away_fixtures",
        null=True,
        blank=True,
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["competition_id", "round_number", "home_club_id"]
        indexes = [
            models.Index(
                fields=["competition", "round_number"],
                name="fixture_comp_round_idx",
            ),
            models.Index(
                fields=["federation_competition", "round_number"],
                name="fixture_fed_comp_round_idx",
            ),
            models.Index(
                fields=["federation_competition", "draw_generation", "round_number"],
                name="fixture_fed_gen_round_idx",
            ),
            models.Index(
                fields=["home_club", "competition"],
                name="fixture_home_comp_idx",
            ),
            models.Index(
                fields=["away_club", "competition"],
                name="fixture_away_comp_idx",
            ),
        ]
        constraints = [
            models.CheckConstraint(
                condition=Q(round_number__gte=1, round_number__lte=LEAGUE_TOTAL_ROUNDS),
                name="fixture_valid_round",
            ),
            models.CheckConstraint(
                condition=Q(leg__in=[1, 2]),
                name="fixture_valid_leg",
            ),
            models.CheckConstraint(
                condition=Q(competition_type__in=LeagueCompetitionType.values),
                name="fixture_valid_comp_type",
            ),
            models.CheckConstraint(
                condition=(
                    Q(
                        competition_type=LeagueCompetitionType.ADULT,
                        home_youth_team__isnull=True,
                        away_youth_team__isnull=True,
                    )
                    | Q(
                        competition_type=LeagueCompetitionType.YOUTH,
                        home_youth_team__isnull=False,
                        away_youth_team__isnull=False,
                    )
                ),
                name="fixture_participant_matches_type",
            ),
            models.CheckConstraint(
                condition=(
                    Q(
                        competition__isnull=False,
                        federation_competition__isnull=True,
                        leg=1,
                        round_number__lte=LEAGUE_ROUNDS_PER_LEG,
                    )
                    | Q(
                        competition__isnull=False,
                        federation_competition__isnull=True,
                        leg=2,
                        round_number__gt=LEAGUE_ROUNDS_PER_LEG,
                    )
                    | Q(
                        competition__isnull=True,
                        federation_competition__isnull=False,
                    )
                ),
                name="fixture_leg_round_consistent",
            ),
            models.CheckConstraint(
                condition=~Q(home_club=F("away_club")),
                name="fixture_distinct_clubs",
            ),
            models.CheckConstraint(
                condition=(
                    Q(competition__isnull=False, federation_competition__isnull=True)
                    | Q(competition__isnull=True, federation_competition__isnull=False)
                ),
                name="fixture_exactly_one_comp",
            ),
            models.UniqueConstraint(
                fields=["competition", "home_club", "away_club"],
                condition=Q(competition__isnull=False, replay_of_fixture__isnull=True),
                name="uq_fixture_league_pair",
            ),
            models.UniqueConstraint(
                fields=["competition", "round_number", "home_club"],
                condition=Q(competition__isnull=False, replay_of_fixture__isnull=True),
                name="uq_fixture_league_r_home",
            ),
            models.UniqueConstraint(
                fields=["competition", "round_number", "away_club"],
                condition=Q(competition__isnull=False, replay_of_fixture__isnull=True),
                name="uq_fixture_league_r_away",
            ),
            models.CheckConstraint(
                condition=(
                    Q(replay_of_fixture__isnull=True, replay_sequence=0)
                    | Q(replay_of_fixture__isnull=False, replay_sequence__gte=1)
                ),
                name="fixture_replay_metadata_consistent",
            ),
            models.UniqueConstraint(
                fields=["federation_competition", "draw_generation", "round_number", "home_club", "away_club"],
                condition=Q(federation_competition__isnull=False, replay_of_fixture__isnull=True),
                name="uq_fixture_fed_gen_pair",
            ),
            models.UniqueConstraint(
                fields=["federation_competition", "draw_generation", "round_number", "home_club"],
                condition=Q(federation_competition__isnull=False, replay_of_fixture__isnull=True),
                name="uq_fixture_fed_gen_home",
            ),
            models.UniqueConstraint(
                fields=["federation_competition", "draw_generation", "round_number", "away_club"],
                condition=Q(federation_competition__isnull=False, replay_of_fixture__isnull=True),
                name="uq_fixture_fed_gen_away",
            ),
            models.UniqueConstraint(
                fields=["replay_of_fixture", "replay_sequence"],
                condition=Q(replay_of_fixture__isnull=False),
                name="uq_fixture_replay_sequence",
            ),
        ]

    def __str__(self):
        source_id = self.competition_id or self.federation_competition_id
        return (
            f"{source_id} R{self.round_number}: "
            f"{self.home_club_id} vs {self.away_club_id}"
        )

    @property
    def season(self):
        if self.competition_id:
            return self.competition.season
        return self.federation_competition.season

    @property
    def competition_source_id(self):
        return self.competition_id or self.federation_competition_id


class Match(models.Model):
    """Authoritative execution state and result for exactly one Fixture."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    fixture = models.OneToOneField(
        Fixture,
        on_delete=models.PROTECT,
        related_name="match",
    )
    status = models.CharField(
        max_length=12,
        choices=MatchStatus.choices,
        default=MatchStatus.PENDING,
    )
    execution_mode = models.CharField(
        max_length=16,
        choices=MatchExecutionMode.choices,
        default=MatchExecutionMode.AUTO,
    )
    scheduled_at = models.DateTimeField(null=True, blank=True)
    started_at = models.DateTimeField(null=True, blank=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    cancelled_at = models.DateTimeField(null=True, blank=True)
    home_score = models.PositiveSmallIntegerField(null=True, blank=True)
    away_score = models.PositiveSmallIntegerField(null=True, blank=True)
    result_type = models.CharField(
        max_length=16,
        choices=MatchResultType.choices,
        default=MatchResultType.NONE,
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["created_at", "id"]
        indexes = [
            models.Index(fields=["status"], name="match_status_idx"),
            models.Index(fields=["scheduled_at"], name="match_scheduled_idx"),
        ]
        constraints = [
            models.CheckConstraint(
                condition=Q(status__in=MatchStatus.values),
                name="match_valid_status",
            ),
            models.CheckConstraint(
                condition=Q(execution_mode__in=MatchExecutionMode.values),
                name="match_valid_execution_mode",
            ),
            models.CheckConstraint(
                condition=(
                    Q(
                        status=MatchStatus.PENDING,
                        scheduled_at__isnull=True,
                        started_at__isnull=True,
                        completed_at__isnull=True,
                        cancelled_at__isnull=True,
                        home_score__isnull=True,
                        away_score__isnull=True,
                        result_type=MatchResultType.NONE,
                    )
                    | Q(
                        status=MatchStatus.SCHEDULED,
                        scheduled_at__isnull=False,
                        started_at__isnull=True,
                        completed_at__isnull=True,
                        cancelled_at__isnull=True,
                        home_score__isnull=True,
                        away_score__isnull=True,
                        result_type=MatchResultType.NONE,
                    )
                    | Q(
                        status=MatchStatus.IN_PROGRESS,
                        scheduled_at__isnull=False,
                        started_at__isnull=False,
                        completed_at__isnull=True,
                        cancelled_at__isnull=True,
                        home_score__isnull=True,
                        away_score__isnull=True,
                        result_type=MatchResultType.NONE,
                    )
                    | Q(
                        status=MatchStatus.COMPLETED,
                        scheduled_at__isnull=False,
                        started_at__isnull=False,
                        completed_at__isnull=False,
                        cancelled_at__isnull=True,
                        home_score__isnull=False,
                        away_score__isnull=False,
                        result_type=MatchResultType.PLAYED,
                    )
                    | Q(
                        status=MatchStatus.COMPLETED,
                        scheduled_at__isnull=False,
                        started_at__isnull=True,
                        completed_at__isnull=False,
                        cancelled_at__isnull=True,
                        home_score__isnull=False,
                        away_score__isnull=False,
                        result_type=MatchResultType.ADMINISTRATIVE,
                    )
                    | Q(
                        status=MatchStatus.CANCELLED,
                        started_at__isnull=True,
                        completed_at__isnull=True,
                        cancelled_at__isnull=False,
                        home_score__isnull=True,
                        away_score__isnull=True,
                        result_type=MatchResultType.NONE,
                    )
                ),
                name="match_lifecycle",
            ),
            models.CheckConstraint(
                condition=(
                    Q(started_at__isnull=True)
                    | Q(completed_at__isnull=True)
                    | Q(completed_at__gte=F("started_at"))
                ),
                name="match_completed_after_start",
            ),
        ]

    def __str__(self):
        return f"Match {self.id} ({self.status})"

    @property
    def home_club_id(self):
        return self.fixture.home_club_id

    @property
    def away_club_id(self):
        return self.fixture.away_club_id


class MatchLineup(models.Model):
    """One club's submitted match configuration for a Match.

    DRAFT lineups are editable. SUBMITTED lineups are complete but can still
    be explicitly reopened before kickoff. Match start revalidates both clubs'
    current rosters and atomically locks the two lineups. LOCKED lineups are
    historical match configuration and are never rewritten from later roster
    changes.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.ForeignKey(
        Match,
        on_delete=models.PROTECT,
        related_name="lineups",
    )
    club = models.ForeignKey(
        "clubs.Club",
        on_delete=models.PROTECT,
        related_name="match_lineups",
    )
    participant_type = models.CharField(
        max_length=10,
        choices=LeagueCompetitionType.choices,
        default=LeagueCompetitionType.ADULT,
        editable=False,
    )
    youth_team = models.ForeignKey(
        "academy.ClubYouthTeam",
        on_delete=models.PROTECT,
        related_name="match_lineups",
        null=True,
        blank=True,
    )
    formation = models.CharField(
        max_length=16,
        choices=FormationCode.choices,
    )
    status = models.CharField(
        max_length=12,
        choices=LineupStatus.choices,
        default=LineupStatus.DRAFT,
    )
    submitted_at = models.DateTimeField(null=True, blank=True)
    locked_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["match_id", "club_id"]
        indexes = [
            models.Index(fields=["match", "status"], name="lineup_match_status_idx"),
            models.Index(fields=["club", "match"], name="lineup_club_match_idx"),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=["match", "club"],
                name="uq_match_lineup_club",
            ),
            models.CheckConstraint(
                condition=Q(formation__in=FormationCode.values),
                name="lineup_valid_formation",
            ),
            models.CheckConstraint(
                condition=Q(participant_type__in=LeagueCompetitionType.values),
                name="lineup_valid_participant_type",
            ),
            models.CheckConstraint(
                condition=(
                    Q(participant_type=LeagueCompetitionType.ADULT, youth_team__isnull=True)
                    | Q(participant_type=LeagueCompetitionType.YOUTH, youth_team__isnull=False)
                ),
                name="lineup_participant_matches_type",
            ),
            models.CheckConstraint(
                condition=Q(status__in=LineupStatus.values),
                name="lineup_valid_status",
            ),
            models.CheckConstraint(
                condition=(
                    Q(
                        status=LineupStatus.DRAFT,
                        submitted_at__isnull=True,
                        locked_at__isnull=True,
                    )
                    | Q(
                        status=LineupStatus.SUBMITTED,
                        submitted_at__isnull=False,
                        locked_at__isnull=True,
                    )
                    | Q(
                        status=LineupStatus.LOCKED,
                        submitted_at__isnull=False,
                        locked_at__isnull=False,
                    )
                ),
                name="lineup_lifecycle",
            ),
            models.CheckConstraint(
                condition=(
                    Q(submitted_at__isnull=True)
                    | Q(locked_at__isnull=True)
                    | Q(locked_at__gte=F("submitted_at"))
                ),
                name="lineup_locked_after_submit",
            ),
        ]

    def __str__(self):
        return f"{self.match_id} / {self.club_id} / {self.formation}"


class MatchSetPiecePlan(models.Model):
    """Editable pre-kickoff dead-ball plan frozen into the simulation snapshot."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    lineup = models.OneToOneField(
        MatchLineup, on_delete=models.CASCADE, related_name="set_piece_plan"
    )
    penalty_taker = models.ForeignKey(
        "players.Player", null=True, blank=True, on_delete=models.PROTECT,
        related_name="penalty_set_piece_plans",
    )
    direct_free_kick_taker = models.ForeignKey(
        "players.Player", null=True, blank=True, on_delete=models.PROTECT,
        related_name="free_kick_set_piece_plans",
    )
    left_corner_taker = models.ForeignKey(
        "players.Player", null=True, blank=True, on_delete=models.PROTECT,
        related_name="left_corner_set_piece_plans",
    )
    right_corner_taker = models.ForeignKey(
        "players.Player", null=True, blank=True, on_delete=models.PROTECT,
        related_name="right_corner_set_piece_plans",
    )
    aerial_target_player = models.ForeignKey(
        "players.Player", null=True, blank=True, on_delete=models.PROTECT,
        related_name="aerial_target_set_piece_plans",
    )
    penalty_order = models.JSONField(default=list, blank=True)
    corner_routine = models.CharField(
        max_length=24, choices=CornerRoutine.choices, default=CornerRoutine.MIXED
    )
    free_kick_routine = models.CharField(
        max_length=16, choices=FreeKickRoutine.choices, default=FreeKickRoutine.MIXED
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [models.Index(fields=["lineup"], name="setpiece_lineup_idx")]
        constraints = [
            models.CheckConstraint(
                condition=Q(corner_routine__in=CornerRoutine.values),
                name="setpiece_valid_corner_routine",
            ),
            models.CheckConstraint(
                condition=Q(free_kick_routine__in=FreeKickRoutine.values),
                name="setpiece_valid_fk_routine",
            ),
        ]

    def __str__(self):
        return f"Set pieces / {self.lineup_id}"


class MatchLineupEntry(models.Model):
    """One selected player in a MatchLineup."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    lineup = models.ForeignKey(
        MatchLineup,
        on_delete=models.CASCADE,
        related_name="entries",
    )
    player = models.ForeignKey(
        "players.Player",
        on_delete=models.PROTECT,
        related_name="match_lineup_entries",
    )
    role = models.CharField(
        max_length=12,
        choices=LineupEntryRole.choices,
    )
    tactical_role = models.CharField(
        max_length=40,
        choices=TacticalPlayerRole.choices,
        default=TacticalPlayerRole.AUTO,
    )
    slot = models.CharField(max_length=8, blank=True, default="")
    is_captain = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["lineup_id", "role", "slot", "created_at"]
        indexes = [
            models.Index(fields=["lineup", "role"], name="lineup_entry_role_idx"),
            models.Index(fields=["player"], name="lineup_entry_player_idx"),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=["lineup", "player"],
                name="uq_lineup_player",
            ),
            models.UniqueConstraint(
                fields=["lineup", "slot"],
                condition=Q(role=LineupEntryRole.STARTER),
                name="uq_lineup_starting_slot",
            ),
            models.UniqueConstraint(
                fields=["lineup"],
                condition=Q(is_captain=True),
                name="uq_lineup_captain",
            ),
            models.CheckConstraint(
                condition=Q(role__in=LineupEntryRole.values),
                name="lineup_entry_valid_role",
            ),
            models.CheckConstraint(
                condition=Q(tactical_role__in=TacticalPlayerRole.values),
                name="lineup_entry_valid_tactical_role",
            ),
            models.CheckConstraint(
                condition=(
                    Q(role=LineupEntryRole.STARTER)
                    | Q(role=LineupEntryRole.SUBSTITUTE, tactical_role=TacticalPlayerRole.AUTO)
                ),
                name="lineup_substitute_role_auto",
            ),
            models.CheckConstraint(
                condition=(
                    Q(
                        role=LineupEntryRole.STARTER,
                        slot__in=ALL_FORMATION_SLOTS,
                    )
                    | Q(
                        role=LineupEntryRole.SUBSTITUTE,
                        slot="",
                        is_captain=False,
                    )
                ),
                name="lineup_entry_role_slot",
            ),
        ]

    def __str__(self):
        return f"{self.player_id} / {self.role} / {self.slot or '-'} / {self.tactical_role}"


class _ImmutableSimulationQuerySet(models.QuerySet):
    """Protect persisted simulation evidence from ORM bulk mutation."""

    def update(self, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError

        raise SimulationEvidenceImmutableError(
            "Simulation snapshots/results are immutable after creation."
        )

    def delete(self):
        from .exceptions import SimulationEvidenceImmutableError

        raise SimulationEvidenceImmutableError(
            "Simulation snapshots/results are immutable after creation."
        )


class MatchSimulationSnapshot(models.Model):
    """Immutable kickoff-time input captured for the pure simulation engine."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.OneToOneField(
        Match,
        on_delete=models.PROTECT,
        related_name="simulation_snapshot",
    )
    schema_version = models.PositiveSmallIntegerField(default=1)
    seed = models.PositiveBigIntegerField()
    state_payload = models.JSONField()
    state_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["created_at", "id"]
        constraints = [
            models.CheckConstraint(
                condition=Q(schema_version__gte=1),
                name="sim_snapshot_schema_gte_1",
            ),
            models.CheckConstraint(
                condition=Q(seed__gte=1),
                name="sim_snapshot_seed_gte_1",
            ),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError

            raise SimulationEvidenceImmutableError(
                "Simulation snapshots are immutable after creation."
            )
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError

        raise SimulationEvidenceImmutableError(
            "Simulation snapshots are immutable after creation."
        )

    def __str__(self):
        return f"Snapshot {self.match_id} / v{self.schema_version}"


class MatchSimulationRun(models.Model):
    """Immutable persisted output from exactly one simulation engine run."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    snapshot = models.OneToOneField(
        MatchSimulationSnapshot,
        on_delete=models.PROTECT,
        related_name="simulation_run",
    )
    engine_key = models.CharField(max_length=64)
    engine_version = models.CharField(max_length=64)
    result_payload = models.JSONField()
    result_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["created_at", "id"]
        constraints = [
            models.CheckConstraint(
                condition=~Q(engine_key=""),
                name="sim_run_engine_key_not_empty",
            ),
            models.CheckConstraint(
                condition=~Q(engine_version=""),
                name="sim_run_engine_version_not_empty",
            ),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError

            raise SimulationEvidenceImmutableError(
                "Simulation results are immutable after creation."
            )
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError

        raise SimulationEvidenceImmutableError(
            "Simulation results are immutable after creation."
        )

    @property
    def match_id(self):
        return self.snapshot.match_id

    def __str__(self):
        return (
            f"Simulation {self.snapshot.match_id} / "
            f"{self.engine_key}@{self.engine_version}"
        )

class MatchSimulationReport(models.Model):
    """Immutable versioned detailed report derived from one simulation run."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    run = models.OneToOneField(
        MatchSimulationRun,
        on_delete=models.PROTECT,
        related_name="report",
    )
    schema_version = models.PositiveSmallIntegerField(default=1)
    builder_key = models.CharField(max_length=64)
    builder_version = models.CharField(max_length=64)
    report_payload = models.JSONField()
    report_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["created_at", "id"]
        constraints = [
            models.CheckConstraint(
                condition=Q(schema_version__gte=1),
                name="sim_report_schema_gte_1",
            ),
            models.CheckConstraint(
                condition=~Q(builder_key=""),
                name="sim_report_builder_key_not_empty",
            ),
            models.CheckConstraint(
                condition=~Q(builder_version=""),
                name="sim_report_builder_version_not_empty",
            ),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError

            raise SimulationEvidenceImmutableError(
                "Simulation reports are immutable after creation."
            )
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError

        raise SimulationEvidenceImmutableError(
            "Simulation reports are immutable after creation."
        )

    @property
    def match_id(self):
        return self.run.snapshot.match_id


class MatchEvent(models.Model):
    """Immutable normalized timeline event sourced from a simulation report.

    Report v1 persists GOAL only. Report v2 expands this normalized timeline
    with substitutions, cards, injuries, extra time and penalty shootout events.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    report = models.ForeignKey(
        MatchSimulationReport,
        on_delete=models.PROTECT,
        related_name="events",
    )
    match = models.ForeignKey(
        Match,
        on_delete=models.PROTECT,
        related_name="events",
    )
    sequence = models.PositiveSmallIntegerField()
    minute = models.PositiveSmallIntegerField()
    phase = models.CharField(
        max_length=16,
        choices=MatchEventPhase.choices,
        default=MatchEventPhase.REGULATION,
    )
    event_type = models.CharField(
        max_length=24,
        choices=MatchEventType.choices,
    )
    club = models.ForeignKey(
        "clubs.Club",
        on_delete=models.PROTECT,
        related_name="match_events",
    )
    player = models.ForeignKey(
        "players.Player",
        on_delete=models.PROTECT,
        related_name="match_events",
    )
    secondary_player = models.ForeignKey(
        "players.Player",
        on_delete=models.PROTECT,
        related_name="secondary_match_events",
        null=True,
        blank=True,
    )
    detail_payload = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "minute", "sequence"]
        indexes = [
            models.Index(fields=["match", "minute", "sequence"], name="event_match_time_idx"),
            models.Index(fields=["player", "match"], name="event_player_match_idx"),
            models.Index(fields=["club", "match"], name="event_club_match_idx"),
        ]
        constraints = [
            models.UniqueConstraint(
                fields=["match", "sequence"],
                name="uq_match_event_sequence",
            ),
            models.CheckConstraint(
                condition=Q(minute__gte=1, minute__lte=120),
                name="event_minute_1_120",
            ),
            models.CheckConstraint(
                condition=Q(sequence__gte=1),
                name="event_sequence_gte_1",
            ),
            models.CheckConstraint(
                condition=Q(event_type__in=MatchEventType.values),
                name="event_valid_type",
            ),
            models.CheckConstraint(
                condition=Q(phase__in=MatchEventPhase.values),
                name="event_valid_phase",
            ),
            models.CheckConstraint(
                condition=(
                    Q(event_type=MatchEventType.SUBSTITUTION, secondary_player__isnull=False)
                    | (~Q(event_type=MatchEventType.SUBSTITUTION) & Q(secondary_player__isnull=True))
                ),
                name="event_substitution_has_secondary",
            ),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError

            raise SimulationEvidenceImmutableError(
                "Match events are immutable after creation."
            )
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError

        raise SimulationEvidenceImmutableError(
            "Match events are immutable after creation."
        )

    def __str__(self):
        return f"{self.match_id} #{self.sequence} {self.event_type} {self.minute}'"



# ---------------------------------------------------------------------------
# Exact kickoff scheduling foundation
# ---------------------------------------------------------------------------
from django.db.models.functions import Lower

from .constants import MatchScheduleReason
from .scheduling_policy import KickoffSchedulingPolicyV1


class CountrySchedulingProfile(models.Model):
    """Operational scheduling defaults for a country/jurisdiction.

    Country is intentionally a string because League/Club currently use a
    string country identity. A future normalized geography domain can migrate
    these rows without rewriting historical Match schedule evidence.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    country = models.CharField(max_length=80)
    timezone_name = models.CharField(max_length=64)
    adult_kickoff_time = models.TimeField(default="18:00:00")
    youth_kickoff_time = models.TimeField(default="15:00:00")
    cup_kickoff_time = models.TimeField(default="19:00:00")
    continental_kickoff_time = models.TimeField(default="20:00:00")
    min_rest_hours = models.PositiveSmallIntegerField(default=72)
    max_auto_shift_days = models.PositiveSmallIntegerField(default=7)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["country"]
        constraints = [
            models.UniqueConstraint(
                Lower("country"), name="uq_country_sched_country_ci"
            ),
            models.CheckConstraint(
                condition=Q(min_rest_hours__gte=24, min_rest_hours__lte=168),
                name="country_sched_rest_24_168",
            ),
            models.CheckConstraint(
                condition=Q(max_auto_shift_days__gte=0, max_auto_shift_days__lte=14),
                name="country_sched_shift_0_14",
            ),
        ]

    def clean(self):
        from django.core.exceptions import ValidationError
        try:
            self.timezone_name = KickoffSchedulingPolicyV1.validate_timezone_name(self.timezone_name)
        except ValueError as exc:
            raise ValidationError({"timezone_name": str(exc)}) from exc

    def save(self, *args, **kwargs):
        self.full_clean()
        return super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.country} ({self.timezone_name})"


class CountryMatchEnvironmentProfile(models.Model):
    """Configurable climate defaults used to freeze kickoff weather.

    It is intentionally country-string based to match the existing Club/League
    geography model.  Historical matches never read this row after kickoff;
    the resolved environment is copied into immutable simulation evidence.
    """

    CLIMATE_CHOICES = [
        ("TEMPERATE", "Temperate"),
        ("CONTINENTAL", "Continental"),
        ("MEDITERRANEAN", "Mediterranean"),
        ("ARID", "Arid"),
        ("TROPICAL", "Tropical"),
        ("COLD", "Cold"),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    country = models.CharField(max_length=80)
    climate_zone = models.CharField(max_length=20, choices=CLIMATE_CHOICES, default="TEMPERATE")
    mean_temperature_c = models.SmallIntegerField(default=14)
    seasonal_amplitude_c = models.PositiveSmallIntegerField(default=11)
    season_peak_month = models.PositiveSmallIntegerField(default=7)
    humidity_index = models.PositiveSmallIntegerField(default=55)
    rainfall_index = models.PositiveSmallIntegerField(default=45)
    wind_index = models.PositiveSmallIntegerField(default=35)
    snow_index = models.PositiveSmallIntegerField(default=10)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["country"]
        constraints = [
            models.UniqueConstraint(Lower("country"), name="uq_country_match_env_country_ci"),
            models.CheckConstraint(condition=Q(mean_temperature_c__gte=-15, mean_temperature_c__lte=40), name="country_env_mean_temp"),
            models.CheckConstraint(condition=Q(seasonal_amplitude_c__lte=30), name="country_env_season_amp"),
            models.CheckConstraint(condition=Q(season_peak_month__gte=1, season_peak_month__lte=12), name="country_env_peak_month"),
            models.CheckConstraint(condition=Q(humidity_index__lte=100), name="country_env_humidity"),
            models.CheckConstraint(condition=Q(rainfall_index__lte=100), name="country_env_rainfall"),
            models.CheckConstraint(condition=Q(wind_index__lte=100), name="country_env_wind"),
            models.CheckConstraint(condition=Q(snow_index__lte=100), name="country_env_snow"),
        ]

    def __str__(self):
        return f"{self.country} / {self.climate_zone}"


class MatchEnvironmentEvidence(models.Model):
    """Immutable normalized projection of the kickoff environment snapshot."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.OneToOneField(Match, on_delete=models.PROTECT, related_name="environment_evidence")
    snapshot = models.OneToOneField(MatchSimulationSnapshot, on_delete=models.PROTECT, related_name="environment_evidence")
    venue_source = models.CharField(max_length=32, default="FALLBACK")
    venue_reference = models.CharField(max_length=80, blank=True, default="")
    climate_source = models.CharField(max_length=32, default="DEFAULT")
    environment_payload = models.JSONField(default=dict)
    effects_payload = models.JSONField(default=dict)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id"]
        constraints = [
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="match_env_evidence_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError
            raise SimulationEvidenceImmutableError("Match environment evidence is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError
        raise SimulationEvidenceImmutableError("Match environment evidence is immutable.")

    def __str__(self):
        return f"Environment / {self.match_id} / {self.venue_source}"


class ClubMatchMedicalProfile(models.Model):
    """Mutable club medical capability; frozen into each kickoff snapshot.

    This profile intentionally models operational capability rather than named
    clinicians. Historical replay never reads the live row after kickoff.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    club = models.OneToOneField(
        "clubs.Club", on_delete=models.PROTECT, related_name="match_medical_profile"
    )
    assessment_quality = models.PositiveSmallIntegerField(default=60)
    treatment_quality = models.PositiveSmallIntegerField(default=60)
    concussion_recognition = models.PositiveSmallIntegerField(default=70)
    welfare_bias = models.PositiveSmallIntegerField(default=75)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["club_id"]
        constraints = [
            models.CheckConstraint(condition=Q(assessment_quality__gte=1, assessment_quality__lte=100), name="club_med_assess_1_100"),
            models.CheckConstraint(condition=Q(treatment_quality__gte=1, treatment_quality__lte=100), name="club_med_treat_1_100"),
            models.CheckConstraint(condition=Q(concussion_recognition__gte=1, concussion_recognition__lte=100), name="club_med_concuss_1_100"),
            models.CheckConstraint(condition=Q(welfare_bias__gte=1, welfare_bias__lte=100), name="club_med_welfare_1_100"),
        ]

    def __str__(self):
        return f"Medical profile / {self.club_id}"


class MatchMedicalEvidence(models.Model):
    """Immutable kickoff medical policy/capability evidence."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.OneToOneField(Match, on_delete=models.PROTECT, related_name="medical_evidence")
    snapshot = models.OneToOneField(MatchSimulationSnapshot, on_delete=models.PROTECT, related_name="medical_evidence")
    rules_payload = models.JSONField(default=dict)
    home_medical_payload = models.JSONField(default=dict)
    away_medical_payload = models.JSONField(default=dict)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id"]
        constraints = [
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="match_med_evidence_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError
            raise SimulationEvidenceImmutableError("Match medical evidence is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError
        raise SimulationEvidenceImmutableError("Match medical evidence is immutable.")

    def __str__(self):
        return f"Medical evidence / {self.match_id}"


class ClubHomeStadium(models.Model):
    """Scheduling-facing home stadium profile.

    This is deliberately not the future tradable/NFT stadium asset. It is the
    minimal venue identity needed to schedule real local kickoff times today;
    a future asset model can point to or replace this profile cleanly.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    club = models.OneToOneField(
        "clubs.Club", on_delete=models.PROTECT, related_name="home_stadium_profile"
    )
    name = models.CharField(max_length=140)
    timezone_name = models.CharField(max_length=64, blank=True, default="")
    kickoff_time_override = models.TimeField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["club__name"]

    def clean(self):
        from django.core.exceptions import ValidationError
        if self.timezone_name:
            try:
                self.timezone_name = KickoffSchedulingPolicyV1.validate_timezone_name(self.timezone_name)
            except ValueError as exc:
                raise ValidationError({"timezone_name": str(exc)}) from exc

    def save(self, *args, **kwargs):
        self.full_clean()
        return super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.name} / {self.club}"


class _ImmutableScheduleEvidenceQuerySet(models.QuerySet):
    def update(self, **kwargs):
        from .exceptions import MatchScheduleEvidenceError
        raise MatchScheduleEvidenceError("Match schedule revision evidence is immutable.")

    def delete(self):
        from .exceptions import MatchScheduleEvidenceError
        raise MatchScheduleEvidenceError("Match schedule revision evidence is immutable.")


class MatchSportingResolution(models.Model):
    """Immutable sporting resolution for event-aware engine matches.

    Match.home_score/away_score remain football goals (including extra time)
    and never include penalty-shootout kicks.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.OneToOneField(
        Match, on_delete=models.PROTECT, related_name="sporting_resolution"
    )
    decision_stage = models.CharField(
        max_length=16, choices=SportingDecisionStage.choices
    )
    regulation_home_score = models.PositiveSmallIntegerField()
    regulation_away_score = models.PositiveSmallIntegerField()
    extra_time_home_goals = models.PositiveSmallIntegerField(default=0)
    extra_time_away_goals = models.PositiveSmallIntegerField(default=0)
    home_penalties = models.PositiveSmallIntegerField(null=True, blank=True)
    away_penalties = models.PositiveSmallIntegerField(null=True, blank=True)
    engine_key = models.CharField(max_length=64)
    engine_version = models.CharField(max_length=64)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        constraints = [
            models.CheckConstraint(
                condition=Q(decision_stage__in=SportingDecisionStage.values),
                name="sport_resolution_valid_stage",
            ),
            models.CheckConstraint(
                condition=(
                    Q(decision_stage=SportingDecisionStage.PENALTIES, home_penalties__isnull=False, away_penalties__isnull=False)
                    | Q(decision_stage__in=[SportingDecisionStage.REGULATION, SportingDecisionStage.EXTRA_TIME], home_penalties__isnull=True, away_penalties__isnull=True)
                ),
                name="sport_resolution_penalty_shape",
            ),
            models.CheckConstraint(condition=~Q(engine_key=""), name="sport_resolution_engine_key"),
            models.CheckConstraint(condition=~Q(engine_version=""), name="sport_resolution_engine_ver"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="sport_resolution_hash"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError
            raise SimulationEvidenceImmutableError("Sporting resolution is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError
        raise SimulationEvidenceImmutableError("Sporting resolution is immutable.")


class MatchScheduleRevision(models.Model):
    """Immutable audit record for every authoritative kickoff assignment."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.ForeignKey(Match, on_delete=models.PROTECT, related_name="schedule_revisions")
    revision_number = models.PositiveSmallIntegerField()
    calendar_slot = models.ForeignKey(
        "seasons.SeasonCompetitionCalendarSlot",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="match_schedule_revisions",
    )
    previous_scheduled_at = models.DateTimeField(null=True, blank=True)
    scheduled_at = models.DateTimeField()
    timezone_name = models.CharField(max_length=64)
    reason = models.CharField(max_length=20, choices=MatchScheduleReason.choices)
    reason_text = models.CharField(max_length=500, blank=True, default="")
    policy_key = models.CharField(max_length=100)
    policy_version = models.CharField(max_length=30)
    schema_version = models.PositiveSmallIntegerField(default=1)
    evidence_hash = models.CharField(max_length=64)
    performed_by = models.ForeignKey(
        "users.User", on_delete=models.PROTECT, null=True, blank=True,
        related_name="match_schedule_revisions",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableScheduleEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "revision_number"]
        constraints = [
            models.UniqueConstraint(
                fields=["match", "revision_number"], name="uq_match_schedule_revision_no"
            ),
            models.CheckConstraint(
                condition=Q(revision_number__gte=1), name="match_sched_rev_gte_1"
            ),
            models.CheckConstraint(
                condition=Q(schema_version__gte=1), name="match_sched_schema_gte_1"
            ),
            models.CheckConstraint(
                condition=~Q(evidence_hash=""), name="match_sched_hash_nonempty"
            ),
        ]
        indexes = [
            models.Index(fields=["match", "created_at"], name="match_sched_match_idx"),
            models.Index(fields=["scheduled_at"], name="match_sched_time_idx"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import MatchScheduleEvidenceError
            raise MatchScheduleEvidenceError("Match schedule revision evidence is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import MatchScheduleEvidenceError
        raise MatchScheduleEvidenceError("Match schedule revision evidence is immutable.")


# ---------------------------------------------------------------------------
# Matchday operations / pre-match foundation
# ---------------------------------------------------------------------------
from .constants import (
    MatchdayAttendanceStatus,
    MatchdayAuditEventType,
    MatchdayOperationStatus,
    MatchdayReadinessStatus,
    MatchPlayerSuspensionReason,
)
from .matchday_policy import MatchdayOperationsPolicyV1


class MatchdayOperationsProfile(models.Model):
    """Country-level pre-match operational defaults.

    Values are copied onto MatchdayOperation at preparation time so later
    profile edits never rewrite historical deadlines or evidence.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    country = models.CharField(max_length=80)
    lineup_deadline_minutes = models.PositiveSmallIntegerField(default=60)
    checkin_open_minutes = models.PositiveSmallIntegerField(default=120)
    checkin_deadline_minutes = models.PositiveSmallIntegerField(default=15)
    max_delay_minutes = models.PositiveSmallIntegerField(default=15)
    auto_start_enabled = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["country"]
        constraints = [
            models.UniqueConstraint(Lower("country"), name="uq_matchday_profile_country_ci"),
            models.CheckConstraint(
                condition=Q(lineup_deadline_minutes__gte=15, lineup_deadline_minutes__lte=360),
                name="matchday_lineup_dl_15_360",
            ),
            models.CheckConstraint(
                condition=Q(checkin_open_minutes__gte=30, checkin_open_minutes__lte=360),
                name="matchday_checkin_open_30_360",
            ),
            models.CheckConstraint(
                condition=Q(checkin_deadline_minutes__gte=0, checkin_deadline_minutes__lte=120),
                name="matchday_checkin_dl_0_120",
            ),
            models.CheckConstraint(
                condition=Q(max_delay_minutes__gte=0, max_delay_minutes__lte=120),
                name="matchday_delay_0_120",
            ),
            models.CheckConstraint(
                condition=Q(checkin_open_minutes__gt=F("checkin_deadline_minutes")),
                name="matchday_profile_open_order",
            ),
            models.CheckConstraint(
                condition=Q(lineup_deadline_minutes__gte=F("checkin_deadline_minutes")),
                name="matchday_lineup_checkin_order",
            ),
        ]

    def clean(self):
        from django.core.exceptions import ValidationError

        try:
            MatchdayOperationsPolicyV1.validate_parameters(
                lineup_deadline_minutes=self.lineup_deadline_minutes,
                checkin_open_minutes=self.checkin_open_minutes,
                checkin_deadline_minutes=self.checkin_deadline_minutes,
                max_delay_minutes=self.max_delay_minutes,
            )
        except (TypeError, ValueError) as exc:
            raise ValidationError(str(exc)) from exc

    def save(self, *args, **kwargs):
        self.full_clean()
        return super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.country} matchday operations"


class MatchdayOperation(models.Model):
    """Mutable operational aggregate for one scheduled Match.

    Audit facts are append-only in MatchdayAuditEvent / eligibility checks.
    The aggregate stores only current state for efficient workers/selectors.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.OneToOneField(
        Match, on_delete=models.PROTECT, related_name="matchday_operation"
    )
    profile = models.ForeignKey(
        MatchdayOperationsProfile,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="operations",
    )
    status = models.CharField(
        max_length=24,
        choices=MatchdayOperationStatus.choices,
        default=MatchdayOperationStatus.OPEN,
    )
    lineup_deadline_minutes = models.PositiveSmallIntegerField()
    checkin_open_minutes = models.PositiveSmallIntegerField()
    checkin_deadline_minutes = models.PositiveSmallIntegerField()
    max_delay_minutes = models.PositiveSmallIntegerField()
    auto_start_enabled = models.BooleanField(default=True)
    lineup_deadline_at = models.DateTimeField()
    checkin_opens_at = models.DateTimeField()
    checkin_deadline_at = models.DateTimeField()
    kickoff_at = models.DateTimeField()
    grace_deadline_at = models.DateTimeField()
    policy_key = models.CharField(max_length=100)
    policy_version = models.CharField(max_length=30)
    schema_version = models.PositiveSmallIntegerField(default=1)
    prepared_at = models.DateTimeField(auto_now_add=True)
    deadline_processed_at = models.DateTimeField(null=True, blank=True)
    ready_at = models.DateTimeField(null=True, blank=True)
    started_at = models.DateTimeField(null=True, blank=True)
    closed_at = models.DateTimeField(null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["kickoff_at", "match_id"]
        indexes = [
            models.Index(fields=["status", "kickoff_at"], name="matchday_status_kickoff_idx"),
            models.Index(fields=["lineup_deadline_at"], name="matchday_lineup_deadline_idx"),
            models.Index(fields=["grace_deadline_at"], name="matchday_grace_deadline_idx"),
        ]
        constraints = [
            models.CheckConstraint(
                condition=Q(status__in=MatchdayOperationStatus.values),
                name="matchday_valid_status",
            ),
            models.CheckConstraint(
                condition=Q(schema_version__gte=1), name="matchday_schema_gte_1"
            ),
            models.CheckConstraint(
                condition=Q(checkin_opens_at__lte=F("checkin_deadline_at")),
                name="matchday_operation_open_order",
            ),
            models.CheckConstraint(
                condition=Q(lineup_deadline_at__lte=F("checkin_deadline_at")),
                name="matchday_lineup_deadline_order",
            ),
            models.CheckConstraint(
                condition=Q(checkin_deadline_at__lte=F("kickoff_at")),
                name="matchday_checkin_pre_kickoff",
            ),
            models.CheckConstraint(
                condition=Q(kickoff_at__lte=F("grace_deadline_at")),
                name="matchday_grace_after_kickoff",
            ),
            models.CheckConstraint(condition=~Q(policy_key=""), name="matchday_policy_key_nonempty"),
            models.CheckConstraint(condition=~Q(policy_version=""), name="matchday_policy_ver_nonempty"),
        ]

    def __str__(self):
        return f"Matchday {self.match_id} / {self.status}"


class MatchdayTeamState(models.Model):
    """Current attendance/readiness state for one fixture participant."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    operation = models.ForeignKey(
        MatchdayOperation, on_delete=models.CASCADE, related_name="team_states"
    )
    club = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="matchday_team_states"
    )
    attendance_status = models.CharField(
        max_length=12,
        choices=MatchdayAttendanceStatus.choices,
        default=MatchdayAttendanceStatus.PENDING,
    )
    readiness_status = models.CharField(
        max_length=12,
        choices=MatchdayReadinessStatus.choices,
        default=MatchdayReadinessStatus.PENDING,
    )
    checked_in_at = models.DateTimeField(null=True, blank=True)
    checked_in_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="matchday_checkins",
    )
    readiness_checked_at = models.DateTimeField(null=True, blank=True)
    block_reason = models.CharField(max_length=500, blank=True, default="")
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["operation_id", "club_id"]
        constraints = [
            models.UniqueConstraint(
                fields=["operation", "club"], name="uq_matchday_operation_club"
            ),
            models.CheckConstraint(
                condition=Q(attendance_status__in=MatchdayAttendanceStatus.values),
                name="matchday_valid_attendance",
            ),
            models.CheckConstraint(
                condition=Q(readiness_status__in=MatchdayReadinessStatus.values),
                name="matchday_valid_readiness",
            ),
        ]
        indexes = [
            models.Index(fields=["operation", "readiness_status"], name="matchday_team_ready_idx"),
            models.Index(fields=["club", "attendance_status"], name="matchday_club_attend_idx"),
        ]

    def __str__(self):
        return f"{self.operation.match_id} / {self.club_id} / {self.readiness_status}"


class _ImmutableMatchdayEvidenceQuerySet(models.QuerySet):
    def update(self, **kwargs):
        from .exceptions import MatchdayEvidenceImmutableError
        raise MatchdayEvidenceImmutableError("Matchday evidence is immutable.")

    def delete(self):
        from .exceptions import MatchdayEvidenceImmutableError
        raise MatchdayEvidenceImmutableError("Matchday evidence is immutable.")


class PlayerMatchSuspension(models.Model):
    """A match-scoped suspension consumed by pre-match eligibility checks.

    Discipline/card accumulation can be implemented later by creating these
    immutable assignments for the affected future matches.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.ForeignKey(
        Match, on_delete=models.PROTECT, related_name="player_suspensions"
    )
    player = models.ForeignKey(
        "players.Player", on_delete=models.PROTECT, related_name="match_suspensions"
    )
    reason = models.CharField(max_length=24, choices=MatchPlayerSuspensionReason.choices)
    reason_text = models.CharField(max_length=500, blank=True, default="")
    source_type = models.CharField(max_length=50, blank=True, default="")
    source_id = models.CharField(max_length=100, blank=True, default="")
    issued_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="issued_match_suspensions",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "player_id"]
        constraints = [
            models.UniqueConstraint(fields=["match", "player"], name="uq_match_player_suspension"),
            models.CheckConstraint(
                condition=Q(reason__in=MatchPlayerSuspensionReason.values),
                name="match_suspension_valid_reason",
            ),
        ]
        indexes = [
            models.Index(fields=["match", "player"], name="match_susp_match_player_idx"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import MatchdayEvidenceImmutableError
            raise MatchdayEvidenceImmutableError("Match suspension assignments are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import MatchdayEvidenceImmutableError
        raise MatchdayEvidenceImmutableError("Match suspension assignments are immutable.")


class PlayerMatchSuspensionRevocation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    suspension = models.OneToOneField(
        PlayerMatchSuspension,
        on_delete=models.PROTECT,
        related_name="revocation",
    )
    reason_text = models.CharField(max_length=500)
    revoked_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="revoked_match_suspensions",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import MatchdayEvidenceImmutableError
            raise MatchdayEvidenceImmutableError("Suspension revocations are immutable.")
        if not (self.reason_text or "").strip():
            from django.core.exceptions import ValidationError
            raise ValidationError({"reason_text": "Revocation requires a reason."})
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import MatchdayEvidenceImmutableError
        raise MatchdayEvidenceImmutableError("Suspension revocations are immutable.")


class MatchdayEligibilityCheck(models.Model):
    """Append-only eligibility result for a team at one point in time."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    operation = models.ForeignKey(
        MatchdayOperation, on_delete=models.PROTECT, related_name="eligibility_checks"
    )
    club = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="matchday_eligibility_checks"
    )
    revision_number = models.PositiveSmallIntegerField()
    eligible = models.BooleanField()
    payload = models.JSONField()
    evidence_hash = models.CharField(max_length=64)
    policy_key = models.CharField(max_length=100)
    policy_version = models.CharField(max_length=30)
    schema_version = models.PositiveSmallIntegerField(default=1)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["operation_id", "club_id", "revision_number"]
        constraints = [
            models.UniqueConstraint(
                fields=["operation", "club", "revision_number"],
                name="uq_matchday_elig_revision",
            ),
            models.CheckConstraint(condition=Q(revision_number__gte=1), name="matchday_elig_rev_gte_1"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="matchday_elig_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import MatchdayEvidenceImmutableError
            raise MatchdayEvidenceImmutableError("Eligibility checks are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import MatchdayEvidenceImmutableError
        raise MatchdayEvidenceImmutableError("Eligibility checks are immutable.")


class MatchdayAuditEvent(models.Model):
    """Append-only state transition/evidence log for MatchdayOperation."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    operation = models.ForeignKey(
        MatchdayOperation, on_delete=models.PROTECT, related_name="audit_events"
    )
    sequence = models.PositiveSmallIntegerField()
    event_type = models.CharField(max_length=24, choices=MatchdayAuditEventType.choices)
    club = models.ForeignKey(
        "clubs.Club",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="matchday_audit_events",
    )
    payload = models.JSONField(default=dict)
    evidence_hash = models.CharField(max_length=64)
    performed_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="matchday_audit_events",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["operation_id", "sequence"]
        constraints = [
            models.UniqueConstraint(
                fields=["operation", "sequence"], name="uq_matchday_audit_sequence"
            ),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="matchday_audit_seq_gte_1"),
            models.CheckConstraint(
                condition=Q(event_type__in=MatchdayAuditEventType.values),
                name="matchday_audit_valid_type",
            ),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="matchday_audit_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import MatchdayEvidenceImmutableError
            raise MatchdayEvidenceImmutableError("Matchday audit events are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import MatchdayEvidenceImmutableError
        raise MatchdayEvidenceImmutableError("Matchday audit events are immutable.")


# ---------------------------------------------------------------------------
# Competition discipline / cards foundation
# ---------------------------------------------------------------------------
class CompetitionDisciplineProfile(models.Model):
    """Per-competition override for the versioned default discipline policy."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    league_competition = models.OneToOneField(
        "leagues.LeagueCompetition",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="discipline_profile",
    )
    federation_competition = models.OneToOneField(
        "federations.FederationCompetition",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="discipline_profile",
    )
    yellow_threshold = models.PositiveSmallIntegerField(default=3)
    yellow_suspension_matches = models.PositiveSmallIntegerField(default=1)
    direct_red_suspension_matches = models.PositiveSmallIntegerField(default=1)
    second_yellow_suspension_matches = models.PositiveSmallIntegerField(default=1)
    second_yellow_counts_toward_accumulation = models.BooleanField(default=False)
    forfeit_score_for = models.PositiveSmallIntegerField(default=3)
    forfeit_score_against = models.PositiveSmallIntegerField(default=0)
    auto_no_show_forfeit = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.CheckConstraint(
                condition=(
                    Q(league_competition__isnull=False, federation_competition__isnull=True)
                    | Q(league_competition__isnull=True, federation_competition__isnull=False)
                ),
                name="discipline_profile_exactly_one_comp",
            ),
            models.CheckConstraint(
                condition=Q(yellow_threshold__gte=1),
                name="discipline_yellow_threshold_gte_1",
            ),
            models.CheckConstraint(
                condition=Q(yellow_suspension_matches__gte=1),
                name="discipline_yellow_ban_gte_1",
            ),
            models.CheckConstraint(
                condition=Q(direct_red_suspension_matches__gte=1),
                name="discipline_red_ban_gte_1",
            ),
            models.CheckConstraint(
                condition=Q(second_yellow_suspension_matches__gte=1),
                name="discipline_second_yellow_ban_gte_1",
            ),
            models.CheckConstraint(
                condition=Q(forfeit_score_for__gt=F("forfeit_score_against")),
                name="discipline_forfeit_winner_gt_loser",
            ),
        ]

    def __str__(self):
        source = self.league_competition_id or self.federation_competition_id
        return f"Discipline profile {source}"


class DisciplinaryCardEvent(models.Model):
    """Immutable official card event used as discipline evidence."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.ForeignKey(Match, on_delete=models.PROTECT, related_name="disciplinary_cards")
    player = models.ForeignKey(
        "players.Player", on_delete=models.PROTECT, related_name="disciplinary_cards"
    )
    club = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="disciplinary_cards"
    )
    sequence = models.PositiveSmallIntegerField()
    minute = models.PositiveSmallIntegerField()
    card_type = models.CharField(max_length=20, choices=DisciplinaryCardType.choices)
    source = models.CharField(
        max_length=20,
        choices=DisciplinaryCardSource.choices,
        default=DisciplinaryCardSource.REFEREE,
    )
    source_match_event = models.OneToOneField(
        MatchEvent,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="disciplinary_card",
    )
    evidence_hash = models.CharField(max_length=64)
    recorded_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="recorded_disciplinary_cards",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "sequence"]
        constraints = [
            models.UniqueConstraint(fields=["match", "sequence"], name="uq_discipline_card_sequence"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="discipline_card_seq_gte_1"),
            models.CheckConstraint(
                condition=Q(minute__gte=1, minute__lte=120),
                name="discipline_card_minute_1_120",
            ),
            models.CheckConstraint(
                condition=Q(card_type__in=DisciplinaryCardType.values),
                name="discipline_card_valid_type",
            ),
            models.CheckConstraint(
                condition=Q(source__in=DisciplinaryCardSource.values),
                name="discipline_card_valid_source",
            ),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="discipline_card_hash_nonempty"),
        ]
        indexes = [
            models.Index(fields=["player", "match"], name="discipline_card_pl_match_idx"),
            models.Index(fields=["club", "match"], name="discipline_card_club_match_idx"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Disciplinary card events are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Disciplinary card events are immutable.")


class DisciplinaryCardRevocation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    card = models.OneToOneField(
        DisciplinaryCardEvent, on_delete=models.PROTECT, related_name="revocation"
    )
    reason_text = models.CharField(max_length=500)
    revoked_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="revoked_disciplinary_cards",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Card revocations are immutable.")
        if not (self.reason_text or "").strip():
            from django.core.exceptions import ValidationError
            raise ValidationError({"reason_text": "Card revocation requires a reason."})
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Card revocations are immutable.")


class PlayerDisciplinarySanction(models.Model):
    """Immutable competition-scoped suspension debt for a player."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    player = models.ForeignKey(
        "players.Player", on_delete=models.PROTECT, related_name="disciplinary_sanctions"
    )
    club_at_issue = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="player_disciplinary_sanctions"
    )
    league_competition = models.ForeignKey(
        "leagues.LeagueCompetition",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="player_disciplinary_sanctions",
    )
    federation_competition = models.ForeignKey(
        "federations.FederationCompetition",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="player_disciplinary_sanctions",
    )
    source_match = models.ForeignKey(
        Match, on_delete=models.PROTECT, related_name="issued_disciplinary_sanctions"
    )
    source_card = models.ForeignKey(
        DisciplinaryCardEvent,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="sanctions",
    )
    sanction_type = models.CharField(max_length=24, choices=DisciplinarySanctionType.choices)
    matches_total = models.PositiveSmallIntegerField()
    semantic_key = models.CharField(max_length=180, unique=True)
    policy_key = models.CharField(max_length=100)
    policy_version = models.CharField(max_length=30)
    schema_version = models.PositiveSmallIntegerField(default=1)
    evidence_hash = models.CharField(max_length=64)
    issued_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="issued_disciplinary_sanctions",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["created_at", "id"]
        constraints = [
            models.CheckConstraint(
                condition=(
                    Q(league_competition__isnull=False, federation_competition__isnull=True)
                    | Q(league_competition__isnull=True, federation_competition__isnull=False)
                ),
                name="discipline_sanction_exactly_one_comp",
            ),
            models.CheckConstraint(
                condition=Q(sanction_type__in=DisciplinarySanctionType.values),
                name="discipline_sanction_valid_type",
            ),
            models.CheckConstraint(condition=Q(matches_total__gte=1), name="discipline_sanction_matches_gte_1"),
            models.CheckConstraint(condition=~Q(semantic_key=""), name="discipline_sanction_key_nonempty"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="discipline_sanction_hash_nonempty"),
        ]
        indexes = [
            models.Index(fields=["player", "league_competition"], name="discipline_san_pl_league_idx"),
            models.Index(fields=["player", "federation_competition"], name="discipline_sanction_pl_fed_idx"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Disciplinary sanctions are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Disciplinary sanctions are immutable.")


class DisciplinarySuspensionAssignment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sanction = models.ForeignKey(
        PlayerDisciplinarySanction,
        on_delete=models.PROTECT,
        related_name="assignments",
    )
    suspension = models.OneToOneField(
        PlayerMatchSuspension,
        on_delete=models.PROTECT,
        related_name="discipline_assignment",
    )
    ordinal = models.PositiveSmallIntegerField()
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["sanction_id", "ordinal"]
        constraints = [
            models.UniqueConstraint(fields=["sanction", "ordinal"], name="uq_discipline_sanction_assignment_ord"),
            models.CheckConstraint(condition=Q(ordinal__gte=1), name="discipline_assignment_ord_gte_1"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Suspension assignments are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Suspension assignments are immutable.")


class DisciplinarySanctionRevocation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sanction = models.OneToOneField(
        PlayerDisciplinarySanction, on_delete=models.PROTECT, related_name="revocation"
    )
    reason_text = models.CharField(max_length=500)
    revoked_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="revoked_disciplinary_sanctions",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Sanction revocations are immutable.")
        if not (self.reason_text or "").strip():
            from django.core.exceptions import ValidationError
            raise ValidationError({"reason_text": "Sanction revocation requires a reason."})
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Sanction revocations are immutable.")


class DisciplinaryAppeal(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sanction = models.OneToOneField(
        PlayerDisciplinarySanction, on_delete=models.PROTECT, related_name="appeal"
    )
    reason_text = models.CharField(max_length=1000)
    submitted_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="submitted_disciplinary_appeals",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Disciplinary appeals are immutable.")
        if not (self.reason_text or "").strip():
            from django.core.exceptions import ValidationError
            raise ValidationError({"reason_text": "Appeal requires a reason."})
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Disciplinary appeals are immutable.")


class DisciplinaryAppealDecision(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    appeal = models.OneToOneField(
        DisciplinaryAppeal, on_delete=models.PROTECT, related_name="decision"
    )
    outcome = models.CharField(
        max_length=12, choices=DisciplinaryAppealDecisionOutcome.choices
    )
    reason_text = models.CharField(max_length=1000)
    decided_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="disciplinary_appeal_decisions",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        constraints = [
            models.CheckConstraint(
                condition=Q(outcome__in=DisciplinaryAppealDecisionOutcome.values),
                name="discipline_appeal_valid_outcome",
            )
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Appeal decisions are immutable.")
        if not (self.reason_text or "").strip():
            from django.core.exceptions import ValidationError
            raise ValidationError({"reason_text": "Appeal decision requires a reason."})
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Appeal decisions are immutable.")


class DisciplineProcessingRun(models.Model):
    """Immutable proof that one completed played match was discipline-finalized."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.OneToOneField(
        Match, on_delete=models.PROTECT, related_name="discipline_processing_run"
    )
    card_count = models.PositiveSmallIntegerField(default=0)
    sanction_count = models.PositiveSmallIntegerField(default=0)
    policy_payload = models.JSONField(default=dict)
    evidence_payload = models.JSONField(default=dict)
    evidence_hash = models.CharField(max_length=64)
    processed_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="discipline_processing_runs",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        constraints = [
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="discipline_run_hash_nonempty")
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Discipline processing runs are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Discipline processing runs are immutable.")


class MatchAdministrativeDecision(models.Model):
    """Immutable administrative result replacing unplayed sporting resolution."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.OneToOneField(
        Match, on_delete=models.PROTECT, related_name="administrative_decision"
    )
    reason = models.CharField(max_length=24, choices=AdministrativeDecisionReason.choices)
    outcome = models.CharField(max_length=16, choices=AdministrativeDecisionOutcome.choices)
    home_score = models.PositiveSmallIntegerField()
    away_score = models.PositiveSmallIntegerField()
    reason_text = models.CharField(max_length=1000, blank=True, default="")
    policy_payload = models.JSONField(default=dict)
    evidence_hash = models.CharField(max_length=64)
    decided_by = models.ForeignKey(
        "users.User",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        related_name="match_administrative_decisions",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableMatchdayEvidenceQuerySet.as_manager()

    class Meta:
        constraints = [
            models.CheckConstraint(
                condition=Q(reason__in=AdministrativeDecisionReason.values),
                name="admin_decision_valid_reason",
            ),
            models.CheckConstraint(
                condition=Q(outcome__in=AdministrativeDecisionOutcome.values),
                name="admin_decision_valid_outcome",
            ),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="admin_decision_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import DisciplineEvidenceImmutableError
            raise DisciplineEvidenceImmutableError("Administrative decisions are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import DisciplineEvidenceImmutableError
        raise DisciplineEvidenceImmutableError("Administrative decisions are immutable.")

# ---------------------------------------------------------------------------
# Live tactics & match intelligence
# ---------------------------------------------------------------------------


class MatchTacticalPlan(models.Model):
    """Editable pre-kickoff tactical plan bound to one lineup.

    The two strategy axes are intentionally independent: every team always has
    one attacking and one defensive strategy active at the same time.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    lineup = models.OneToOneField(
        MatchLineup, on_delete=models.PROTECT, related_name="tactical_plan"
    )
    attacking_strategy = models.CharField(
        max_length=24, choices=AttackingStrategy.choices, default=AttackingStrategy.BALANCED
    )
    defensive_strategy = models.CharField(
        max_length=24, choices=DefensiveStrategy.choices, default=DefensiveStrategy.BALANCED
    )
    adaptation_mode = models.CharField(
        max_length=16, choices=TacticalAdaptationMode.choices,
        default=TacticalAdaptationMode.BALANCED,
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["lineup__match_id", "lineup__club_id"]
        constraints = [
            models.CheckConstraint(
                condition=Q(attacking_strategy__in=AttackingStrategy.values),
                name="tactic_plan_valid_attack",
            ),
            models.CheckConstraint(
                condition=Q(defensive_strategy__in=DefensiveStrategy.values),
                name="tactic_plan_valid_defence",
            ),
            models.CheckConstraint(
                condition=Q(adaptation_mode__in=TacticalAdaptationMode.values),
                name="tactic_plan_valid_adapt",
            ),
        ]

    def __str__(self):
        return (
            f"{self.lineup_id}: {self.attacking_strategy}/"
            f"{self.defensive_strategy} ({self.adaptation_mode})"
        )


class MatchTacticalInstruction(models.Model):
    """One preconfigured live tactical rule evaluated by the pure engine."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    plan = models.ForeignKey(
        MatchTacticalPlan, on_delete=models.CASCADE, related_name="instructions"
    )
    priority = models.PositiveSmallIntegerField()
    trigger_type = models.CharField(max_length=24, choices=TacticalTriggerType.choices)
    minute_from = models.PositiveSmallIntegerField(default=1)
    attacking_strategy = models.CharField(max_length=24, choices=AttackingStrategy.choices)
    defensive_strategy = models.CharField(max_length=24, choices=DefensiveStrategy.choices)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["plan_id", "priority", "id"]
        constraints = [
            models.UniqueConstraint(fields=["plan", "priority"], name="uq_tactic_plan_priority"),
            models.CheckConstraint(
                condition=Q(priority__gte=1, priority__lte=100),
                name="tactic_instruction_priority_1_100",
            ),
            models.CheckConstraint(
                condition=Q(minute_from__gte=1, minute_from__lte=120),
                name="tactic_instruction_minute_1_120",
            ),
            models.CheckConstraint(
                condition=Q(trigger_type__in=TacticalTriggerType.values),
                name="tactic_instruction_valid_trigger",
            ),
            models.CheckConstraint(
                condition=Q(attacking_strategy__in=AttackingStrategy.values),
                name="tactic_instruction_valid_attack",
            ),
            models.CheckConstraint(
                condition=Q(defensive_strategy__in=DefensiveStrategy.values),
                name="tactic_instruction_valid_defence",
            ),
        ]


class MatchTacticalContextSnapshot(models.Model):
    """Immutable kickoff evidence for tactics, staff and opponent intelligence."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.ForeignKey(Match, on_delete=models.PROTECT, related_name="tactical_contexts")
    club = models.ForeignKey("clubs.Club", on_delete=models.PROTECT, related_name="match_tactical_contexts")
    lineup = models.OneToOneField(MatchLineup, on_delete=models.PROTECT, related_name="tactical_context_snapshot")
    plan = models.ForeignKey(
        MatchTacticalPlan, null=True, blank=True, on_delete=models.PROTECT,
        related_name="context_snapshots",
    )
    head_coach_assignment = models.ForeignKey(
        "staff.ClubStaffAssignment", null=True, blank=True, on_delete=models.PROTECT, related_name="+"
    )
    assistant_coach_assignment = models.ForeignKey(
        "staff.ClubStaffAssignment", null=True, blank=True, on_delete=models.PROTECT, related_name="+"
    )
    analyst_assignment = models.ForeignKey(
        "staff.ClubStaffAssignment", null=True, blank=True, on_delete=models.PROTECT, related_name="+"
    )
    attacking_strategy = models.CharField(max_length=24, choices=AttackingStrategy.choices)
    defensive_strategy = models.CharField(max_length=24, choices=DefensiveStrategy.choices)
    adaptation_mode = models.CharField(max_length=16, choices=TacticalAdaptationMode.choices)
    coaching_quality = models.DecimalField(max_digits=6, decimal_places=3)
    analysis_quality = models.PositiveSmallIntegerField(default=0)
    context_payload = models.JSONField()
    context_hash = models.CharField(max_length=64)
    policy_key = models.CharField(max_length=100, default=LIVE_TACTICS_POLICY_KEY)
    policy_version = models.CharField(max_length=30, default=LIVE_TACTICS_POLICY_VERSION)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "club_id"]
        constraints = [
            models.UniqueConstraint(fields=["match", "club"], name="uq_match_tactic_context_club"),
            models.CheckConstraint(condition=Q(attacking_strategy__in=AttackingStrategy.values), name="tactic_context_valid_attack"),
            models.CheckConstraint(condition=Q(defensive_strategy__in=DefensiveStrategy.values), name="tactic_context_valid_defence"),
            models.CheckConstraint(condition=Q(adaptation_mode__in=TacticalAdaptationMode.values), name="tactic_context_valid_adapt"),
            models.CheckConstraint(
                condition=Q(analysis_quality__gte=0, analysis_quality__lte=100),
                name="tactic_context_analysis_0_100",
            ),
            models.CheckConstraint(condition=~Q(context_hash=""), name="tactic_context_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import TacticalEvidenceImmutableError
            raise TacticalEvidenceImmutableError("Tactical context snapshots are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import TacticalEvidenceImmutableError
        raise TacticalEvidenceImmutableError("Tactical context snapshots are immutable.")


class MatchTacticalDecision(models.Model):
    """Immutable tactical transition emitted by Match Engine v2.1/v2.2."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    run = models.ForeignKey(MatchSimulationRun, on_delete=models.PROTECT, related_name="tactical_decisions")
    match = models.ForeignKey(Match, on_delete=models.PROTECT, related_name="tactical_decisions")
    club = models.ForeignKey("clubs.Club", on_delete=models.PROTECT, related_name="match_tactical_decisions")
    live_command = models.ForeignKey(
        "matches.LiveMatchCommand", null=True, blank=True, on_delete=models.PROTECT,
        related_name="tactical_decisions",
    )
    sequence = models.PositiveSmallIntegerField()
    minute = models.PositiveSmallIntegerField()
    phase = models.CharField(max_length=16, choices=MatchEventPhase.choices)
    source = models.CharField(max_length=20, choices=TacticalDecisionSource.choices)
    trigger_type = models.CharField(max_length=24, choices=TacticalTriggerType.choices)
    previous_attacking_strategy = models.CharField(max_length=24, choices=AttackingStrategy.choices)
    previous_defensive_strategy = models.CharField(max_length=24, choices=DefensiveStrategy.choices)
    attacking_strategy = models.CharField(max_length=24, choices=AttackingStrategy.choices)
    defensive_strategy = models.CharField(max_length=24, choices=DefensiveStrategy.choices)
    home_score = models.PositiveSmallIntegerField()
    away_score = models.PositiveSmallIntegerField()
    own_red_cards = models.PositiveSmallIntegerField(default=0)
    opponent_red_cards = models.PositiveSmallIntegerField(default=0)
    effect_payload = models.JSONField(default=dict)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "sequence"]
        constraints = [
            models.UniqueConstraint(fields=["match", "sequence"], name="uq_match_tactical_decision_seq"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="tactic_decision_seq_gte1"),
            models.CheckConstraint(condition=Q(minute__gte=1, minute__lte=120), name="tactic_decision_minute_1_120"),
            models.CheckConstraint(
                condition=Q(source__in=TacticalDecisionSource.values),
                name="tactic_decision_valid_source",
            ),
            models.CheckConstraint(
                condition=Q(trigger_type__in=TacticalTriggerType.values),
                name="tactic_decision_valid_trigger",
            ),
            models.CheckConstraint(condition=Q(phase__in=MatchEventPhase.values), name="tactic_decision_valid_phase"),
            models.CheckConstraint(condition=Q(previous_attacking_strategy__in=AttackingStrategy.values), name="tactic_decision_prev_attack"),
            models.CheckConstraint(condition=Q(previous_defensive_strategy__in=DefensiveStrategy.values), name="tactic_decision_prev_defence"),
            models.CheckConstraint(condition=Q(attacking_strategy__in=AttackingStrategy.values), name="tactic_decision_valid_attack"),
            models.CheckConstraint(condition=Q(defensive_strategy__in=DefensiveStrategy.values), name="tactic_decision_valid_defence"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="tactic_decision_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import TacticalEvidenceImmutableError
            raise TacticalEvidenceImmutableError("Tactical decisions are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import TacticalEvidenceImmutableError
        raise TacticalEvidenceImmutableError("Tactical decisions are immutable.")


class MatchDefensiveEvent(models.Model):
    """Immutable normalized defensive/goalkeeper event emitted by v3.6+."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    run = models.ForeignKey(
        MatchSimulationRun, on_delete=models.PROTECT, related_name="defensive_events"
    )
    match = models.ForeignKey(
        Match, on_delete=models.PROTECT, related_name="defensive_events"
    )
    sequence = models.PositiveSmallIntegerField()
    minute = models.PositiveSmallIntegerField()
    phase = models.CharField(max_length=16, choices=MatchEventPhase.choices)
    event_type = models.CharField(max_length=32, choices=DefensiveEventType.choices)
    defending_club = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="defensive_events_for"
    )
    attacking_club = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="defensive_events_against"
    )
    player = models.ForeignKey(
        "players.Player", on_delete=models.PROTECT, related_name="defensive_events",
        null=True, blank=True,
    )
    opponent_player = models.ForeignKey(
        "players.Player", on_delete=models.PROTECT, related_name="opponent_defensive_events",
        null=True, blank=True,
    )
    outcome = models.CharField(max_length=32, blank=True, default="")
    zone = models.CharField(max_length=32, blank=True, default="")
    detail_payload = models.JSONField(default=dict, blank=True)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "sequence"]
        indexes = [
            models.Index(fields=["match", "minute", "sequence"], name="def_event_match_time_idx"),
            models.Index(fields=["player", "match"], name="def_event_player_match_idx"),
            models.Index(fields=["defending_club", "match"], name="def_event_club_match_idx"),
        ]
        constraints = [
            models.UniqueConstraint(fields=["match", "sequence"], name="uq_match_defensive_event_seq"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="def_event_seq_gte1"),
            models.CheckConstraint(condition=Q(minute__gte=1, minute__lte=120), name="def_event_minute_1_120"),
            models.CheckConstraint(condition=Q(phase__in=MatchEventPhase.values), name="def_event_valid_phase"),
            models.CheckConstraint(condition=Q(event_type__in=DefensiveEventType.values), name="def_event_valid_type"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="def_event_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError
            raise SimulationEvidenceImmutableError("Defensive event evidence is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError
        raise SimulationEvidenceImmutableError("Defensive event evidence is immutable.")


class MatchPossessionEvent(models.Model):
    """Immutable normalized possession/spatial event emitted by v3.7+."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    run = models.ForeignKey(
        MatchSimulationRun, on_delete=models.PROTECT, related_name="possession_events"
    )
    match = models.ForeignKey(
        Match, on_delete=models.PROTECT, related_name="possession_events"
    )
    sequence = models.PositiveIntegerField()
    possession_sequence = models.PositiveIntegerField()
    action_sequence = models.PositiveSmallIntegerField()
    minute = models.PositiveSmallIntegerField()
    phase = models.CharField(max_length=16, choices=MatchEventPhase.choices)
    event_type = models.CharField(max_length=24, choices=PossessionEventType.choices)
    club = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="possession_events_for"
    )
    opponent_club = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="possession_events_against"
    )
    player = models.ForeignKey(
        "players.Player", on_delete=models.PROTECT, related_name="possession_events",
        null=True, blank=True,
    )
    target_player = models.ForeignKey(
        "players.Player", on_delete=models.PROTECT, related_name="target_possession_events",
        null=True, blank=True,
    )
    origin_zone = models.CharField(max_length=24)
    destination_zone = models.CharField(max_length=24)
    channel = models.CharField(max_length=12)
    outcome = models.CharField(max_length=32, blank=True, default="")
    transition_state = models.CharField(max_length=16, default="SETTLED")
    detail_payload = models.JSONField(default=dict, blank=True)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "sequence"]
        indexes = [
            models.Index(fields=["match", "possession_sequence", "action_sequence"], name="poss_evt_match_pos_idx"),
            models.Index(fields=["club", "match"], name="poss_evt_club_match_idx"),
            models.Index(fields=["player", "match"], name="poss_evt_player_match_idx"),
        ]
        constraints = [
            models.UniqueConstraint(fields=["match", "sequence"], name="uq_match_poss_event_seq"),
            models.UniqueConstraint(fields=["match", "possession_sequence", "action_sequence"], name="uq_match_poss_action"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="poss_evt_seq_gte1"),
            models.CheckConstraint(condition=Q(possession_sequence__gte=1), name="poss_evt_poss_gte1"),
            models.CheckConstraint(condition=Q(action_sequence__gte=1), name="poss_evt_action_gte1"),
            models.CheckConstraint(condition=Q(minute__gte=1, minute__lte=120), name="poss_evt_minute_1_120"),
            models.CheckConstraint(condition=Q(phase__in=MatchEventPhase.values), name="poss_evt_valid_phase"),
            models.CheckConstraint(condition=Q(event_type__in=PossessionEventType.values), name="poss_evt_valid_type"),
            models.CheckConstraint(condition=Q(origin_zone__in=["DEFENSIVE_THIRD", "MIDDLE_THIRD", "FINAL_THIRD", "PENALTY_AREA"]), name="poss_evt_valid_origin"),
            models.CheckConstraint(condition=Q(destination_zone__in=["DEFENSIVE_THIRD", "MIDDLE_THIRD", "FINAL_THIRD", "PENALTY_AREA"]), name="poss_evt_valid_dest"),
            models.CheckConstraint(condition=Q(channel__in=["LEFT", "CENTRE", "RIGHT"]), name="poss_evt_valid_channel"),
            models.CheckConstraint(condition=Q(transition_state__in=["SETTLED", "BUILDUP", "PROGRESSION", "COUNTER", "SECOND_BALL"]), name="poss_evt_valid_transition"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="poss_evt_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError
            raise SimulationEvidenceImmutableError("Possession event evidence is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError
        raise SimulationEvidenceImmutableError("Possession event evidence is immutable.")


class MatchPressingEvent(models.Model):
    """Immutable pressing/shape event emitted by causal engine v3.8+."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    run = models.ForeignKey(MatchSimulationRun, on_delete=models.PROTECT, related_name="pressing_events")
    match = models.ForeignKey(Match, on_delete=models.PROTECT, related_name="pressing_events")
    sequence = models.PositiveIntegerField()
    possession_sequence = models.PositiveIntegerField()
    minute = models.PositiveSmallIntegerField()
    phase = models.CharField(max_length=16, choices=MatchEventPhase.choices)
    event_type = models.CharField(max_length=32, choices=PressingEventType.choices)
    pressing_club = models.ForeignKey("clubs.Club", on_delete=models.PROTECT, related_name="pressing_events_for")
    opponent_club = models.ForeignKey("clubs.Club", on_delete=models.PROTECT, related_name="pressing_events_against")
    player = models.ForeignKey("players.Player", on_delete=models.PROTECT, related_name="pressing_events", null=True, blank=True)
    target_player = models.ForeignKey("players.Player", on_delete=models.PROTECT, related_name="target_pressing_events", null=True, blank=True)
    zone = models.CharField(max_length=24)
    channel = models.CharField(max_length=12)
    defensive_strategy = models.CharField(max_length=24, choices=DefensiveStrategy.choices)
    trigger = models.CharField(max_length=32, blank=True, default="")
    line_height = models.PositiveSmallIntegerField()
    compactness = models.PositiveSmallIntegerField()
    width = models.PositiveSmallIntegerField()
    press_intensity = models.DecimalField(max_digits=4, decimal_places=3)
    outcome = models.CharField(max_length=32, blank=True, default="")
    detail_payload = models.JSONField(default=dict, blank=True)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "sequence"]
        indexes = [
            models.Index(fields=["match", "minute", "sequence"], name="press_evt_match_time_idx"),
            models.Index(fields=["pressing_club", "match"], name="press_evt_club_match_idx"),
            models.Index(fields=["player", "match"], name="press_evt_player_match_idx"),
        ]
        constraints = [
            models.UniqueConstraint(fields=["match", "sequence"], name="uq_match_press_event_seq"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="press_evt_seq_gte1"),
            models.CheckConstraint(condition=Q(possession_sequence__gte=1), name="press_evt_poss_gte1"),
            models.CheckConstraint(condition=Q(minute__gte=1, minute__lte=120), name="press_evt_minute_1_120"),
            models.CheckConstraint(condition=Q(phase__in=MatchEventPhase.values), name="press_evt_valid_phase"),
            models.CheckConstraint(condition=Q(event_type__in=PressingEventType.values), name="press_evt_valid_type"),
            models.CheckConstraint(condition=Q(zone__in=["DEFENSIVE_THIRD", "MIDDLE_THIRD", "FINAL_THIRD", "PENALTY_AREA"]), name="press_evt_valid_zone"),
            models.CheckConstraint(condition=Q(channel__in=["LEFT", "CENTRE", "RIGHT"]), name="press_evt_valid_channel"),
            models.CheckConstraint(condition=Q(line_height__gte=0, line_height__lte=100), name="press_evt_line_0_100"),
            models.CheckConstraint(condition=Q(compactness__gte=0, compactness__lte=100), name="press_evt_compact_0_100"),
            models.CheckConstraint(condition=Q(width__gte=0, width__lte=100), name="press_evt_width_0_100"),
            models.CheckConstraint(condition=Q(press_intensity__gte=0, press_intensity__lte=1), name="press_evt_intensity_0_1"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="press_evt_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError
            raise SimulationEvidenceImmutableError("Pressing event evidence is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError
        raise SimulationEvidenceImmutableError("Pressing event evidence is immutable.")


class MatchOffBallEvent(models.Model):
    """Immutable off-ball movement / space occupation event emitted by v3.9+."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    run = models.ForeignKey(MatchSimulationRun, on_delete=models.PROTECT, related_name="off_ball_events")
    match = models.ForeignKey(Match, on_delete=models.PROTECT, related_name="off_ball_events")
    sequence = models.PositiveIntegerField()
    possession_sequence = models.PositiveIntegerField()
    minute = models.PositiveSmallIntegerField()
    phase = models.CharField(max_length=16, choices=MatchEventPhase.choices)
    event_type = models.CharField(max_length=32, choices=OffBallEventType.choices)
    club = models.ForeignKey("clubs.Club", on_delete=models.PROTECT, related_name="off_ball_events_for")
    opponent_club = models.ForeignKey("clubs.Club", on_delete=models.PROTECT, related_name="off_ball_events_against")
    player = models.ForeignKey("players.Player", on_delete=models.PROTECT, related_name="off_ball_events", null=True, blank=True)
    related_player = models.ForeignKey("players.Player", on_delete=models.PROTECT, related_name="related_off_ball_events", null=True, blank=True)
    origin_zone = models.CharField(max_length=24)
    destination_zone = models.CharField(max_length=24)
    origin_lane = models.CharField(max_length=24)
    destination_lane = models.CharField(max_length=24)
    tactical_role = models.CharField(max_length=32, blank=True, default="")
    outcome = models.CharField(max_length=40, blank=True, default="")
    detail_payload = models.JSONField(default=dict, blank=True)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "sequence"]
        indexes = [
            models.Index(fields=["match", "minute", "sequence"], name="offball_evt_match_time_idx"),
            models.Index(fields=["club", "match"], name="offball_evt_club_match_idx"),
            models.Index(fields=["player", "match"], name="offball_evt_player_match_idx"),
        ]
        constraints = [
            models.UniqueConstraint(fields=["match", "sequence"], name="uq_match_offball_event_seq"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="offball_evt_seq_gte1"),
            models.CheckConstraint(condition=Q(possession_sequence__gte=1), name="offball_evt_poss_gte1"),
            models.CheckConstraint(condition=Q(minute__gte=1, minute__lte=120), name="offball_evt_minute_1_120"),
            models.CheckConstraint(condition=Q(phase__in=MatchEventPhase.values), name="offball_evt_valid_phase"),
            models.CheckConstraint(condition=Q(event_type__in=OffBallEventType.values), name="offball_evt_valid_type"),
            models.CheckConstraint(condition=Q(origin_zone__in=["DEFENSIVE_THIRD", "MIDDLE_THIRD", "FINAL_THIRD", "PENALTY_AREA"]), name="offball_evt_valid_origin_zone"),
            models.CheckConstraint(condition=Q(destination_zone__in=["DEFENSIVE_THIRD", "MIDDLE_THIRD", "FINAL_THIRD", "PENALTY_AREA"]), name="offball_evt_valid_dest_zone"),
            models.CheckConstraint(condition=Q(origin_lane__in=["LEFT_WIDE", "LEFT_HALF_SPACE", "CENTRE", "RIGHT_HALF_SPACE", "RIGHT_WIDE"]), name="offball_evt_valid_origin_lane"),
            models.CheckConstraint(condition=Q(destination_lane__in=["LEFT_WIDE", "LEFT_HALF_SPACE", "CENTRE", "RIGHT_HALF_SPACE", "RIGHT_WIDE"]), name="offball_evt_valid_dest_lane"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="offball_evt_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError
            raise SimulationEvidenceImmutableError("Off-ball movement evidence is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError
        raise SimulationEvidenceImmutableError("Off-ball movement evidence is immutable.")


class MatchGoalkeeperDistributionEvent(models.Model):
    """Immutable goalkeeper restart/distribution evidence emitted by v3.10+."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    run = models.ForeignKey(MatchSimulationRun, on_delete=models.PROTECT, related_name="goalkeeper_distribution_events")
    match = models.ForeignKey(Match, on_delete=models.PROTECT, related_name="goalkeeper_distribution_events")
    sequence = models.PositiveIntegerField()
    possession_sequence = models.PositiveIntegerField()
    minute = models.PositiveSmallIntegerField()
    phase = models.CharField(max_length=16, choices=MatchEventPhase.choices)
    club = models.ForeignKey("clubs.Club", on_delete=models.PROTECT, related_name="goalkeeper_distribution_events_for")
    opponent_club = models.ForeignKey("clubs.Club", on_delete=models.PROTECT, related_name="goalkeeper_distribution_events_against")
    goalkeeper = models.ForeignKey("players.Player", on_delete=models.PROTECT, related_name="goalkeeper_distribution_events")
    receiver = models.ForeignKey("players.Player", on_delete=models.PROTECT, related_name="received_goalkeeper_distributions", null=True, blank=True)
    distribution_type = models.CharField(max_length=24, choices=GoalkeeperDistributionType.choices)
    source = models.CharField(max_length=24)
    origin_zone = models.CharField(max_length=24, default="DEFENSIVE_THIRD")
    destination_zone = models.CharField(max_length=24)
    channel = models.CharField(max_length=12)
    under_pressure = models.BooleanField(default=False)
    success_probability = models.DecimalField(max_digits=4, decimal_places=3)
    outcome = models.CharField(max_length=24)
    detail_payload = models.JSONField(default=dict, blank=True)
    evidence_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableSimulationQuerySet.as_manager()

    class Meta:
        ordering = ["match_id", "sequence"]
        indexes = [
            models.Index(fields=["match", "minute", "sequence"], name="gkdist_evt_match_time_idx"),
            models.Index(fields=["goalkeeper", "match"], name="gkdist_evt_keeper_match_idx"),
            models.Index(fields=["club", "match"], name="gkdist_evt_club_match_idx"),
        ]
        constraints = [
            models.UniqueConstraint(fields=["match", "sequence"], name="uq_match_gkdist_event_seq"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="gkdist_evt_seq_gte1"),
            models.CheckConstraint(condition=Q(possession_sequence__gte=1), name="gkdist_evt_poss_gte1"),
            models.CheckConstraint(condition=Q(minute__gte=1, minute__lte=120), name="gkdist_evt_minute_1_120"),
            models.CheckConstraint(condition=Q(phase__in=MatchEventPhase.values), name="gkdist_evt_valid_phase"),
            models.CheckConstraint(condition=Q(distribution_type__in=GoalkeeperDistributionType.values), name="gkdist_evt_valid_type"),
            models.CheckConstraint(condition=Q(origin_zone="DEFENSIVE_THIRD"), name="gkdist_evt_origin_def_third"),
            models.CheckConstraint(condition=Q(destination_zone__in=["DEFENSIVE_THIRD", "MIDDLE_THIRD", "FINAL_THIRD"]), name="gkdist_evt_valid_dest"),
            models.CheckConstraint(condition=Q(channel__in=["LEFT", "CENTRE", "RIGHT"]), name="gkdist_evt_valid_channel"),
            models.CheckConstraint(condition=Q(success_probability__gte=0, success_probability__lte=1), name="gkdist_evt_prob_0_1"),
            models.CheckConstraint(condition=~Q(evidence_hash=""), name="gkdist_evt_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import SimulationEvidenceImmutableError
            raise SimulationEvidenceImmutableError("Goalkeeper distribution evidence is immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import SimulationEvidenceImmutableError
        raise SimulationEvidenceImmutableError("Goalkeeper distribution evidence is immutable.")


# ---------------------------------------------------------------------------
# Interactive Match Runner / Live Command API
# ---------------------------------------------------------------------------


class _ImmutableInteractiveEvidenceQuerySet(models.QuerySet):
    def update(self, **kwargs):
        from .exceptions import InteractiveMatchEvidenceImmutableError
        raise InteractiveMatchEvidenceImmutableError("Interactive match evidence is immutable.")

    def delete(self):
        from .exceptions import InteractiveMatchEvidenceImmutableError
        raise InteractiveMatchEvidenceImmutableError("Interactive match evidence is immutable.")


class InteractiveMatchSession(models.Model):
    """Server-owned checkpoint runner for one INTERACTIVE match.

    The mutable row is only the coordination cursor. Commands/checkpoints are
    append-only evidence, so a session can be resumed after worker failure
    without persisting PRNG internals or trusting client-side state.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    match = models.OneToOneField(
        Match, on_delete=models.PROTECT, related_name="interactive_session"
    )
    snapshot = models.OneToOneField(
        MatchSimulationSnapshot, null=True, blank=True, on_delete=models.PROTECT,
        related_name="interactive_session",
    )
    status = models.CharField(
        max_length=16,
        choices=InteractiveMatchSessionStatus.choices,
        default=InteractiveMatchSessionStatus.PREPARED,
    )
    engine_key = models.CharField(max_length=64, default="ftg.match.v3.causal")
    engine_version = models.CharField(max_length=64, default="3.12.0")
    current_segment = models.PositiveSmallIntegerField(default=0)
    current_minute = models.PositiveSmallIntegerField(default=0)
    home_score = models.PositiveSmallIntegerField(default=0)
    away_score = models.PositiveSmallIntegerField(default=0)
    revision = models.PositiveIntegerField(default=0)
    stream_sequence = models.PositiveIntegerField(default=0)
    segment_duration_seconds = models.PositiveSmallIntegerField(default=60)
    next_advance_at = models.DateTimeField(null=True, blank=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    aborted_at = models.DateTimeField(null=True, blank=True)
    policy_key = models.CharField(max_length=100, default=INTERACTIVE_MATCH_POLICY_KEY)
    policy_version = models.CharField(max_length=30, default=INTERACTIVE_MATCH_POLICY_VERSION)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["match_id"]
        indexes = [
            models.Index(fields=["status", "next_advance_at"], name="live_session_due_idx"),
        ]
        constraints = [
            models.CheckConstraint(
                condition=Q(status__in=InteractiveMatchSessionStatus.values),
                name="live_session_valid_status",
            ),
            models.CheckConstraint(
                condition=Q(current_segment__gte=0, current_segment__lte=8),
                name="live_session_segment_0_8",
            ),
            models.CheckConstraint(
                condition=Q(current_minute__gte=0, current_minute__lte=120),
                name="live_session_minute_0_120",
            ),
            models.CheckConstraint(
                condition=Q(segment_duration_seconds__gte=5, segment_duration_seconds__lte=900),
                name="live_session_duration_5_900",
            ),
            models.CheckConstraint(
                condition=(
                    Q(status=InteractiveMatchSessionStatus.PREPARED, snapshot__isnull=True, next_advance_at__isnull=True, completed_at__isnull=True, aborted_at__isnull=True)
                    | Q(status=InteractiveMatchSessionStatus.OPEN, snapshot__isnull=False, next_advance_at__isnull=False, completed_at__isnull=True, aborted_at__isnull=True)
                    | Q(status=InteractiveMatchSessionStatus.COMPLETED, snapshot__isnull=False, next_advance_at__isnull=True, completed_at__isnull=False, aborted_at__isnull=True)
                    | Q(status=InteractiveMatchSessionStatus.ABORTED, next_advance_at__isnull=True, completed_at__isnull=True, aborted_at__isnull=False)
                ),
                name="live_session_lifecycle",
            ),
        ]

    def __str__(self):
        return f"Interactive {self.match_id} / {self.status} / seg={self.current_segment}"


class LiveMatchCommand(models.Model):
    """Immutable accepted manager command effective at the next checkpoint."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    session = models.ForeignKey(
        InteractiveMatchSession, on_delete=models.PROTECT, related_name="commands"
    )
    club = models.ForeignKey(
        "clubs.Club", on_delete=models.PROTECT, related_name="live_match_commands"
    )
    actor = models.ForeignKey(
        "users.User", on_delete=models.PROTECT, related_name="live_match_commands"
    )
    sequence = models.PositiveIntegerField()
    idempotency_key = models.CharField(max_length=64)
    command_type = models.CharField(max_length=16, choices=LiveMatchCommandType.choices)
    effective_segment = models.PositiveSmallIntegerField()
    submitted_minute = models.PositiveSmallIntegerField(default=0)
    expected_revision = models.PositiveIntegerField()
    payload = models.JSONField(default=dict)
    command_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableInteractiveEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["session_id", "sequence"]
        indexes = [
            models.Index(fields=["session", "club", "effective_segment"], name="live_cmd_segment_idx"),
        ]
        constraints = [
            models.UniqueConstraint(fields=["session", "sequence"], name="uq_live_cmd_sequence"),
            models.UniqueConstraint(fields=["session", "club", "idempotency_key"], name="uq_live_cmd_idempotency"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="live_cmd_sequence_gte1"),
            models.CheckConstraint(
                condition=Q(command_type__in=LiveMatchCommandType.values),
                name="live_cmd_valid_type",
            ),
            models.CheckConstraint(
                condition=Q(effective_segment__gte=1, effective_segment__lte=8),
                name="live_cmd_segment_1_8",
            ),
            models.CheckConstraint(
                condition=Q(submitted_minute__gte=0, submitted_minute__lte=120),
                name="live_cmd_minute_0_120",
            ),
            models.CheckConstraint(condition=~Q(idempotency_key=""), name="live_cmd_idempotency_nonempty"),
            models.CheckConstraint(condition=~Q(command_hash=""), name="live_cmd_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import InteractiveMatchEvidenceImmutableError
            raise InteractiveMatchEvidenceImmutableError("Live commands are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import InteractiveMatchEvidenceImmutableError
        raise InteractiveMatchEvidenceImmutableError("Live commands are immutable.")


class InteractiveMatchCheckpoint(models.Model):
    """Immutable public state after one deterministic simulation segment."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    session = models.ForeignKey(
        InteractiveMatchSession, on_delete=models.PROTECT, related_name="checkpoints"
    )
    segment = models.PositiveSmallIntegerField()
    start_minute = models.PositiveSmallIntegerField()
    end_minute = models.PositiveSmallIntegerField()
    phase = models.CharField(max_length=16, choices=MatchEventPhase.choices)
    home_score = models.PositiveSmallIntegerField()
    away_score = models.PositiveSmallIntegerField()
    events_payload = models.JSONField(default=list)
    tactical_decisions_payload = models.JSONField(default=list)
    statistics_payload = models.JSONField(default=dict)
    command_sequence = models.PositiveIntegerField(default=0)
    projection_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableInteractiveEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["session_id", "segment"]
        constraints = [
            models.UniqueConstraint(fields=["session", "segment"], name="uq_live_checkpoint_segment"),
            models.CheckConstraint(condition=Q(segment__gte=1, segment__lte=8), name="live_checkpoint_segment_1_8"),
            models.CheckConstraint(condition=Q(start_minute__gte=1, start_minute__lte=120), name="live_checkpoint_start_1_120"),
            models.CheckConstraint(condition=Q(end_minute__gte=1, end_minute__lte=120), name="live_checkpoint_end_1_120"),
            models.CheckConstraint(condition=Q(end_minute__gte=F("start_minute")), name="live_checkpoint_end_after_start"),
            models.CheckConstraint(condition=Q(phase__in=[MatchEventPhase.REGULATION, MatchEventPhase.EXTRA_TIME]), name="live_checkpoint_field_phase"),
            models.CheckConstraint(condition=~Q(projection_hash=""), name="live_checkpoint_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import InteractiveMatchEvidenceImmutableError
            raise InteractiveMatchEvidenceImmutableError("Interactive checkpoints are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import InteractiveMatchEvidenceImmutableError
        raise InteractiveMatchEvidenceImmutableError("Interactive checkpoints are immutable.")


class LiveMatchStreamEvent(models.Model):
    """Immutable durable synchronization event for one interactive match.

    Sequence is monotonic per session.  PUBLIC events form the spectator feed;
    CLUB events synchronize only the relevant manager devices; STAFF is
    reserved for operational messages.  Heartbeats are transport-level and are
    deliberately not persisted here.
    """

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    session = models.ForeignKey(
        InteractiveMatchSession, on_delete=models.PROTECT, related_name="stream_events"
    )
    sequence = models.PositiveIntegerField()
    schema_version = models.PositiveSmallIntegerField(default=LIVE_STREAM_SCHEMA_VERSION)
    policy_key = models.CharField(max_length=100, default=LIVE_STREAM_POLICY_KEY)
    policy_version = models.CharField(max_length=30, default=LIVE_STREAM_POLICY_VERSION)
    event_type = models.CharField(max_length=32, choices=LiveStreamEventType.choices)
    visibility = models.CharField(
        max_length=12, choices=LiveStreamVisibility.choices,
        default=LiveStreamVisibility.PUBLIC,
    )
    club = models.ForeignKey(
        "clubs.Club", null=True, blank=True, on_delete=models.PROTECT,
        related_name="live_stream_events",
    )
    revision = models.PositiveIntegerField(default=0)
    payload = models.JSONField(default=dict)
    event_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = _ImmutableInteractiveEvidenceQuerySet.as_manager()

    class Meta:
        ordering = ["session_id", "sequence"]
        indexes = [
            models.Index(fields=["session", "sequence"], name="live_stream_seq_idx"),
            models.Index(fields=["session", "visibility", "sequence"], name="live_stream_vis_seq_idx"),
        ]
        constraints = [
            models.UniqueConstraint(fields=["session", "sequence"], name="uq_live_stream_sequence"),
            models.CheckConstraint(condition=Q(sequence__gte=1), name="live_stream_sequence_gte1"),
            models.CheckConstraint(condition=Q(schema_version__gte=1), name="live_stream_schema_gte1"),
            models.CheckConstraint(
                condition=Q(event_type__in=LiveStreamEventType.values),
                name="live_stream_valid_type",
            ),
            models.CheckConstraint(
                condition=Q(visibility__in=LiveStreamVisibility.values),
                name="live_stream_valid_visibility",
            ),
            models.CheckConstraint(
                condition=(
                    Q(visibility=LiveStreamVisibility.CLUB, club__isnull=False)
                    | Q(visibility__in=[LiveStreamVisibility.PUBLIC, LiveStreamVisibility.STAFF], club__isnull=True)
                ),
                name="live_stream_visibility_club_consistent",
            ),
            models.CheckConstraint(condition=~Q(event_hash=""), name="live_stream_hash_nonempty"),
        ]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            from .exceptions import InteractiveMatchEvidenceImmutableError
            raise InteractiveMatchEvidenceImmutableError("Live stream events are immutable.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        from .exceptions import InteractiveMatchEvidenceImmutableError
        raise InteractiveMatchEvidenceImmutableError("Live stream events are immutable.")
