"""Deterministic, pure-Python FTG Match Engine v1."""

from __future__ import annotations

import math
from dataclasses import dataclass

from ..randomness import SplitMix64
from ..state import MatchState, SimulationResult
from .config import (
    ATTACK_DEFENCE_XG_FACTOR,
    BASE_EXPECTED_GOALS,
    ENGINE_KEY,
    ENGINE_VERSION,
    HOME_ADVANTAGE_XG,
    MAX_EXPECTED_GOALS,
    MIDFIELD_CONTROL_XG_FACTOR,
    MIN_EXPECTED_GOALS,
)
from .evaluator import TeamEvaluation, evaluate_team


@dataclass(frozen=True, slots=True)
class MatchEvaluation:
    home: TeamEvaluation
    away: TeamEvaluation
    home_expected_goals: float
    away_expected_goals: float


def _clamp(value: float, minimum: float, maximum: float) -> float:
    return max(minimum, min(maximum, value))



def _poisson(rng: SplitMix64, expected_goals: float) -> int:
    """Sample a Poisson count using only the local deterministic RNG."""

    threshold = math.exp(-expected_goals)
    product = 1.0
    count = 0
    while product > threshold:
        count += 1
        product *= rng.random()
    return count - 1


class FTGMatchEngineV1:
    """First concrete FTG match engine.

    v1 intentionally models only the final score.  It evaluates the locked
    starting XI by tactical slot, applies a modest natural-position penalty,
    small formation/captain modifiers, converts team profiles to expected
    goals, then samples goals from a seeded Poisson distribution.

    Match events, substitutions, fatigue, injuries and player statistics are
    deliberately not invented here; they belong to later engine versions once
    their domain contracts exist.
    """

    key = ENGINE_KEY
    version = ENGINE_VERSION

    def evaluate(self, state: MatchState) -> MatchEvaluation:
        home = evaluate_team(state.home)
        away = evaluate_team(state.away)

        home_pressure = home.attack * 0.60 + home.midfield * 0.40
        away_pressure = away.attack * 0.60 + away.midfield * 0.40

        home_resistance = away.defence * 0.68 + away.goalkeeping * 0.32
        away_resistance = home.defence * 0.68 + home.goalkeeping * 0.32

        home_delta = home_pressure - home_resistance
        away_delta = away_pressure - away_resistance
        home_control_delta = home.midfield - away.midfield
        away_control_delta = -home_control_delta

        home_xg = (
            BASE_EXPECTED_GOALS
            + HOME_ADVANTAGE_XG
            + home_delta * ATTACK_DEFENCE_XG_FACTOR
            + home_control_delta * MIDFIELD_CONTROL_XG_FACTOR
        )
        away_xg = (
            BASE_EXPECTED_GOALS
            + away_delta * ATTACK_DEFENCE_XG_FACTOR
            + away_control_delta * MIDFIELD_CONTROL_XG_FACTOR
        )

        return MatchEvaluation(
            home=home,
            away=away,
            home_expected_goals=_clamp(
                home_xg, MIN_EXPECTED_GOALS, MAX_EXPECTED_GOALS
            ),
            away_expected_goals=_clamp(
                away_xg, MIN_EXPECTED_GOALS, MAX_EXPECTED_GOALS
            ),
        )

    def simulate(self, state: MatchState, *, seed: int) -> SimulationResult:
        if isinstance(seed, bool) or not isinstance(seed, int) or seed < 1:
            raise ValueError("seed must be a positive integer.")

        evaluation = self.evaluate(state)
        rng = SplitMix64(seed)
        home_score = _poisson(rng, evaluation.home_expected_goals)
        away_score = _poisson(rng, evaluation.away_expected_goals)
        return SimulationResult(home_score=home_score, away_score=away_score)
