from __future__ import annotations

import re


DESKTOP_THEME_SETTING_KEY = "desktop_theme"

DESKTOP_THEME_FIELDS: list[tuple[str, str]] = [
    ("shell_bg", "theme_shell_bg"),
    ("sidebar_bg", "theme_sidebar_bg"),
    ("content_bg", "theme_content_bg"),
    ("card_bg", "theme_card_bg"),
    ("text", "theme_text"),
    ("muted", "theme_muted"),
    ("accent", "theme_accent"),
    ("accent_soft", "theme_accent_soft"),
    ("accent_hover", "theme_accent_hover"),
    ("tree_bg", "theme_tree_bg"),
    ("tree_odd", "theme_tree_odd"),
    ("tree_even", "theme_tree_even"),
]

DEFAULT_DESKTOP_THEME: dict[str, str] = {
    "shell_bg": "#f3f5f8",
    "sidebar_bg": "#e8edf3",
    "content_bg": "#f7f8fb",
    "card_bg": "#ffffff",
    "text": "#1d2430",
    "muted": "#5f6b7a",
    "accent": "#1f4f82",
    "accent_soft": "#dce5ef",
    "accent_hover": "#cfd9e5",
    "tree_bg": "#ffffff",
    "tree_odd": "#f7f9fc",
    "tree_even": "#ffffff",
}

HEX_COLOR_PATTERN = re.compile(r"^#[0-9A-Fa-f]{6}$")


def normalize_hex_color(value: object, fallback: str) -> str:
    text = str(value or "").strip()
    if not text:
        return fallback
    if not text.startswith("#"):
        text = f"#{text}"
    if re.fullmatch(r"#[0-9A-Fa-f]{3}", text):
        text = "#" + "".join(char * 2 for char in text[1:])
    if HEX_COLOR_PATTERN.fullmatch(text):
        return text.lower()
    return fallback


def normalize_desktop_theme(payload: object | None) -> dict[str, str]:
    source = payload if isinstance(payload, dict) else {}
    normalized = dict(DEFAULT_DESKTOP_THEME)
    for key, fallback in DEFAULT_DESKTOP_THEME.items():
        normalized[key] = normalize_hex_color(source.get(key), fallback)
    return normalized
