"""Pure report contract for Match Engine v2.1 live tactics."""
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 = 3
REPORT_BUILDER_KEY = "ftg.match.report.v2.live"
REPORT_BUILDER_VERSION = "2.1.0"


@dataclass(frozen=True, slots=True)
class TacticalDecisionV21:
    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
    effect: tuple[tuple[str, Any], ...] = ()

    def __post_init__(self):
        if self.sequence < 1 or not 1 <= self.minute <= 120:
            raise EngineStateError("Invalid tactical decision sequence/minute.")
        if self.source not in {"USER_RULE", "AUTO_ADAPTATION"}:
            raise EngineStateError("Unsupported tactical decision source.")
        if self.trigger_type not in TACTICAL_TRIGGER_TYPES:
            raise EngineStateError("Unsupported tactical decision trigger.")
        if self.previous_attacking_strategy not in ATTACKING_STRATEGIES or self.attacking_strategy not in ATTACKING_STRATEGIES:
            raise EngineStateError("Unsupported tactical decision attacking strategy.")
        if self.previous_defensive_strategy not in DEFENSIVE_STRATEGIES or self.defensive_strategy not in DEFENSIVE_STRATEGIES:
            raise EngineStateError("Unsupported tactical decision defensive strategy.")
        if self.phase not in {"REGULATION", "EXTRA_TIME"}:
            raise EngineStateError("Tactical decisions are only valid during field play.")
        if self.home_score < 0 or self.away_score < 0:
            raise EngineStateError("Tactical decision score cannot be negative.")
        if self.own_red_cards < 0 or self.opponent_red_cards < 0:
            raise EngineStateError("Tactical red-card counts cannot be negative.")

    @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,
            "effect": self.effect_payload,
        }


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

    def __post_init__(self):
        if self.schema_version != REPORT_SCHEMA_VERSION:
            raise EngineStateError("Unsupported Match Report v2.1 schema.")
        # Reuse all v2 event/stat invariants.
        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("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("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],
        }
