"""Pure team/player evaluation for FTG Match Engine v1."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Mapping

from ..state import EngineStateError, PlayerState, TeamState
from .config import (
    ATTACK_UNIT_WEIGHTS,
    CAPTAIN_LEADERSHIP_ATTRIBUTES,
    DEFAULT_OUT_OF_POSITION_FIT,
    DEFENCE_UNIT_WEIGHTS,
    DEFENDER_ROLES,
    FORMATION_MODIFIERS,
    FORWARD_ROLES,
    LEADERSHIP_FACTOR_PER_POINT,
    LEADERSHIP_REFERENCE,
    MIDFIELD_ROLES,
    MIDFIELD_UNIT_WEIGHTS,
    POSITION_FIT,
    ROLE_ATTRIBUTE_WEIGHTS,
    SLOT_ROLE,
)


class EngineV1InputError(EngineStateError):
    """The immutable match state cannot be evaluated by engine v1."""


@dataclass(frozen=True, slots=True)
class PlayerEvaluation:
    player_id: str
    slot: str
    role: str
    raw_role_score: float
    position_fit: float
    effective_role_score: float


@dataclass(frozen=True, slots=True)
class TeamEvaluation:
    club_id: str
    formation: str
    attack: float
    midfield: float
    defence: float
    goalkeeping: float
    leadership: float
    average_position_fit: float
    players: tuple[PlayerEvaluation, ...]


def _rating_map(player: PlayerState) -> dict[str, int]:
    return dict(player.ratings)


def _weighted_rating(
    ratings: Mapping[str, int],
    weights: Mapping[str, float],
    *,
    player_id: str,
    role: str,
) -> float:
    missing = sorted(set(weights) - set(ratings))
    if missing:
        raise EngineV1InputError(
            f"Player {player_id} is missing ratings required for {role}: "
            + ", ".join(missing)
        )
    weight_total = sum(weights.values())
    if weight_total <= 0:
        raise EngineV1InputError(f"Role {role} has invalid attribute weights.")
    return sum(ratings[name] * weight for name, weight in weights.items()) / weight_total


def _position_fit(*, role: str, natural_position: str, slot: str) -> float:
    role_fits = POSITION_FIT.get(role)
    if role_fits is None:
        raise EngineV1InputError(f"Unsupported tactical role: {role}")
    if role == "goalkeeper" and natural_position != "GK":
        raise EngineV1InputError(
            "Engine v1 requires a natural goalkeeper in the GK slot."
        )

    # Side-aware exact fits: a natural RB at LB (or RM at LM, RW at LW) is
    # deliberately a small penalty rather than fully equivalent.
    side_exact = {
        "LB": "LB",
        "RB": "RB",
        "LM": "LM",
        "RM": "RM",
        "LW": "LW",
        "RW": "RW",
    }
    expected = side_exact.get(slot)
    if expected and natural_position in role_fits:
        if natural_position == expected:
            return role_fits[natural_position]
        opposite_pairs = {
            ("LB", "RB"), ("RB", "LB"),
            ("LM", "RM"), ("RM", "LM"),
            ("LW", "RW"), ("RW", "LW"),
        }
        if (expected, natural_position) in opposite_pairs:
            return min(role_fits[natural_position], 0.95)

    return role_fits.get(natural_position, DEFAULT_OUT_OF_POSITION_FIT)


def evaluate_player(player: PlayerState) -> PlayerEvaluation:
    role = SLOT_ROLE.get(player.lineup_slot)
    if role is None:
        raise EngineV1InputError(
            f"Unsupported lineup slot for engine v1: {player.lineup_slot}"
        )
    weights = ROLE_ATTRIBUTE_WEIGHTS[role]
    ratings = _rating_map(player)
    raw_score = _weighted_rating(
        ratings,
        weights,
        player_id=player.player_id,
        role=role,
    )
    fit = _position_fit(
        role=role,
        natural_position=player.natural_position,
        slot=player.lineup_slot,
    )
    return PlayerEvaluation(
        player_id=player.player_id,
        slot=player.lineup_slot,
        role=role,
        raw_role_score=raw_score,
        position_fit=fit,
        effective_role_score=raw_score * fit,
    )


def _average(values: list[float], *, label: str) -> float:
    if not values:
        raise EngineV1InputError(f"Team has no players in required unit: {label}")
    return sum(values) / len(values)


def _captain_leadership(team: TeamState) -> float:
    captain = next((player for player in team.starters if player.is_captain), None)
    if captain is None:  # TeamState normally prevents this already.
        raise EngineV1InputError("Team has no starting captain.")
    ratings = _rating_map(captain)
    missing = [name for name in CAPTAIN_LEADERSHIP_ATTRIBUTES if name not in ratings]
    if missing:
        raise EngineV1InputError(
            f"Captain {captain.player_id} is missing leadership ratings: "
            + ", ".join(missing)
        )
    return sum(ratings[name] for name in CAPTAIN_LEADERSHIP_ATTRIBUTES) / len(
        CAPTAIN_LEADERSHIP_ATTRIBUTES
    )


def _blend(*, defenders: float, midfield: float, forwards: float, weights) -> float:
    return (
        defenders * weights["defenders"]
        + midfield * weights["midfield"]
        + forwards * weights["forwards"]
    )


def evaluate_team(team: TeamState) -> TeamEvaluation:
    formation_modifiers = FORMATION_MODIFIERS.get(team.formation)
    if formation_modifiers is None:
        raise EngineV1InputError(
            f"Formation {team.formation!r} is not supported by engine v1."
        )

    player_evaluations = tuple(evaluate_player(player) for player in team.starters)

    goalkeeper_scores = [
        player.effective_role_score
        for player in player_evaluations
        if player.role == "goalkeeper"
    ]
    defender_scores = [
        player.effective_role_score
        for player in player_evaluations
        if player.role in DEFENDER_ROLES
    ]
    midfield_scores = [
        player.effective_role_score
        for player in player_evaluations
        if player.role in MIDFIELD_ROLES
    ]
    forward_scores = [
        player.effective_role_score
        for player in player_evaluations
        if player.role in FORWARD_ROLES
    ]

    if len(goalkeeper_scores) != 1:
        raise EngineV1InputError("Engine v1 requires exactly one starting goalkeeper.")

    defenders = _average(defender_scores, label="defence")
    midfield = _average(midfield_scores, label="midfield")
    forwards = _average(forward_scores, label="attack")
    goalkeeping = goalkeeper_scores[0]

    leadership = _captain_leadership(team)
    leadership_multiplier = 1.0 + (
        leadership - LEADERSHIP_REFERENCE
    ) * LEADERSHIP_FACTOR_PER_POINT

    attack = _blend(
        defenders=defenders,
        midfield=midfield,
        forwards=forwards,
        weights=ATTACK_UNIT_WEIGHTS,
    )
    midfield_control = _blend(
        defenders=defenders,
        midfield=midfield,
        forwards=forwards,
        weights=MIDFIELD_UNIT_WEIGHTS,
    )
    defence = _blend(
        defenders=defenders,
        midfield=midfield,
        forwards=forwards,
        weights=DEFENCE_UNIT_WEIGHTS,
    )

    attack *= formation_modifiers["attack"] * leadership_multiplier
    midfield_control *= formation_modifiers["midfield"] * leadership_multiplier
    defence *= formation_modifiers["defence"] * leadership_multiplier
    goalkeeping *= leadership_multiplier

    average_fit = sum(player.position_fit for player in player_evaluations) / len(
        player_evaluations
    )

    return TeamEvaluation(
        club_id=team.club_id,
        formation=team.formation,
        attack=attack,
        midfield=midfield_control,
        defence=defence,
        goalkeeping=goalkeeping,
        leadership=leadership,
        average_position_fit=average_fit,
        players=player_evaluations,
    )
