"""BrandPack: marca conmutable en 1 click (presets + active)."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from app.core.config import get_settings

REQUIRED = (
    "id",
    "name",
    "tagline",
    "primary",
    "accent",
    "bg",
    "fg",
    "logo",
)


def _root() -> Path:
    return get_settings().data_dir / "brand"


def _presets_dir() -> Path:
    d = _root() / "presets"
    d.mkdir(parents=True, exist_ok=True)
    return d


def _active_path() -> Path:
    return _root() / "active.json"


def _default_pack() -> dict[str, Any]:
    return {
        "id": "jobsworld",
        "name": "JobsWorld",
        "tagline": "Tu copiloto de empleo para España e internacional",
        "logo": "/icon-512.png",
        "favicon": "/icon-512.png",
        "primary": "#5a7a18",
        "accent": "#c8f542",
        "bg": "#080a09",
        "fg": "#f3efe4",
        "muted": "#9aa394",
        "font_display": '"Fraunces", "Times New Roman", serif',
        "font_body": '"Outfit", system-ui, sans-serif',
        "pwa_name": "JobsWorld",
        "theme_color": "#080a09",
        "legal_name": "JobsWorld",
        "domain_hint": "jobsworld.local",
    }


def list_presets() -> list[dict[str, Any]]:
    out: list[dict[str, Any]] = []
    for p in sorted(_presets_dir().glob("*.json")):
        try:
            data = json.loads(p.read_text(encoding="utf-8"))
            if isinstance(data, dict) and data.get("id"):
                out.append(data)
        except Exception:  # noqa: BLE001
            continue
    if not out:
        pack = _default_pack()
        save_preset(pack)
        out.append(pack)
    return out


def get_preset(preset_id: str) -> dict[str, Any] | None:
    path = _presets_dir() / f"{preset_id}.json"
    if not path.is_file():
        return None
    return json.loads(path.read_text(encoding="utf-8"))


def save_preset(pack: dict[str, Any]) -> dict[str, Any]:
    pid = str(pack.get("id") or "").strip()
    if not pid:
        raise ValueError("preset id requerido")
    for k in REQUIRED:
        if k not in pack:
            raise ValueError(f"falta campo {k}")
    path = _presets_dir() / f"{pid}.json"
    path.write_text(json.dumps(pack, ensure_ascii=False, indent=2), encoding="utf-8")
    return pack


def get_active() -> dict[str, Any]:
    path = _active_path()
    if path.is_file():
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            if isinstance(data, dict) and data.get("id"):
                return data
        except Exception:  # noqa: BLE001
            pass
    # Preferir preset canónico jobsworld
    pack = get_preset("jobsworld") or _default_pack()
    if not get_preset("jobsworld"):
        save_preset(pack)
    set_active(str(pack["id"]))
    return pack


def set_active(preset_id: str) -> dict[str, Any]:
    pack = get_preset(preset_id)
    if not pack:
        raise FileNotFoundError(f"preset {preset_id} no encontrado")
    _root().mkdir(parents=True, exist_ok=True)
    _active_path().write_text(json.dumps(pack, ensure_ascii=False, indent=2), encoding="utf-8")
    return pack


def css_variables(pack: dict[str, Any] | None = None) -> str:
    p = pack or get_active()
    return (
        ":root{"
        f"--brand-primary:{p.get('primary', '#5a7a18')};"
        f"--brand-accent:{p.get('accent', '#c8f542')};"
        f"--brand-bg:{p.get('bg', '#080a09')};"
        f"--brand-fg:{p.get('fg', '#f3efe4')};"
        f"--brand-muted:{p.get('muted', '#9aa394')};"
        f"--brand-font-display:{p.get('font_display', 'system-ui')};"
        f"--brand-font-body:{p.get('font_body', 'system-ui')};"
        "}"
    )
