"""Pure competition-discipline policy for cards and automatic sanctions.

The policy module has no Django dependency.  Persistence, competition lookup,
and suspension assignment belong to ``matches.discipline``.
"""
from __future__ import annotations

from dataclasses import asdict, dataclass
from hashlib import sha256
import json
from typing import Iterable


POLICY_KEY = "ftg.competition.discipline.v1"
POLICY_VERSION = "1.0.0"
SCHEMA_VERSION = 1

CARD_YELLOW = "YELLOW"
CARD_SECOND_YELLOW = "SECOND_YELLOW"
CARD_DIRECT_RED = "DIRECT_RED"

SANCTION_DIRECT_RED = "DIRECT_RED"
SANCTION_SECOND_YELLOW = "SECOND_YELLOW"
SANCTION_YELLOW_ACCUMULATION = "YELLOW_ACCUMULATION"


class DisciplinePolicyError(ValueError):
    pass


@dataclass(frozen=True, slots=True)
class DisciplinePolicySnapshot:
    yellow_threshold: int = 3
    yellow_suspension_matches: int = 1
    direct_red_suspension_matches: int = 1
    second_yellow_suspension_matches: int = 1
    second_yellow_counts_toward_accumulation: bool = False
    forfeit_score_for: int = 3
    forfeit_score_against: int = 0

    def validate(self) -> None:
        ints = {
            "yellow_threshold": self.yellow_threshold,
            "yellow_suspension_matches": self.yellow_suspension_matches,
            "direct_red_suspension_matches": self.direct_red_suspension_matches,
            "second_yellow_suspension_matches": self.second_yellow_suspension_matches,
            "forfeit_score_for": self.forfeit_score_for,
            "forfeit_score_against": self.forfeit_score_against,
        }
        for name, value in ints.items():
            if isinstance(value, bool) or not isinstance(value, int) or value < 0:
                raise DisciplinePolicyError(f"{name} must be a non-negative integer.")
        if self.yellow_threshold < 1:
            raise DisciplinePolicyError("yellow_threshold must be at least 1.")
        if self.yellow_suspension_matches < 1:
            raise DisciplinePolicyError("yellow_suspension_matches must be at least 1.")
        if self.direct_red_suspension_matches < 1:
            raise DisciplinePolicyError("direct_red_suspension_matches must be at least 1.")
        if self.second_yellow_suspension_matches < 1:
            raise DisciplinePolicyError("second_yellow_suspension_matches must be at least 1.")
        if self.forfeit_score_for <= self.forfeit_score_against:
            raise DisciplinePolicyError("Forfeit winner score must exceed loser score.")

    def to_payload(self) -> dict:
        self.validate()
        return {
            "policy_key": POLICY_KEY,
            "policy_version": POLICY_VERSION,
            "schema_version": SCHEMA_VERSION,
            **asdict(self),
        }

    def payload_hash(self) -> str:
        raw = json.dumps(
            self.to_payload(), sort_keys=True, separators=(",", ":")
        ).encode("utf-8")
        return sha256(raw).hexdigest()


@dataclass(frozen=True, slots=True)
class SanctionTrigger:
    sanction_type: str
    matches: int
    semantic_suffix: str


@dataclass(frozen=True, slots=True)
class PlayerDisciplineEvaluation:
    prior_accumulation_yellows: int
    resulting_accumulation_yellows: int
    triggers: tuple[SanctionTrigger, ...]


class CompetitionDisciplinePolicyV1:
    policy_key = POLICY_KEY
    policy_version = POLICY_VERSION
    schema_version = SCHEMA_VERSION

    @staticmethod
    def evaluate_player_cards(
        *,
        prior_accumulation_yellows: int,
        card_types: Iterable[str],
        policy: DisciplinePolicySnapshot,
    ) -> PlayerDisciplineEvaluation:
        policy.validate()
        if (
            isinstance(prior_accumulation_yellows, bool)
            or not isinstance(prior_accumulation_yellows, int)
            or prior_accumulation_yellows < 0
        ):
            raise DisciplinePolicyError(
                "prior_accumulation_yellows must be a non-negative integer."
            )

        card_types = tuple(str(card) for card in card_types)
        allowed = {CARD_YELLOW, CARD_SECOND_YELLOW, CARD_DIRECT_RED}
        unknown = [card for card in card_types if card not in allowed]
        if unknown:
            raise DisciplinePolicyError(f"Unsupported disciplinary card type: {unknown[0]}")

        triggers: list[SanctionTrigger] = []
        yellow_total = prior_accumulation_yellows
        prior_crossings = yellow_total // policy.yellow_threshold

        for index, card in enumerate(card_types, start=1):
            if card == CARD_DIRECT_RED:
                triggers.append(
                    SanctionTrigger(
                        sanction_type=SANCTION_DIRECT_RED,
                        matches=policy.direct_red_suspension_matches,
                        semantic_suffix=f"direct-red-{index}",
                    )
                )
            elif card == CARD_SECOND_YELLOW:
                triggers.append(
                    SanctionTrigger(
                        sanction_type=SANCTION_SECOND_YELLOW,
                        matches=policy.second_yellow_suspension_matches,
                        semantic_suffix=f"second-yellow-{index}",
                    )
                )
                if policy.second_yellow_counts_toward_accumulation:
                    yellow_total += 1
            else:
                yellow_total += 1

        resulting_crossings = yellow_total // policy.yellow_threshold
        for crossing in range(prior_crossings + 1, resulting_crossings + 1):
            triggers.append(
                SanctionTrigger(
                    sanction_type=SANCTION_YELLOW_ACCUMULATION,
                    matches=policy.yellow_suspension_matches,
                    semantic_suffix=f"yellow-threshold-{crossing}",
                )
            )

        return PlayerDisciplineEvaluation(
            prior_accumulation_yellows=prior_accumulation_yellows,
            resulting_accumulation_yellows=yellow_total,
            triggers=tuple(triggers),
        )

    @staticmethod
    def administrative_score(*, outcome: str, policy: DisciplinePolicySnapshot) -> tuple[int, int]:
        policy.validate()
        if outcome == "HOME_FORFEIT":
            return policy.forfeit_score_against, policy.forfeit_score_for
        if outcome == "AWAY_FORFEIT":
            return policy.forfeit_score_for, policy.forfeit_score_against
        raise DisciplinePolicyError("Unsupported administrative decision outcome.")
