from __future__ import annotations

import re
import unicodedata
from typing import Any, Iterable


DISPLAY_NAME_MAX_LENGTH = 48
TECHNICAL_ID_MAX_LENGTH = 28
CAR_SLUG_MAX_LENGTH = 18
EXTERNAL_FOLDER_MAX_LENGTH = 48


def normalize_display_name(value: Any, fallback: str = "New Skin 2026") -> str:
    text = re.sub(r"\s+", " ", str(value or "").strip())
    if not text:
        text = fallback
    return text[:DISPLAY_NAME_MAX_LENGTH].strip()


def slug(value: Any, fallback: str = "skin", max_length: int = TECHNICAL_ID_MAX_LENGTH) -> str:
    text = unicodedata.normalize("NFKD", str(value or ""))
    text = "".join(ch for ch in text if not unicodedata.combining(ch))
    text = text.lower().replace("ß", "ss").replace("&", " and ")
    text = re.sub(r"[^a-z0-9]+", "_", text)
    text = re.sub(r"_+", "_", text).strip("._-")
    text = text[:max(1, int(max_length))].strip("._-")
    return text or fallback


def technical_skin_id(value: Any, fallback: str = "new_skin") -> str:
    return slug(value, fallback=fallback, max_length=TECHNICAL_ID_MAX_LENGTH)


def short_car_slug(car_model: Any, fallback: str = "car") -> str:
    value = slug(car_model, fallback=fallback, max_length=80)
    if value.startswith("ks_"):
        value = value[3:]
    if len(value) <= CAR_SLUG_MAX_LENGTH:
        return value
    parts = [part for part in value.split("_") if part]
    for count in (4, 3, 2):
        candidate = "_".join(parts[-count:])
        if candidate and len(candidate) <= CAR_SLUG_MAX_LENGTH:
            return candidate
    return value[:CAR_SLUG_MAX_LENGTH].strip("._-") or fallback


def with_collision_suffix(base: str, suffix: str, max_length: int) -> str:
    clean_suffix = slug(suffix, fallback="2", max_length=max_length).strip("_")
    tail = f"_{clean_suffix}"
    room = max(1, int(max_length) - len(tail))
    stem = str(base or "").strip("._-")[:room].strip("._-") or "skin"
    return f"{stem}{tail}"


def unique_slug(base: str, existing: Iterable[Any], *, max_length: int = TECHNICAL_ID_MAX_LENGTH) -> str:
    clean_existing = {str(item or "").strip().lower() for item in existing if str(item or "").strip()}
    clean_base = slug(base, fallback="skin", max_length=max_length)
    if clean_base.lower() not in clean_existing:
        return clean_base
    for index in range(2, 1000):
        candidate = with_collision_suffix(clean_base, str(index), max_length)
        if candidate.lower() not in clean_existing:
            return candidate
    return with_collision_suffix(clean_base, "999", max_length)


def external_folder_slug(value: Any, fallback: str = "official_livery") -> str:
    text = unicodedata.normalize("NFKD", str(value or ""))
    text = "".join(ch for ch in text if not unicodedata.combining(ch))
    text = text.lower().replace("ß", "ss").replace("&", " and ")
    text = re.sub(r"[^a-z0-9._-]+", "_", text).strip("._-")
    text = text[:EXTERNAL_FOLDER_MAX_LENGTH].strip("._-")
    return text or fallback


def unique_external_folder_name(base: str, existing: Iterable[Any]) -> str:
    clean_existing = {str(item or "").strip().lower() for item in existing if str(item or "").strip()}
    clean_base = external_folder_slug(base)
    if clean_base.lower() not in clean_existing:
        return clean_base
    for index in range(2, 1000):
        candidate = with_collision_suffix(clean_base, str(index), EXTERNAL_FOLDER_MAX_LENGTH)
        if candidate.lower() not in clean_existing:
            return candidate
    return with_collision_suffix(clean_base, "999", EXTERNAL_FOLDER_MAX_LENGTH)


def official_external_folder_name(car_model: Any, skin_id: Any) -> str:
    car = short_car_slug(car_model)
    skin = technical_skin_id(skin_id)
    prefix = f"{car}__"
    room = max(8, EXTERNAL_FOLDER_MAX_LENGTH - len(prefix))
    return external_folder_slug(f"{prefix}{slug(skin, fallback='skin', max_length=room)}")


def identity_locked(entry: dict[str, Any] | None) -> bool:
    if not isinstance(entry, dict):
        return False
    if entry.get("identity_locked") is True or entry.get("identityLocked") is True:
        return True
    details = entry.get("official_external") if isinstance(entry.get("official_external"), dict) else {}
    return details.get("identityLocked") is True or details.get("identity_locked") is True
