"""Pure contracts for FTG Match Engine v2 sporting resolution."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any

from ..reporting.v2 import MatchReportV2
from ..state import EngineStateError, SimulationResult

RESOLUTION_REGULATION = "REGULATION"
RESOLUTION_EXTRA_TIME = "EXTRA_TIME"
RESOLUTION_PENALTIES = "PENALTIES"


@dataclass(frozen=True, slots=True)
class SportingResolutionV2:
    regulation_home_score: int
    regulation_away_score: int
    extra_time_home_goals: int = 0
    extra_time_away_goals: int = 0
    home_penalties: int | None = None
    away_penalties: int | None = None
    decision_stage: str = RESOLUTION_REGULATION

    def __post_init__(self):
        values = (
            self.regulation_home_score, self.regulation_away_score,
            self.extra_time_home_goals, self.extra_time_away_goals,
        )
        if any(isinstance(v, bool) or not isinstance(v, int) or v < 0 for v in values):
            raise EngineStateError("Sporting resolution scores must be non-negative integers.")
        if self.decision_stage not in {
            RESOLUTION_REGULATION, RESOLUTION_EXTRA_TIME, RESOLUTION_PENALTIES
        }:
            raise EngineStateError("Unsupported sporting decision stage.")
        if self.decision_stage == RESOLUTION_REGULATION:
            if self.extra_time_home_goals or self.extra_time_away_goals:
                raise EngineStateError("Regulation resolution cannot contain extra-time goals.")
            if self.home_penalties is not None or self.away_penalties is not None:
                raise EngineStateError("Regulation resolution cannot contain penalties.")
        elif self.decision_stage == RESOLUTION_EXTRA_TIME:
            if self.home_penalties is not None or self.away_penalties is not None:
                raise EngineStateError("Extra-time resolution cannot contain penalties.")
            if self.final_home_score == self.final_away_score:
                raise EngineStateError("Extra-time resolution must identify a winner.")
        else:
            if self.home_penalties is None or self.away_penalties is None:
                raise EngineStateError("Penalty resolution requires shootout scores.")
            if self.home_penalties == self.away_penalties:
                raise EngineStateError("A penalty shootout cannot finish level.")
            if self.final_home_score != self.final_away_score:
                raise EngineStateError("Penalty shootout is only valid after a drawn field score.")

    @property
    def final_home_score(self) -> int:
        return self.regulation_home_score + self.extra_time_home_goals

    @property
    def final_away_score(self) -> int:
        return self.regulation_away_score + self.extra_time_away_goals

    def to_payload(self) -> dict[str, Any]:
        return {
            "decision_stage": self.decision_stage,
            "regulation_home_score": self.regulation_home_score,
            "regulation_away_score": self.regulation_away_score,
            "extra_time_home_goals": self.extra_time_home_goals,
            "extra_time_away_goals": self.extra_time_away_goals,
            "home_penalties": self.home_penalties,
            "away_penalties": self.away_penalties,
            "final_home_score": self.final_home_score,
            "final_away_score": self.final_away_score,
        }


@dataclass(frozen=True, slots=True)
class MatchV2Outcome:
    result: SimulationResult
    resolution: SportingResolutionV2
    report: MatchReportV2

    def __post_init__(self):
        if self.result.home_score != self.resolution.final_home_score:
            raise EngineStateError("Outcome home score does not match sporting resolution.")
        if self.result.away_score != self.resolution.final_away_score:
            raise EngineStateError("Outcome away score does not match sporting resolution.")
