"""Pure v3.14 spatial matchup policy. Scores are model indices, not win odds.

No formation-name counter table: actual slots, roles, attributes, familiarity,
fatigue and the current attack/defence strategies determine the interaction.
"""

from .roles import execution_fit, resolve_tactical_role, slot_family

POLICY_VERSION = "1.0.0"


def clamp(value, lo=0.0, hi=100.0):
    return max(lo, min(hi, value))


def profile(players, attack="BALANCED", defence="BALANCED", minute=0):
    sums = {
        "center": 0.0,
        "left": 0.0,
        "right": 0.0,
        "left_cover": 0.0,
        "right_cover": 0.0,
        "screen": 0.0,
        "pocket": 0.0,
        "box": 0.0,
        "rest": 0.0,
        "build": 0.0,
        "press": 0.0,
    }
    speed = stamina = total = 0.0
    for player in players:
        slot = player.lineup_slot
        if not slot or slot == "GK":
            continue
        family = slot_family(slot)
        role = resolve_tactical_role(player.tactical_role, slot)
        ratings = dict(player.ratings)
        fit = execution_fit(player.position_familiarity)
        endurance = float(ratings.get("stamina", 50))
        fatigue = clamp(
            float(player.fatigue_index) / 100 + minute / 120 * (1 - endurance / 150),
            0,
            0.65,
        )
        execution = fit * (1 - 0.25 * fatigue)

        def quality(*attrs, ratings=ratings, execution=execution):
            return (
                sum(float(ratings.get(a, 50)) for a in attrs)
                / len(attrs)
                / 50
                * execution
            )

        technique = quality("passing", "vision", "decision_making", "teamwork")
        defending = quality("positioning", "tackling", "anticipation", "marking")
        running = quality("pace", "stamina", "work_rate", "off_ball")
        is_mid = family in {
            "central_midfield",
            "defensive_midfield",
            "attacking_midfield",
        }
        sums["center"] += technique * (1 if is_mid else 0.18)
        sums["build"] += technique * (
            1
            if family in {"central_midfield", "defensive_midfield"}
            else 0.55
            if family == "centre_back"
            else 0.3
        )
        sums["rest"] += defending * (
            {
                "centre_back": 1,
                "fullback": 0.55,
                "wingback": 0.35,
                "defensive_midfield": 0.8,
                "central_midfield": 0.25,
            }.get(family, 0.04)
        )
        sums["screen"] += defending * (
            1.3
            if family == "defensive_midfield"
            else 0.4
            if family == "central_midfield"
            else 0.15
            if family == "centre_back"
            else 0
        )
        sums["pocket"] += technique * (
            1.3
            if family == "attacking_midfield"
            else 0.55
            if family == "central_midfield"
            else 0.25
            if family == "winger"
            else 0.1
        )
        sums["box"] += quality("finishing", "heading", "off_ball") * (
            1.2
            if family == "striker"
            else 0.65
            if family in {"winger", "attacking_midfield"}
            else 0.15
        )
        sums["press"] += running * (0.25 if family == "centre_back" else 0.85)
        side = (
            "left"
            if slot.startswith("L")
            else "right"
            if slot.startswith("R")
            else None
        )
        if side:
            width = {
                "winger": 1.25,
                "wide_midfield": 1.05,
                "wingback": 1,
                "fullback": 0.65,
            }.get(family, 0.1)
            cover = {
                "fullback": 1.15,
                "wingback": 0.95,
                "wide_midfield": 0.6,
                "centre_back": 0.45,
                "defensive_midfield": 0.4,
            }.get(family, 0.12)
            if role == "INVERTED_FULL_BACK":
                width *= 0.5
                sums["center"] += technique * 0.5
            elif role == "WING_BACK":
                width *= 1.2
                cover *= 0.85
            elif role == "INSIDE_FORWARD":
                width *= 0.7
                sums["pocket"] += technique * 0.35
            sums[side] += quality("pace", "dribbling", "crossing") * width
            sums[side + "_cover"] += defending * cover
        if role == "FALSE_NINE":
            sums["pocket"] += technique * 0.6
            sums["center"] += technique * 0.25
            sums["box"] -= quality("finishing", "heading", "off_ball") * 0.3
        if role == "DEEP_LYING_PLAYMAKER":
            sums["build"] += technique * 0.3
        speed += quality("pace", "acceleration") * 50
        stamina += endurance
        total += 1
    normalizers = {
        "center": 4.5,
        "left": 2,
        "right": 2,
        "left_cover": 2,
        "right_cover": 2,
        "screen": 2.6,
        "pocket": 2.9,
        "box": 3.8,
        "rest": 4.4,
        "build": 5.5,
        "press": 6.6,
    }
    scores = {k: clamp(50 * v / normalizers[k]) for k, v in sums.items()}
    scores["speed"] = speed / max(1, total)
    scores["stamina"] = stamina / max(1, total)
    if attack == "POSSESSION":
        scores["center"] += 5
        scores["build"] += 5
    elif attack == "WIDE_PLAY":
        scores["left"] += 9
        scores["right"] += 9
        scores["rest"] -= 4
    elif attack == "COUNTER_ATTACK":
        scores["speed"] += 7
        scores["rest"] += 4
    elif attack == "DIRECT":
        scores["box"] += 5
        scores["build"] -= 5
    elif attack == "HIGH_TEMPO":
        scores["press"] += 5
        scores["rest"] -= 4
        scores["build"] -= max(0, 65 - scores["stamina"]) * 0.2
    if defence == "HIGH_PRESS":
        scores["press"] += 10
        scores["rest"] -= 8
    elif defence == "LOW_BLOCK":
        scores["screen"] += 8
        scores["rest"] += 8
        scores["press"] -= 10
    elif defence == "ZONAL_COMPACT":
        scores["screen"] += 8
        scores["left_cover"] -= 3
        scores["right_cover"] -= 3
    elif defence == "MAN_MARKING":
        scores["press"] += 4
        scores["rest"] -= 3
    return {k: round(clamp(v), 4) for k, v in scores.items()}


def interaction(own, opponent, attack="BALANCED", opponent_defence="BALANCED"):
    central = (own["center"] - opponent["center"]) / 100
    wide = (
        (own["left"] - opponent["right_cover"])
        + (own["right"] - opponent["left_cover"])
    ) / 200
    pocket = (own["pocket"] - opponent["screen"]) / 100
    build = (own["build"] - opponent["press"]) / 100
    box = (own["box"] - opponent["rest"]) / 100
    counter = (own["speed"] - opponent["rest"]) / 100
    risk = max(0, opponent["speed"] - own["rest"]) / 100
    weights = {
        "central": 0.22,
        "wide": 0.22,
        "pocket": 0.2,
        "build": 0.16,
        "box": 0.12,
        "counter": 0.08,
    }
    if attack == "WIDE_PLAY":
        weights.update(
            central=0.08, wide=0.48, pocket=0.1, build=0.1, box=0.16, counter=0.08
        )
    elif attack == "COUNTER_ATTACK":
        weights.update(
            central=0.08, wide=0.12, pocket=0.12, build=0.08, box=0.2, counter=0.4
        )
    elif attack == "DIRECT":
        weights.update(
            central=0.06, wide=0.16, pocket=0.12, build=0.06, box=0.4, counter=0.2
        )
    elif attack == "POSSESSION":
        weights.update(
            central=0.34, wide=0.12, pocket=0.22, build=0.24, box=0.06, counter=0.02
        )
    edges = {
        "central": central,
        "wide": wide,
        "pocket": pocket,
        "build": build,
        "box": box,
        "counter": counter,
    }
    edge = sum(edges[k] * v for k, v in weights.items()) - 0.15 * risk
    factor = clamp(1 + 0.16 * edge, 0.92, 1.08)
    return {
        "chance_factor": round(factor, 6),
        "possession_delta": round(
            clamp((central * 0.6 + build * 0.4) * 0.07, -0.035, 0.035), 6
        ),
        "edges": {k: round(v, 4) for k, v in edges.items()},
        "transition_risk": round(risk, 4),
        "weights": weights,
    }


def evaluate_pair(
    home,
    away,
    home_attack="BALANCED",
    home_defence="BALANCED",
    away_attack="BALANCED",
    away_defence="BALANCED",
    minute=0,
):
    first = profile(home, home_attack, home_defence, minute)
    second = profile(away, away_attack, away_defence, minute)
    return {
        "policy_version": POLICY_VERSION,
        "home_profile": first,
        "away_profile": second,
        "home": interaction(first, second, home_attack, away_defence),
        "away": interaction(second, first, away_attack, home_defence),
        "interpretation": "MODEL_INDICES_NOT_WIN_PROBABILITIES",
    }
