"""Competition discipline, cards, sanctions, appeals and administrative results."""
from __future__ import annotations

import hashlib
import json
from collections import defaultdict

from django.db import IntegrityError, transaction
from django.db.models import Q
from django.utils import timezone

from clubs.models import ClubSquadMembership

from .competition_support import lock_competition_source_and_match
from .constants import (
    AdministrativeDecisionOutcome,
    AdministrativeDecisionReason,
    DisciplinaryAppealDecisionOutcome,
    DisciplinaryCardSource,
    DisciplinaryCardType,
    DisciplinarySanctionType,
    MatchPlayerSuspensionReason,
    MatchResultType,
    MatchStatus,
    MatchdayAttendanceStatus,
    MatchdayAuditEventType,
    MatchdayOperationStatus,
)
from .discipline_policy import (
    CompetitionDisciplinePolicyV1,
    DisciplinePolicySnapshot,
    SANCTION_DIRECT_RED,
    SANCTION_SECOND_YELLOW,
    SANCTION_YELLOW_ACCUMULATION,
)
from .exceptions import (
    AdministrativeResultError,
    DisciplineAppealError,
    DisciplineCardError,
    DisciplineConfigurationError,
    DisciplineProcessingError,
)
from .models import (
    CompetitionDisciplineProfile,
    DisciplineProcessingRun,
    DisciplinaryAppeal,
    DisciplinaryAppealDecision,
    DisciplinaryCardEvent,
    DisciplinaryCardRevocation,
    DisciplinarySanctionRevocation,
    DisciplinarySuspensionAssignment,
    Match,
    MatchAdministrativeDecision,
    MatchEvent,
    MatchLineupEntry,
    MatchdayOperation,
    MatchdayTeamState,
    PlayerDisciplinarySanction,
    PlayerMatchSuspension,
    PlayerMatchSuspensionRevocation,
)


def _sha256(payload: dict) -> str:
    return hashlib.sha256(
        json.dumps(
            payload,
            sort_keys=True,
            separators=(",", ":"),
            default=str,
        ).encode("utf-8")
    ).hexdigest()


def _competition_kwargs(match: Match) -> dict:
    fixture = match.fixture
    if fixture.competition_id:
        return {
            "league_competition_id": fixture.competition_id,
            "federation_competition_id": None,
        }
    if fixture.federation_competition_id:
        return {
            "league_competition_id": None,
            "federation_competition_id": fixture.federation_competition_id,
        }
    raise DisciplineConfigurationError("Match fixture has no competition source.")


def _competition_key(match: Match) -> str:
    fixture = match.fixture
    if fixture.competition_id:
        return f"league:{fixture.competition_id}"
    if fixture.federation_competition_id:
        return f"federation:{fixture.federation_competition_id}"
    raise DisciplineConfigurationError("Match fixture has no competition source.")


class CompetitionDisciplineProfileResolver:
    @staticmethod
    def for_match(match: Match) -> tuple[CompetitionDisciplineProfile | None, DisciplinePolicySnapshot]:
        kwargs = _competition_kwargs(match)
        profile = CompetitionDisciplineProfile.objects.filter(
            **kwargs,
            is_active=True,
        ).first()
        if profile is None:
            snapshot = DisciplinePolicySnapshot()
        else:
            snapshot = DisciplinePolicySnapshot(
                yellow_threshold=profile.yellow_threshold,
                yellow_suspension_matches=profile.yellow_suspension_matches,
                direct_red_suspension_matches=profile.direct_red_suspension_matches,
                second_yellow_suspension_matches=profile.second_yellow_suspension_matches,
                second_yellow_counts_toward_accumulation=(
                    profile.second_yellow_counts_toward_accumulation
                ),
                forfeit_score_for=profile.forfeit_score_for,
                forfeit_score_against=profile.forfeit_score_against,
            )
        try:
            snapshot.validate()
        except ValueError as exc:
            raise DisciplineConfigurationError(str(exc)) from exc
        return profile, snapshot


class DisciplineCardService:
    @classmethod
    @transaction.atomic
    def record(
        cls,
        *,
        match_id,
        club_id,
        player_id,
        minute: int,
        card_type: str,
        source: str = DisciplinaryCardSource.REFEREE,
        source_match_event_id=None,
        recorded_by=None,
    ) -> DisciplinaryCardEvent:
        match = (
            Match.objects.select_for_update()
            .select_related("fixture")
            .get(pk=match_id)
        )
        if match.status not in {MatchStatus.IN_PROGRESS, MatchStatus.COMPLETED}:
            raise DisciplineCardError(
                "Cards can only be recorded for an IN_PROGRESS or COMPLETED match."
            )
        if match.status == MatchStatus.COMPLETED and match.result_type != MatchResultType.PLAYED:
            raise DisciplineCardError("Administrative results cannot receive played-match cards.")
        if DisciplineProcessingRun.objects.filter(match=match).exists():
            raise DisciplineCardError(
                "Discipline processing is already finalized for this match."
            )
        if card_type not in DisciplinaryCardType.values:
            raise DisciplineCardError("Unsupported card type.")
        if source not in DisciplinaryCardSource.values:
            raise DisciplineCardError("Unsupported card source.")
        if isinstance(minute, bool) or not isinstance(minute, int) or not 1 <= minute <= 120:
            raise DisciplineCardError("Card minute must be between 1 and 120.")
        # Engine event payloads carry string UUIDs while Django FK IDs are UUID objects.
        # Resolve to the participant's canonical PK before any security checks or hashes.
        participant_ids = (match.fixture.home_club_id, match.fixture.away_club_id)
        club_id = next((pk for pk in participant_ids if str(pk) == str(club_id)), None)
        if club_id is None:
            raise DisciplineCardError("Card club is not a fixture participant.")
        # Match Report v2 carries UUIDs as strings, whereas Django reads
        # MatchEvent.player_id back as a UUID. Canonicalize through the
        # authoritative match lineup before comparing source-event identities.
        # A different player or an off-lineup player must still be rejected.
        canonical_player_id = MatchLineupEntry.objects.filter(
            lineup__match=match,
            lineup__club_id=club_id,
            player_id=player_id,
        ).values_list("player_id", flat=True).first()
        if canonical_player_id is None:
            raise DisciplineCardError(
                "Card player must belong to the recorded club's match lineup."
            )
        player_id = canonical_player_id

        existing = list(
            DisciplinaryCardEvent.objects.filter(
                match=match,
                player_id=player_id,
                revocation__isnull=True,
            ).order_by("sequence")
        )
        if any(
            card.card_type in {
                DisciplinaryCardType.DIRECT_RED,
                DisciplinaryCardType.SECOND_YELLOW,
            }
            for card in existing
        ):
            raise DisciplineCardError("A dismissed player cannot receive another active card.")
        if card_type == DisciplinaryCardType.SECOND_YELLOW and not any(
            card.card_type == DisciplinaryCardType.YELLOW for card in existing
        ):
            raise DisciplineCardError("SECOND_YELLOW requires an earlier active yellow card.")

        source_event = None
        if source_match_event_id is not None:
            try:
                source_event = MatchEvent.objects.get(pk=source_match_event_id)
            except MatchEvent.DoesNotExist as exc:
                raise DisciplineCardError("Source MatchEvent does not exist.") from exc
            if (
                source_event.match_id != match.pk
                or source_event.club_id != club_id
                or source_event.player_id != player_id
            ):
                raise DisciplineCardError("Source MatchEvent identity does not match the card.")
            expected = {
                DisciplinaryCardType.YELLOW: "YELLOW_CARD",
                DisciplinaryCardType.SECOND_YELLOW: "SECOND_YELLOW",
                DisciplinaryCardType.DIRECT_RED: "RED_CARD",
            }[card_type]
            if source_event.event_type != expected:
                raise DisciplineCardError(
                    "Source MatchEvent is not the matching card event taxonomy."
                )

        sequence = (
            DisciplinaryCardEvent.objects.filter(match=match).count() + 1
        )
        payload = {
            "match_id": str(match.pk),
            "club_id": str(club_id),
            "player_id": str(player_id),
            "sequence": sequence,
            "minute": minute,
            "card_type": card_type,
            "source": source,
            "source_match_event_id": (
                str(source_match_event_id) if source_match_event_id else None
            ),
            "policy_key": CompetitionDisciplinePolicyV1.policy_key,
            "policy_version": CompetitionDisciplinePolicyV1.policy_version,
        }
        return DisciplinaryCardEvent.objects.create(
            match=match,
            club_id=club_id,
            player_id=player_id,
            sequence=sequence,
            minute=minute,
            card_type=card_type,
            source=source,
            source_match_event=source_event,
            evidence_hash=_sha256(payload),
            recorded_by=recorded_by,
        )

    @staticmethod
    @transaction.atomic
    def revoke(*, card_id, reason_text: str, revoked_by=None) -> DisciplinaryCardRevocation:
        if not (reason_text or "").strip():
            raise DisciplineCardError("Card revocation requires a reason.")
        card = DisciplinaryCardEvent.objects.select_for_update().select_related("match").get(pk=card_id)
        if DisciplineProcessingRun.objects.filter(match=card.match).exists():
            raise DisciplineCardError(
                "A processed card must be challenged through its sanction appeal path."
            )
        existing = DisciplinaryCardRevocation.objects.filter(card=card).first()
        if existing is not None:
            return existing
        return DisciplinaryCardRevocation.objects.create(
            card=card,
            reason_text=reason_text.strip(),
            revoked_by=revoked_by,
        )


class CompetitionDisciplineService:
    @classmethod
    @transaction.atomic
    def finalize_match(cls, *, match_id, processed_by=None) -> DisciplineProcessingRun:
        match = (
            Match.objects.select_for_update()
            .select_related("fixture")
            .get(pk=match_id)
        )
        existing = DisciplineProcessingRun.objects.filter(match=match).first()
        if existing is not None:
            return existing
        if match.status != MatchStatus.COMPLETED or match.result_type != MatchResultType.PLAYED:
            raise DisciplineProcessingError(
                "Only a completed PLAYED match can be discipline-finalized."
            )

        if match.fixture.federation_competition_id:
            from match_officials_governance.exceptions import MatchOfficialsGovernanceError
            from match_officials_governance.services import OfficialMatchReportService
            try:
                OfficialMatchReportService.assert_discipline_finalization_allowed(match=match)
            except MatchOfficialsGovernanceError as exc:
                raise DisciplineProcessingError(str(exc)) from exc

        _profile, policy = CompetitionDisciplineProfileResolver.for_match(match)
        active_cards = list(
            DisciplinaryCardEvent.objects.select_for_update(of=("self",))
            .filter(match=match, revocation__isnull=True)
            .select_related("player", "club")
            .order_by("sequence")
        )
        grouped: dict[str, list[DisciplinaryCardEvent]] = defaultdict(list)
        for card in active_cards:
            grouped[str(card.player_id)].append(card)

        created_sanctions: list[PlayerDisciplinarySanction] = []
        player_evidence = []
        for player_id, cards in sorted(grouped.items()):
            if cls._has_unprocessed_prior_cards(match=match, player_id=player_id):
                raise DisciplineProcessingError(
                    "An earlier card-bearing match for this player must be discipline-finalized first."
                )
            prior_yellows = cls._prior_accumulation_yellows(
                match=match,
                player_id=player_id,
                policy=policy,
            )
            evaluation = CompetitionDisciplinePolicyV1.evaluate_player_cards(
                prior_accumulation_yellows=prior_yellows,
                card_types=[card.card_type for card in cards],
                policy=policy,
            )
            for trigger in evaluation.triggers:
                source_card = cls._source_card_for_trigger(cards=cards, trigger=trigger)
                sanction = cls._create_sanction(
                    match=match,
                    player_id=player_id,
                    club_id=cards[0].club_id,
                    source_card=source_card,
                    sanction_type=trigger.sanction_type,
                    matches_total=trigger.matches,
                    semantic_suffix=trigger.semantic_suffix,
                    policy=policy,
                    issued_by=processed_by,
                )
                created_sanctions.append(sanction)
                cls.assign_outstanding_for_sanction(sanction=sanction, issued_by=processed_by)
            player_evidence.append(
                {
                    "player_id": player_id,
                    "card_ids": [str(card.pk) for card in cards],
                    "prior_accumulation_yellows": evaluation.prior_accumulation_yellows,
                    "resulting_accumulation_yellows": evaluation.resulting_accumulation_yellows,
                    "triggers": [
                        {
                            "sanction_type": item.sanction_type,
                            "matches": item.matches,
                            "semantic_suffix": item.semantic_suffix,
                        }
                        for item in evaluation.triggers
                    ],
                }
            )

        evidence_payload = {
            "match_id": str(match.pk),
            "competition": _competition_key(match),
            "cards": [
                {
                    "id": str(card.pk),
                    "player_id": str(card.player_id),
                    "club_id": str(card.club_id),
                    "sequence": card.sequence,
                    "minute": card.minute,
                    "card_type": card.card_type,
                    "evidence_hash": card.evidence_hash,
                }
                for card in active_cards
            ],
            "players": player_evidence,
            "sanction_ids": [str(item.pk) for item in created_sanctions],
            "policy": policy.to_payload(),
        }
        return DisciplineProcessingRun.objects.create(
            match=match,
            card_count=len(active_cards),
            sanction_count=len(created_sanctions),
            policy_payload=policy.to_payload(),
            evidence_payload=evidence_payload,
            evidence_hash=_sha256(evidence_payload),
            processed_by=processed_by,
        )

    @classmethod
    def _has_unprocessed_prior_cards(cls, *, match, player_id) -> bool:
        filters = {
            "player_id": player_id,
            "revocation__isnull": True,
            "match__fixture__round_number__lt": match.fixture.round_number,
            "match__discipline_processing_run__isnull": True,
        }
        kwargs = _competition_kwargs(match)
        if kwargs["league_competition_id"]:
            filters["match__fixture__competition_id"] = kwargs["league_competition_id"]
        else:
            filters["match__fixture__federation_competition_id"] = kwargs[
                "federation_competition_id"
            ]
        return DisciplinaryCardEvent.objects.filter(**filters).exists()

    @classmethod
    def _prior_accumulation_yellows(cls, *, match, player_id, policy) -> int:
        kwargs = _competition_kwargs(match)
        active_card_types = [DisciplinaryCardType.YELLOW]
        if policy.second_yellow_counts_toward_accumulation:
            active_card_types.append(DisciplinaryCardType.SECOND_YELLOW)
        filters = {
            "player_id": player_id,
            "card_type__in": active_card_types,
            "revocation__isnull": True,
            "match__discipline_processing_run__isnull": False,
            "match__fixture__round_number__lt": match.fixture.round_number,
        }
        if kwargs["league_competition_id"]:
            filters["match__fixture__competition_id"] = kwargs["league_competition_id"]
        else:
            filters["match__fixture__federation_competition_id"] = kwargs[
                "federation_competition_id"
            ]
        return DisciplinaryCardEvent.objects.filter(**filters).exclude(match=match).count()

    @staticmethod
    def _source_card_for_trigger(*, cards, trigger):
        if trigger.sanction_type == SANCTION_DIRECT_RED:
            for card in cards:
                if card.card_type == DisciplinaryCardType.DIRECT_RED:
                    return card
        if trigger.sanction_type == SANCTION_SECOND_YELLOW:
            for card in cards:
                if card.card_type == DisciplinaryCardType.SECOND_YELLOW:
                    return card
        yellows = [card for card in cards if card.card_type == DisciplinaryCardType.YELLOW]
        return yellows[-1] if yellows else cards[-1]

    @classmethod
    def _create_sanction(
        cls,
        *,
        match,
        player_id,
        club_id,
        source_card,
        sanction_type,
        matches_total,
        semantic_suffix,
        policy,
        issued_by,
    ):
        comp_key = _competition_key(match)
        if sanction_type == DisciplinarySanctionType.YELLOW_ACCUMULATION:
            semantic_key = f"{comp_key}:player:{player_id}:{semantic_suffix}"
        else:
            semantic_key = (
                f"{comp_key}:player:{player_id}:match:{match.pk}:{semantic_suffix}"
            )
        existing = PlayerDisciplinarySanction.objects.filter(
            semantic_key=semantic_key
        ).first()
        if existing is not None:
            return existing
        payload = {
            "semantic_key": semantic_key,
            "competition": comp_key,
            "player_id": str(player_id),
            "club_at_issue_id": str(club_id),
            "source_match_id": str(match.pk),
            "source_card_id": str(source_card.pk) if source_card else None,
            "sanction_type": sanction_type,
            "matches_total": matches_total,
            "policy": policy.to_payload(),
        }
        kwargs = _competition_kwargs(match)
        return PlayerDisciplinarySanction.objects.create(
            player_id=player_id,
            club_at_issue_id=club_id,
            source_match=match,
            source_card=source_card,
            sanction_type=sanction_type,
            matches_total=matches_total,
            semantic_key=semantic_key,
            policy_key=CompetitionDisciplinePolicyV1.policy_key,
            policy_version=CompetitionDisciplinePolicyV1.policy_version,
            schema_version=CompetitionDisciplinePolicyV1.schema_version,
            evidence_hash=_sha256(payload),
            issued_by=issued_by,
            **kwargs,
        )

    @classmethod
    @transaction.atomic
    def assign_outstanding_for_sanction(cls, *, sanction, issued_by=None) -> int:
        sanction = (
            PlayerDisciplinarySanction.objects.select_for_update()
            .select_related("source_match__fixture", "player", "club_at_issue")
            .get(pk=sanction.pk)
        )
        if DisciplinarySanctionRevocation.objects.filter(sanction=sanction).exists():
            return 0
        active_assignment_count = DisciplinarySuspensionAssignment.objects.filter(
            sanction=sanction,
            suspension__revocation__isnull=True,
        ).count()
        remaining = sanction.matches_total - active_assignment_count
        if remaining <= 0:
            return 0

        membership = ClubSquadMembership.objects.filter(player_id=sanction.player_id).first()
        club_id = membership.club_id if membership else sanction.club_at_issue_id
        source_round = sanction.source_match.fixture.round_number
        match_filter = Q(
            fixture__round_number__gt=source_round,
            status__in=[MatchStatus.PENDING, MatchStatus.SCHEDULED],
        ) & (Q(fixture__home_club_id=club_id) | Q(fixture__away_club_id=club_id))
        if sanction.league_competition_id:
            match_filter &= Q(fixture__competition_id=sanction.league_competition_id)
        else:
            match_filter &= Q(
                fixture__federation_competition_id=sanction.federation_competition_id
            )
        candidates = list(
            Match.objects.filter(match_filter)
            .select_related("fixture")
            .order_by("fixture__round_number", "scheduled_at", "id")
        )

        max_ordinal = (
            DisciplinarySuspensionAssignment.objects.filter(sanction=sanction)
            .order_by("-ordinal")
            .values_list("ordinal", flat=True)
            .first()
            or 0
        )
        created = 0
        for candidate in candidates:
            if created >= remaining:
                break
            if PlayerMatchSuspension.objects.filter(
                match=candidate,
                player_id=sanction.player_id,
                revocation__isnull=True,
            ).exists():
                continue
            reason = {
                DisciplinarySanctionType.DIRECT_RED: MatchPlayerSuspensionReason.RED_CARD,
                DisciplinarySanctionType.SECOND_YELLOW: MatchPlayerSuspensionReason.RED_CARD,
                DisciplinarySanctionType.YELLOW_ACCUMULATION: MatchPlayerSuspensionReason.CARD_ACCUMULATION,
                DisciplinarySanctionType.GOVERNANCE: MatchPlayerSuspensionReason.GOVERNANCE,
            }[sanction.sanction_type]
            try:
                suspension = PlayerMatchSuspension.objects.create(
                    match=candidate,
                    player_id=sanction.player_id,
                    reason=reason,
                    reason_text=f"Competition discipline sanction {sanction.pk}.",
                    source_type="DISCIPLINE_SANCTION",
                    source_id=str(sanction.pk),
                    issued_by=issued_by,
                )
            except IntegrityError:
                continue
            max_ordinal += 1
            DisciplinarySuspensionAssignment.objects.create(
                sanction=sanction,
                suspension=suspension,
                ordinal=max_ordinal,
            )
            created += 1
        return created

    @classmethod
    def sync_outstanding_for_match(cls, *, match_id) -> int:
        """Assign pending sanction debt when a later knockout Match is created."""
        match = Match.objects.select_related("fixture").get(pk=match_id)
        fixture = match.fixture
        sanctions = PlayerDisciplinarySanction.objects.filter(
            revocation__isnull=True,
            source_match__fixture__round_number__lt=fixture.round_number,
        )
        if fixture.competition_id:
            sanctions = sanctions.filter(league_competition_id=fixture.competition_id)
        else:
            sanctions = sanctions.filter(
                federation_competition_id=fixture.federation_competition_id
            )
        participant_ids = {fixture.home_club_id, fixture.away_club_id}
        total = 0
        for sanction in sanctions.select_related("player", "club_at_issue"):
            membership = ClubSquadMembership.objects.filter(player_id=sanction.player_id).first()
            club_id = membership.club_id if membership else sanction.club_at_issue_id
            if club_id not in participant_ids:
                continue
            total += cls.assign_outstanding_for_sanction(sanction=sanction)
        return total


class DisciplinaryAppealService:
    @staticmethod
    @transaction.atomic
    def submit(*, sanction_id, reason_text: str, submitted_by=None) -> DisciplinaryAppeal:
        if not (reason_text or "").strip():
            raise DisciplineAppealError("Appeal requires a reason.")
        sanction = PlayerDisciplinarySanction.objects.select_for_update().get(pk=sanction_id)
        if DisciplinarySanctionRevocation.objects.filter(sanction=sanction).exists():
            raise DisciplineAppealError("Revoked sanction cannot be appealed again.")
        existing = DisciplinaryAppeal.objects.filter(sanction=sanction).first()
        if existing is not None:
            return existing
        return DisciplinaryAppeal.objects.create(
            sanction=sanction,
            reason_text=reason_text.strip(),
            submitted_by=submitted_by,
        )

    @staticmethod
    @transaction.atomic
    def decide(
        *, appeal_id, outcome: str, reason_text: str, decided_by=None
    ) -> DisciplinaryAppealDecision:
        if outcome not in DisciplinaryAppealDecisionOutcome.values:
            raise DisciplineAppealError("Unsupported appeal outcome.")
        if not (reason_text or "").strip():
            raise DisciplineAppealError("Appeal decision requires a reason.")
        appeal = (
            DisciplinaryAppeal.objects.select_for_update()
            .select_related("sanction")
            .get(pk=appeal_id)
        )
        existing = DisciplinaryAppealDecision.objects.filter(appeal=appeal).first()
        if existing is not None:
            if existing.outcome != outcome:
                raise DisciplineAppealError("Appeal already has another final decision.")
            return existing
        decision = DisciplinaryAppealDecision.objects.create(
            appeal=appeal,
            outcome=outcome,
            reason_text=reason_text.strip(),
            decided_by=decided_by,
        )
        if outcome == DisciplinaryAppealDecisionOutcome.UPHELD:
            sanction = appeal.sanction
            if not DisciplinarySanctionRevocation.objects.filter(sanction=sanction).exists():
                DisciplinarySanctionRevocation.objects.create(
                    sanction=sanction,
                    reason_text=f"Appeal upheld: {reason_text.strip()}",
                    revoked_by=decided_by,
                )
            future_assignments = (
                DisciplinarySuspensionAssignment.objects.filter(
                    sanction=sanction,
                    suspension__match__status__in=[
                        MatchStatus.PENDING,
                        MatchStatus.SCHEDULED,
                    ],
                    suspension__revocation__isnull=True,
                )
                .select_related("suspension")
                .order_by("ordinal")
            )
            for assignment in future_assignments:
                PlayerMatchSuspensionRevocation.objects.create(
                    suspension=assignment.suspension,
                    reason_text=f"Underlying sanction revoked after upheld appeal {appeal.pk}.",
                    revoked_by=decided_by,
                )
        return decision


class AdministrativeResultService:
    @classmethod
    @transaction.atomic
    def apply_no_show_forfeit(
        cls, *, match_id, reason_text: str = "", decided_by=None
    ) -> MatchAdministrativeDecision:
        source = lock_competition_source_and_match(match_id)
        match = source.match
        if match.status == MatchStatus.COMPLETED:
            existing = MatchAdministrativeDecision.objects.filter(match=match).first()
            if existing is not None:
                return existing
            raise AdministrativeResultError("Completed played match cannot receive a forfeit result.")
        if match.status != MatchStatus.SCHEDULED:
            raise AdministrativeResultError("No-show forfeit requires a SCHEDULED match.")
        if match.started_at is not None:
            raise AdministrativeResultError("A started match cannot be resolved as pre-match no-show.")

        operation = (
            MatchdayOperation.objects.select_for_update()
            .filter(match=match)
            .first()
        )
        if operation is None or operation.status != MatchdayOperationStatus.NO_SHOW_REVIEW:
            raise AdministrativeResultError(
                "Match must be in NO_SHOW_REVIEW before a no-show forfeit can be applied."
            )
        states = list(
            MatchdayTeamState.objects.select_for_update()
            .filter(operation=operation)
            .order_by("club_id")
        )
        no_shows = [
            state for state in states
            if state.attendance_status == MatchdayAttendanceStatus.NO_SHOW
        ]
        if len(no_shows) != 1:
            raise AdministrativeResultError(
                "Automatic no-show forfeit requires exactly one NO_SHOW club; double no-show needs governance review."
            )
        no_show_club_id = no_shows[0].club_id
        if no_show_club_id == match.fixture.home_club_id:
            outcome = AdministrativeDecisionOutcome.HOME_FORFEIT
        elif no_show_club_id == match.fixture.away_club_id:
            outcome = AdministrativeDecisionOutcome.AWAY_FORFEIT
        else:
            raise AdministrativeResultError("NO_SHOW club is not a fixture participant.")

        profile, policy = CompetitionDisciplineProfileResolver.for_match(match)
        if profile is not None and not profile.auto_no_show_forfeit:
            raise AdministrativeResultError(
                "Competition discipline profile disables automatic no-show forfeiture."
            )
        try:
            home_score, away_score = CompetitionDisciplinePolicyV1.administrative_score(
                outcome=outcome,
                policy=policy,
            )
        except ValueError as exc:
            raise AdministrativeResultError(str(exc)) from exc

        payload = {
            "match_id": str(match.pk),
            "competition": _competition_key(match),
            "reason": AdministrativeDecisionReason.NO_SHOW,
            "outcome": outcome,
            "no_show_club_id": str(no_show_club_id),
            "home_score": home_score,
            "away_score": away_score,
            "reason_text": (reason_text or "").strip(),
            "policy": policy.to_payload(),
        }
        decision = MatchAdministrativeDecision.objects.create(
            match=match,
            reason=AdministrativeDecisionReason.NO_SHOW,
            outcome=outcome,
            home_score=home_score,
            away_score=away_score,
            reason_text=(reason_text or "").strip(),
            policy_payload=policy.to_payload(),
            evidence_hash=_sha256(payload),
            decided_by=decided_by,
        )
        now = timezone.now()
        match.home_score = home_score
        match.away_score = away_score
        match.completed_at = now
        match.status = MatchStatus.COMPLETED
        match.result_type = MatchResultType.ADMINISTRATIVE
        match.save(
            update_fields=[
                "home_score",
                "away_score",
                "completed_at",
                "status",
                "result_type",
                "updated_at",
            ]
        )

        from .matchday import MatchdayOperationsService
        MatchdayOperationsService.mark_administrative_result(
            match=match,
            decision=decision,
            performed_by=decided_by,
        )
        if match.fixture.federation_competition_id:
            from federations.tournaments import FederationTournamentProgressionService
            FederationTournamentProgressionService.resolve_completed_match(
                match=match,
                competition=source.competition,
            )
        return decision
