from __future__ import annotations

from pathlib import Path
import time
import unicodedata
import xml.etree.ElementTree as ET


_CACHE = {"expires_at": 0.0, "data": None, "path": ""}


def _normalize_label(value):
    text = "" if value is None else str(value).strip().lower()
    normalized = unicodedata.normalize("NFKD", text)
    ascii_only = "".join(ch for ch in normalized if not unicodedata.combining(ch))
    for dash in ("-", "_", "–", "—", "‑"):
        ascii_only = ascii_only.replace(dash, " ")
    return " ".join(ascii_only.split())


def _candidate_paths():
    # Preferred location: this package directory.
    here = Path(__file__).resolve()
    package_dir = here.parent
    repo_root = here.parents[4]
    outer_root = repo_root.parent

    return [
        package_dir / "noeDictionary_v_2_0.xml",
        repo_root / "noeDictionary_v_2_0.xml",
        outer_root / "noeDictionary_v_2_0.xml",
    ]


def _resolve_dictionary_path(dictionary_path=None):
    if dictionary_path:
        explicit = Path(dictionary_path)
        if explicit.exists():
            return explicit

    for candidate in _candidate_paths():
        if candidate.exists():
            return candidate

    raise FileNotFoundError("Cannot find noeDictionary_v_2_0.xml in expected locations")


def _parse_dictionary(path):
    tree = ET.parse(path)
    root = tree.getroot()
    data = {}

    for section in root:
        rows = []
        for node in section.findall("d"):
            rows.append(
                {
                    "id": str(node.attrib.get("id", "")).strip(),
                    "label": (node.text or "").strip(),
                }
            )
        data[section.tag] = rows

    return data


def get_no_dictionary(dictionary_path=None, ttl_seconds=21600):
    now = time.time()
    resolved_path = _resolve_dictionary_path(dictionary_path)
    path_str = str(resolved_path)

    if (
        _CACHE["data"] is not None
        and _CACHE["path"] == path_str
        and now < _CACHE["expires_at"]
    ):
        return _CACHE["data"]

    parsed = _parse_dictionary(resolved_path)
    _CACHE["data"] = parsed
    _CACHE["path"] = path_str
    _CACHE["expires_at"] = now + ttl_seconds
    return parsed


def map_no_code(section, label, aliases=None, default="", dictionary_path=None):
    aliases = aliases or {}
    normalized_aliases = {_normalize_label(k): str(v) for k, v in aliases.items()}
    normalized_input = _normalize_label(label)

    if normalized_input in normalized_aliases:
        alias_value = normalized_aliases[normalized_input]
        if alias_value.isdigit() or (alias_value.startswith("-") and alias_value[1:].isdigit()):
            return alias_value
        normalized_input = _normalize_label(alias_value)

    dictionary = get_no_dictionary(dictionary_path=dictionary_path)
    rows = dictionary.get(section, [])
    ids = {str(row["id"]).strip() for row in rows if row.get("id")}
    # Allow passing already-resolved numeric codes (e.g. "2" for Wynajem).
    if normalized_input in ids:
        return normalized_input
    label_to_code = {_normalize_label(row["label"]): row["id"] for row in rows if row.get("id")}
    return label_to_code.get(normalized_input, default)
