"""Durable live-match event stream and client synchronization services.

The database event log is authoritative.  SSE is only a transport over that
log, so reconnect/catch-up semantics do not depend on one web worker staying
alive.  Web/mobile clients persist the last sequence they have applied and ask
for events strictly after that cursor.
"""
from __future__ import annotations

from dataclasses import dataclass
from django.db import transaction
from django.db.models import Q
from django.utils import timezone

from .constants import (
    InteractiveMatchSessionStatus,
    LiveStreamEventType,
    LiveStreamVisibility,
    LIVE_STREAM_POLICY_KEY,
    LIVE_STREAM_POLICY_VERSION,
    LIVE_STREAM_SCHEMA_VERSION,
)
from .engine.serialization import payload_sha256
from .engine.v22 import FTGMatchEngineV22
from .exceptions import (
    InteractiveMatchAuthorizationError,
    InteractiveMatchSessionNotFoundError,
    LiveMatchStreamCursorError,
    LiveMatchStreamIntegrityError,
)
from .models import InteractiveMatchCheckpoint, InteractiveMatchSession, LiveMatchStreamEvent


DEFAULT_SYNC_LIMIT = 100
MAX_SYNC_LIMIT = 250


def _event_evidence_payload(
    *, session_id, sequence, schema_version, policy_key, policy_version,
    event_type, visibility, club_id, revision, payload
):
    return {
        "session_id": str(session_id),
        "sequence": int(sequence),
        "schema_version": int(schema_version),
        "policy_key": policy_key,
        "policy_version": policy_version,
        "event_type": event_type,
        "visibility": visibility,
        "club_id": str(club_id) if club_id else None,
        "revision": int(revision),
        "payload": payload,
    }


def verify_stream_event(row: LiveMatchStreamEvent) -> None:
    expected = payload_sha256(_event_evidence_payload(
        session_id=row.session_id,
        sequence=row.sequence,
        schema_version=row.schema_version,
        policy_key=row.policy_key,
        policy_version=row.policy_version,
        event_type=row.event_type,
        visibility=row.visibility,
        club_id=row.club_id,
        revision=row.revision,
        payload=row.payload,
    ))
    if expected != row.event_hash:
        raise LiveMatchStreamIntegrityError(
            "Live stream event hash does not match its immutable payload."
        )


def _manager_club(session: InteractiveMatchSession, user):
    if getattr(user, "is_staff", False):
        return None
    fixture = session.match.fixture
    for club in (fixture.home_club, fixture.away_club):
        career = getattr(club, "coach_career", None)
        if career is not None and career.user_id == user.pk:
            return club
    return None


def _verify_checkpoint_evidence(*, session: InteractiveMatchSession, row: InteractiveMatchCheckpoint) -> None:
    if session.snapshot_id is None:
        raise LiveMatchStreamIntegrityError(
            "Published checkpoint belongs to a session without a kickoff snapshot."
        )
    projection = {
        "session_id": str(session.pk),
        "snapshot_hash": session.snapshot.state_hash,
        "segment": row.segment,
        "start_minute": row.start_minute,
        "end_minute": row.end_minute,
        "phase": row.phase,
        "home_score": row.home_score,
        "away_score": row.away_score,
        "events": row.events_payload,
        "tactical_decisions": row.tactical_decisions_payload,
        "command_sequence": row.command_sequence,
    }
    # Historical v2.2 checkpoint hashes predate live statistics. New v3
    # checkpoints seal their causal statistics snapshot as additional evidence.
    if session.engine_key != FTGMatchEngineV22.key:
        projection["statistics"] = row.statistics_payload
    expected = payload_sha256(projection)
    if expected != row.projection_hash:
        raise LiveMatchStreamIntegrityError(
            "Interactive checkpoint hash does not match its immutable payload."
        )


def _serialize_event(row: LiveMatchStreamEvent) -> dict:
    verify_stream_event(row)
    return {
        "id": str(row.pk),
        "sequence": row.sequence,
        "schema_version": row.schema_version,
        "event_type": row.event_type,
        "payload": row.payload,
        "created_at": row.created_at.isoformat(),
    }


class LiveMatchStreamPublisher:
    """Append-only publisher.

    `_publish_locked` must be called while the session row is protected by the
    surrounding transaction.  InteractiveMatchRunnerService already owns that
    lock at every mutation boundary, which keeps stream sequence allocation in
    the same transaction as the domain change it describes.
    """

    @staticmethod
    def _publish_locked(
        *,
        session: InteractiveMatchSession,
        event_type: str,
        payload: dict,
        visibility: str = LiveStreamVisibility.PUBLIC,
        club=None,
    ) -> LiveMatchStreamEvent:
        if event_type not in LiveStreamEventType.values:
            raise ValueError("Unsupported live stream event type.")
        if visibility not in LiveStreamVisibility.values:
            raise ValueError("Unsupported live stream visibility.")
        if visibility == LiveStreamVisibility.CLUB and club is None:
            raise ValueError("CLUB stream event requires club.")
        if visibility != LiveStreamVisibility.CLUB and club is not None:
            raise ValueError("Only CLUB stream events may carry club.")
        if club is not None:
            fixture = session.match.fixture
            if club.pk not in {fixture.home_club_id, fixture.away_club_id}:
                raise ValueError("CLUB stream event must target a fixture participant.")

        sequence = session.stream_sequence + 1
        evidence = _event_evidence_payload(
            session_id=session.pk,
            sequence=sequence,
            schema_version=LIVE_STREAM_SCHEMA_VERSION,
            policy_key=LIVE_STREAM_POLICY_KEY,
            policy_version=LIVE_STREAM_POLICY_VERSION,
            event_type=event_type,
            visibility=visibility,
            club_id=getattr(club, "pk", None),
            revision=session.revision,
            payload=payload,
        )
        row = LiveMatchStreamEvent.objects.create(
            session=session,
            sequence=sequence,
            schema_version=LIVE_STREAM_SCHEMA_VERSION,
            policy_key=LIVE_STREAM_POLICY_KEY,
            policy_version=LIVE_STREAM_POLICY_VERSION,
            event_type=event_type,
            visibility=visibility,
            club=club,
            revision=session.revision,
            payload=payload,
            event_hash=payload_sha256(evidence),
        )
        session.stream_sequence = sequence
        session.save(update_fields=["stream_sequence", "updated_at"])
        return row

    @classmethod
    @transaction.atomic
    def publish(
        cls,
        *,
        session_id,
        event_type: str,
        payload: dict,
        visibility: str = LiveStreamVisibility.PUBLIC,
        club=None,
    ):
        session = InteractiveMatchSession.objects.select_for_update().get(pk=session_id)
        return cls._publish_locked(
            session=session,
            event_type=event_type,
            payload=payload,
            visibility=visibility,
            club=club,
        )

    @classmethod
    def session_opened(cls, *, session: InteractiveMatchSession):
        return cls._publish_locked(
            session=session,
            event_type=LiveStreamEventType.SESSION_OPENED,
            payload={
                "session_id": str(session.pk),
                "match_id": str(session.match_id),
                "status": session.status,
                "current_segment": session.current_segment,
                "current_minute": session.current_minute,
                "home_score": session.home_score,
                "away_score": session.away_score,
                "next_advance_at": session.next_advance_at.isoformat() if session.next_advance_at else None,
                "engine": {"key": session.engine_key, "version": session.engine_version},
            },
        )

    @classmethod
    def command_accepted(cls, *, session: InteractiveMatchSession, command):
        return cls._publish_locked(
            session=session,
            event_type=LiveStreamEventType.COMMAND_ACCEPTED,
            visibility=LiveStreamVisibility.CLUB,
            club=command.club,
            payload={
                "command_id": str(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.isoformat(),
            },
        )

    @classmethod
    def checkpoint_published(
        cls,
        *,
        session: InteractiveMatchSession,
        checkpoint: InteractiveMatchCheckpoint,
    ):
        return cls._publish_locked(
            session=session,
            event_type=LiveStreamEventType.CHECKPOINT_PUBLISHED,
            payload={
                "checkpoint_id": str(checkpoint.pk),
                "segment": checkpoint.segment,
                "start_minute": checkpoint.start_minute,
                "end_minute": checkpoint.end_minute,
                "phase": checkpoint.phase,
                "home_score": checkpoint.home_score,
                "away_score": checkpoint.away_score,
                "events": checkpoint.events_payload,
                "tactical_decisions": checkpoint.tactical_decisions_payload,
                "statistics": checkpoint.statistics_payload,
                "command_sequence": checkpoint.command_sequence,
                "projection_hash": checkpoint.projection_hash,
                "status": session.status,
                "revision": session.revision,
                "next_advance_at": session.next_advance_at.isoformat() if session.next_advance_at else None,
            },
        )

    @classmethod
    def match_completed(cls, *, session: InteractiveMatchSession):
        return cls._publish_locked(
            session=session,
            event_type=LiveStreamEventType.MATCH_COMPLETED,
            payload={
                "session_id": str(session.pk),
                "match_id": str(session.match_id),
                "status": session.status,
                "current_segment": session.current_segment,
                "current_minute": session.current_minute,
                "home_score": session.home_score,
                "away_score": session.away_score,
                "completed_at": session.completed_at.isoformat() if session.completed_at else None,
            },
        )

    @classmethod
    def match_aborted(cls, *, session: InteractiveMatchSession):
        return cls._publish_locked(
            session=session,
            event_type=LiveStreamEventType.MATCH_ABORTED,
            payload={
                "session_id": str(session.pk),
                "match_id": str(session.match_id),
                "status": session.status,
                "current_minute": session.current_minute,
                "home_score": session.home_score,
                "away_score": session.away_score,
                "aborted_at": session.aborted_at.isoformat() if session.aborted_at else None,
            },
        )


@dataclass(frozen=True)
class StreamSyncResult:
    events: tuple[dict, ...]
    cursor: int
    latest_sequence: int
    has_more: bool
    terminal: bool

    def to_payload(self) -> dict:
        return {
            "events": list(self.events),
            "cursor": self.cursor,
            "latest_sequence": self.latest_sequence,
            "has_more": self.has_more,
            "terminal": self.terminal,
        }


class LiveMatchStreamService:
    @staticmethod
    def _session(match_id):
        try:
            return (
                InteractiveMatchSession.objects.select_related(
                    "match__fixture__home_club__coach_career",
                    "match__fixture__away_club__coach_career",
                    "snapshot",
                )
                .get(match_id=match_id)
            )
        except InteractiveMatchSession.DoesNotExist as exc:
            raise InteractiveMatchSessionNotFoundError(
                "Interactive session does not exist."
            ) from exc

    @staticmethod
    def _parse_cursor(value) -> int:
        if value in (None, ""):
            return 0
        if isinstance(value, bool):
            raise LiveMatchStreamCursorError("Stream cursor must be a non-negative integer.")
        try:
            cursor = int(value)
        except (TypeError, ValueError) as exc:
            raise LiveMatchStreamCursorError(
                "Stream cursor must be a non-negative integer."
            ) from exc
        if cursor < 0:
            raise LiveMatchStreamCursorError("Stream cursor must be a non-negative integer.")
        return cursor

    @staticmethod
    def _parse_limit(value) -> int:
        if value in (None, ""):
            return DEFAULT_SYNC_LIMIT
        if isinstance(value, bool):
            raise LiveMatchStreamCursorError("Stream limit must be an integer.")
        try:
            limit = int(value)
        except (TypeError, ValueError) as exc:
            raise LiveMatchStreamCursorError("Stream limit must be an integer.") from exc
        if not 1 <= limit <= MAX_SYNC_LIMIT:
            raise LiveMatchStreamCursorError(
                f"Stream limit must be between 1 and {MAX_SYNC_LIMIT}."
            )
        return limit

    @classmethod
    def catch_up(cls, *, match_id, user, after_sequence=0, limit=DEFAULT_SYNC_LIMIT) -> StreamSyncResult:
        if user is None or not getattr(user, "is_authenticated", False):
            raise InteractiveMatchAuthorizationError("Authentication is required for live stream access.")
        cursor = cls._parse_cursor(after_sequence)
        limit = cls._parse_limit(limit)
        session = cls._session(match_id)
        latest = session.stream_sequence
        if cursor > latest:
            raise LiveMatchStreamCursorError(
                f"Stream cursor {cursor} is ahead of latest sequence {latest}."
            )

        manager_club = _manager_club(session, user)
        visible = Q(visibility=LiveStreamVisibility.PUBLIC)
        if getattr(user, "is_staff", False):
            visible |= Q(visibility=LiveStreamVisibility.STAFF) | Q(visibility=LiveStreamVisibility.CLUB)
        elif manager_club is not None:
            visible |= Q(visibility=LiveStreamVisibility.CLUB, club=manager_club)

        # Freeze the upper sequence boundary before reading rows.  Without the
        # `sequence__lte=latest` bound, a concurrently committed public event
        # could appear in this query after `latest` was read and then be
        # skipped when an invisible tail advances the cursor.
        rows = list(
            LiveMatchStreamEvent.objects.filter(
                Q(session=session),
                Q(sequence__gt=cursor, sequence__lte=latest),
                visible,
            )
            .select_related("club")
            .order_by("sequence")[: limit + 1]
        )
        has_more = len(rows) > limit
        page = rows[:limit]
        events = tuple(_serialize_event(row) for row in page)
        if has_more:
            next_cursor = page[-1].sequence
        else:
            # It is safe to advance over invisible events at the tail: any future
            # event must receive a greater global session sequence.
            next_cursor = latest
        terminal = session.status in {
            InteractiveMatchSessionStatus.COMPLETED,
            InteractiveMatchSessionStatus.ABORTED,
        }
        return StreamSyncResult(
            events=events,
            cursor=next_cursor,
            latest_sequence=latest,
            has_more=has_more,
            terminal=terminal,
        )

    @classmethod
    def verify_session(cls, *, match_id) -> dict:
        session = cls._session(match_id)
        rows = list(
            LiveMatchStreamEvent.objects.filter(session=session)
            .select_related("club")
            .order_by("sequence")
        )
        expected = 1
        public_checkpoints = 0
        for row in rows:
            if row.sequence != expected:
                raise LiveMatchStreamIntegrityError(
                    f"Live stream sequence gap: expected {expected}, found {row.sequence}."
                )
            verify_stream_event(row)
            if row.event_type == LiveStreamEventType.CHECKPOINT_PUBLISHED and row.visibility == LiveStreamVisibility.PUBLIC:
                public_checkpoints += 1
            expected += 1
        observed = rows[-1].sequence if rows else 0
        if observed != session.stream_sequence:
            raise LiveMatchStreamIntegrityError(
                f"Session cursor is {session.stream_sequence} but durable log ends at {observed}."
            )
        checkpoint_count = session.checkpoints.count()
        if public_checkpoints != checkpoint_count:
            raise LiveMatchStreamIntegrityError(
                f"Checkpoint stream coverage mismatch: {public_checkpoints} events for {checkpoint_count} checkpoints."
            )
        return {
            "session_id": str(session.pk),
            "match_id": str(session.match_id),
            "status": session.status,
            "stream_sequence": session.stream_sequence,
            "event_count": len(rows),
            "checkpoint_count": checkpoint_count,
        }

    @classmethod
    def spectator_snapshot(cls, *, match_id, user) -> dict:
        if user is None or not getattr(user, "is_authenticated", False):
            raise InteractiveMatchAuthorizationError("Authentication is required for spectator state.")
        # No manager relationship is required.  Only already-published public
        # checkpoint data is exposed.
        session = cls._session(match_id)
        timeline = []
        tactical = []
        live_statistics = {}
        checkpoints = session.checkpoints.order_by("segment")
        for checkpoint in checkpoints:
            _verify_checkpoint_evidence(session=session, row=checkpoint)
            timeline.extend(checkpoint.events_payload or [])
            tactical.extend(checkpoint.tactical_decisions_payload or [])
            if checkpoint.statistics_payload:
                live_statistics = checkpoint.statistics_payload
        return {
            "session_id": str(session.pk),
            "match_id": str(session.match_id),
            "status": session.status,
            "stream_cursor": session.stream_sequence,
            "current_segment": session.current_segment,
            "current_minute": session.current_minute,
            "home_score": session.home_score,
            "away_score": session.away_score,
            "home_club": {
                "id": str(session.match.fixture.home_club_id),
                "name": session.match.fixture.home_club.name,
                "short_name": session.match.fixture.home_club.short_name,
            },
            "away_club": {
                "id": str(session.match.fixture.away_club_id),
                "name": session.match.fixture.away_club.name,
                "short_name": session.match.fixture.away_club.short_name,
            },
            "next_advance_at": session.next_advance_at,
            "timeline": timeline,
            "tactical_decisions": tactical,
            "live_statistics": live_statistics,
        }
