"""
Phosphor icon loading.

Icons are standalone white-fill SVGs extracted from the design handoff
sprite (assets/icons/ph-*.svg). We render them at the requested pixel
size via pygame's SVG support, then tint to any token color by
multiplying — one SVG serves every color.
"""

from __future__ import annotations

import os
from functools import lru_cache

import pygame

_ICON_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "assets", "icons")


@lru_cache(maxsize=256)
def _load_white(name: str, size: int) -> pygame.Surface:
    """Load a white icon SVG at `size`x`size`. Cached."""
    path = os.path.join(_ICON_DIR, f"{name}.svg")
    if not os.path.exists(path):
        # visible magenta box so a missing icon is obvious in dev
        surf = pygame.Surface((size, size), pygame.SRCALPHA)
        surf.fill((255, 0, 255, 120))
        return surf
    try:
        surf = pygame.image.load_sized_svg(path, (size, size))
        return surf.convert_alpha()
    except Exception:
        surf = pygame.Surface((size, size), pygame.SRCALPHA)
        surf.fill((255, 0, 255, 120))
        return surf


@lru_cache(maxsize=512)
def icon(name: str, size: int, color: tuple[int, int, int]) -> pygame.Surface:
    """
    Return the named Phosphor glyph at `size` px, tinted to `color`.
    `name` is the sprite id, e.g. "ph-bluetooth".
    """
    base = _load_white(name, size).copy()
    # Multiply white pixels by the target color, preserving alpha shape.
    tint = pygame.Surface(base.get_size(), pygame.SRCALPHA)
    tint.fill((color[0], color[1], color[2], 255))
    base.blit(tint, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
    return base
