"""Canonical editable tactical plans and a client-readable football catalog."""

from .constants import (
    ALL_FORMATION_SLOTS,
    FORMATION_SLOTS,
    AttackingStrategy,
    DefensiveStrategy,
    TacticalAdaptationMode,
    TacticalPlayerRole,
    TacticalTriggerType,
)
from .engine.roles import ROLE_ALLOWED_FAMILIES, SLOT_FAMILY
from .exceptions import InvalidLineupPlayerError

DEFAULT_PLAN = {
    "attacking_strategy": "BALANCED",
    "defensive_strategy": "BALANCED",
    "adaptation_mode": "BALANCED",
    "instructions": [],
}
PRESETS = [
    ("BALANCED", "متعادل", "BALANCED", "BALANCED"),
    ("CONTROL", "مالکیت و کنترل", "POSSESSION", "MID_BLOCK"),
    ("TIKI_TAKA", "پاس کوتاه و بازی ترکیبی", "POSSESSION", "ZONAL_COMPACT"),
    ("GEGENPRESS", "پرس و بازی سریع", "HIGH_TEMPO", "HIGH_PRESS"),
    ("COUNTER", "ضدحمله", "COUNTER_ATTACK", "LOW_BLOCK"),
    ("WING_PLAY", "حمله از کناره‌ها", "WIDE_PLAY", "MID_BLOCK"),
    ("DIRECT", "بازی مستقیم", "DIRECT", "MID_BLOCK"),
    ("DEEP_BLOCK", "دفاع فشرده و خروج سریع", "DIRECT", "LOW_BLOCK"),
    ("POSSESSION_PRESS", "مالکیت همراه پرس بالا", "POSSESSION", "HIGH_PRESS"),
    ("WIDE_PRESS", "عرض زیاد و پرس بالا", "WIDE_PLAY", "HIGH_PRESS"),
    ("COUNTER_PRESS", "ضدحمله با پرس میانی", "COUNTER_ATTACK", "MID_BLOCK"),
    ("MAN_MARKING", "یارگیری نفر به نفر", "BALANCED", "MAN_MARKING"),
]
LABELS = {
    "4-4-2-D": "۴-۴-۲ لوزی باریک",
    "4-4-2-WD": "۴-۴-۲ لوزی باز",
    "4-3-3-DM": "۴-۳-۳ تک محور دفاعی",
    "4-3-3-2DM": "۴-۳-۳ دو هافبک دفاعی",
    "4-3-3-AM": "۴-۳-۳ هجومی",
    "CUSTOM": "چیدمان سفارشی",
}


def validate_plan(value):
    if not isinstance(value, dict) or set(value) - set(DEFAULT_PLAN):
        raise InvalidLineupPlayerError("Unsupported tactical plan fields.")
    plan = {**DEFAULT_PLAN, **value}
    for field, choices in (
        ("attacking_strategy", AttackingStrategy.values),
        ("defensive_strategy", DefensiveStrategy.values),
        ("adaptation_mode", TacticalAdaptationMode.values),
    ):
        if plan[field] not in choices:
            raise InvalidLineupPlayerError(f"Unsupported {field}.")
    rules = plan["instructions"]
    if not isinstance(rules, list) or len(rules) > 10:
        raise InvalidLineupPlayerError(
            "A plan supports at most ten conditional instructions."
        )
    priorities = set()
    for row in rules:
        expected = {
            "priority",
            "trigger_type",
            "minute_from",
            "attacking_strategy",
            "defensive_strategy",
        }
        if not isinstance(row, dict) or set(row) != expected:
            raise InvalidLineupPlayerError("Invalid conditional tactical instruction.")
        if any(
            isinstance(row[k], bool) or not isinstance(row[k], int)
            for k in ("priority", "minute_from")
        ):
            raise InvalidLineupPlayerError(
                "Instruction priority and minute must be integers."
            )
        if (
            not 1 <= row["priority"] <= 100
            or row["priority"] in priorities
            or not 1 <= row["minute_from"] <= 120
        ):
            raise InvalidLineupPlayerError(
                "Instruction priorities must be unique; minute must be 1..120."
            )
        priorities.add(row["priority"])
        if (
            row["trigger_type"] not in TacticalTriggerType.values
            or row["trigger_type"] == "LIVE_COMMAND"
            or row["attacking_strategy"] not in AttackingStrategy.values
            or row["defensive_strategy"] not in DefensiveStrategy.values
        ):
            raise InvalidLineupPlayerError("Unsupported conditional tactic.")
    return {**plan, "instructions": sorted(rules, key=lambda r: r["priority"])}


def plan_payload(lineup):
    plan = getattr(lineup, "tactical_plan", None)
    if plan is None:
        return {**DEFAULT_PLAN, "instructions": []}
    return {
        "attacking_strategy": plan.attacking_strategy,
        "defensive_strategy": plan.defensive_strategy,
        "adaptation_mode": plan.adaptation_mode,
        "instructions": list(
            plan.instructions.order_by("priority").values(
                "priority",
                "trigger_type",
                "minute_from",
                "attacking_strategy",
                "defensive_strategy",
            )
        ),
    }


def apply_plan(lineup, value):
    from .tactics import MatchTacticalPlanService

    plan = validate_plan(value)
    MatchTacticalPlanService.configure(
        lineup_id=lineup.pk,
        **{
            k: plan[k]
            for k in ("attacking_strategy", "defensive_strategy", "adaptation_mode")
        },
    )
    MatchTacticalPlanService.clear_instructions(lineup_id=lineup.pk)
    for rule in plan["instructions"]:
        MatchTacticalPlanService.add_instruction(lineup_id=lineup.pk, **rule)


def catalog():
    return {
        "formations": [
            {
                "code": code,
                "label": LABELS.get(code, code),
                "slots": list(slots)
                if code != "CUSTOM"
                else list(FORMATION_SLOTS["4-3-3"]),
                "custom": code == "CUSTOM",
            }
            for code, slots in FORMATION_SLOTS.items()
        ],
        "slots": list(ALL_FORMATION_SLOTS),
        "slot_families": SLOT_FAMILY,
        "roles": [
            {
                "code": code,
                "label": label,
                "families": sorted(
                    ROLE_ALLOWED_FAMILIES.get(code, set(SLOT_FAMILY.values()))
                ),
            }
            for code, label in TacticalPlayerRole.choices
        ],
        "attacking_strategies": list(AttackingStrategy.values),
        "defensive_strategies": list(DefensiveStrategy.values),
        "adaptation_modes": list(TacticalAdaptationMode.values),
        "triggers": [v for v in TacticalTriggerType.values if v != "LIVE_COMMAND"],
        "presets": [
            {
                "code": code,
                "label": label,
                "attacking_strategy": attack,
                "defensive_strategy": defence,
            }
            for code, label, attack, defence in PRESETS
        ],
    }
