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

import copy

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,
        "category_at_top": False,       # render category as overlay band at top of image
        "category_header_height": 80,   # px height of that band
    },
    "separator": {
        "height": 10,
        "color": [42, 42, 42],
    },
    "frame": {
        "margin": 0,
        "border_width": 0,
        "color": [58, 58, 58],
        "inner_padding": 28,
        "corner_radius": 0,
    },
    "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.75,
        "gap": 12,
        "header_font_size": 42,         # font size when rendered in top header band
        "header_background_alpha": 180, # dark band transparency (0=transparent, 255=opaque)
    },
    "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],
        "blur_enabled": True,                   # set False for solid matte background
        "inner_background_color": [26, 26, 26], # used when blur_enabled=False
    },
    "font": {
        "family": "Helvetica Neue",
        "bold_family": "/System/Library/Fonts/HelveticaNeue.ttc",
        "bold_family_index": 1,                  # index 1 = Helvetica Neue Bold in TTC
        "regular_family": "/System/Library/Fonts/HelveticaNeue.ttc",
        "regular_family_index": 0,               # index 0 = Helvetica Neue Regular in TTC
        "bold_suffix": " Bold",
        "regular_suffix": "",
    },
    "badges": {
        "enabled": True,
        "height": 36,
        "spacing": 6,
        "margin_bottom": 12,
        "margin_left": 28,
    },
}

# Overrides applied on top of _BUILTIN_TEMPLATE to produce the "internet" style.
_INTERNET_STYLE_OVERRIDES: dict = {
    "poster": {
        "category_at_top": True,
        "category_header_height": 100,
        "badges_on_image": True,             # render badges on preview image, not text area
    },
    "separator": {
        "height": 0,
    },
    "frame": {
        "margin": 0,
        "border_width": 0,
        "inner_padding": 48,
        "corner_radius": 0,
    },
    "title": {
        "min_font_size": 44,
        "max_font_size": 120,
    },
    "category": {
        "color": [210, 210, 210],
        "header_font_size": 46,
        "header_background_alpha": 190,
    },
    "note": {
        "font_size": 36,
    },
    "text_area": {
        "blur_enabled": False,
        "background_color": [30, 30, 30],
        "inner_background_color": [30, 30, 30],
    },
    "badges": {
        "height": 46,
        "spacing": 8,
        "margin_left": 18,
        "margin_bottom": 32,             # higher than default for better image balance
    },
}


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


# Registry of all built-in named styles.
# To add a new style, insert an entry here with a "description" and a "template" dict.
_STYLES: dict[str, dict] = {
    "internet": {
        "description": "Modern layout for internet/YouTube videos: category header at top, matte black background, large fonts",
        "template": _deep_merge(_BUILTIN_TEMPLATE, _INTERNET_STYLE_OVERRIDES),
    },
}


def get_style(name: str) -> dict:
    """Return a deep copy of the template dict for *name*.

    Raises :exc:`ValueError` when *name* is not a registered style.
    Use :func:`list_styles` to discover available names.
    """
    entry = _STYLES.get(name)
    if entry is None:
        available = ", ".join(f"'{n}'" for n in _STYLES)
        raise ValueError(f"Unknown style '{name}'. Available: {available}")
    return copy.deepcopy(entry["template"])


def list_styles() -> list[dict]:
    """Return a list of ``{"name": ..., "description": ...}`` dicts for all styles."""
    return [{"name": name, "description": entry["description"]} for name, entry in _STYLES.items()]
