"""Centralised font-loading utilities for all image-composition modules."""

import os

from PIL import ImageFont


def get_system_font(
    size: int,
    bold: bool = True,
) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
    """Return a system font at *size*, preferring bold when *bold* is ``True``.

    Falls back to the PIL default font when no system font is found.
    """
    if bold:
        candidates = [
            "/System/Library/Fonts/Helvetica.ttc",                            # macOS
            "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",           # Linux
            "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
            "/usr/share/fonts/liberation/LiberationSans-Bold.ttf",
        ]
    else:
        candidates = [
            "/System/Library/Fonts/Helvetica.ttc",                            # macOS
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",                # Linux
            "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
            "/usr/share/fonts/liberation/LiberationSans-Regular.ttf",
        ]
    for path in candidates:
        if os.path.exists(path):
            try:
                return ImageFont.truetype(path, size)
            except OSError:
                continue
    return ImageFont.load_default()


def load_template_font(
    template: dict,
    size: int,
    bold: bool = False,
) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
    """Load a font based on *template* configuration.

    Tries the configured font family + suffix, then without suffix, then falls
    back to :func:`get_system_font`.

    Parameters
    ----------
    template:
        The poster template dict (may contain a ``font`` section).
    size:
        Font size in pixels.
    bold:
        When ``True`` use ``bold_suffix``; otherwise use ``regular_suffix``.
    """
    font_cfg = template.get("font", {})
    family = font_cfg.get("family", "Helvetica")
    suffix = font_cfg.get("bold_suffix", " Bold") if bold else font_cfg.get("regular_suffix", "")
    font_name = f"{family}{suffix}"

    try:
        return ImageFont.truetype(font_name, size)
    except (OSError, IOError):
        pass

    # Try without suffix
    if suffix:
        try:
            return ImageFont.truetype(family, size)
        except (OSError, IOError):
            pass

    # Fall back to built-in system-font candidates
    return get_system_font(size, bold=bold)
