import time
import unicodedata
from ...local_io import urlopen
import xml.etree.ElementTree as ET


_BASE_URL = "https://eksporty.domiporta.pl/Spec"
_CACHE = {"expires_at": 0.0, "categories": None, "features": {}}
_FAILURE_TTL_SECONDS = 300


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))
    return " ".join(ascii_only.replace("-", " ").replace("_", " ").split())


def _fetch_xml(url):
    with urlopen(url, timeout=15) as response:
        body = response.read()
    # Domiporta responses are XML; tolerate UTF-8 BOM.
    if body.startswith(b"\xef\xbb\xbf"):
        body = body[3:]
    return ET.fromstring(body)


def fetch_category_dictionary(ttl_seconds=21600):
    now = time.time()
    if _CACHE["categories"] is not None and now < _CACHE["expires_at"]:
        return _CACHE["categories"]

    try:
        root = _fetch_xml(f"{_BASE_URL}/GetCategoryDictionary")
        categories = []
        for node in root:
            cat_id = node.attrib.get("id")
            name = node.attrib.get("name", "")
            if cat_id:
                categories.append({"id": str(cat_id), "name": name})
        expires_at = now + ttl_seconds
    except Exception:
        categories = []
        expires_at = now + _FAILURE_TTL_SECONDS

    _CACHE["categories"] = categories
    _CACHE["expires_at"] = expires_at
    return categories


def fetch_feature_dictionary(feature_type, ttl_seconds=21600):
    now = time.time()
    cached = _CACHE["features"].get(feature_type)
    if cached and now < cached["expires_at"]:
        return cached["data"]

    try:
        root = _fetch_xml(f"{_BASE_URL}/GetFeatureDictionary?type={feature_type}")
        rows = []
        for node in root:
            feature_id = node.attrib.get("id")
            name = node.attrib.get("name", "")
            category_id = node.attrib.get("categoryId", "")
            if feature_id:
                rows.append({"id": str(feature_id), "name": name, "categoryId": str(category_id or "")})
        expires_at = now + ttl_seconds
    except Exception:
        rows = []
        expires_at = now + _FAILURE_TTL_SECONDS

    _CACHE["features"][feature_type] = {"expires_at": expires_at, "data": rows}
    return rows


def map_category_code(label, aliases=None, default=""):
    aliases = aliases or {}
    normalized_input = _normalize_label(label)
    normalized_aliases = {_normalize_label(k): str(v) for k, v in aliases.items()}
    if normalized_input in normalized_aliases:
        return normalized_aliases[normalized_input]

    categories = fetch_category_dictionary()

    label_to_code = {_normalize_label(item["name"]): item["id"] for item in categories}
    return label_to_code.get(normalized_input, default)


def map_feature_code(feature_type, label, category_id=None, aliases=None, default=""):
    aliases = aliases or {}
    normalized_input = _normalize_label(label)
    normalized_aliases = {_normalize_label(k): str(v) for k, v in aliases.items()}
    alias_value = normalized_aliases.get(normalized_input)
    if alias_value:
        if alias_value.isdigit():
            return alias_value
        normalized_input = _normalize_label(alias_value)

    rows = fetch_feature_dictionary(feature_type)

    normalized_category = "" if category_id is None else str(category_id)
    for row in rows:
        if _normalize_label(row["name"]) != normalized_input:
            continue
        if normalized_category and row["categoryId"] and row["categoryId"] != normalized_category:
            continue
        return row["id"]

    return default
