"""Shared UI theme helpers — theme presets, CSS vars. Used by feed, roster, settings, Vastian app.

Loads config/ui-preferences.yaml from the vastian data path (VASTIAN_DATA_ROOT or
config/local/data_root.txt). Supports theme (light/dark/system), theme_preset, density.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any


def _ui_prefs_path(project_root: Path | None = None) -> Path:
    """Return path to ui-preferences.yaml. Respects data root when set."""
    from vastian.access_tiers import _find_project_root
    from vastian.storage.data_root import get_config_dir

    root = project_root if project_root is not None else _find_project_root()
    return get_config_dir(root) / "ui-preferences.yaml"


def load_ui_preferences(project_root: Path | None = None) -> dict[str, Any]:
    """Load ui-preferences.yaml. Returns dict with theme, theme_preset, density."""
    path = _ui_prefs_path(project_root)
    prefs: dict[str, Any] = {}
    if path.exists():
        try:
            import yaml

            prefs = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
        except Exception:
            pass
    return {
        "theme": prefs.get("theme") or "dark",
        "theme_preset": prefs.get("theme_preset") or "default",
        "density": prefs.get("density") or "normal",
    }


THEME_PRESETS: dict[str, dict[str, str]] = {
    "default": {"accent": "#58a6ff", "accent2": "#388bfd"},
    "ocean": {"accent": "#0d9488", "accent2": "#06b6d4"},
    "forest": {"accent": "#059669", "accent2": "#10b981"},
    "sunset": {"accent": "#ea580c", "accent2": "#f59e0b"},
    "midnight": {"accent": "#6366f1", "accent2": "#8b5cf6"},
    "rose": {"accent": "#e11d48", "accent2": "#f43f5e"},
    "slate": {"accent": "#64748b", "accent2": "#94a3b8"},
}

DENSITY_CSS: dict[str, str] = {
    "compact": "--padding: 8px; --gap: 6px; --font-scale: 0.92;",
    "normal": "--padding: 12px; --gap: 10px; --font-scale: 1;",
    "spacious": "--padding: 16px; --gap: 14px; --font-scale: 1.05;",
}


def get_theme_css(project_root: Path | None = None) -> str:
    """Load ui-preferences from config (vastian data path) and return :root CSS vars.

    Includes theme_preset accent colors, theme (light/dark/system), density.
    """
    prefs = load_ui_preferences(project_root)
    preset = str(prefs.get("theme_preset") or "default").lower()
    theme = str(prefs.get("theme") or "dark").lower()
    density = str(prefs.get("density") or "normal").lower()

    colors = THEME_PRESETS.get(preset, THEME_PRESETS["default"])
    density_vars = DENSITY_CSS.get(density, DENSITY_CSS["normal"])

    # Accent colors (shared by light/dark)
    accent_css = f":root {{ --accent: {colors['accent']}; --accent2: {colors['accent2']}; {density_vars} }}\n"

    # Light/dark mode — semantic color vars
    if theme == "light":
        mode_css = (
            ":root, body { --bg: #f6f8fa; --card: #ffffff; --border: #d0d7de; "
            "--text: #1f2328; --muted: #656d76; }\n"
        )
    elif theme == "system":
        mode_css = (
            ":root, body { --bg: #0d1117; --card: #161b22; --border: #30363d; "
            "--text: #e6edf3; --muted: #8b949e; }\n"
            "@media (prefers-color-scheme: light) {\n"
            "  :root, body { --bg: #f6f8fa; --card: #ffffff; --border: #d0d7de; "
            "--text: #1f2328; --muted: #656d76; }\n"
            "}\n"
        )
    else:
        # dark (default)
        mode_css = (
            ":root, body { --bg: #0d1117; --card: #161b22; --border: #30363d; "
            "--text: #e6edf3; --muted: #8b949e; }\n"
        )

    # Shared accent rules
    rules_css = (
        ".tab-btn.active { color: var(--accent); border-bottom-color: var(--accent); }\n"
        "h1, h2, .top-bar h1 { color: var(--accent); }\n"
        "a, .history-toggle, .k-expand, .nav-item:hover, .nav-item.active { color: var(--accent); }\n"
    )

    return accent_css + mode_css + rules_css
