"""Pure referee, offside, advantage and VAR policy primitives.

The module deliberately has no Django imports.  Everything required by a match
must be frozen into :class:`MatchRules` before kickoff so replaying the same
snapshot/seed reproduces the same decisions.
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Mapping


def _int_0_100(value: Any, name: str) -> int:
    if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100:
        raise ValueError(f"{name} must be an integer between 0 and 100.")
    return value


@dataclass(frozen=True, slots=True)
class OfficiatingRules:
    """Frozen match-officiating configuration.

    Accuracy values represent decision quality rather than a guarantee that every
    incident is detected.  Marginal decisions intentionally apply an extra
    difficulty penalty inside the engine.
    """

    var_enabled: bool = True
    advantage_enabled: bool = True
    referee_strictness: int = 52
    referee_accuracy: int = 92
    assistant_accuracy: int = 94
    var_accuracy: int = 99

    def __post_init__(self):
        if not isinstance(self.var_enabled, bool):
            raise ValueError("var_enabled must be boolean.")
        if not isinstance(self.advantage_enabled, bool):
            raise ValueError("advantage_enabled must be boolean.")
        for name in (
            "referee_strictness", "referee_accuracy", "assistant_accuracy", "var_accuracy",
        ):
            _int_0_100(getattr(self, name), name)

    def to_payload(self) -> dict[str, Any]:
        return {
            "var_enabled": self.var_enabled,
            "advantage_enabled": self.advantage_enabled,
            "referee_strictness": self.referee_strictness,
            "referee_accuracy": self.referee_accuracy,
            "assistant_accuracy": self.assistant_accuracy,
            "var_accuracy": self.var_accuracy,
        }

    @classmethod
    def from_payload(cls, payload: Mapping[str, Any] | None) -> "OfficiatingRules":
        payload = payload or {}
        return cls(
            var_enabled=payload.get("var_enabled", True),
            advantage_enabled=payload.get("advantage_enabled", True),
            referee_strictness=payload.get("referee_strictness", 52),
            referee_accuracy=payload.get("referee_accuracy", 92),
            assistant_accuracy=payload.get("assistant_accuracy", 94),
            var_accuracy=payload.get("var_accuracy", 99),
        )
