"""Pure formation/role/positional-familiarity policy for Match Engine v3.1.

No Django imports are allowed here.  The same primitives are used by snapshot
construction, lineup validation and the pure simulation engine so a tactical
role has one meaning across AUTO and INTERACTIVE execution.
"""
from __future__ import annotations

AUTO_ROLE = "AUTO"

# Slot -> canonical football position used by the persistent familiarity model.
SLOT_TARGET_POSITION = {
    "GK": "GK",
    "LB": "LB", "LWB": "LB",
    "RB": "RB", "RWB": "RB",
    "LCB": "CB", "CB": "CB", "RCB": "CB",
    "DM": "CDM", "LDM": "CDM", "RDM": "CDM",
    "LCM": "CM", "CM": "CM", "RCM": "CM",
    "LAM": "CAM", "CAM": "CAM", "RAM": "CAM",
    "LM": "LM", "RM": "RM",
    "LW": "LW", "RW": "RW",
    "ST": "ST", "LST": "ST", "RST": "ST",
}

SLOT_FAMILY = {
    "GK": "goalkeeper",
    "LB": "fullback", "RB": "fullback",
    "LWB": "wingback", "RWB": "wingback",
    "LCB": "centre_back", "CB": "centre_back", "RCB": "centre_back",
    "DM": "defensive_midfield", "LDM": "defensive_midfield", "RDM": "defensive_midfield",
    "LCM": "central_midfield", "CM": "central_midfield", "RCM": "central_midfield",
    "LAM": "attacking_midfield", "CAM": "attacking_midfield", "RAM": "attacking_midfield",
    "LM": "wide_midfield", "RM": "wide_midfield",
    "LW": "winger", "RW": "winger",
    "ST": "striker", "LST": "striker", "RST": "striker",
}

DEFAULT_ROLE_BY_FAMILY = {
    "goalkeeper": "GOALKEEPER",
    "centre_back": "CENTRE_BACK",
    "fullback": "FULL_BACK",
    "wingback": "WING_BACK",
    "defensive_midfield": "ANCHOR",
    "central_midfield": "CENTRAL_MIDFIELDER",
    "attacking_midfield": "ADVANCED_PLAYMAKER",
    "wide_midfield": "WIDE_MIDFIELDER",
    "winger": "WINGER",
    "striker": "COMPLETE_FORWARD",
}

ROLE_ALLOWED_FAMILIES = {
    "GOALKEEPER": {"goalkeeper"},
    "SWEEPER_KEEPER": {"goalkeeper"},
    "CENTRE_BACK": {"centre_back"},
    "BALL_PLAYING_DEFENDER": {"centre_back"},
    "NO_NONSENSE_CENTRE_BACK": {"centre_back"},
    "FULL_BACK": {"fullback"},
    "WING_BACK": {"fullback", "wingback"},
    "INVERTED_FULL_BACK": {"fullback", "wingback"},
    "ANCHOR": {"defensive_midfield"},
    "BALL_WINNING_MIDFIELDER": {"defensive_midfield", "central_midfield"},
    "DEEP_LYING_PLAYMAKER": {"defensive_midfield", "central_midfield"},
    "CENTRAL_MIDFIELDER": {"central_midfield"},
    "BOX_TO_BOX": {"central_midfield"},
    "ADVANCED_PLAYMAKER": {"central_midfield", "attacking_midfield"},
    "WIDE_MIDFIELDER": {"wide_midfield"},
    "WINGER": {"wide_midfield", "winger"},
    "INSIDE_FORWARD": {"winger", "attacking_midfield"},
    "TARGET_FORWARD": {"striker"},
    "PRESSING_FORWARD": {"striker"},
    "POACHER": {"striker"},
    "FALSE_NINE": {"striker", "attacking_midfield"},
    "COMPLETE_FORWARD": {"striker"},
}

# Behaviour multipliers are deliberately modest.  Roles should change *how* a
# player participates, while football attributes still decide whether they are
# good at that behaviour.
ROLE_BEHAVIOUR = {
    "GOALKEEPER": {"pass": 0.82, "creator": 0.40, "shooter": 0.05, "defender": 1.00, "press": 0.70, "fatigue": 0.82},
    "SWEEPER_KEEPER": {"pass": 1.18, "creator": 0.65, "shooter": 0.05, "defender": 1.02, "press": 0.90, "fatigue": 0.92},
    "CENTRE_BACK": {"pass": 0.82, "creator": 0.48, "shooter": 0.34, "defender": 1.08, "press": 0.92, "fatigue": 0.94},
    "BALL_PLAYING_DEFENDER": {"pass": 1.15, "creator": 0.78, "shooter": 0.38, "defender": 0.98, "press": 0.92, "fatigue": 0.98},
    "NO_NONSENSE_CENTRE_BACK": {"pass": 0.67, "creator": 0.35, "shooter": 0.30, "defender": 1.16, "press": 0.95, "fatigue": 0.95},
    "FULL_BACK": {"pass": 0.96, "creator": 0.82, "shooter": 0.54, "defender": 1.05, "press": 1.00, "fatigue": 1.02},
    "WING_BACK": {"pass": 1.02, "creator": 1.05, "shooter": 0.68, "defender": 0.92, "press": 1.06, "fatigue": 1.10},
    "INVERTED_FULL_BACK": {"pass": 1.12, "creator": 1.00, "shooter": 0.62, "defender": 0.98, "press": 1.03, "fatigue": 1.06},
    "ANCHOR": {"pass": 0.92, "creator": 0.72, "shooter": 0.42, "defender": 1.14, "press": 0.96, "fatigue": 0.96},
    "BALL_WINNING_MIDFIELDER": {"pass": 0.90, "creator": 0.78, "shooter": 0.64, "defender": 1.10, "press": 1.16, "fatigue": 1.12},
    "DEEP_LYING_PLAYMAKER": {"pass": 1.20, "creator": 1.18, "shooter": 0.62, "defender": 0.90, "press": 0.88, "fatigue": 0.96},
    "CENTRAL_MIDFIELDER": {"pass": 1.00, "creator": 1.00, "shooter": 0.84, "defender": 0.96, "press": 1.00, "fatigue": 1.00},
    "BOX_TO_BOX": {"pass": 1.00, "creator": 0.96, "shooter": 1.00, "defender": 1.00, "press": 1.10, "fatigue": 1.16},
    "ADVANCED_PLAYMAKER": {"pass": 1.16, "creator": 1.25, "shooter": 0.92, "defender": 0.72, "press": 0.84, "fatigue": 1.00},
    "WIDE_MIDFIELDER": {"pass": 1.02, "creator": 1.02, "shooter": 0.78, "defender": 0.92, "press": 1.02, "fatigue": 1.06},
    "WINGER": {"pass": 0.96, "creator": 1.08, "shooter": 1.04, "defender": 0.72, "press": 1.00, "fatigue": 1.07},
    "INSIDE_FORWARD": {"pass": 0.92, "creator": 0.98, "shooter": 1.28, "defender": 0.66, "press": 0.98, "fatigue": 1.08},
    "TARGET_FORWARD": {"pass": 0.84, "creator": 0.78, "shooter": 1.18, "defender": 0.62, "press": 0.82, "fatigue": 1.02},
    "PRESSING_FORWARD": {"pass": 0.88, "creator": 0.82, "shooter": 1.04, "defender": 0.74, "press": 1.28, "fatigue": 1.18},
    "POACHER": {"pass": 0.72, "creator": 0.62, "shooter": 1.36, "defender": 0.52, "press": 0.74, "fatigue": 0.96},
    "FALSE_NINE": {"pass": 1.12, "creator": 1.18, "shooter": 1.04, "defender": 0.62, "press": 0.90, "fatigue": 1.02},
    "COMPLETE_FORWARD": {"pass": 0.96, "creator": 0.94, "shooter": 1.18, "defender": 0.62, "press": 0.94, "fatigue": 1.08},
}

# Natural-position fallback when no explicit trained familiarity row exists.
# Values are football familiarity, not direct skill multipliers.
BASE_POSITION_FAMILIARITY = {
    "GK": {"GK": 100},
    "CB": {"CB": 100, "CDM": 82, "LB": 72, "RB": 72, "CM": 58},
    "LB": {"LB": 100, "LM": 86, "LW": 72, "CB": 75, "RB": 68, "CDM": 65},
    "RB": {"RB": 100, "RM": 86, "RW": 72, "CB": 75, "LB": 68, "CDM": 65},
    "CDM": {"CDM": 100, "CM": 92, "CB": 84, "CAM": 68, "LB": 66, "RB": 66},
    "CM": {"CM": 100, "CDM": 90, "CAM": 88, "LM": 76, "RM": 76, "CF": 64},
    "CAM": {"CAM": 100, "CM": 88, "CF": 88, "LW": 82, "RW": 82, "ST": 76, "LM": 78, "RM": 78},
    "LM": {"LM": 100, "LW": 92, "LB": 82, "CM": 80, "RM": 70, "CAM": 76},
    "RM": {"RM": 100, "RW": 92, "RB": 82, "CM": 80, "LM": 70, "CAM": 76},
    "LW": {"LW": 100, "LM": 92, "CAM": 84, "CF": 82, "ST": 78, "RW": 72, "LB": 68},
    "RW": {"RW": 100, "RM": 92, "CAM": 84, "CF": 82, "ST": 78, "LW": 72, "RB": 68},
    "ST": {"ST": 100, "CF": 96, "CAM": 76, "LW": 76, "RW": 76},
    "CF": {"CF": 100, "ST": 96, "CAM": 90, "LW": 82, "RW": 82, "CM": 62},
}


def slot_family(slot: str) -> str:
    try:
        return SLOT_FAMILY[slot]
    except KeyError as exc:
        raise ValueError(f"Unsupported tactical slot: {slot}") from exc


def target_position(slot: str) -> str:
    try:
        return SLOT_TARGET_POSITION[slot]
    except KeyError as exc:
        raise ValueError(f"Unsupported tactical slot: {slot}") from exc


def resolve_tactical_role(role: str | None, slot: str) -> str:
    family = slot_family(slot)
    if role in (None, "", AUTO_ROLE):
        return DEFAULT_ROLE_BY_FAMILY[family]
    if role not in ROLE_ALLOWED_FAMILIES:
        raise ValueError(f"Unsupported tactical role: {role}")
    if family not in ROLE_ALLOWED_FAMILIES[role]:
        raise ValueError(f"Tactical role {role} is not valid for slot {slot}.")
    return role


def role_behaviour(role: str | None, slot: str, key: str) -> float:
    resolved = resolve_tactical_role(role, slot)
    return float(ROLE_BEHAVIOUR.get(resolved, {}).get(key, 1.0))


def baseline_position_familiarity(natural_position: str, slot: str) -> int:
    target = target_position(slot)
    if natural_position == "GK" or target == "GK":
        return 100 if natural_position == target == "GK" else 0
    return int(BASE_POSITION_FAMILIARITY.get(natural_position, {}).get(target, 42))


def execution_fit(familiarity: int) -> float:
    """Convert 0..100 familiarity to an execution multiplier.

    100 familiarity is neutral.  Emergency unfamiliarity can cost about 35%,
    while ordinary secondary positions usually lose only 5-12%.
    """
    familiarity = max(0, min(100, int(familiarity)))
    return 0.65 + 0.35 * (familiarity / 100.0)


def familiarity_from_map(natural_position: str, familiarities, slot: str) -> int:
    target = target_position(slot)
    if natural_position == target:
        return 100
    if natural_position == "GK" or target == "GK":
        return 0
    values = dict(familiarities or ())
    return max(0, min(100, int(values.get(target, baseline_position_familiarity(natural_position, slot)))))
