from __future__ import annotations

import json
from pathlib import Path
from typing import Any


PROFILE_DIR = Path(__file__).resolve().parent / "builtin_profiles"

PROFILE_ALIASES = {
    "ZeroI_D": "fwlib0iD64",
    "ZeroI_F": "fwlib0iD64",
    "ZeroI_MF": "fwlib0iD64",
    "ZeroI_TF": "fwlib0iD64",
    "Sixteen_i": "FWLIB64",
    "Thirty_i": "fwlib30i64",
    "ThirtyOne_i": "fwlib30i64",
    "ThirtyTwo_i": "fwlib30i64",
    "PowerMotion_i": "fwlib0DN64",
}


def list_profiles() -> list[str]:
    return sorted(path.stem for path in PROFILE_DIR.glob("*.json"))


def resolve_profile_name(profile_name: str) -> str:
    return PROFILE_ALIASES.get(profile_name, profile_name)


def load_profile(profile_name: str) -> dict[str, Any]:
    profile_name = resolve_profile_name(profile_name)
    candidates = [
        PROFILE_DIR / f"{profile_name}.json",
        PROFILE_DIR / f"{Path(profile_name).stem}.json",
    ]
    for candidate in candidates:
        if candidate.exists():
            return json.loads(candidate.read_text(encoding="utf-8"))
    available = ", ".join(list_profiles())
    raise FileNotFoundError(f"Unknown profile '{profile_name}'. Available profiles: {available}")
