from __future__ import annotations

from dataclasses import dataclass
from math import ceil
from typing import Any, Iterable, Mapping


@dataclass(frozen=True, slots=True)
class ClockRules:
    enabled: bool = True
    max_added_minutes_per_half: int = 12
    possessions_per_added_minute: int = 2
    substitution_seconds: int = 30
    goal_seconds: int = 30
    red_card_seconds: int = 35
    var_review_seconds: int = 55

    def __post_init__(self):
        if not isinstance(self.enabled, bool):
            raise ValueError("clock enabled must be boolean")
        for name in (
            "max_added_minutes_per_half", "possessions_per_added_minute",
            "substitution_seconds", "goal_seconds", "red_card_seconds", "var_review_seconds",
        ):
            value = getattr(self, name)
            if isinstance(value, bool) or not isinstance(value, int) or value < 0:
                raise ValueError(f"{name} must be a non-negative integer")
        if self.max_added_minutes_per_half > 15:
            raise ValueError("max_added_minutes_per_half exceeds supported limit")
        if self.possessions_per_added_minute > 4:
            raise ValueError("possessions_per_added_minute exceeds supported limit")

    def to_payload(self) -> dict[str, Any]:
        return {
            "enabled": self.enabled,
            "max_added_minutes_per_half": self.max_added_minutes_per_half,
            "possessions_per_added_minute": self.possessions_per_added_minute,
            "substitution_seconds": self.substitution_seconds,
            "goal_seconds": self.goal_seconds,
            "red_card_seconds": self.red_card_seconds,
            "var_review_seconds": self.var_review_seconds,
        }

    @classmethod
    def from_payload(cls, payload: Mapping[str, Any] | None) -> "ClockRules":
        payload = payload or {}
        return cls(
            enabled=payload.get("enabled", True),
            max_added_minutes_per_half=payload.get("max_added_minutes_per_half", 12),
            possessions_per_added_minute=payload.get("possessions_per_added_minute", 2),
            substitution_seconds=payload.get("substitution_seconds", 30),
            goal_seconds=payload.get("goal_seconds", 30),
            red_card_seconds=payload.get("red_card_seconds", 35),
            var_review_seconds=payload.get("var_review_seconds", 55),
        )


def _in_period(minute: int, period: int) -> bool:
    if period == 1:
        return 1 <= int(minute) <= 45
    if period == 2:
        return 46 <= int(minute) <= 90
    if period == 3:
        return 91 <= int(minute) <= 105
    if period == 4:
        return 106 <= int(minute) <= 120
    return False


def stoppage_breakdown(*, period: int, rules: ClockRules, report_events: Iterable[Any], referee_events: Iterable[Mapping[str, Any]], medical_events: Iterable[Mapping[str, Any]], goal_events: Iterable[tuple], include_direct_red_card: bool = False) -> dict[str, int]:
    if not rules.enabled:
        return {"medical": 0, "var": 0, "substitutions": 0, "goals": 0, "red_cards": 0, "total": 0}
    medical_raw = sum(
        int(row.get("stoppage_seconds") or 0)
        for row in medical_events
        if _in_period(int(row.get("minute") or 0), period) and row.get("type") in {"ASSESSMENT", "TREATMENT"}
    )
    # Broadcast/medical ledgers record the full treatment interval; football clocks
    # recover the material lost portion rather than every second of parallel care.
    medical = int(round(medical_raw * 0.70))
    var = sum(
        rules.var_review_seconds
        for row in referee_events
        if _in_period(int(row.get("minute") or 0), period) and bool(row.get("var_used"))
    )
    substitutions = sum(
        rules.substitution_seconds
        for row in report_events
        if _in_period(int(getattr(row, "minute", 0)), period) and getattr(row, "event_type", "") == "SUBSTITUTION"
    )
    red_cards = sum(
        rules.red_card_seconds
        for row in report_events
        if _in_period(int(getattr(row, "minute", 0)), period) and getattr(row, "event_type", "") in ({"RED", "SECOND_YELLOW", "RED_CARD"} if include_direct_red_card else {"RED", "SECOND_YELLOW"})
    )
    goals = sum(rules.goal_seconds for row in goal_events if _in_period(int(row[0]), period))
    return {
        "medical": medical,
        "var": var,
        "substitutions": substitutions,
        "goals": goals,
        "red_cards": red_cards,
        "total": medical + var + substitutions + goals + red_cards,
    }


def added_minutes_from_seconds(seconds: int, rules: ClockRules) -> int:
    if not rules.enabled or seconds <= 0:
        return 0
    return min(rules.max_added_minutes_per_half, max(1, int(ceil(seconds / 60.0))))


def display_minute(base_minute: int, stoppage_minute: int) -> str:
    return f"{int(base_minute)}+{max(1, int(stoppage_minute))}"
