from __future__ import annotations

from typing import Any


LEAGUE_LABELS: dict[str, dict[str, str]] = {
    "khl": {"ru": "КХЛ", "en": "KHL"},
    "vhl": {"ru": "ВХЛ", "en": "VHL"},
    "vhlb": {"ru": "Первенство ВХЛ", "en": "VHL Tournament"},
    "mhl": {"ru": "МХЛ", "en": "MHL"},
    "mhlb": {"ru": "НМХЛ / Первенство МХЛ", "en": "NMHL / MHL Tournament"},
    "whl": {"ru": "ЖХЛ", "en": "WHL"},
    "fhr": {"ru": "ФХР", "en": "FHR"},
    "hist": {"ru": "Исторические турниры", "en": "Historical tournaments"},
    "histb": {"ru": "Исторические лиги", "en": "Historical leagues"},
}

STAGE_LABELS: dict[str, dict[str, str]] = {
    "regular": {"ru": "Регулярный чемпионат", "en": "Regular season"},
    "playoff": {"ru": "Плей-офф", "en": "Playoffs"},
    "playout": {"ru": "Плей-аут", "en": "Playout"},
    "cup": {"ru": "Кубок", "en": "Cup"},
    "other": {"ru": "Другой этап", "en": "Other stage"},
}


def normalise_language(value: str | None, fallback: str = "ru") -> str:
    value = str(value or "").lower().strip()
    return value if value in {"ru", "en"} else fallback


def choose_text(
    ru: str | None,
    en: str | None,
    *,
    language: str,
    fallback_language: str = "ru",
) -> str:
    language = normalise_language(language)
    fallback_language = normalise_language(fallback_language)
    values = {"ru": str(ru or "").strip(), "en": str(en or "").strip()}
    return (
        values.get(language)
        or values.get(fallback_language)
        or values["ru"]
        or values["en"]
    )


def league_label(level: str, language: str) -> str:
    language = normalise_language(language)
    return LEAGUE_LABELS.get(level, {}).get(language) or level.upper() or "—"


def stage_key(season_part: str, round_code: str = "") -> str:
    value = str(season_part or "").lower()
    if value in {"regular", "playoff", "playout"}:
        return value
    if str(round_code or "").lower() in {"c", "s", "n"}:
        return "cup"
    return "other"


def stage_label(season_part: str, round_code: str, language: str) -> str:
    key = stage_key(season_part, round_code)
    language = normalise_language(language)
    return STAGE_LABELS[key][language]


def bilingual(ru: Any, en: Any) -> dict[str, str]:
    return {"ru": str(ru or ""), "en": str(en or "")}
