"""Load and manage poster design templates from TOML files."""

import copy
import os

try:
    import tomllib
except ImportError:
    import tomli as tomllib  # type: ignore[no-redef]

TEMPLATE_FILENAME = "poster_template.toml"

_BUILTIN_TEMPLATE: dict = {
    "poster": {
        "width": 1080,
        "height": 1620,
        "image_height": 1080,
        "text_area_height": 540,
        "blur_radius": 30,
        "vignette_strength": 0.18,
        "quality": 90,
    },
    "separator": {
        "height": 0,
        "color": [42, 42, 42],
    },
    "frame": {
        "margin": 12,
        "border_width": 2,
        "color": [58, 58, 58],
        "inner_padding": 20,
        "corner_radius": 8,
    },
    "title": {
        "min_font_size": 40,
        "max_font_size": 72,
        "color": [255, 255, 255],
        "font_weight": "bold",
    },
    "category": {
        "color": [204, 204, 204],
        "font_weight": "regular",
        "size_ratio": 0.65,
        "gap": 12,
    },
    "note": {
        "font_size": 30,
        "color": [215, 215, 215],
        "font_weight": "regular",
    },
    "logo": {
        "wide_max_height": 70,
        "portrait_max_height": 120,
        "wide_threshold": 1.3,
    },
    "shadow": {
        "offset_x": 2,
        "offset_y": 2,
        "alpha": 128,
    },
    "landscape": {
        "width": 1920,
        "height": 1080,
        "lower_third_height": 360,
        "gradient_max_alpha": 160,
        "text_padding": 60,
        "min_font_size": 24,
        "max_font_size": 80,
    },
    "text_area": {
        "darken_opacity": 0.4,
        "blur_radius": 30,
        "background_color": [26, 26, 26],
    },
    "font": {
        "family": "Helvetica",
        "bold_suffix": " Bold",
        "regular_suffix": "",
    },
    "badges": {
        "enabled": True,
        "height": 36,
        "spacing": 6,
        "margin_bottom": 12,
        "margin_left": 16,
    },
}


def _deep_merge(base: dict, override: dict) -> dict:
    """Recursively merge *override* into *base*, returning a new dict."""
    result = copy.deepcopy(base)
    for key, value in override.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = _deep_merge(result[key], value)
        else:
            result[key] = copy.deepcopy(value)
    return result


def _user_config_path() -> str:
    """Return the default user template path: ~/.config/video-thumbnail-creator/poster_template.toml"""
    return os.path.join(
        os.path.expanduser("~"),
        ".config",
        "video-thumbnail-creator",
        TEMPLATE_FILENAME,
    )


def load_template(template_path: str | None = None) -> dict:
    """Load a poster template from a TOML file.

    Resolution order:
    1. Explicit path (``--poster-template`` CLI option)
    2. User config dir (``~/.config/video-thumbnail-creator/poster_template.toml``)
    3. Built-in defaults

    The loaded TOML is deep-merged with built-in defaults so that users only
    need to override the values they want to change.
    """
    candidates = []
    if template_path:
        candidates.append(template_path)
    candidates.append(_user_config_path())

    for path in candidates:
        if os.path.isfile(path):
            with open(path, "rb") as fh:
                overrides = tomllib.load(fh)
            return _deep_merge(_BUILTIN_TEMPLATE, overrides)

    return copy.deepcopy(_BUILTIN_TEMPLATE)
