import json
import time

from django.conf import settings
from django.db import close_old_connections
from django.http import StreamingHttpResponse
from django.utils import timezone

from drf_spectacular.utils import extend_schema
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle

from .exceptions import (
    InteractiveMatchAuthorizationError,
    InteractiveMatchCommandError,
    InteractiveMatchCommandWindowClosedError,
    InteractiveMatchConfigurationError,
    InteractiveMatchError,
    InteractiveMatchRevisionConflictError,
    InteractiveMatchSessionError,
    InteractiveMatchSessionNotFoundError,
    LiveMatchStreamCursorError,
    LiveMatchStreamIntegrityError,
)
from .interactive import InteractiveMatchRunnerService
from .streaming import LiveMatchStreamService
from .serializers import (
    LiveMatchAdvanceSerializer,
    LiveMatchCommandCreateSerializer,
    LiveMatchCommandSerializer,
    LiveMatchPrepareSerializer,
    LiveMatchPrepareResponseSerializer,
    LiveMatchStateSerializer,
    LiveMatchSyncQuerySerializer,
    LiveMatchSyncResponseSerializer,
    LiveMatchSpectatorStateSerializer,
    MatchAdvancedAnalyticsSerializer,
    MatchEnvironmentEvidenceSerializer,
    MatchMedicalEvidenceSerializer,
    MatchDefensiveMechanicsSerializer,
    MatchPossessionMechanicsSerializer,
    MatchPressingMechanicsSerializer,
    MatchOffBallMechanicsSerializer,
    MatchGoalkeeperDistributionMechanicsSerializer,
    MatchSetPiecePlanSerializer,
    MatchSetPiecePlanUpdateSerializer,
    MatchLineupDraftUpdateSerializer,
    MatchLineupSerializer,
)


class LiveMatchThrottle(UserRateThrottle):
    rate = "120/min"
    scope = "live_match"


class LiveMatchAPI(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    throttle_classes = [LiveMatchThrottle]

    def handle_exception(self, exc):
        if isinstance(exc, InteractiveMatchError):
            code = status.HTTP_400_BAD_REQUEST
            if isinstance(exc, InteractiveMatchSessionNotFoundError):
                code = status.HTTP_404_NOT_FOUND
            elif isinstance(exc, InteractiveMatchAuthorizationError):
                code = status.HTTP_403_FORBIDDEN
            elif isinstance(exc, (InteractiveMatchRevisionConflictError, InteractiveMatchCommandWindowClosedError, InteractiveMatchSessionError)):
                code = status.HTTP_409_CONFLICT
            elif isinstance(exc, InteractiveMatchConfigurationError):
                code = status.HTTP_400_BAD_REQUEST
            elif isinstance(exc, LiveMatchStreamCursorError):
                code = status.HTTP_400_BAD_REQUEST
            elif isinstance(exc, LiveMatchStreamIntegrityError):
                code = status.HTTP_409_CONFLICT
            return Response({"code": exc.__class__.__name__, "detail": str(exc)}, status=code)
        return super().handle_exception(exc)

    def input(self, serializer_class):
        serializer = serializer_class(data=self.request.data)
        serializer.is_valid(raise_exception=True)
        return serializer.validated_data


class LiveMatchStateView(LiveMatchAPI):
    serializer_class = LiveMatchStateSerializer

    @extend_schema(responses=LiveMatchStateSerializer)
    def get(self, request, match_id):
        state_payload = InteractiveMatchRunnerService.state_for_user(
            match_id=match_id, user=request.user
        )
        return Response(LiveMatchStateSerializer(state_payload).data)


class LiveMatchCommandView(LiveMatchAPI):
    serializer_class = LiveMatchCommandCreateSerializer

    @extend_schema(request=LiveMatchCommandCreateSerializer, responses={201: LiveMatchCommandSerializer})
    def post(self, request, match_id):
        data = self.input(LiveMatchCommandCreateSerializer)
        command, _ = InteractiveMatchRunnerService.submit_command(
            match_id=match_id,
            user=request.user,
            **data,
        )
        payload = {
            "id": command.pk,
            "sequence": command.sequence,
            "command_type": command.command_type,
            "effective_segment": command.effective_segment,
            "payload": command.payload,
            "command_hash": command.command_hash,
            "created_at": command.created_at,
        }
        return Response(LiveMatchCommandSerializer(payload).data, status=status.HTTP_201_CREATED)


class LiveMatchPrepareView(LiveMatchAPI):
    permission_classes = [permissions.IsAdminUser]
    serializer_class = LiveMatchPrepareSerializer

    @extend_schema(request=LiveMatchPrepareSerializer, responses={201: LiveMatchPrepareResponseSerializer})
    def post(self, request, match_id):
        data = self.input(LiveMatchPrepareSerializer)
        session = InteractiveMatchRunnerService.prepare(match_id=match_id, **data)
        # PREPARED sessions have no kickoff snapshot/state yet.
        payload = {
            "session_id": session.pk,
            "match_id": session.match_id,
            "status": session.status,
            "segment_duration_seconds": session.segment_duration_seconds,
        }
        return Response(LiveMatchPrepareResponseSerializer(payload).data, status=status.HTTP_201_CREATED)


class LiveMatchAdvanceView(LiveMatchAPI):
    permission_classes = [permissions.IsAdminUser]
    serializer_class = LiveMatchAdvanceSerializer

    @extend_schema(request=LiveMatchAdvanceSerializer, responses=LiveMatchStateSerializer)
    def post(self, request, match_id):
        data = self.input(LiveMatchAdvanceSerializer)
        InteractiveMatchRunnerService.advance(match_id=match_id, **data)
        state_payload = InteractiveMatchRunnerService.state_for_user(
            match_id=match_id, user=request.user
        )
        return Response(LiveMatchStateSerializer(state_payload).data)


class LiveMatchSyncView(LiveMatchAPI):
    """Finite catch-up endpoint for reconnects and background/mobile clients."""

    serializer_class = LiveMatchSyncResponseSerializer

    @extend_schema(parameters=[LiveMatchSyncQuerySerializer], responses=LiveMatchSyncResponseSerializer)
    def get(self, request, match_id):
        query = LiveMatchSyncQuerySerializer(data=request.query_params)
        query.is_valid(raise_exception=True)
        result = LiveMatchStreamService.catch_up(
            match_id=match_id,
            user=request.user,
            after_sequence=query.validated_data["after"],
            limit=query.validated_data["limit"],
        )
        return Response(LiveMatchSyncResponseSerializer(result.to_payload()).data)


class LiveMatchSpectatorStateView(LiveMatchAPI):
    """Public-within-authentication state: never exposes pending team commands."""

    serializer_class = LiveMatchSpectatorStateSerializer

    @extend_schema(responses=LiveMatchSpectatorStateSerializer)
    def get(self, request, match_id):
        payload = LiveMatchStreamService.spectator_snapshot(match_id=match_id, user=request.user)
        return Response(LiveMatchSpectatorStateSerializer(payload).data)


class LiveMatchStreamView(LiveMatchAPI):
    """Authenticated SSE stream backed by the durable event log.

    Browsers should use fetch()/ReadableStream so the JWT Authorization header
    can be supplied.  Mobile SSE clients may use the same header.  The server
    intentionally closes each connection after a bounded interval; reconnect
    with the last received `id` / sequence to catch up without polling.
    """

    serializer_class = LiveMatchSyncResponseSerializer

    def get(self, request, match_id):
        raw_after = request.query_params.get("after")
        if raw_after in (None, ""):
            raw_after = request.headers.get("Last-Event-ID", "0")
        # Validate before starting the streaming response so malformed cursors
        # get a normal JSON 400 rather than a late generator failure.
        LiveMatchStreamService.catch_up(
            match_id=match_id,
            user=request.user,
            after_sequence=raw_after,
            limit=1,
        )
        start_cursor = LiveMatchStreamService._parse_cursor(raw_after)
        user = request.user
        poll_seconds = max(0.25, float(getattr(settings, "LIVE_MATCH_SSE_POLL_SECONDS", 1.0)))
        heartbeat_seconds = max(2.0, float(getattr(settings, "LIVE_MATCH_SSE_HEARTBEAT_SECONDS", 10.0)))
        max_connection_seconds = max(
            heartbeat_seconds,
            float(getattr(settings, "LIVE_MATCH_SSE_MAX_CONNECTION_SECONDS", 55.0)),
        )

        def encode_event(event):
            data = json.dumps(event, ensure_ascii=False, separators=(",", ":"))
            return (
                f"id: {event['sequence']}\n"
                f"event: {event['event_type'].lower()}\n"
                f"data: {data}\n\n"
            )

        def event_stream():
            cursor = start_cursor
            opened = time.monotonic()
            last_heartbeat = opened
            yield ": ftg-live-stream-v1\nretry: 2000\n\n"
            while time.monotonic() - opened < max_connection_seconds:
                close_old_connections()
                result = LiveMatchStreamService.catch_up(
                    match_id=match_id,
                    user=user,
                    after_sequence=cursor,
                    limit=100,
                )
                for event in result.events:
                    cursor = event["sequence"]
                    yield encode_event(event)
                if not result.has_more:
                    # Advance over any private events hidden from this viewer.
                    cursor = result.cursor
                if result.terminal and not result.has_more and cursor >= result.latest_sequence:
                    yield (
                        f"id: {cursor}\n"
                        "event: stream_end\n"
                        f"data: {json.dumps({'cursor': cursor}, separators=(',', ':'))}\n\n"
                    )
                    break
                now_mono = time.monotonic()
                if now_mono - last_heartbeat >= heartbeat_seconds:
                    heartbeat = {
                        "cursor": cursor,
                        "server_time": timezone.now().isoformat(),
                    }
                    yield (
                        f"id: {cursor}\n"
                        "event: heartbeat\n"
                        f"data: {json.dumps(heartbeat, separators=(',', ':'))}\n\n"
                    )
                    last_heartbeat = now_mono
                time.sleep(poll_seconds)
            close_old_connections()

        response = StreamingHttpResponse(event_stream(), content_type="text/event-stream")
        response["Cache-Control"] = "no-cache, no-transform"
        response["X-Accel-Buffering"] = "no"
        response["Vary"] = "Authorization"
        return response


class MatchAdvancedAnalyticsView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchAdvancedAnalyticsSerializer

    @extend_schema(responses=MatchAdvancedAnalyticsSerializer)
    def get(self, request, match_id):
        from game_statistics.models import MatchAnalyticsRun
        try:
            run = MatchAnalyticsRun.objects.get(match_id=match_id)
        except MatchAnalyticsRun.DoesNotExist:
            return Response(
                {"code": "AdvancedAnalyticsUnavailable", "detail": "Advanced analytics are not available for this match yet."},
                status=status.HTTP_404_NOT_FOUND,
            )
        from matches.engine.serialization import payload_sha256
        if payload_sha256(run.analytics_payload) != run.output_hash:
            return Response(
                {"code": "AdvancedAnalyticsIntegrityError", "detail": "Stored analytics evidence failed integrity verification."},
                status=status.HTTP_409_CONFLICT,
            )
        return Response(MatchAdvancedAnalyticsSerializer(run.analytics_payload).data)


class MatchEnvironmentEvidenceView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchEnvironmentEvidenceSerializer

    @extend_schema(responses=MatchEnvironmentEvidenceSerializer)
    def get(self, request, match_id):
        from .engine.serialization import payload_sha256
        from .models import MatchEnvironmentEvidence
        try:
            evidence = MatchEnvironmentEvidence.objects.select_related("snapshot").get(match_id=match_id)
        except MatchEnvironmentEvidence.DoesNotExist:
            return Response(
                {"code": "MatchEnvironmentUnavailable", "detail": "Kickoff environment evidence is not available for this match yet."},
                status=status.HTTP_404_NOT_FOUND,
            )
        payload = {
            "match_id": str(evidence.match_id),
            "snapshot_id": str(evidence.snapshot_id),
            "venue_source": evidence.venue_source,
            "venue_reference": evidence.venue_reference,
            "climate_source": evidence.climate_source,
            "environment": evidence.environment_payload,
            "effects": evidence.effects_payload,
        }
        if payload_sha256(payload) != evidence.evidence_hash:
            return Response(
                {"code": "MatchEnvironmentIntegrityError", "detail": "Stored environment evidence failed integrity verification."},
                status=status.HTTP_409_CONFLICT,
            )
        return Response(MatchEnvironmentEvidenceSerializer({
            **payload,
            "evidence_hash": evidence.evidence_hash,
            "created_at": evidence.created_at,
        }).data)


class MatchMedicalEvidenceView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchMedicalEvidenceSerializer

    @extend_schema(responses=MatchMedicalEvidenceSerializer)
    def get(self, request, match_id):
        from .engine.serialization import payload_sha256
        from .models import MatchMedicalEvidence
        try:
            evidence = MatchMedicalEvidence.objects.select_related("snapshot").get(match_id=match_id)
        except MatchMedicalEvidence.DoesNotExist:
            return Response(
                {"code": "MatchMedicalEvidenceUnavailable", "detail": "Kickoff medical evidence is not available for this match yet."},
                status=status.HTTP_404_NOT_FOUND,
            )
        hash_payload = {
            "match_id": str(evidence.match_id),
            "snapshot_id": str(evidence.snapshot_id),
            "rules": evidence.rules_payload,
            "home": evidence.home_medical_payload,
            "away": evidence.away_medical_payload,
        }
        if payload_sha256(hash_payload) != evidence.evidence_hash:
            return Response(
                {"code": "MatchMedicalEvidenceIntegrityError", "detail": "Stored medical evidence failed integrity verification."},
                status=status.HTTP_409_CONFLICT,
            )
        return Response(MatchMedicalEvidenceSerializer({
            "match_id": evidence.match_id,
            "snapshot_id": evidence.snapshot_id,
            "rules": evidence.rules_payload,
            "home_medical": evidence.home_medical_payload,
            "away_medical": evidence.away_medical_payload,
            "evidence_hash": evidence.evidence_hash,
            "created_at": evidence.created_at,
        }).data)


class MatchDefensiveMechanicsView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchDefensiveMechanicsSerializer

    @extend_schema(responses=MatchDefensiveMechanicsSerializer)
    def get(self, request, match_id):
        from .engine.serialization import payload_sha256
        from .models import MatchDefensiveEvent, MatchSimulationRun
        try:
            run = MatchSimulationRun.objects.select_related("snapshot").get(snapshot__match_id=match_id)
        except MatchSimulationRun.DoesNotExist:
            return Response(
                {"code": "DefensiveMechanicsUnavailable", "detail": "Defensive mechanics are not available for this match yet."},
                status=status.HTTP_404_NOT_FOUND,
            )
        rows = list(MatchDefensiveEvent.objects.filter(match_id=match_id, run=run).order_by("sequence"))
        events = []
        for expected_sequence, row in enumerate(rows, start=1):
            if row.sequence != expected_sequence:
                return Response(
                    {"code": "DefensiveMechanicsIntegrityError", "detail": "Defensive event sequence is not contiguous."},
                    status=status.HTTP_409_CONFLICT,
                )
            payload = {
                "match_id": str(match_id),
                "run_id": str(run.pk),
                "sequence": row.sequence,
                "minute": row.minute,
                "phase": row.phase,
                "type": row.event_type,
                "defending_club_id": str(row.defending_club_id),
                "attacking_club_id": str(row.attacking_club_id),
                "player_id": str(row.player_id) if row.player_id else None,
                "opponent_player_id": str(row.opponent_player_id) if row.opponent_player_id else None,
                "outcome": row.outcome,
                "zone": row.zone,
                "detail": row.detail_payload,
            }
            if payload_sha256(payload) != row.evidence_hash:
                return Response(
                    {"code": "DefensiveMechanicsIntegrityError", "detail": "Stored defensive event failed integrity verification."},
                    status=status.HTTP_409_CONFLICT,
                )
            events.append({key: value for key, value in payload.items() if key not in {"match_id", "run_id"}})
        summary = {
            "total_actions": len(events),
            "interceptions": sum(row["type"] == "INTERCEPTION" for row in events),
            "tackles": sum(row["type"] == "TACKLE" for row in events),
            "ground_duels": sum(row["type"] == "GROUND_DUEL" for row in events),
            "aerial_duels": sum(row["type"] == "AERIAL_DUEL" for row in events),
            "blocks": sum(row["type"] == "BLOCK" for row in events),
            "clearances": sum(row["type"] in {"CLEARANCE", "SWEEPER_CLEARANCE"} for row in events),
            "goalkeeper_saves": sum(row["type"] in {"KEEPER_SAVE", "KEEPER_PARRY", "ONE_ON_ONE_SAVE"} for row in events),
            "goalkeeper_claims": sum(row["type"] == "KEEPER_CLAIM" for row in events),
            "goalkeeper_punches": sum(row["type"] == "KEEPER_PUNCH" for row in events),
            "sweeper_actions": sum(row["type"] in {"SWEEPER_CLEARANCE", "SWEEPER_MISJUDGEMENT"} for row in events),
            "defensive_errors": sum(row["type"] == "DEFENSIVE_ERROR" for row in events),
        }
        return Response(MatchDefensiveMechanicsSerializer({
            "match_id": match_id,
            "run_id": run.pk,
            "engine_key": run.engine_key,
            "engine_version": run.engine_version,
            "defensive_events": events,
            "defensive_summary": summary,
        }).data)


class MatchPossessionMechanicsView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchPossessionMechanicsSerializer

    @extend_schema(responses=MatchPossessionMechanicsSerializer)
    def get(self, request, match_id):
        from .engine.serialization import payload_sha256
        from .models import MatchPossessionEvent, MatchSimulationReport, MatchSimulationRun
        try:
            run = MatchSimulationRun.objects.select_related("snapshot").get(snapshot__match_id=match_id)
            report = MatchSimulationReport.objects.get(run=run)
        except (MatchSimulationRun.DoesNotExist, MatchSimulationReport.DoesNotExist):
            return Response(
                {"code": "PossessionMechanicsUnavailable", "detail": "Possession mechanics are not available for this match yet."},
                status=status.HTTP_404_NOT_FOUND,
            )
        if payload_sha256(report.report_payload) != report.report_hash:
            return Response(
                {"code": "PossessionMechanicsIntegrityError", "detail": "Stored simulation report failed integrity verification."},
                status=status.HTTP_409_CONFLICT,
            )
        rows = list(MatchPossessionEvent.objects.filter(match_id=match_id, run=run).order_by("sequence"))
        events = []
        action_cursor = {}
        for expected_sequence, row in enumerate(rows, start=1):
            if row.sequence != expected_sequence:
                return Response(
                    {"code": "PossessionMechanicsIntegrityError", "detail": "Possession event sequence is not contiguous."},
                    status=status.HTTP_409_CONFLICT,
                )
            expected_action = action_cursor.get(row.possession_sequence, 0) + 1
            if row.action_sequence != expected_action:
                return Response(
                    {"code": "PossessionMechanicsIntegrityError", "detail": "Possession action sequence is not contiguous."},
                    status=status.HTTP_409_CONFLICT,
                )
            action_cursor[row.possession_sequence] = row.action_sequence
            payload = {
                "match_id": str(match_id), "run_id": str(run.pk),
                "sequence": row.sequence, "minute": row.minute, "phase": row.phase,
                "possession_sequence": row.possession_sequence, "action_sequence": row.action_sequence,
                "type": row.event_type, "club_id": str(row.club_id),
                "opponent_club_id": str(row.opponent_club_id),
                "player_id": str(row.player_id) if row.player_id else None,
                "target_player_id": str(row.target_player_id) if row.target_player_id else None,
                "origin_zone": row.origin_zone, "destination_zone": row.destination_zone,
                "channel": row.channel, "outcome": row.outcome,
                "transition_state": row.transition_state, "detail": row.detail_payload,
            }
            if payload_sha256(payload) != row.evidence_hash:
                return Response(
                    {"code": "PossessionMechanicsIntegrityError", "detail": "Stored possession event failed integrity verification."},
                    status=status.HTTP_409_CONFLICT,
                )
            events.append({key: value for key, value in payload.items() if key not in {"match_id", "run_id"}})

        advanced = dict((report.report_payload or {}).get("advanced_analytics") or {})
        report_events = list(advanced.get("possession_events") or [])
        if len(report_events) != len(events):
            return Response(
                {"code": "PossessionMechanicsIntegrityError", "detail": "Possession projection does not match authoritative report."},
                status=status.HTTP_409_CONFLICT,
            )
        return Response(MatchPossessionMechanicsSerializer({
            "match_id": match_id, "run_id": run.pk,
            "engine_key": run.engine_key, "engine_version": run.engine_version,
            "possession_events": events,
            "possession_summary": advanced.get("possession_summary") or {},
            "pass_events": advanced.get("pass_events") or [],
            "passing_network": advanced.get("passing_network") or [],
            "transition_summary": advanced.get("transition_summary") or {},
        }).data)


class MatchPressingMechanicsView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchPressingMechanicsSerializer

    @extend_schema(responses=MatchPressingMechanicsSerializer)
    def get(self, request, match_id):
        from .engine.serialization import payload_sha256
        from .models import MatchPressingEvent, MatchSimulationReport, MatchSimulationRun
        try:
            run = MatchSimulationRun.objects.select_related("snapshot").get(snapshot__match_id=match_id)
            report = MatchSimulationReport.objects.get(run=run)
        except (MatchSimulationRun.DoesNotExist, MatchSimulationReport.DoesNotExist):
            return Response(
                {"code": "PressingMechanicsUnavailable", "detail": "Pressing mechanics are not available for this match yet."},
                status=status.HTTP_404_NOT_FOUND,
            )
        if payload_sha256(report.report_payload) != report.report_hash:
            return Response(
                {"code": "PressingMechanicsIntegrityError", "detail": "Stored simulation report failed integrity verification."},
                status=status.HTTP_409_CONFLICT,
            )
        rows = list(MatchPressingEvent.objects.filter(match_id=match_id, run=run).order_by("sequence"))
        events = []
        for expected_sequence, row in enumerate(rows, start=1):
            if row.sequence != expected_sequence:
                return Response(
                    {"code": "PressingMechanicsIntegrityError", "detail": "Pressing event sequence is not contiguous."},
                    status=status.HTTP_409_CONFLICT,
                )
            payload = {
                "match_id": str(match_id), "run_id": str(run.pk),
                "sequence": row.sequence, "minute": row.minute, "phase": row.phase,
                "type": row.event_type, "pressing_club_id": str(row.pressing_club_id),
                "opponent_club_id": str(row.opponent_club_id),
                "possession_sequence": row.possession_sequence,
                "player_id": str(row.player_id) if row.player_id else None,
                "target_player_id": str(row.target_player_id) if row.target_player_id else None,
                "zone": row.zone, "channel": row.channel,
                "defensive_strategy": row.defensive_strategy, "trigger": row.trigger,
                "line_height": row.line_height, "compactness": row.compactness, "width": row.width,
                "press_intensity": float(row.press_intensity), "outcome": row.outcome, "detail": row.detail_payload,
            }
            if payload_sha256(payload) != row.evidence_hash:
                return Response(
                    {"code": "PressingMechanicsIntegrityError", "detail": "Stored pressing event failed integrity verification."},
                    status=status.HTTP_409_CONFLICT,
                )
            events.append({key: value for key, value in payload.items() if key not in {"match_id", "run_id"}})
        advanced = dict((report.report_payload or {}).get("advanced_analytics") or {})
        if len(list(advanced.get("pressing_events") or [])) != len(events):
            return Response(
                {"code": "PressingMechanicsIntegrityError", "detail": "Pressing projection does not match authoritative report."},
                status=status.HTTP_409_CONFLICT,
            )
        return Response(MatchPressingMechanicsSerializer({
            "match_id": match_id, "run_id": run.pk, "engine_key": run.engine_key,
            "engine_version": run.engine_version, "pressing_events": events,
            "pressing_summary": advanced.get("pressing_summary") or {},
        }).data)


class MatchOffBallMechanicsView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchOffBallMechanicsSerializer

    @extend_schema(responses=MatchOffBallMechanicsSerializer)
    def get(self, request, match_id):
        from .engine.serialization import payload_sha256
        from .models import MatchOffBallEvent, MatchSimulationReport, MatchSimulationRun
        try:
            run = MatchSimulationRun.objects.select_related("snapshot").get(snapshot__match_id=match_id)
            report = MatchSimulationReport.objects.get(run=run)
        except (MatchSimulationRun.DoesNotExist, MatchSimulationReport.DoesNotExist):
            return Response(
                {"code": "OffBallMechanicsUnavailable", "detail": "Off-ball mechanics are not available for this match yet."},
                status=status.HTTP_404_NOT_FOUND,
            )
        if payload_sha256(report.report_payload) != report.report_hash:
            return Response(
                {"code": "OffBallMechanicsIntegrityError", "detail": "Stored simulation report failed integrity verification."},
                status=status.HTTP_409_CONFLICT,
            )
        rows = list(MatchOffBallEvent.objects.filter(match_id=match_id, run=run).order_by("sequence"))
        events = []
        for expected_sequence, row in enumerate(rows, start=1):
            if row.sequence != expected_sequence:
                return Response(
                    {"code": "OffBallMechanicsIntegrityError", "detail": "Off-ball event sequence is not contiguous."},
                    status=status.HTTP_409_CONFLICT,
                )
            payload = {
                "match_id": str(match_id), "run_id": str(run.pk),
                "sequence": row.sequence, "minute": row.minute, "phase": row.phase,
                "type": row.event_type, "club_id": str(row.club_id),
                "opponent_club_id": str(row.opponent_club_id),
                "possession_sequence": row.possession_sequence,
                "player_id": str(row.player_id) if row.player_id else None,
                "related_player_id": str(row.related_player_id) if row.related_player_id else None,
                "origin_zone": row.origin_zone, "destination_zone": row.destination_zone,
                "origin_lane": row.origin_lane, "destination_lane": row.destination_lane,
                "tactical_role": row.tactical_role, "outcome": row.outcome,
                "detail": row.detail_payload,
            }
            if payload_sha256(payload) != row.evidence_hash:
                return Response(
                    {"code": "OffBallMechanicsIntegrityError", "detail": "Stored off-ball event failed integrity verification."},
                    status=status.HTTP_409_CONFLICT,
                )
            events.append({key: value for key, value in payload.items() if key not in {"match_id", "run_id"}})
        advanced = dict((report.report_payload or {}).get("advanced_analytics") or {})
        if len(list(advanced.get("off_ball_events") or [])) != len(events):
            return Response(
                {"code": "OffBallMechanicsIntegrityError", "detail": "Off-ball projection does not match authoritative report."},
                status=status.HTTP_409_CONFLICT,
            )
        return Response(MatchOffBallMechanicsSerializer({
            "match_id": match_id, "run_id": run.pk, "engine_key": run.engine_key,
            "engine_version": run.engine_version, "off_ball_events": events,
            "off_ball_summary": advanced.get("off_ball_summary") or {},
        }).data)


class MatchGoalkeeperDistributionMechanicsView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchGoalkeeperDistributionMechanicsSerializer

    @extend_schema(responses=MatchGoalkeeperDistributionMechanicsSerializer)
    def get(self, request, match_id):
        from .engine.serialization import payload_sha256
        from .models import MatchGoalkeeperDistributionEvent, MatchSimulationReport, MatchSimulationRun
        try:
            run = MatchSimulationRun.objects.select_related("snapshot").get(snapshot__match_id=match_id)
            report = MatchSimulationReport.objects.get(run=run)
        except (MatchSimulationRun.DoesNotExist, MatchSimulationReport.DoesNotExist):
            return Response(
                {"code": "GoalkeeperDistributionUnavailable", "detail": "Goalkeeper distribution mechanics are not available for this match yet."},
                status=status.HTTP_404_NOT_FOUND,
            )
        if payload_sha256(report.report_payload) != report.report_hash:
            return Response(
                {"code": "GoalkeeperDistributionIntegrityError", "detail": "Stored simulation report failed integrity verification."},
                status=status.HTTP_409_CONFLICT,
            )
        rows = list(MatchGoalkeeperDistributionEvent.objects.filter(match_id=match_id, run=run).order_by("sequence"))
        events = []
        for expected_sequence, row in enumerate(rows, start=1):
            if row.sequence != expected_sequence:
                return Response(
                    {"code": "GoalkeeperDistributionIntegrityError", "detail": "Goalkeeper distribution sequence is not contiguous."},
                    status=status.HTTP_409_CONFLICT,
                )
            payload = {
                "match_id": str(match_id), "run_id": str(run.pk), "sequence": row.sequence,
                "minute": row.minute, "phase": row.phase, "possession_sequence": row.possession_sequence,
                "club_id": str(row.club_id), "opponent_club_id": str(row.opponent_club_id),
                "goalkeeper_player_id": str(row.goalkeeper_id),
                "receiver_player_id": str(row.receiver_id) if row.receiver_id else None,
                "distribution_type": row.distribution_type, "source": row.source,
                "origin_zone": row.origin_zone, "destination_zone": row.destination_zone, "channel": row.channel,
                "under_pressure": row.under_pressure, "success_probability": float(row.success_probability),
                "outcome": row.outcome, "detail": row.detail_payload,
            }
            if payload_sha256(payload) != row.evidence_hash:
                return Response(
                    {"code": "GoalkeeperDistributionIntegrityError", "detail": "Stored goalkeeper distribution event failed integrity verification."},
                    status=status.HTTP_409_CONFLICT,
                )
            events.append({key: value for key, value in payload.items() if key not in {"match_id", "run_id"}})
        advanced = dict((report.report_payload or {}).get("advanced_analytics") or {})
        if len(list(advanced.get("goalkeeper_distribution_events") or [])) != len(events):
            return Response(
                {"code": "GoalkeeperDistributionIntegrityError", "detail": "Goalkeeper distribution projection does not match authoritative report."},
                status=status.HTTP_409_CONFLICT,
            )
        return Response(MatchGoalkeeperDistributionMechanicsSerializer({
            "match_id": match_id, "run_id": run.pk, "engine_key": run.engine_key, "engine_version": run.engine_version,
            "goalkeeper_distribution_events": events,
            "goalkeeper_distribution_summary": advanced.get("goalkeeper_distribution_summary") or {},
        }).data)


class _MatchLineupAPIBase(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]

    @staticmethod
    def _get_lineup(match_id, club_id):
        from .models import MatchLineup
        return (
            MatchLineup.objects.select_related("club", "youth_team")
            .prefetch_related("entries__player")
            .filter(match_id=match_id, club_id=club_id)
            .first()
        )

    @staticmethod
    def _payload(lineup):
        from .tactical_catalog import plan_payload
        return {
            "tactical_plan": plan_payload(lineup),
            "id": lineup.pk,
            "match_id": lineup.match_id,
            "club_id": lineup.club_id,
            "formation": lineup.formation,
            "status": lineup.status,
            "participant_type": lineup.participant_type,
            "youth_team_id": lineup.youth_team_id,
            "submitted_at": lineup.submitted_at,
            "locked_at": lineup.locked_at,
            "entries": [
                {
                    "id": entry.pk,
                    "player_id": entry.player_id,
                    "player_name": f"{entry.player.first_name} {entry.player.last_name}".strip(),
                    "player_position": entry.player.position,
                    "player_overall": entry.player.overall,
                    "role": entry.role,
                    "tactical_role": entry.tactical_role,
                    "slot": entry.slot,
                    "is_captain": entry.is_captain,
                }
                for entry in lineup.entries.all()
            ],
        }

    @staticmethod
    def _can_manage(user, club):
        from clubs.access import can_manage_club
        return can_manage_club(user, club)

    def _lineup_or_404(self, match_id, club_id):
        lineup = self._get_lineup(match_id, club_id)
        if lineup is None:
            return None, Response({"detail": "Lineup not found."}, status=status.HTTP_404_NOT_FOUND)
        if not self._can_manage(self.request.user, lineup.club):
            return None, Response({"detail": "Club management permission required."}, status=status.HTTP_403_FORBIDDEN)
        return lineup, None


class MatchLineupView(_MatchLineupAPIBase):
    serializer_class = MatchLineupDraftUpdateSerializer

    @extend_schema(responses=MatchLineupSerializer)
    def get(self, request, match_id, club_id):
        lineup, error = self._lineup_or_404(match_id, club_id)
        if error:
            return error
        return Response(MatchLineupSerializer(self._payload(lineup)).data)

    @extend_schema(request=MatchLineupDraftUpdateSerializer, responses=MatchLineupSerializer)
    def put(self, request, match_id, club_id):
        from clubs.models import Club
        from .exceptions import LineupError
        from .lineups import MatchLineupService

        club = Club.objects.filter(pk=club_id).first()
        if club is None:
            return Response({"detail": "Club not found."}, status=status.HTTP_404_NOT_FOUND)
        if not self._can_manage(request.user, club):
            return Response({"detail": "Club management permission required."}, status=status.HTTP_403_FORBIDDEN)

        serializer = MatchLineupDraftUpdateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = dict(serializer.validated_data)
        try:
            lineup = MatchLineupService.save_draft(
                match_id=match_id,
                club_id=club_id,
                formation=data["formation"],
                starters=data["starters"],
                substitutes=data.get("substitutes", ()),
                captain_id=data.get("captain_id"),
                youth_team_id=data.get("youth_team_id"),
                tactical_plan=data.get("tactical_plan"),
            )
        except LineupError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_409_CONFLICT)
        return Response(MatchLineupSerializer(self._payload(lineup)).data)


class MatchLineupSubmitView(_MatchLineupAPIBase):
    serializer_class = MatchLineupSerializer

    @extend_schema(request=None, responses=MatchLineupSerializer)
    def post(self, request, match_id, club_id):
        from .exceptions import LineupError
        from .lineups import MatchLineupService
        lineup, error = self._lineup_or_404(match_id, club_id)
        if error:
            return error
        try:
            lineup = MatchLineupService.submit(lineup_id=lineup.pk)
        except LineupError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_409_CONFLICT)
        return Response(MatchLineupSerializer(self._payload(lineup)).data)


class MatchLineupReopenView(_MatchLineupAPIBase):
    serializer_class = MatchLineupSerializer

    @extend_schema(request=None, responses=MatchLineupSerializer)
    def post(self, request, match_id, club_id):
        from .exceptions import LineupError
        from .lineups import MatchLineupService
        lineup, error = self._lineup_or_404(match_id, club_id)
        if error:
            return error
        try:
            lineup = MatchLineupService.reopen(lineup_id=lineup.pk)
        except LineupError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_409_CONFLICT)
        return Response(MatchLineupSerializer(self._payload(lineup)).data)


class MatchSetPiecePlanView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = MatchSetPiecePlanUpdateSerializer

    @staticmethod
    def _load(match_id, club_id):
        from .models import MatchLineup
        return MatchLineup.objects.select_related("club", "club__coach_career__user").get(
            match_id=match_id, club_id=club_id
        )

    @staticmethod
    def _payload(lineup):
        from .models import MatchSetPiecePlan
        try:
            plan = lineup.set_piece_plan
        except MatchSetPiecePlan.DoesNotExist:
            return {
                "lineup_id": lineup.pk, "club_id": lineup.club_id,
                "penalty_taker_id": None, "direct_free_kick_taker_id": None,
                "left_corner_taker_id": None, "right_corner_taker_id": None,
                "aerial_target_player_id": None, "penalty_order": [],
                "corner_routine": "MIXED", "free_kick_routine": "MIXED",
            }
        return {
            "lineup_id": lineup.pk, "club_id": lineup.club_id,
            "penalty_taker_id": plan.penalty_taker_id,
            "direct_free_kick_taker_id": plan.direct_free_kick_taker_id,
            "left_corner_taker_id": plan.left_corner_taker_id,
            "right_corner_taker_id": plan.right_corner_taker_id,
            "aerial_target_player_id": plan.aerial_target_player_id,
            "penalty_order": plan.penalty_order or [],
            "corner_routine": plan.corner_routine,
            "free_kick_routine": plan.free_kick_routine,
        }

    @extend_schema(responses=MatchSetPiecePlanSerializer)
    def get(self, request, match_id, club_id):
        from clubs.access import can_manage_club
        from .models import MatchLineup
        try:
            lineup = self._load(match_id, club_id)
        except MatchLineup.DoesNotExist:
            return Response({"detail": "Lineup not found."}, status=status.HTTP_404_NOT_FOUND)
        if not can_manage_club(request.user, lineup.club):
            return Response({"detail": "Club management permission required."}, status=status.HTTP_403_FORBIDDEN)
        return Response(MatchSetPiecePlanSerializer(self._payload(lineup)).data)

    @extend_schema(request=MatchSetPiecePlanUpdateSerializer, responses=MatchSetPiecePlanSerializer)
    def put(self, request, match_id, club_id):
        from clubs.access import can_manage_club
        from .exceptions import InvalidLineupPlayerError, LineupNotEditableError
        from .models import MatchLineup
        from .set_piece_plans import MatchSetPiecePlanService
        try:
            lineup = self._load(match_id, club_id)
        except MatchLineup.DoesNotExist:
            return Response({"detail": "Lineup not found."}, status=status.HTTP_404_NOT_FOUND)
        if not can_manage_club(request.user, lineup.club):
            return Response({"detail": "Club management permission required."}, status=status.HTTP_403_FORBIDDEN)
        serializer = MatchSetPiecePlanUpdateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        current = self._payload(lineup)
        values = dict(current)
        values.update(serializer.validated_data)
        for key in ("lineup_id", "club_id"):
            values.pop(key, None)
        try:
            MatchSetPiecePlanService.configure(lineup_id=lineup.pk, **values)
        except (InvalidLineupPlayerError, LineupNotEditableError) as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_409_CONFLICT)
        lineup = self._load(match_id, club_id)
        return Response(MatchSetPiecePlanSerializer(self._payload(lineup)).data)


class MyMatchesView(generics.GenericAPIView):
    """Read-only fixtures of clubs the authenticated user belongs to or manages.

    No client-provided club id is trusted. The same endpoint serves both
    player and coach dashboards without leaking another club's fixtures.
    """
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        from django.db.models import Q
        from api_core.permissions import is_platform_admin
        from clubs.models import Club
        from .models import Match

        clubs = Club.objects.filter(
            Q(coach_career__user=request.user)
            | Q(ownership_record__owner=request.user)
            | Q(squad_memberships__player__career__user=request.user)
        ).values_list("pk", flat=True).distinct()
        matches = Match.objects.select_related(
            "fixture__home_club", "fixture__away_club",
            "fixture__competition__league", "fixture__federation_competition",
        )
        if not is_platform_admin(request.user):
            matches = matches.filter(
                Q(fixture__home_club_id__in=clubs) | Q(fixture__away_club_id__in=clubs)
                | Q(lineups__entries__player__career__user=request.user)
            ).distinct()
        from rest_framework import serializers
        from .result_read_model import result_fields
        class PageQuery(serializers.Serializer):
            limit = serializers.IntegerField(default=100, min_value=1, max_value=200)
            offset = serializers.IntegerField(default=0, min_value=0)
        query = PageQuery(data=request.query_params)
        query.is_valid(raise_exception=True)
        limit, offset = query.validated_data['limit'], query.validated_data['offset']
        total = matches.count()
        matches = matches.order_by("-created_at", "-pk")[offset:offset + limit]
        result = []
        for match in matches:
            fixture = match.fixture
            result.append({
                "id": str(match.pk),
                "status": match.status,
                "scheduled_at": match.scheduled_at.isoformat() if match.scheduled_at else None,
                "home_club_id": str(fixture.home_club_id),
                "home_club_name": fixture.home_club.name,
                "away_club_id": str(fixture.away_club_id),
                "away_club_name": fixture.away_club.name,
                **result_fields(match),
                "competition_name": (
                    fixture.competition.league.name if fixture.competition_id
                    else fixture.federation_competition.name if fixture.federation_competition_id
                    else "Competition"
                ),
                "round_number": fixture.round_number,
            })
        return Response({"count": total, "limit": limit, "offset": offset, "results": result})
