"""Matchday operations and pre-match orchestration.

This module owns operational state from lineup deadline through kickoff.  It
composes existing lineup, injury and match lifecycle services rather than
reimplementing those domains.
"""
from __future__ import annotations

import hashlib
import json

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

from injuries.resolver import InjuryResolver

from .constants import (
    LineupStatus,
    MatchPlayerSuspensionReason,
    MatchStatus,
    MatchdayAttendanceStatus,
    MatchdayAuditEventType,
    MatchdayOperationStatus,
    MatchdayReadinessStatus,
)
from .exceptions import (
    MatchSuspensionError,
    MatchdayAutoStartError,
    MatchdayCheckInError,
    MatchdayConfigurationError,
    MatchdayLineupDeadlineError,
    MatchdayNotPreparedError,
    MatchdayReadinessError,
)
from .matchday_policy import (
    DEFAULT_CHECKIN_DEADLINE_MINUTES,
    DEFAULT_CHECKIN_OPEN_MINUTES,
    DEFAULT_LINEUP_DEADLINE_MINUTES,
    DEFAULT_MAX_DELAY_MINUTES,
    MatchdayOperationsPolicyV1,
)
from .models import (
    Match,
    MatchLineup,
    MatchLineupEntry,
    MatchdayAuditEvent,
    MatchdayEligibilityCheck,
    MatchdayOperation,
    MatchdayOperationsProfile,
    MatchdayTeamState,
    PlayerMatchSuspension,
    PlayerMatchSuspensionRevocation,
)


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


class MatchdayOperationsService:
    """Authoritative pre-match workflow for one scheduled Match."""

    @classmethod
    @transaction.atomic
    def prepare_for_match(cls, *, match_id, performed_by=None) -> MatchdayOperation:
        match = cls._lock_match(match_id)
        if match.status != MatchStatus.SCHEDULED or match.scheduled_at is None:
            raise MatchdayConfigurationError("Only a SCHEDULED match can prepare matchday operations.")

        operation = MatchdayOperation.objects.select_for_update().filter(match=match).first()
        if operation is not None:
            return cls._refresh_locked_operation(
                operation=operation,
                match=match,
                performed_by=performed_by,
            )

        profile = MatchdayOperationsProfile.objects.filter(
            country__iexact=match.fixture.home_club.country,
            is_active=True,
        ).first()
        params = cls._profile_params(profile)
        timeline = MatchdayOperationsPolicyV1.build_timeline(
            kickoff_at=match.scheduled_at,
            **params,
        )
        operation = MatchdayOperation.objects.create(
            match=match,
            profile=profile,
            status=MatchdayOperationStatus.OPEN,
            lineup_deadline_minutes=params["lineup_deadline_minutes"],
            checkin_open_minutes=params["checkin_open_minutes"],
            checkin_deadline_minutes=params["checkin_deadline_minutes"],
            max_delay_minutes=params["max_delay_minutes"],
            auto_start_enabled=(profile.auto_start_enabled if profile else True),
            lineup_deadline_at=timeline.lineup_deadline_at,
            checkin_opens_at=timeline.checkin_opens_at,
            checkin_deadline_at=timeline.checkin_deadline_at,
            kickoff_at=timeline.kickoff_at,
            grace_deadline_at=timeline.grace_deadline_at,
            policy_key=MatchdayOperationsPolicyV1.policy_key,
            policy_version=MatchdayOperationsPolicyV1.policy_version,
            schema_version=MatchdayOperationsPolicyV1.schema_version,
        )
        cls._ensure_team_states(operation=operation, match=match)
        cls._audit(
            operation=operation,
            event_type=MatchdayAuditEventType.PREPARED,
            performed_by=performed_by,
            payload=cls._timeline_payload(operation),
        )
        return operation

    @classmethod
    @transaction.atomic
    def refresh_for_match_schedule(cls, *, match_id, performed_by=None) -> MatchdayOperation:
        """Create/refresh the operation after an authoritative kickoff assignment.

        A kickoff may not be moved once the lineup deadline has been reached or
        processed.  Because calendar rescheduling wraps this call in the same DB
        transaction, rejection also rolls the Match schedule change back.
        """
        match = cls._lock_match(match_id)
        if match.status != MatchStatus.SCHEDULED or match.scheduled_at is None:
            raise MatchdayConfigurationError("Matchday timeline requires a scheduled kickoff.")
        operation = MatchdayOperation.objects.select_for_update().filter(match=match).first()
        if operation is None:
            return cls.prepare_for_match(match_id=match.pk, performed_by=performed_by)
        return cls._refresh_locked_operation(
            operation=operation, match=match, performed_by=performed_by
        )

    @classmethod
    def assert_lineup_editable(cls, *, match: Match, at=None) -> None:
        operation = MatchdayOperation.objects.filter(match_id=match.pk).first()
        if operation is None:
            return
        at = at or timezone.now()
        if operation.deadline_processed_at is not None or at >= operation.lineup_deadline_at:
            raise MatchdayLineupDeadlineError(
                "The authoritative lineup deadline has passed; this lineup is frozen."
            )

    @classmethod
    @transaction.atomic
    def check_in(cls, *, match_id, club_id, performed_by=None, at=None) -> MatchdayTeamState:
        at = at or timezone.now()
        match = cls._lock_match(match_id)
        operation = cls._lock_operation(match)
        if match.status != MatchStatus.SCHEDULED:
            raise MatchdayCheckInError("Only a SCHEDULED match accepts team check-in.")
        if at < operation.checkin_opens_at:
            raise MatchdayCheckInError("Team check-in is not open yet.")
        if at > operation.grace_deadline_at:
            raise MatchdayCheckInError("The matchday grace window has closed.")

        team_state = cls._team_state(operation=operation, club_id=club_id, lock=True)
        if team_state.attendance_status == MatchdayAttendanceStatus.NO_SHOW:
            raise MatchdayCheckInError("A confirmed NO_SHOW requires operator review; it cannot self-check-in.")

        attendance = MatchdayOperationsPolicyV1.attendance_status(
            checked_in_at=at,
            checkin_deadline_at=operation.checkin_deadline_at,
        )
        if team_state.checked_in_at is None:
            team_state.checked_in_at = at
            team_state.checked_in_by = performed_by
        team_state.attendance_status = attendance
        team_state.save(
            update_fields=["checked_in_at", "checked_in_by", "attendance_status", "updated_at"]
        )
        cls._audit(
            operation=operation,
            event_type=MatchdayAuditEventType.CHECKED_IN,
            club_id=team_state.club_id,
            performed_by=performed_by,
            payload={
                "checked_in_at": team_state.checked_in_at.isoformat(),
                "attendance_status": attendance,
            },
        )
        if operation.deadline_processed_at is not None:
            cls._refresh_team_readiness(operation=operation, team_state=team_state)
        return team_state

    @classmethod
    @transaction.atomic
    def process_lineup_deadline(cls, *, match_id, performed_by=None, at=None) -> MatchdayOperation:
        at = at or timezone.now()
        match = cls._lock_match(match_id)
        operation = cls._lock_operation(match)
        if at < operation.lineup_deadline_at:
            raise MatchdayLineupDeadlineError("Lineup deadline has not been reached yet.")
        if operation.deadline_processed_at is not None:
            return operation

        from .lineups import MatchLineupService

        results = MatchLineupService.lock_submitted_at_deadline(match=match, locked_at=at)
        operation.deadline_processed_at = at
        operation.status = MatchdayOperationStatus.DEADLINE_PASSED
        operation.save(update_fields=["deadline_processed_at", "status", "updated_at"])
        cls._audit(
            operation=operation,
            event_type=MatchdayAuditEventType.LINEUP_DEADLINE,
            performed_by=performed_by,
            payload={"processed_at": at.isoformat(), "clubs": results},
        )
        for team_state in MatchdayTeamState.objects.select_for_update().filter(operation=operation).order_by("club_id"):
            cls._refresh_team_readiness(operation=operation, team_state=team_state)
        return operation

    @classmethod
    @transaction.atomic
    def refresh_readiness(cls, *, match_id) -> MatchdayOperation:
        match = cls._lock_match(match_id)
        operation = cls._lock_operation(match)
        if operation.deadline_processed_at is None:
            raise MatchdayReadinessError("Readiness cannot be finalized before lineup deadline processing.")
        for team_state in MatchdayTeamState.objects.select_for_update().filter(operation=operation).order_by("club_id"):
            cls._refresh_team_readiness(operation=operation, team_state=team_state)
        cls._derive_operation_status(operation=operation, now=timezone.now(), allow_no_show=False)
        return operation

    @classmethod
    def sync(cls, *, match_id, performed_by=None, now=None, auto_start=True) -> MatchdayOperation:
        """Advance one operation and optionally auto-start after committing state.

        The auto-start call is intentionally outside the state transaction.
        MatchLifecycleService owns the canonical Competition -> Match lock order;
        calling it while this worker already held Match would invert that order.
        """
        now = now or timezone.now()
        should_auto_start = False

        with transaction.atomic():
            match = cls._lock_match(match_id)
            operation = cls._lock_operation(match)

            if match.status == MatchStatus.CANCELLED:
                if operation.status != MatchdayOperationStatus.CANCELLED:
                    operation.status = MatchdayOperationStatus.CANCELLED
                    operation.closed_at = operation.closed_at or now
                    operation.save(update_fields=["status", "closed_at", "updated_at"])
                    cls._audit(
                        operation=operation,
                        event_type=MatchdayAuditEventType.CANCELLED,
                        performed_by=performed_by,
                        payload={"at": now.isoformat()},
                    )
                return operation
            if match.status == MatchStatus.COMPLETED:
                if operation.status != MatchdayOperationStatus.CLOSED:
                    operation.status = MatchdayOperationStatus.CLOSED
                    operation.closed_at = operation.closed_at or match.completed_at or now
                    operation.save(update_fields=["status", "closed_at", "updated_at"])
                    cls._audit(
                        operation=operation,
                        event_type=MatchdayAuditEventType.CLOSED,
                        performed_by=performed_by,
                        payload={"at": operation.closed_at.isoformat()},
                    )
                return operation
            if match.status == MatchStatus.IN_PROGRESS:
                if operation.status != MatchdayOperationStatus.STARTED:
                    operation.status = MatchdayOperationStatus.STARTED
                    operation.started_at = operation.started_at or match.started_at or now
                    operation.save(update_fields=["status", "started_at", "updated_at"])
                return operation

            if now >= operation.lineup_deadline_at and operation.deadline_processed_at is None:
                from .lineups import MatchLineupService
                results = MatchLineupService.lock_submitted_at_deadline(match=match, locked_at=now)
                operation.deadline_processed_at = now
                operation.status = MatchdayOperationStatus.DEADLINE_PASSED
                operation.save(update_fields=["deadline_processed_at", "status", "updated_at"])
                cls._audit(
                    operation=operation,
                    event_type=MatchdayAuditEventType.LINEUP_DEADLINE,
                    performed_by=performed_by,
                    payload={"processed_at": now.isoformat(), "clubs": results},
                )

            if operation.deadline_processed_at is not None:
                for team_state in MatchdayTeamState.objects.select_for_update().filter(operation=operation).order_by("club_id"):
                    cls._refresh_team_readiness(operation=operation, team_state=team_state)

            both_ready = cls._derive_operation_status(
                operation=operation,
                now=now,
                allow_no_show=True,
                performed_by=performed_by,
            )
            should_auto_start = (
                auto_start
                and operation.auto_start_enabled
                and both_ready
                and now >= operation.kickoff_at
                and now <= operation.grace_deadline_at
            )

        if should_auto_start:
            from .services import MatchLifecycleService
            try:
                started = MatchLifecycleService.start(match_id=match_id)
            except Exception as exc:
                raise MatchdayAutoStartError("Auto-start failed after readiness passed.") from exc
            with transaction.atomic():
                operation = MatchdayOperation.objects.select_for_update().get(match_id=match_id)
                # MatchLifecycleService already records STARTED. Add the
                # automation-specific evidence as a second immutable event.
                cls._audit(
                    operation=operation,
                    event_type=MatchdayAuditEventType.AUTO_START,
                    performed_by=performed_by,
                    payload={"started_at": started.started_at.isoformat()},
                )
                return operation

        return MatchdayOperation.objects.get(match_id=match_id)

    @classmethod
    def assert_match_start_ready(cls, *, match: Match, at=None) -> None:
        """Extra gate used by MatchLifecycleService when a matchday operation exists."""
        operation = MatchdayOperation.objects.select_for_update().filter(match_id=match.pk).first()
        if operation is None:
            return  # legacy/non-calendar match path
        at = at or timezone.now()
        if operation.deadline_processed_at is None:
            raise MatchdayReadinessError("Lineup deadline has not been processed.")
        states = list(
            MatchdayTeamState.objects.select_for_update()
            .filter(operation=operation)
            .order_by("club_id")
        )
        if len(states) != 2:
            raise MatchdayReadinessError("Both fixture participants require matchday state.")
        # Re-run eligibility at the exact start boundary so a last-minute injury,
        # suspension assignment, or suspension revocation cannot be hidden by a
        # stale READY state from an earlier worker pass.
        for state in states:
            cls._refresh_team_readiness(operation=operation, team_state=state)
        for state in states:
            if state.readiness_status != MatchdayReadinessStatus.READY:
                raise MatchdayReadinessError("Both teams must pass eligibility/readiness checks.")
            if state.attendance_status not in {
                MatchdayAttendanceStatus.PRESENT,
                MatchdayAttendanceStatus.LATE,
            }:
                raise MatchdayReadinessError("Both teams must check in before match start.")
        if at < operation.kickoff_at:
            raise MatchdayReadinessError("Match cannot start before its scheduled kickoff.")
        if at > operation.grace_deadline_at:
            raise MatchdayReadinessError("Grace deadline passed; operator/no-show review is required.")

    @classmethod
    @transaction.atomic
    def mark_cancelled(cls, *, match: Match, performed_by=None) -> None:
        operation = MatchdayOperation.objects.select_for_update().filter(match_id=match.pk).first()
        if operation is None:
            return
        if operation.status == MatchdayOperationStatus.CANCELLED:
            return
        operation.status = MatchdayOperationStatus.CANCELLED
        operation.closed_at = match.cancelled_at or timezone.now()
        operation.save(update_fields=["status", "closed_at", "updated_at"])
        cls._audit(
            operation=operation,
            event_type=MatchdayAuditEventType.CANCELLED,
            performed_by=performed_by,
            payload={"at": operation.closed_at.isoformat()},
        )

    @classmethod
    @transaction.atomic
    def mark_started(cls, *, match: Match, performed_by=None) -> None:
        operation = MatchdayOperation.objects.select_for_update().filter(match_id=match.pk).first()
        if operation is None:
            return
        operation.status = MatchdayOperationStatus.STARTED
        operation.started_at = match.started_at or timezone.now()
        operation.save(update_fields=["status", "started_at", "updated_at"])
        cls._audit(
            operation=operation,
            event_type=MatchdayAuditEventType.STARTED,
            performed_by=performed_by,
            payload={"started_at": operation.started_at.isoformat()},
        )

    @classmethod
    @transaction.atomic
    def mark_administrative_result(cls, *, match: Match, decision, performed_by=None) -> None:
        operation = MatchdayOperation.objects.select_for_update().filter(match_id=match.pk).first()
        if operation is None:
            return
        if operation.status == MatchdayOperationStatus.CLOSED:
            return
        operation.status = MatchdayOperationStatus.CLOSED
        operation.closed_at = match.completed_at or timezone.now()
        operation.save(update_fields=["status", "closed_at", "updated_at"])
        cls._audit(
            operation=operation,
            event_type=MatchdayAuditEventType.ADMINISTRATIVE_RESULT,
            performed_by=performed_by,
            payload={
                "decision_id": str(decision.pk),
                "reason": decision.reason,
                "outcome": decision.outcome,
                "home_score": decision.home_score,
                "away_score": decision.away_score,
                "evidence_hash": decision.evidence_hash,
                "closed_at": operation.closed_at.isoformat(),
            },
        )

    @classmethod
    def _refresh_locked_operation(cls, *, operation, match, performed_by=None):
        if operation.kickoff_at == match.scheduled_at:
            cls._ensure_team_states(operation=operation, match=match)
            return operation
        now = timezone.now()
        if operation.deadline_processed_at is not None or now >= operation.lineup_deadline_at:
            raise MatchdayConfigurationError(
                "Kickoff cannot be moved after the lineup deadline is reached/processed."
            )
        timeline = MatchdayOperationsPolicyV1.build_timeline(
            kickoff_at=match.scheduled_at,
            lineup_deadline_minutes=operation.lineup_deadline_minutes,
            checkin_open_minutes=operation.checkin_open_minutes,
            checkin_deadline_minutes=operation.checkin_deadline_minutes,
            max_delay_minutes=operation.max_delay_minutes,
        )
        previous = operation.kickoff_at
        operation.lineup_deadline_at = timeline.lineup_deadline_at
        operation.checkin_opens_at = timeline.checkin_opens_at
        operation.checkin_deadline_at = timeline.checkin_deadline_at
        operation.kickoff_at = timeline.kickoff_at
        operation.grace_deadline_at = timeline.grace_deadline_at
        operation.save(
            update_fields=[
                "lineup_deadline_at", "checkin_opens_at", "checkin_deadline_at",
                "kickoff_at", "grace_deadline_at", "updated_at",
            ]
        )
        cls._ensure_team_states(operation=operation, match=match)
        cls._audit(
            operation=operation,
            event_type=MatchdayAuditEventType.SCHEDULE_REFRESHED,
            performed_by=performed_by,
            payload={
                "previous_kickoff_at": previous.isoformat(),
                "new_kickoff_at": operation.kickoff_at.isoformat(),
                **cls._timeline_payload(operation),
            },
        )
        return operation

    @classmethod
    def _refresh_team_readiness(cls, *, operation, team_state):
        lineup = (
            MatchLineup.objects.filter(match_id=operation.match_id, club_id=team_state.club_id)
            .prefetch_related("entries__player")
            .first()
        )
        issues = []
        player_rows = []
        if lineup is None:
            issues.append({"code": "LINEUP_MISSING", "detail": "No lineup exists."})
        elif lineup.status != LineupStatus.LOCKED:
            issues.append({"code": "LINEUP_NOT_LOCKED", "detail": f"Lineup status is {lineup.status}."})
        else:
            entries = list(lineup.entries.all())
            starters = [entry for entry in entries if entry.role == "STARTER"]
            if len(starters) != 11:
                issues.append({"code": "STARTERS_INVALID", "detail": "Exactly 11 starters are required."})

            # Re-prove competition-specific registration at the matchday boundary.
            # This catches approved squad amendments that occurred after an
            # earlier lineup draft was created.
            try:
                from competition_registration.services import CompetitionEligibilityService
                from competition_registration.exceptions import CompetitionRegistrationError

                CompetitionEligibilityService.assert_match_players_registered(
                    match=operation.match,
                    club_id=team_state.club_id,
                    youth_team_id=lineup.youth_team_id,
                    player_ids=[entry.player_id for entry in entries],
                )
            except CompetitionRegistrationError as exc:
                issues.append({
                    "code": "COMPETITION_REGISTRATION_INVALID",
                    "detail": str(exc),
                })

            active_suspensions = {
                str(row.player_id): row
                for row in PlayerMatchSuspension.objects.filter(
                    match_id=operation.match_id,
                    player_id__in=[entry.player_id for entry in entries],
                    revocation__isnull=True,
                ).order_by("player_id")
            }
            for entry in sorted(entries, key=lambda item: str(item.player_id)):
                injury = InjuryResolver.for_player(player=entry.player)
                suspended = str(entry.player_id) in active_suspensions
                if not injury.match_eligible:
                    issues.append({
                        "code": "MEDICALLY_UNAVAILABLE",
                        "player_id": str(entry.player_id),
                        "active_injury_count": injury.active_injury_count,
                    })
                if suspended:
                    suspension = active_suspensions[str(entry.player_id)]
                    issues.append({
                        "code": "SUSPENDED",
                        "player_id": str(entry.player_id),
                        "reason": suspension.reason,
                        "suspension_id": str(suspension.pk),
                    })
                player_rows.append({
                    "player_id": str(entry.player_id),
                    "role": entry.role,
                    "slot": entry.slot,
                    "match_eligible_medical": injury.match_eligible,
                    "suspended": suspended,
                })

        eligible = not issues
        payload = {
            "match_id": str(operation.match_id),
            "club_id": str(team_state.club_id),
            "lineup_id": str(lineup.pk) if lineup else None,
            "lineup_status": lineup.status if lineup else None,
            "players": player_rows,
            "issues": issues,
            "eligible": eligible,
            "policy_key": operation.policy_key,
            "policy_version": operation.policy_version,
            "schema_version": operation.schema_version,
        }
        check = cls._record_eligibility(operation=operation, club_id=team_state.club_id, payload=payload)
        team_state.readiness_checked_at = check.created_at
        team_state.readiness_status = (
            MatchdayReadinessStatus.READY if eligible else MatchdayReadinessStatus.BLOCKED
        )
        team_state.block_reason = "" if eligible else "; ".join(issue["code"] for issue in issues)[:500]
        team_state.save(
            update_fields=["readiness_checked_at", "readiness_status", "block_reason", "updated_at"]
        )
        return eligible

    @classmethod
    def _derive_operation_status(cls, *, operation, now, allow_no_show, performed_by=None) -> bool:
        states = list(
            MatchdayTeamState.objects.select_for_update()
            .filter(operation=operation)
            .order_by("club_id")
        )
        both_ready = len(states) == 2 and all(
            state.readiness_status == MatchdayReadinessStatus.READY
            and state.attendance_status in {
                MatchdayAttendanceStatus.PRESENT,
                MatchdayAttendanceStatus.LATE,
            }
            for state in states
        )
        desired = MatchdayOperationsPolicyV1.temporal_state(
            now=now,
            timeline=cls._timeline(operation),
            both_ready=both_ready,
        )
        if desired == MatchdayOperationStatus.NO_SHOW_REVIEW and allow_no_show:
            for state in states:
                if state.attendance_status == MatchdayAttendanceStatus.PENDING:
                    state.attendance_status = MatchdayAttendanceStatus.NO_SHOW
                    state.save(update_fields=["attendance_status", "updated_at"])
                    cls._audit(
                        operation=operation,
                        event_type=MatchdayAuditEventType.NO_SHOW,
                        club_id=state.club_id,
                        performed_by=performed_by,
                        payload={"detected_at": now.isoformat()},
                    )
        if desired == MatchdayOperationStatus.READY and operation.ready_at is None:
            operation.ready_at = now
        if desired != operation.status:
            old = operation.status
            operation.status = desired
            fields = ["status", "updated_at"]
            if operation.ready_at is not None:
                fields.append("ready_at")
            operation.save(update_fields=fields)
            if desired == MatchdayOperationStatus.DELAYED:
                cls._audit(
                    operation=operation,
                    event_type=MatchdayAuditEventType.DELAYED,
                    performed_by=performed_by,
                    payload={"from_status": old, "at": now.isoformat()},
                )
        return both_ready

    @classmethod
    def _record_eligibility(cls, *, operation, club_id, payload):
        latest = (
            MatchdayEligibilityCheck.objects.filter(operation=operation, club_id=club_id)
            .order_by("-revision_number")
            .first()
        )
        evidence_hash = _hash(payload)
        if latest is not None and latest.evidence_hash == evidence_hash:
            return latest
        revision = 1 if latest is None else latest.revision_number + 1
        check = MatchdayEligibilityCheck.objects.create(
            operation=operation,
            club_id=club_id,
            revision_number=revision,
            eligible=payload["eligible"],
            payload=payload,
            evidence_hash=evidence_hash,
            policy_key=operation.policy_key,
            policy_version=operation.policy_version,
            schema_version=operation.schema_version,
        )
        cls._audit(
            operation=operation,
            event_type=MatchdayAuditEventType.READINESS_CHECKED,
            club_id=club_id,
            payload={
                "revision_number": revision,
                "eligible": check.eligible,
                "evidence_hash": evidence_hash,
            },
        )
        return check

    @classmethod
    def _audit(cls, *, operation, event_type, payload, club_id=None, performed_by=None):
        sequence = MatchdayAuditEvent.objects.filter(operation=operation).count() + 1
        hash_payload = {
            "operation_id": str(operation.pk),
            "match_id": str(operation.match_id),
            "sequence": sequence,
            "event_type": event_type,
            "club_id": str(club_id) if club_id else None,
            "payload": payload,
            "policy_key": operation.policy_key,
            "policy_version": operation.policy_version,
        }
        return MatchdayAuditEvent.objects.create(
            operation=operation,
            sequence=sequence,
            event_type=event_type,
            club_id=club_id,
            payload=payload,
            evidence_hash=_hash(hash_payload),
            performed_by=performed_by,
        )

    @staticmethod
    def _profile_params(profile):
        return {
            "lineup_deadline_minutes": (
                profile.lineup_deadline_minutes if profile else DEFAULT_LINEUP_DEADLINE_MINUTES
            ),
            "checkin_open_minutes": (
                profile.checkin_open_minutes if profile else DEFAULT_CHECKIN_OPEN_MINUTES
            ),
            "checkin_deadline_minutes": (
                profile.checkin_deadline_minutes if profile else DEFAULT_CHECKIN_DEADLINE_MINUTES
            ),
            "max_delay_minutes": (
                profile.max_delay_minutes if profile else DEFAULT_MAX_DELAY_MINUTES
            ),
        }

    @staticmethod
    def _timeline(operation):
        from .matchday_policy import MatchdayTimeline
        return MatchdayTimeline(
            lineup_deadline_at=operation.lineup_deadline_at,
            checkin_opens_at=operation.checkin_opens_at,
            checkin_deadline_at=operation.checkin_deadline_at,
            kickoff_at=operation.kickoff_at,
            grace_deadline_at=operation.grace_deadline_at,
        )

    @staticmethod
    def _timeline_payload(operation):
        return {
            "lineup_deadline_at": operation.lineup_deadline_at.isoformat(),
            "checkin_opens_at": operation.checkin_opens_at.isoformat(),
            "checkin_deadline_at": operation.checkin_deadline_at.isoformat(),
            "kickoff_at": operation.kickoff_at.isoformat(),
            "grace_deadline_at": operation.grace_deadline_at.isoformat(),
            "auto_start_enabled": operation.auto_start_enabled,
        }

    @staticmethod
    def _ensure_team_states(*, operation, match):
        expected = [match.fixture.home_club_id, match.fixture.away_club_id]
        for club_id in expected:
            MatchdayTeamState.objects.get_or_create(operation=operation, club_id=club_id)
        extra = MatchdayTeamState.objects.filter(operation=operation).exclude(club_id__in=expected)
        if extra.exists():
            raise MatchdayConfigurationError("Matchday team state contains a non-fixture club.")

    @staticmethod
    def _team_state(*, operation, club_id, lock=False):
        qs = MatchdayTeamState.objects
        if lock:
            qs = qs.select_for_update()
        try:
            return qs.get(operation=operation, club_id=club_id)
        except MatchdayTeamState.DoesNotExist as exc:
            raise MatchdayCheckInError("Club is not a participant in this match.") from exc

    @staticmethod
    def _lock_match(match_id):
        try:
            return (
                Match.objects.select_for_update()
                .select_related("fixture", "fixture__home_club", "fixture__away_club")
                .get(pk=match_id)
            )
        except Match.DoesNotExist as exc:
            from .exceptions import MatchNotFoundError
            raise MatchNotFoundError("Match does not exist.") from exc

    @staticmethod
    def _lock_operation(match):
        try:
            return MatchdayOperation.objects.select_for_update().get(match=match)
        except MatchdayOperation.DoesNotExist as exc:
            raise MatchdayNotPreparedError("Matchday operation has not been prepared.") from exc


class MatchSuspensionService:
    """Minimal auditable match-scoped suspension assignment service."""

    @staticmethod
    @transaction.atomic
    def assign(
        *, match_id, player_id, reason=MatchPlayerSuspensionReason.DISCIPLINARY,
        reason_text="", source_type="", source_id="", issued_by=None
    ) -> PlayerMatchSuspension:
        if reason not in MatchPlayerSuspensionReason.values:
            raise MatchSuspensionError("Unsupported suspension reason.")
        match = MatchdayOperationsService._lock_match(match_id)
        if match.status not in {MatchStatus.PENDING, MatchStatus.SCHEDULED}:
            raise MatchSuspensionError("Suspensions can only be assigned before match start.")
        try:
            return PlayerMatchSuspension.objects.create(
                match=match,
                player_id=player_id,
                reason=reason,
                reason_text=(reason_text or "").strip(),
                source_type=(source_type or "").strip(),
                source_id=(source_id or "").strip(),
                issued_by=issued_by,
            )
        except IntegrityError as exc:
            raise MatchSuspensionError("Player already has a suspension assignment for this match.") from exc

    @staticmethod
    @transaction.atomic
    def revoke(*, suspension_id, reason_text, revoked_by=None) -> PlayerMatchSuspensionRevocation:
        if not (reason_text or "").strip():
            raise MatchSuspensionError("Suspension revocation requires a reason.")
        try:
            suspension = PlayerMatchSuspension.objects.select_for_update().get(pk=suspension_id)
        except PlayerMatchSuspension.DoesNotExist as exc:
            raise MatchSuspensionError("Suspension does not exist.") from exc
        if suspension.match.status not in {MatchStatus.PENDING, MatchStatus.SCHEDULED}:
            raise MatchSuspensionError("A suspension cannot be revoked after match start.")
        if hasattr(suspension, "revocation"):
            return suspension.revocation
        return PlayerMatchSuspensionRevocation.objects.create(
            suspension=suspension,
            reason_text=reason_text.strip(),
            revoked_by=revoked_by,
        )
