"""Pure report contract for the interactive Match Engine v2.2."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any

from ..state import (
    ATTACKING_STRATEGIES, DEFENSIVE_STRATEGIES, TACTICAL_TRIGGER_TYPES, EngineStateError,
)
from .v2 import MatchReportV2, PlayerMatchStatisticsV2, ReportEventV2, TeamMatchStatisticsV2

REPORT_SCHEMA_VERSION = 4
REPORT_BUILDER_KEY = "ftg.match.report.v2.interactive"
REPORT_BUILDER_VERSION = "2.2.0"


@dataclass(frozen=True, slots=True)
class TacticalDecisionV22:
    sequence: int
    minute: int
    phase: str
    club_id: str
    source: str
    trigger_type: str
    previous_attacking_strategy: str
    previous_defensive_strategy: str
    attacking_strategy: str
    defensive_strategy: str
    home_score: int
    away_score: int
    own_red_cards: int
    opponent_red_cards: int
    command_ref: str | None = None
    effect: tuple[tuple[str, Any], ...] = ()

    def __post_init__(self):
        if self.sequence < 1 or not 1 <= self.minute <= 120:
            raise EngineStateError("Invalid interactive tactical decision sequence/minute.")
        if self.source not in {"USER_RULE", "AUTO_ADAPTATION", "LIVE_COMMAND"}:
            raise EngineStateError("Unsupported interactive tactical decision source.")
        if self.trigger_type not in TACTICAL_TRIGGER_TYPES | {"LIVE_COMMAND"}:
            raise EngineStateError("Unsupported interactive tactical decision trigger.")
        if self.previous_attacking_strategy not in ATTACKING_STRATEGIES or self.attacking_strategy not in ATTACKING_STRATEGIES:
            raise EngineStateError("Unsupported tactical attacking strategy.")
        if self.previous_defensive_strategy not in DEFENSIVE_STRATEGIES or self.defensive_strategy not in DEFENSIVE_STRATEGIES:
            raise EngineStateError("Unsupported tactical defensive strategy.")
        if self.phase not in {"REGULATION", "EXTRA_TIME"}:
            raise EngineStateError("Interactive tactical decisions are only valid during field play.")
        if self.home_score < 0 or self.away_score < 0 or self.own_red_cards < 0 or self.opponent_red_cards < 0:
            raise EngineStateError("Interactive tactical decision counters cannot be negative.")
        if self.source == "LIVE_COMMAND":
            if not isinstance(self.command_ref, str) or not self.command_ref.strip():
                raise EngineStateError("LIVE_COMMAND tactical decisions require command_ref.")
        elif self.command_ref is not None:
            raise EngineStateError("Only LIVE_COMMAND tactical decisions may carry command_ref.")

    @property
    def effect_payload(self):
        return {str(k): v for k, v in self.effect}

    def to_payload(self):
        return {
            "sequence": self.sequence,
            "minute": self.minute,
            "phase": self.phase,
            "club_id": self.club_id,
            "source": self.source,
            "trigger_type": self.trigger_type,
            "previous_attacking_strategy": self.previous_attacking_strategy,
            "previous_defensive_strategy": self.previous_defensive_strategy,
            "attacking_strategy": self.attacking_strategy,
            "defensive_strategy": self.defensive_strategy,
            "home_score": self.home_score,
            "away_score": self.away_score,
            "own_red_cards": self.own_red_cards,
            "opponent_red_cards": self.opponent_red_cards,
            "command_ref": self.command_ref,
            "effect": self.effect_payload,
        }


@dataclass(frozen=True, slots=True)
class MatchReportV22:
    events: tuple[ReportEventV2, ...]
    team_statistics: tuple[TeamMatchStatisticsV2, ...]
    player_statistics: tuple[PlayerMatchStatisticsV2, ...]
    tactical_decisions: tuple[TacticalDecisionV22, ...]
    schema_version: int = REPORT_SCHEMA_VERSION

    def __post_init__(self):
        if self.schema_version != REPORT_SCHEMA_VERSION:
            raise EngineStateError("Unsupported Match Report v2.2 schema.")
        MatchReportV2(
            events=self.events,
            team_statistics=self.team_statistics,
            player_statistics=self.player_statistics,
        )
        sequences = [row.sequence for row in self.tactical_decisions]
        if sequences != list(range(1, len(sequences) + 1)):
            raise EngineStateError("Interactive tactical decision sequences must be contiguous from 1.")
        phase_order = {"REGULATION": 0, "EXTRA_TIME": 1}
        if list(self.tactical_decisions) != sorted(
            self.tactical_decisions,
            key=lambda row: (phase_order[row.phase], row.minute, row.sequence),
        ):
            raise EngineStateError("Interactive tactical decisions are not chronologically ordered.")

    def to_payload(self):
        return {
            "schema_version": self.schema_version,
            "events": [row.to_payload() for row in self.events],
            "team_statistics": [row.to_payload() for row in self.team_statistics],
            "player_statistics": [row.to_payload() for row in self.player_statistics],
            "tactical_decisions": [row.to_payload() for row in self.tactical_decisions],
        }
