"""Pure, versioned player form / morale / match-experience policy.

This module deliberately has no Django imports.  Match performance changes
short-term readiness and produces development *credits*; it never mutates a
Player's permanent ratings directly.
"""
from __future__ import annotations

from dataclasses import dataclass
from datetime import date
from decimal import Decimal, ROUND_HALF_UP
from typing import Mapping

DYNAMICS_POLICY_KEY = "ftg.player.dynamics.v1"
DYNAMICS_POLICY_VERSION = "1.0.0"
DYNAMICS_SCHEMA_VERSION = 1

_Q2 = Decimal("0.01")
_Q4 = Decimal("0.0001")
_Q6 = Decimal("0.000001")
_ZERO = Decimal("0")
_FIFTY = Decimal("50")
_HUNDRED = Decimal("100")

RESULT_WIN = "WIN"
RESULT_DRAW = "DRAW"
RESULT_LOSS = "LOSS"
RESULTS = frozenset({RESULT_WIN, RESULT_DRAW, RESULT_LOSS})

MENTAL_FIELDS = frozenset({
    "vision", "positioning", "decision_making", "composure", "concentration",
    "anticipation", "off_ball", "aggression", "work_rate", "teamwork",
})
PHYSICAL_FIELDS = frozenset({
    "pace", "acceleration", "agility", "balance", "strength", "stamina",
    "jumping", "natural_fitness",
})

POSITION_DEVELOPMENT_WEIGHTS: dict[str, tuple[tuple[str, Decimal], ...]] = {
    "GK": (("gk_reflexes", Decimal("0.30")), ("gk_positioning", Decimal("0.25")),
           ("gk_handling", Decimal("0.20")), ("decision_making", Decimal("0.15")),
           ("concentration", Decimal("0.10"))),
    "CB": (("marking", Decimal("0.27")), ("tackling", Decimal("0.25")),
           ("positioning", Decimal("0.23")), ("heading", Decimal("0.15")),
           ("concentration", Decimal("0.10"))),
    "LB": (("positioning", Decimal("0.22")), ("tackling", Decimal("0.22")),
           ("crossing", Decimal("0.20")), ("stamina", Decimal("0.18")),
           ("pace", Decimal("0.18"))),
    "RB": (("positioning", Decimal("0.22")), ("tackling", Decimal("0.22")),
           ("crossing", Decimal("0.20")), ("stamina", Decimal("0.18")),
           ("pace", Decimal("0.18"))),
    "CDM": (("positioning", Decimal("0.24")), ("tackling", Decimal("0.22")),
            ("passing", Decimal("0.20")), ("teamwork", Decimal("0.18")),
            ("anticipation", Decimal("0.16"))),
    "CM": (("passing", Decimal("0.25")), ("vision", Decimal("0.22")),
           ("decision_making", Decimal("0.20")), ("teamwork", Decimal("0.18")),
           ("stamina", Decimal("0.15"))),
    "CAM": (("vision", Decimal("0.25")), ("passing", Decimal("0.22")),
            ("ball_control", Decimal("0.20")), ("off_ball", Decimal("0.18")),
            ("composure", Decimal("0.15"))),
    "LM": (("crossing", Decimal("0.23")), ("dribbling", Decimal("0.22")),
           ("passing", Decimal("0.19")), ("stamina", Decimal("0.18")),
           ("off_ball", Decimal("0.18"))),
    "RM": (("crossing", Decimal("0.23")), ("dribbling", Decimal("0.22")),
           ("passing", Decimal("0.19")), ("stamina", Decimal("0.18")),
           ("off_ball", Decimal("0.18"))),
    "LW": (("dribbling", Decimal("0.24")), ("pace", Decimal("0.20")),
           ("off_ball", Decimal("0.20")), ("crossing", Decimal("0.18")),
           ("finishing", Decimal("0.18"))),
    "RW": (("dribbling", Decimal("0.24")), ("pace", Decimal("0.20")),
           ("off_ball", Decimal("0.20")), ("crossing", Decimal("0.18")),
           ("finishing", Decimal("0.18"))),
    "ST": (("finishing", Decimal("0.28")), ("off_ball", Decimal("0.23")),
           ("composure", Decimal("0.20")), ("first_touch", Decimal("0.16")),
           ("heading", Decimal("0.13"))),
    "CF": (("finishing", Decimal("0.24")), ("off_ball", Decimal("0.22")),
           ("ball_control", Decimal("0.20")), ("vision", Decimal("0.18")),
           ("composure", Decimal("0.16"))),
}


def _d(value) -> Decimal:
    return value if isinstance(value, Decimal) else Decimal(str(value))


def _clamp(value: Decimal, low: Decimal = _ZERO, high: Decimal = _HUNDRED) -> Decimal:
    return min(high, max(low, value))


def age_on(birth_date: date, on_date: date) -> int:
    return on_date.year - birth_date.year - (
        (on_date.month, on_date.day) < (birth_date.month, birth_date.day)
    )


def _decay_to_neutral(value: Decimal, *, days: int, daily_retention: Decimal) -> Decimal:
    if days <= 0:
        return value
    days = min(int(days), 180)
    retention = daily_retention ** days
    return (_FIFTY + (value - _FIFTY) * retention).quantize(_Q2, rounding=ROUND_HALF_UP)


def readiness_multiplier(*, form_score, morale_score) -> Decimal:
    form = _clamp(_d(form_score))
    morale = _clamp(_d(morale_score))
    # Form can move match execution by +/-3.5%; morale by +/-2.0%.
    modifier = (
        Decimal("1")
        + (form - _FIFTY) * Decimal("0.00070")
        + (morale - _FIFTY) * Decimal("0.00040")
    )
    return min(Decimal("1.0550"), max(Decimal("0.9450"), modifier)).quantize(_Q4)


def effective_ratings(base_ratings: Mapping[str, int], *, multiplier: Decimal) -> dict[str, int]:
    multiplier = _d(multiplier)
    result: dict[str, int] = {}
    for name, raw in base_ratings.items():
        base = int(raw)
        if name == "potential":
            result[name] = base
            continue
        if name in MENTAL_FIELDS:
            weight = Decimal("1.00")
        elif name in PHYSICAL_FIELDS:
            weight = Decimal("0.35")
        elif name == "overall":
            weight = Decimal("0.80")
        else:
            weight = Decimal("0.75")
        applied = Decimal("1") + (multiplier - Decimal("1")) * weight
        adjusted = int((Decimal(base) * applied).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
        result[name] = max(1, min(100, adjusted))
    return result


@dataclass(frozen=True)
class PlayerDynamicInput:
    match_date: date
    date_of_birth: date
    overall: int
    potential: int
    position: str
    form_score: Decimal = Decimal("50.00")
    morale_score: Decimal = Decimal("50.00")
    experience_points: Decimal = Decimal("0.000")
    last_effect_date: date | None = None
    started: bool = False
    appeared: bool = False
    unused_substitute: bool = False
    minutes_played: int = 0
    rating: Decimal | None = None
    result: str = RESULT_DRAW
    man_of_the_match: bool = False
    red_cards: int = 0
    injured: bool = False
    age_years: int | None = None


@dataclass(frozen=True)
class PlayerDynamicResult:
    form_before: Decimal
    form_after: Decimal
    morale_before: Decimal
    morale_after: Decimal
    experience_before: Decimal
    experience_gained: Decimal
    experience_after: Decimal
    development_credit: Decimal
    development_allocations: tuple[tuple[str, Decimal], ...]
    age_years: int
    policy_key: str = DYNAMICS_POLICY_KEY
    policy_version: str = DYNAMICS_POLICY_VERSION


class PlayerDynamicsPolicyV1:
    key = DYNAMICS_POLICY_KEY
    version = DYNAMICS_POLICY_VERSION

    @classmethod
    def calculate(cls, data: PlayerDynamicInput) -> PlayerDynamicResult:
        if data.result not in RESULTS:
            raise ValueError("Unsupported match result")
        if data.match_date < data.date_of_birth:
            raise ValueError("match_date cannot be before date_of_birth")
        if not (1 <= int(data.overall) <= 100 and 1 <= int(data.potential) <= 100):
            raise ValueError("overall/potential must be in 1..100")
        if int(data.potential) < int(data.overall):
            raise ValueError("potential cannot be below overall")
        if data.position not in POSITION_DEVELOPMENT_WEIGHTS:
            raise ValueError("Unsupported player position")
        if not (0 <= int(data.minutes_played) <= 120):
            raise ValueError("minutes_played must be in 0..120")
        if data.started and not data.appeared:
            raise ValueError("A starter must have appeared")
        if data.unused_substitute and data.appeared:
            raise ValueError("Unused substitute cannot have appeared")
        if data.appeared and data.rating is None:
            raise ValueError("Appeared player requires a performance rating")
        if data.rating is not None and not (Decimal("3") <= _d(data.rating) <= Decimal("10")):
            raise ValueError("rating must be in 3..10")

        days = 0
        if data.last_effect_date is not None:
            days = max(0, (data.match_date - data.last_effect_date).days)
        form_before = _decay_to_neutral(_clamp(_d(data.form_score)), days=days, daily_retention=Decimal("0.975"))
        morale_before = _decay_to_neutral(_clamp(_d(data.morale_score)), days=days, daily_retention=Decimal("0.990"))

        form_after = form_before
        if data.appeared:
            rating = _d(data.rating)
            performance = _clamp(_FIFTY + (rating - Decimal("6.50")) * Decimal("14.00"))
            exposure = min(Decimal("1"), Decimal(int(data.minutes_played)) / Decimal("90"))
            alpha = Decimal("0.12") + Decimal("0.22") * exposure
            form_after = (form_before * (Decimal("1") - alpha) + performance * alpha)
        elif data.unused_substitute:
            form_after = _FIFTY + (form_before - _FIFTY) * Decimal("0.94")
        form_after = _clamp(form_after).quantize(_Q2, rounding=ROUND_HALF_UP)

        result_delta = {
            RESULT_WIN: Decimal("2.00"),
            RESULT_DRAW: Decimal("0.40"),
            RESULT_LOSS: Decimal("-1.20"),
        }[data.result]
        morale_delta = result_delta
        if data.appeared:
            exposure = min(Decimal("1"), Decimal(int(data.minutes_played)) / Decimal("90"))
            morale_delta += (_d(data.rating) - Decimal("6.50")) * Decimal("0.80") * exposure
            morale_delta += Decimal("0.40") if data.started else Decimal("0.10")
        elif data.unused_substitute:
            morale_delta += Decimal("-1.50")
        if data.man_of_the_match:
            morale_delta += Decimal("1.50")
        morale_delta -= Decimal(int(data.red_cards)) * Decimal("1.20")
        if data.injured:
            morale_delta -= Decimal("0.50")
        morale_after = _clamp(morale_before + morale_delta).quantize(_Q2, rounding=ROUND_HALF_UP)

        experience_before = max(_ZERO, _d(data.experience_points)).quantize(Decimal("0.001"))
        experience_gained = Decimal("0")
        if data.appeared:
            experience_gained = Decimal(int(data.minutes_played)) / Decimal("15")
            experience_gained += Decimal("0.50") if data.started else Decimal("0.20")
            experience_gained += max(Decimal("0"), _d(data.rating) - Decimal("6.00")) * Decimal("0.45")
            if data.man_of_the_match:
                experience_gained += Decimal("0.80")
        experience_gained = experience_gained.quantize(Decimal("0.001"), rounding=ROUND_HALF_UP)
        experience_after = (experience_before + experience_gained).quantize(Decimal("0.001"))

        age = age_on(data.date_of_birth, data.match_date) if data.age_years is None else data.age_years
        age_factor = cls._age_development_factor(age)
        potential_gap = max(0, int(data.potential) - int(data.overall))
        potential_factor = Decimal("0.50") + Decimal(min(potential_gap, 40)) / Decimal("80")
        development_credit = (
            experience_gained * Decimal("0.095") * age_factor * potential_factor
        ).quantize(_Q6, rounding=ROUND_HALF_UP)
        allocations = tuple(
            (attribute, (development_credit * weight).quantize(_Q6, rounding=ROUND_HALF_UP))
            for attribute, weight in POSITION_DEVELOPMENT_WEIGHTS[data.position]
        )
        # Make rounding exact by applying any micro-residual to the first attribute.
        if allocations:
            allocated = sum((value for _, value in allocations), Decimal("0"))
            residual = development_credit - allocated
            if residual:
                first_name, first_value = allocations[0]
                allocations = ((first_name, (first_value + residual).quantize(_Q6)),) + allocations[1:]

        return PlayerDynamicResult(
            form_before=form_before,
            form_after=form_after,
            morale_before=morale_before,
            morale_after=morale_after,
            experience_before=experience_before,
            experience_gained=experience_gained,
            experience_after=experience_after,
            development_credit=development_credit,
            development_allocations=allocations,
            age_years=age,
        )

    @staticmethod
    def _age_development_factor(age: int) -> Decimal:
        if age <= 18:
            return Decimal("1.200")
        if age <= 23:
            return Decimal("1.100")
        if age <= 29:
            return Decimal("1.000")
        if age <= 33:
            return Decimal("0.820")
        if age <= 39:
            return Decimal("0.550")
        return Decimal("0.350")


@dataclass(frozen=True)
class ReadinessResult:
    form_score: Decimal
    morale_score: Decimal
    readiness_multiplier: Decimal
    effective_ratings: dict[str, int]


class PlayerReadinessPolicyV1:
    key = "ftg.player.readiness.v1"
    version = "1.0.0"

    @classmethod
    def calculate(
        cls,
        *,
        base_ratings: Mapping[str, int],
        form_score,
        morale_score,
        days_since_effect: int = 0,
    ) -> ReadinessResult:
        form = _decay_to_neutral(_clamp(_d(form_score)), days=max(0, days_since_effect), daily_retention=Decimal("0.975"))
        morale = _decay_to_neutral(_clamp(_d(morale_score)), days=max(0, days_since_effect), daily_retention=Decimal("0.990"))
        multiplier = readiness_multiplier(form_score=form, morale_score=morale)
        return ReadinessResult(
            form_score=form,
            morale_score=morale,
            readiness_multiplier=multiplier,
            effective_ratings=effective_ratings(base_ratings, multiplier=multiplier),
        )
