"""
National-Team League Loader + Competition-Type Classifier
=========================================================
Loads the A-milli (senior men's) football league IDs from
data/national_leagues.json and classifies a league name into a
competition type. Powers the betting_brain national-match gate.

Why this exists:
    Backtest (2300 national matches) showed national matches behave very
    differently from clubs — only the MS market carries edge, and only in
    the 4.0–7.0 odds band for Hazırlık/Eleme fixtures (tournaments behave
    inversely). Calibration is fine; the issue is *which* bets to allow.
    See mds/national-team-strategy.md.

Usage:
    from utils.national_leagues import load_national_leagues, classify_competition
    natl = load_national_leagues()         # set[str] of league_ids
    ctype = classify_competition(name)     # "HAZIRLIK" | "ELEME" | "TURNUVA"
"""

from __future__ import annotations

import json
import os
from typing import Set


_DATA_FILE = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    "..",
    "data",
    "national_leagues.json",
)


def load_national_leagues() -> Set[str]:
    """Return the set of A-milli football league IDs (empty on any failure)."""
    if not os.path.isfile(_DATA_FILE):
        print(
            f"⚠️  national_leagues.json not found at {_DATA_FILE}. "
            "National-match gate disabled (no league treated as national)."
        )
        return set()
    try:
        with open(_DATA_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
        ids = set(str(x) for x in (data.get("league_ids") or []))
        print(f"✅ Loaded {len(ids)} national-team league IDs")
        return ids
    except (json.JSONDecodeError, KeyError, TypeError) as exc:
        print(f"⚠️  Failed to parse national_leagues.json: {exc}")
        return set()


def classify_competition(league_name: str) -> str:
    """Map a league name to a competition type.

    HAZIRLIK = friendlies, ELEME = qualifiers/play-offs, TURNUVA = finals/cups.
    The backtest edge lives in HAZIRLIK+ELEME (MS, odds 4-7); TURNUVA is
    handled conservatively (no bet) by the gate.
    """
    n = (league_name or "").lower()
    if "hazırlık" in n or "hazirlik" in n or "friendl" in n:
        return "HAZIRLIK"
    if "eleme" in n or "play-off" in n or "playoff" in n or "qualif" in n:
        return "ELEME"
    return "TURNUVA"
