"""Interactive Match Runner orchestration and live-command domain services."""
from __future__ import annotations

from datetime import timedelta

from django.db import transaction
from django.db.models import Max
from django.utils import timezone

from .competition_support import lock_competition_source_and_match
from .constants import (
    AttackingStrategy,
    DefensiveStrategy,
    InteractiveMatchSessionStatus,
    LiveMatchCommandType,
    MatchEventPhase,
    MatchEventType,
    MatchExecutionMode,
    MatchStatus,
)
from .engine.serialization import payload_sha256
from .engine.v22 import FTGMatchEngineV22, LiveCommandState
from .engine.registry import CurrentMatchEngine, engine_class
from .engine.v3 import FTGMatchEngineV3
from .engine.v22.commands import COMMAND_SUBSTITUTION, COMMAND_TACTICS
from .engine.v22.config import FIELD_SEGMENTS
from .exceptions import (
    InteractiveMatchAuthorizationError,
    InteractiveMatchCommandError,
    InteractiveMatchCommandWindowClosedError,
    InteractiveMatchConfigurationError,
    InteractiveMatchEvidenceImmutableError,
    InteractiveMatchRevisionConflictError,
    InteractiveMatchSessionError,
    InteractiveMatchSessionNotFoundError,
)
from .models import (
    InteractiveMatchCheckpoint,
    InteractiveMatchSession,
    LiveMatchCommand,
    Match,
    MatchSimulationRun,
)
from .simulation import MatchSimulationService, _project_v2_injuries


DEFAULT_SEGMENT_DURATION_SECONDS = 60


def _engine_for_session(session):
    try:
        return engine_class(session.engine_key, session.engine_version)()
    except ValueError as exc:
        raise InteractiveMatchSessionError(str(exc)) from exc


def _segment_bounds(segment: int) -> tuple[int, int]:
    try:
        return FIELD_SEGMENTS[segment - 1]
    except (IndexError, TypeError):
        raise InteractiveMatchSessionError("Interactive segment is outside 1..8.")


def _verify_command_evidence(row: LiveMatchCommand) -> None:
    expected = payload_sha256({
        "session_id": str(row.session_id),
        "match_id": str(row.session.match_id),
        "club_id": str(row.club_id),
        "sequence": row.sequence,
        "idempotency_key": row.idempotency_key,
        "command_type": row.command_type,
        "effective_segment": row.effective_segment,
        "submitted_minute": row.submitted_minute,
        "expected_revision": row.expected_revision,
        "payload": row.payload,
    })
    if expected != row.command_hash:
        raise InteractiveMatchEvidenceImmutableError(
            "Live command evidence hash does not match its immutable payload."
        )


def _verify_checkpoint_evidence(*, session: InteractiveMatchSession, row: InteractiveMatchCheckpoint) -> None:
    if session.snapshot_id is None:
        raise InteractiveMatchEvidenceImmutableError(
            "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 InteractiveMatchEvidenceImmutableError(
            "Interactive checkpoint evidence hash does not match its immutable payload."
        )


def _command_state(row: LiveMatchCommand) -> LiveCommandState:
    _verify_command_evidence(row)
    payload = row.payload or {}
    if row.command_type == LiveMatchCommandType.TACTICS:
        return LiveCommandState(
            sequence=row.sequence,
            command_ref=str(row.pk),
            club_id=str(row.club_id),
            command_type=COMMAND_TACTICS,
            effective_segment=row.effective_segment,
            attacking_strategy=payload.get("attacking_strategy"),
            defensive_strategy=payload.get("defensive_strategy"),
        )
    return LiveCommandState(
        sequence=row.sequence,
        command_ref=str(row.pk),
        club_id=str(row.club_id),
        command_type=COMMAND_SUBSTITUTION,
        effective_segment=row.effective_segment,
        player_out_id=str(payload.get("player_out_id") or ""),
        player_in_id=str(payload.get("player_in_id") or ""),
    )


def _next_segment(*, session: InteractiveMatchSession, state) -> int | None:
    if session.current_segment < 6:
        return session.current_segment + 1
    if session.current_segment == 6:
        if (
            state.rules.requires_winner
            and session.home_score == session.away_score
            and state.rules.allows_extra_time
        ):
            return 7
        return None
    if session.current_segment == 7:
        return 8
    return None


def _will_complete(*, state, segment: int, home_score: int, away_score: int) -> bool:
    if segment < 6:
        return False
    if segment == 6:
        return not (
            state.rules.requires_winner
            and home_score == away_score
            and state.rules.allows_extra_time
        )
    return segment == 8


def _score_at(*, outcome, home_club_id: str, away_club_id: str, end_minute: int):
    home = away = 0
    for event in outcome.report.events:
        if event.event_type != MatchEventType.GOAL or event.minute > end_minute:
            continue
        if event.club_id == home_club_id:
            home += 1
        elif event.club_id == away_club_id:
            away += 1
    return home, away


def _visible_roster(*, state, events, club_id: str, minute: int, include_manual_at_minute=True):
    team = state.home if club_id == state.home.club_id else state.away
    active = {p.player_id for p in team.starters}
    bench = {p.player_id for p in team.substitutes}
    sub_minutes = []
    subs = 0
    for event in events:
        if event.club_id != club_id:
            continue
        if event.minute > minute:
            continue
        if event.minute == minute and not include_manual_at_minute:
            if not (
                event.event_type == MatchEventType.SUBSTITUTION
                and event.detail_payload.get("source") == "LIVE_COMMAND"
            ):
                continue
        if event.event_type == MatchEventType.SUBSTITUTION:
            active.discard(event.player_id)
            if event.secondary_player_id:
                bench.discard(event.secondary_player_id)
                active.add(event.secondary_player_id)
            subs += 1
            sub_minutes.append(event.minute)
        elif event.event_type in {MatchEventType.RED_CARD, MatchEventType.SECOND_YELLOW}:
            active.discard(event.player_id)
        elif event.event_type == MatchEventType.INJURY and event.detail_payload.get("match_availability") == "UNAVAILABLE":
            active.discard(event.player_id)
    return {
        "active": sorted(active),
        "bench": sorted(bench),
        "substitutions_used": subs,
        "substitution_windows_used": len(set(sub_minutes)),
    }


class InteractiveMatchRunnerService:
    @staticmethod
    def abort_for_match(*, match: Match):
        """Close a prepared/open interactive cursor when the Match lifecycle is cancelled.

        Match cancellation currently occurs pre-kickoff, but accepting OPEN here keeps
        the aggregate safe if a future administrative cancellation path calls the same
        hook. Commands/checkpoints remain immutable evidence.
        """
        try:
            session = InteractiveMatchSession.objects.select_for_update().get(match=match)
        except InteractiveMatchSession.DoesNotExist:
            return None
        if session.status in {
            InteractiveMatchSessionStatus.COMPLETED,
            InteractiveMatchSessionStatus.ABORTED,
        }:
            return session
        session.status = InteractiveMatchSessionStatus.ABORTED
        session.next_advance_at = None
        session.aborted_at = timezone.now()
        session.revision += 1
        session.save(update_fields=[
            "status", "next_advance_at", "aborted_at", "revision", "updated_at",
        ])
        from .streaming import LiveMatchStreamPublisher
        LiveMatchStreamPublisher.match_aborted(session=session)
        return session

    @staticmethod
    @transaction.atomic
    def prepare(*, match_id, segment_duration_seconds=DEFAULT_SEGMENT_DURATION_SECONDS):
        if isinstance(segment_duration_seconds, bool) or not isinstance(segment_duration_seconds, int):
            raise InteractiveMatchConfigurationError("segment_duration_seconds must be an integer.")
        if not 5 <= segment_duration_seconds <= 900:
            raise InteractiveMatchConfigurationError("segment_duration_seconds must be 5..900.")
        try:
            match = Match.objects.select_for_update().get(pk=match_id)
        except Match.DoesNotExist as exc:
            raise InteractiveMatchConfigurationError("Match does not exist.") from exc
        if match.status not in {MatchStatus.PENDING, MatchStatus.SCHEDULED}:
            raise InteractiveMatchConfigurationError(
                "Interactive execution must be configured before match start."
            )
        if hasattr(match, "simulation_snapshot"):
            raise InteractiveMatchConfigurationError("Kickoff snapshot already exists.")
        match.execution_mode = MatchExecutionMode.INTERACTIVE
        match.save(update_fields=["execution_mode", "updated_at"])
        session, created = InteractiveMatchSession.objects.select_for_update().get_or_create(
            match=match,
            defaults={"segment_duration_seconds": segment_duration_seconds, "engine_key": CurrentMatchEngine.key, "engine_version": CurrentMatchEngine.version},
        )
        if not created:
            if session.status != InteractiveMatchSessionStatus.PREPARED:
                raise InteractiveMatchConfigurationError("Interactive session is no longer PREPARED.")
            if session.segment_duration_seconds != segment_duration_seconds:
                session.segment_duration_seconds = segment_duration_seconds
                session.save(update_fields=["segment_duration_seconds", "updated_at"])
        return session

    @staticmethod
    def activate_for_match_start(*, match: Match, snapshot):
        """Called inside MatchLifecycleService.start() transaction."""
        if match.execution_mode != MatchExecutionMode.INTERACTIVE:
            return None
        session, _ = InteractiveMatchSession.objects.select_for_update().get_or_create(
            match=match,
            defaults={"segment_duration_seconds": DEFAULT_SEGMENT_DURATION_SECONDS},
        )
        if session.status != InteractiveMatchSessionStatus.PREPARED:
            raise InteractiveMatchSessionError("Interactive session must be PREPARED at kickoff.")
        now = timezone.now()
        session.snapshot = snapshot
        session.status = InteractiveMatchSessionStatus.OPEN
        session.next_advance_at = now + timedelta(seconds=session.segment_duration_seconds)
        session.revision += 1
        session.save(update_fields=[
            "snapshot", "status", "next_advance_at", "revision", "updated_at",
        ])
        from .streaming import LiveMatchStreamPublisher
        LiveMatchStreamPublisher.session_opened(session=session)
        return session

    @staticmethod
    def _viewer_club(*, session, user):
        match = session.match
        fixture = match.fixture
        if getattr(user, "is_staff", False):
            return None
        for club in (fixture.home_club, fixture.away_club):
            if user.pk in (club.owner_id, club.coach_user_id):
                return club
        raise InteractiveMatchAuthorizationError("User does not manage a club in this match.")

    @staticmethod
    def _command_club(*, session, user, requested_club_id=None):
        match = session.match
        fixture_clubs = (match.fixture.home_club, match.fixture.away_club)
        if getattr(user, "is_staff", False):
            if requested_club_id is None:
                raise InteractiveMatchAuthorizationError("Staff command requires explicit club_id.")
            for club in fixture_clubs:
                if str(club.pk) == str(requested_club_id):
                    return club
            raise InteractiveMatchAuthorizationError("club_id is not a fixture participant.")
        for club in fixture_clubs:
            if user.pk in (club.owner_id, club.coach_user_id):
                if requested_club_id is not None and str(requested_club_id) != str(club.pk):
                    raise InteractiveMatchAuthorizationError("Cannot command the opponent club.")
                return club
        raise InteractiveMatchAuthorizationError("User does not manage a club in this match.")

    @classmethod
    @transaction.atomic
    def submit_command(
        cls,
        *,
        match_id,
        user,
        expected_revision: int,
        idempotency_key: str,
        command_type: str,
        club_id=None,
        attacking_strategy=None,
        defensive_strategy=None,
        player_out_id=None,
        player_in_id=None,
    ):
        try:
            session = (
                InteractiveMatchSession.objects.select_for_update(of=("self",))
                .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
        club = cls._command_club(session=session, user=user, requested_club_id=club_id)
        idempotency_key = str(idempotency_key or "").strip()
        if not idempotency_key or len(idempotency_key) > 64:
            raise InteractiveMatchCommandError("idempotency_key must be 1..64 characters.")
        if command_type not in LiveMatchCommandType.values:
            raise InteractiveMatchCommandError("Unsupported live command type.")
        if command_type == LiveMatchCommandType.TACTICS:
            if attacking_strategy not in AttackingStrategy.values or defensive_strategy not in DefensiveStrategy.values:
                raise InteractiveMatchCommandError("Unsupported live tactical strategy.")
            canonical_payload = {
                "attacking_strategy": attacking_strategy,
                "defensive_strategy": defensive_strategy,
            }
        else:
            if not player_out_id or not player_in_id or str(player_out_id) == str(player_in_id):
                raise InteractiveMatchCommandError("Substitution requires two different player IDs.")
            canonical_payload = {
                "player_out_id": str(player_out_id),
                "player_in_id": str(player_in_id),
            }

        existing = LiveMatchCommand.objects.filter(
            session=session, club=club, idempotency_key=idempotency_key
        ).first()
        if existing is not None:
            _verify_command_evidence(existing)
            if existing.command_type == command_type and existing.payload == canonical_payload:
                return existing, session
            raise InteractiveMatchCommandError(
                "idempotency_key was already used for a different command."
            )
        if session.status != InteractiveMatchSessionStatus.OPEN:
            raise InteractiveMatchCommandWindowClosedError("Interactive session is not OPEN.")
        now = timezone.now()
        if session.next_advance_at is None or now >= session.next_advance_at:
            raise InteractiveMatchCommandWindowClosedError("Command window for the next checkpoint is closed.")
        if isinstance(expected_revision, bool) or not isinstance(expected_revision, int):
            raise InteractiveMatchRevisionConflictError("expected_revision must be an integer.")
        if expected_revision != session.revision:
            raise InteractiveMatchRevisionConflictError(
                f"Stale live state revision; expected {session.revision}."
            )
        state = MatchSimulationService._state_from_snapshot(session.snapshot)
        effective_segment = _next_segment(session=session, state=state)
        if effective_segment is None:
            raise InteractiveMatchCommandWindowClosedError("No further field segment is available.")

        commands = list(session.commands.select_related("club").order_by("sequence"))
        engine = _engine_for_session(session)
        if command_type == LiveMatchCommandType.SUBSTITUTION:
            outcome = engine.simulate(
                state,
                seed=session.snapshot.seed,
                commands=tuple(_command_state(row) for row in commands),
            )
            start_minute, _ = _segment_bounds(effective_segment)
            roster = _visible_roster(
                state=state,
                events=outcome.report.events,
                club_id=str(club.pk),
                minute=start_minute,
                include_manual_at_minute=False,
            )
            if str(player_out_id) not in roster["active"]:
                raise InteractiveMatchCommandError("player_out is not active at the next checkpoint.")
            if str(player_in_id) not in roster["bench"]:
                raise InteractiveMatchCommandError("player_in is not available on the bench.")
            if roster["substitutions_used"] >= state.rules.max_substitutions:
                raise InteractiveMatchCommandError("Maximum substitutions already used.")
            existing_manual_this_segment = any(
                row.command_type == LiveMatchCommandType.SUBSTITUTION
                and row.club_id == club.pk
                and row.effective_segment == effective_segment
                for row in commands
            )
            if (
                not existing_manual_this_segment
                and roster["substitution_windows_used"] >= state.rules.max_substitution_windows
            ):
                raise InteractiveMatchCommandError("Maximum substitution windows already used.")

        sequence = (session.commands.aggregate(max_seq=Max("sequence"))["max_seq"] or 0) + 1
        command_payload = {
            "session_id": str(session.pk),
            "match_id": str(session.match_id),
            "club_id": str(club.pk),
            "sequence": sequence,
            "idempotency_key": idempotency_key,
            "command_type": command_type,
            "effective_segment": effective_segment,
            "submitted_minute": session.current_minute,
            "expected_revision": expected_revision,
            "payload": canonical_payload,
        }
        command = LiveMatchCommand.objects.create(
            session=session,
            club=club,
            actor=user,
            sequence=sequence,
            idempotency_key=idempotency_key,
            command_type=command_type,
            effective_segment=effective_segment,
            submitted_minute=session.current_minute,
            expected_revision=expected_revision,
            payload=canonical_payload,
            command_hash=payload_sha256(command_payload),
        )
        session.revision += 1
        session.save(update_fields=["revision", "updated_at"])
        from .streaming import LiveMatchStreamPublisher
        LiveMatchStreamPublisher.command_accepted(session=session, command=command)
        return command, session

    @classmethod
    @transaction.atomic
    def advance(cls, *, session_id=None, match_id=None, force=False, now=None):
        if bool(session_id) == bool(match_id):
            raise InteractiveMatchSessionError("Provide exactly one of session_id or match_id.")
        lookup = {"pk": session_id} if session_id else {"match_id": match_id}
        try:
            probe = InteractiveMatchSession.objects.only("match_id").get(**lookup)
        except InteractiveMatchSession.DoesNotExist as exc:
            raise InteractiveMatchSessionNotFoundError("Interactive session does not exist.") from exc
        source = lock_competition_source_and_match(probe.match_id)
        match = source.match
        session = (
            InteractiveMatchSession.objects.select_for_update(of=("self",))
            .select_related("snapshot", "match__fixture")
            .get(pk=probe.pk)
        )
        if session.status != InteractiveMatchSessionStatus.OPEN:
            raise InteractiveMatchSessionError("Interactive session is not OPEN.")
        if match.status != MatchStatus.IN_PROGRESS:
            raise InteractiveMatchSessionError("Interactive match is not IN_PROGRESS.")
        if session.snapshot_id is None:
            raise InteractiveMatchSessionError("Interactive session has no kickoff snapshot.")
        now = now or timezone.now()
        if not force and (session.next_advance_at is None or now < session.next_advance_at):
            raise InteractiveMatchSessionError("Interactive checkpoint is not due yet.")

        state = MatchSimulationService._state_from_snapshot(session.snapshot)
        target_segment = _next_segment(session=session, state=state)
        if target_segment is None:
            raise InteractiveMatchSessionError("No further segment is available.")
        command_rows = list(session.commands.order_by("sequence"))
        commands = tuple(_command_state(row) for row in command_rows)
        engine = _engine_for_session(session)
        outcome = engine.simulate(state, seed=session.snapshot.seed, commands=commands)

        start_minute, end_minute = _segment_bounds(target_segment)
        home_id = str(match.fixture.home_club_id); away_id = str(match.fixture.away_club_id)
        home_score, away_score = _score_at(
            outcome=outcome,
            home_club_id=home_id,
            away_club_id=away_id,
            end_minute=end_minute,
        )
        complete = _will_complete(
            state=state,
            segment=target_segment,
            home_score=home_score,
            away_score=away_score,
        )
        expected_phase = MatchEventPhase.REGULATION if target_segment <= 6 else MatchEventPhase.EXTRA_TIME
        event_delta = [
            row.to_payload()
            for row in outcome.report.events
            if (
                row.phase == expected_phase
                and start_minute <= row.minute <= end_minute
            )
        ]
        if complete:
            event_delta.extend(
                row.to_payload()
                for row in outcome.report.events
                if row.phase == MatchEventPhase.SHOOTOUT
            )
        decision_delta = [
            row.to_payload()
            for row in outcome.report.tactical_decisions
            if row.phase == expected_phase and start_minute <= row.minute <= end_minute
        ]
        command_sequence = command_rows[-1].sequence if command_rows else 0
        statistics_payload = {}
        advanced = getattr(outcome.report, "advanced_analytics", None)
        if advanced:
            statistics_payload = next(
                (dict(row) for row in advanced.get("segment_statistics", []) if int(row.get("segment", 0)) == target_segment),
                {},
            )
        projection_payload = {
            "session_id": str(session.pk),
            "snapshot_hash": session.snapshot.state_hash,
            "segment": target_segment,
            "start_minute": start_minute,
            "end_minute": end_minute,
            "phase": expected_phase,
            "home_score": home_score,
            "away_score": away_score,
            "events": event_delta,
            "tactical_decisions": decision_delta,
            "statistics": statistics_payload,
            "command_sequence": command_sequence,
        }
        checkpoint = InteractiveMatchCheckpoint.objects.create(
            session=session,
            segment=target_segment,
            start_minute=start_minute,
            end_minute=end_minute,
            phase=expected_phase,
            home_score=home_score,
            away_score=away_score,
            events_payload=event_delta,
            tactical_decisions_payload=decision_delta,
            statistics_payload=statistics_payload,
            command_sequence=command_sequence,
            projection_hash=payload_sha256(projection_payload),
        )
        session.current_segment = target_segment
        session.current_minute = end_minute
        session.home_score = home_score
        session.away_score = away_score
        session.revision += 1

        if complete:
            if session.engine_key == FTGMatchEngineV3.key:
                run = MatchSimulationService._persist_v3_outcome(
                    match_id=match.pk,
                    snapshot_id=session.snapshot_id,
                    expected_state_hash=session.snapshot.state_hash,
                    outcome=outcome,
                    engine_key=session.engine_key,
                    engine_version=session.engine_version,
                    report_builder_version=session.engine_version,
                )
            else:
                run = MatchSimulationService._persist_v22_outcome(
                    match_id=match.pk,
                    snapshot_id=session.snapshot_id,
                    expected_state_hash=session.snapshot.state_hash,
                    outcome=outcome,
                )
            session.status = InteractiveMatchSessionStatus.COMPLETED
            session.next_advance_at = None
            session.completed_at = now
            session.save(update_fields=[
                "current_segment", "current_minute", "home_score", "away_score",
                "revision", "status", "next_advance_at", "completed_at", "updated_at",
            ])
            from .streaming import LiveMatchStreamPublisher
            LiveMatchStreamPublisher.checkpoint_published(session=session, checkpoint=checkpoint)
            LiveMatchStreamPublisher.match_completed(session=session)

            def post_commit_integrations():
                _project_v2_injuries(match_id=match.pk)
                from .simulation import _finalize_discipline_if_ready
                _finalize_discipline_if_ready(match_id=match.pk)
            transaction.on_commit(post_commit_integrations)
            return session, run

        session.next_advance_at = now + timedelta(seconds=session.segment_duration_seconds)
        session.save(update_fields=[
            "current_segment", "current_minute", "home_score", "away_score",
            "revision", "next_advance_at", "updated_at",
        ])
        from .streaming import LiveMatchStreamPublisher
        LiveMatchStreamPublisher.checkpoint_published(session=session, checkpoint=checkpoint)
        return session, None

    @classmethod
    def state_for_user(cls, *, match_id, user):
        try:
            session = (
                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
        viewer_club = cls._viewer_club(session=session, user=user)
        state = MatchSimulationService._state_from_snapshot(session.snapshot) if session.snapshot_id else None
        next_segment = _next_segment(session=session, state=state) if state and session.status == InteractiveMatchSessionStatus.OPEN else None
        checkpoints = list(session.checkpoints.order_by("segment"))
        timeline = []
        tactical = []
        live_statistics = {}
        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
        own_pending = []
        if viewer_club is not None and next_segment is not None:
            own_pending = [
                {
                    "id": str(row.pk),
                    "sequence": row.sequence,
                    "command_type": row.command_type,
                    "effective_segment": row.effective_segment,
                    "payload": row.payload,
                    "created_at": row.created_at.isoformat(),
                }
                for row in session.commands.filter(
                    club=viewer_club, effective_segment=next_segment
                ).order_by("sequence")
            ]
        roster = None
        if viewer_club is not None and state is not None and next_segment is not None:
            commands = tuple(_command_state(row) for row in session.commands.order_by("sequence"))
            outcome = _engine_for_session(session).simulate(state, seed=session.snapshot.seed, commands=commands)
            next_start, _ = _segment_bounds(next_segment)
            roster = _visible_roster(
                state=state,
                events=outcome.report.events,
                club_id=str(viewer_club.pk),
                minute=next_start,
                include_manual_at_minute=False,
            )
        return {
            "session_id": str(session.pk),
            "match_id": str(session.match_id),
            "status": session.status,
            "engine": {"key": session.engine_key, "version": session.engine_version},
            "revision": session.revision,
            "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_segment": next_segment,
            "next_advance_at": session.next_advance_at,
            "command_window_open": bool(
                session.status == InteractiveMatchSessionStatus.OPEN
                and session.next_advance_at
                and timezone.now() < session.next_advance_at
                and next_segment is not None
            ),
            "timeline": timeline,
            "tactical_decisions": tactical,
            "live_statistics": live_statistics,
            "my_pending_commands": own_pending,
            "my_roster_state": roster,
        }
