"""Role-aware team evaluation for Match Engine v3.1."""
from __future__ import annotations

from ..roles import execution_fit, resolve_tactical_role, slot_family
from ..state import EngineStateError, PlayerState, TeamState
from ..v1.evaluator import PlayerEvaluation, TeamEvaluation

FORMATION_MODIFIERS = {
    "4-3-3": {"attack": 1.030, "midfield": 1.000, "defence": 0.990},
    "4-4-2": {"attack": 0.995, "midfield": 1.025, "defence": 1.010},
    "4-2-3-1": {"attack": 1.015, "midfield": 1.035, "defence": 1.005},
    "4-1-4-1": {"attack": 0.985, "midfield": 1.040, "defence": 1.025},
    "3-5-2": {"attack": 1.020, "midfield": 1.045, "defence": 0.985},
    "3-4-3": {"attack": 1.045, "midfield": 1.005, "defence": 0.965},
    "5-3-2": {"attack": 0.985, "midfield": 0.995, "defence": 1.055},
}

BASE_FAMILY_WEIGHTS = {
    "goalkeeper": {"gk_reflexes": .24, "gk_positioning": .20, "gk_diving": .18, "gk_one_on_one": .15, "gk_handling": .11, "gk_kicking": .06, "concentration": .03, "decision_making": .03},
    "centre_back": {"marking": .18, "tackling": .18, "positioning": .14, "anticipation": .11, "heading": .09, "strength": .08, "concentration": .08, "composure": .05, "pace": .04, "passing": .03, "teamwork": .02},
    "fullback": {"tackling": .13, "marking": .12, "positioning": .10, "pace": .11, "acceleration": .08, "stamina": .09, "crossing": .08, "passing": .07, "work_rate": .08, "anticipation": .06, "teamwork": .04, "ball_control": .04},
    "wingback": {"pace": .12, "stamina": .11, "crossing": .11, "work_rate": .10, "tackling": .09, "positioning": .08, "passing": .08, "dribbling": .08, "acceleration": .07, "marking": .07, "teamwork": .05, "ball_control": .04},
    "defensive_midfield": {"positioning": .14, "tackling": .13, "passing": .12, "anticipation": .10, "decision_making": .10, "teamwork": .09, "marking": .08, "stamina": .07, "composure": .06, "vision": .06, "work_rate": .05},
    "central_midfield": {"passing": .16, "vision": .14, "decision_making": .12, "ball_control": .11, "teamwork": .09, "stamina": .08, "first_touch": .08, "composure": .06, "work_rate": .06, "positioning": .05, "anticipation": .05},
    "attacking_midfield": {"vision": .16, "passing": .14, "ball_control": .12, "dribbling": .11, "decision_making": .10, "first_touch": .09, "off_ball": .08, "composure": .07, "finishing": .06, "shooting": .04, "teamwork": .03},
    "wide_midfield": {"crossing": .15, "passing": .12, "ball_control": .10, "dribbling": .10, "pace": .10, "stamina": .09, "work_rate": .09, "vision": .08, "acceleration": .06, "teamwork": .06, "decision_making": .05},
    "winger": {"dribbling": .15, "pace": .12, "ball_control": .11, "crossing": .11, "finishing": .10, "off_ball": .09, "acceleration": .08, "first_touch": .07, "composure": .06, "decision_making": .05, "vision": .04, "shooting": .02},
    "striker": {"finishing": .20, "positioning": .15, "composure": .12, "off_ball": .10, "shooting": .10, "first_touch": .08, "ball_control": .07, "heading": .06, "strength": .05, "anticipation": .04, "decision_making": .03},
}

# Role-specific weighted traits.  Missing roles fall back to the slot-family
# profile, so historical AUTO lineups remain stable and explainable.
ROLE_ATTRIBUTE_WEIGHTS = {
    "SWEEPER_KEEPER": {"gk_reflexes": .18, "gk_positioning": .17, "gk_one_on_one": .14, "gk_kicking": .14, "passing": .10, "decision_making": .10, "composure": .07, "anticipation": .06, "gk_handling": .04},
    "BALL_PLAYING_DEFENDER": {"marking": .13, "tackling": .13, "positioning": .12, "passing": .14, "composure": .10, "decision_making": .09, "anticipation": .09, "vision": .07, "heading": .07, "strength": .06},
    "NO_NONSENSE_CENTRE_BACK": {"marking": .20, "tackling": .20, "positioning": .15, "heading": .13, "strength": .11, "concentration": .09, "anticipation": .07, "composure": .05},
    "WING_BACK": {"pace": .13, "stamina": .12, "crossing": .13, "work_rate": .11, "dribbling": .09, "passing": .08, "tackling": .08, "positioning": .07, "acceleration": .06, "teamwork": .03},
    "INVERTED_FULL_BACK": {"passing": .14, "decision_making": .12, "positioning": .11, "ball_control": .10, "tackling": .10, "vision": .10, "teamwork": .08, "stamina": .08, "marking": .07, "first_touch": .05, "composure": .05},
    "ANCHOR": {"positioning": .18, "marking": .13, "tackling": .13, "anticipation": .11, "decision_making": .10, "passing": .09, "concentration": .09, "teamwork": .08, "strength": .05, "composure": .04},
    "BALL_WINNING_MIDFIELDER": {"tackling": .18, "work_rate": .14, "stamina": .12, "aggression": .11, "positioning": .10, "anticipation": .09, "teamwork": .08, "marking": .07, "passing": .06, "decision_making": .05},
    "DEEP_LYING_PLAYMAKER": {"passing": .20, "vision": .18, "decision_making": .14, "composure": .11, "first_touch": .10, "positioning": .08, "teamwork": .07, "ball_control": .06, "anticipation": .04, "stamina": .02},
    "BOX_TO_BOX": {"stamina": .15, "work_rate": .13, "passing": .11, "teamwork": .10, "off_ball": .09, "tackling": .09, "decision_making": .08, "ball_control": .07, "positioning": .07, "finishing": .05, "strength": .04, "anticipation": .02},
    "ADVANCED_PLAYMAKER": {"vision": .20, "passing": .17, "decision_making": .13, "ball_control": .11, "first_touch": .10, "composure": .09, "dribbling": .07, "off_ball": .06, "teamwork": .04, "finishing": .03},
    "WINGER": {"dribbling": .16, "pace": .13, "crossing": .14, "ball_control": .11, "acceleration": .09, "off_ball": .08, "passing": .07, "decision_making": .05, "first_touch": .04, "stamina": .03},
    "INSIDE_FORWARD": {"dribbling": .14, "finishing": .15, "off_ball": .12, "pace": .10, "ball_control": .10, "composure": .09, "shooting": .08, "acceleration": .07, "first_touch": .06, "decision_making": .05, "vision": .04},
    "TARGET_FORWARD": {"heading": .17, "strength": .16, "finishing": .14, "positioning": .12, "first_touch": .10, "off_ball": .09, "composure": .08, "jumping": .07, "teamwork": .04, "passing": .03},
    "PRESSING_FORWARD": {"work_rate": .15, "stamina": .13, "off_ball": .12, "finishing": .12, "aggression": .10, "pace": .09, "positioning": .08, "teamwork": .07, "composure": .06, "first_touch": .05, "strength": .03},
    "POACHER": {"finishing": .23, "positioning": .18, "off_ball": .15, "composure": .12, "anticipation": .09, "first_touch": .08, "pace": .06, "acceleration": .04, "ball_control": .03, "shooting": .02},
    "FALSE_NINE": {"vision": .15, "passing": .14, "first_touch": .12, "ball_control": .11, "off_ball": .10, "decision_making": .10, "composure": .08, "dribbling": .08, "finishing": .07, "teamwork": .05},
    "COMPLETE_FORWARD": {"finishing": .16, "off_ball": .12, "composure": .11, "first_touch": .09, "heading": .09, "strength": .08, "pace": .08, "ball_control": .08, "passing": .06, "dribbling": .06, "positioning": .07},
}

DEFENDER_FAMILIES = {"centre_back", "fullback", "wingback", "defensive_midfield"}
MIDFIELD_FAMILIES = {"defensive_midfield", "central_midfield", "attacking_midfield", "wide_midfield"}
FORWARD_FAMILIES = {"winger", "striker", "attacking_midfield"}


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


def _weighted(player: PlayerState, weights: dict[str, float]) -> float:
    ratings = _ratings(player)
    missing = set(weights) - set(ratings)
    if missing:
        raise EngineStateError(f"Player {player.player_id} is missing role ratings: {', '.join(sorted(missing))}")
    total = sum(weights.values())
    return sum(ratings[key] * weight for key, weight in weights.items()) / total


def evaluate_player_v31(player: PlayerState) -> PlayerEvaluation:
    family = slot_family(player.lineup_slot)
    role = resolve_tactical_role(player.tactical_role, player.lineup_slot)
    weights = ROLE_ATTRIBUTE_WEIGHTS.get(role, BASE_FAMILY_WEIGHTS[family])
    raw = _weighted(player, weights)
    fit = execution_fit(player.position_familiarity)
    return PlayerEvaluation(
        player_id=player.player_id,
        slot=player.lineup_slot,
        role=family,
        raw_role_score=raw,
        position_fit=fit,
        effective_role_score=raw * fit,
    )


def _average(values, label):
    values = list(values)
    if not values:
        raise EngineStateError(f"Formation has no {label} unit.")
    return sum(values) / len(values)


def evaluate_team_v31(team: TeamState) -> TeamEvaluation:
    modifiers = FORMATION_MODIFIERS.get(team.formation)
    if modifiers is None:
        raise EngineStateError(f"Unsupported v3.1 formation: {team.formation}")
    evaluations = tuple(evaluate_player_v31(p) for p in team.starters)
    gk = [e.effective_role_score for e in evaluations if e.role == "goalkeeper"]
    defenders = [e.effective_role_score for e in evaluations if e.role in DEFENDER_FAMILIES]
    midfielders = [e.effective_role_score for e in evaluations if e.role in MIDFIELD_FAMILIES]
    forwards = [e.effective_role_score for e in evaluations if e.role in FORWARD_FAMILIES]
    if len(gk) != 1:
        raise EngineStateError("Match Engine v3.1 requires exactly one goalkeeper.")
    d = _average(defenders, "defensive")
    m = _average(midfielders, "midfield")
    f = _average(forwards, "attacking")
    captain = next(p for p in team.starters if p.is_captain)
    cr = _ratings(captain)
    leadership = sum(cr[name] for name in ("teamwork", "decision_making", "composure", "concentration")) / 4.0
    leadership_multiplier = 1.0 + (leadership - 50.0) * 0.0005
    attack = (f * .67 + m * .25 + d * .08) * modifiers["attack"] * leadership_multiplier
    midfield = (m * .72 + d * .16 + f * .12) * modifiers["midfield"] * leadership_multiplier
    defence = (d * .72 + m * .22 + f * .06) * modifiers["defence"] * leadership_multiplier
    return TeamEvaluation(
        club_id=team.club_id,
        formation=team.formation,
        attack=attack,
        midfield=midfield,
        defence=defence,
        goalkeeping=gk[0] * leadership_multiplier,
        leadership=leadership,
        average_position_fit=sum(e.position_fit for e in evaluations) / len(evaluations),
        players=evaluations,
    )
