"""Small UI icons rendered with Pillow.

Lucide "activity" icon — ISC License, https://lucide.dev/icons/activity
"""
from __future__ import annotations

import io
import tkinter as tk

from PIL import Image, ImageDraw

# Lucide activity (24×24 viewBox)
_ACTIVITY_POINTS = ((22, 12), (18, 12), (15, 21), (9, 3), (6, 12), (2, 12))


def _hex_to_rgba(color: str, alpha: int = 255) -> tuple[int, int, int, int]:
    color = color.lstrip("#")
    r = int(color[0:2], 16)
    g = int(color[2:4], 16)
    b = int(color[4:6], 16)
    return r, g, b, alpha


def render_activity_icon(
    size: int,
    color: str,
    *,
    stroke: float = 2.0,
    gap: int = 0,
) -> Image.Image:
    """Rasterize Lucide activity icon at ``size``×``size`` px."""
    width = size + gap
    img = Image.new("RGBA", (width, size), (0, 0, 0, 0))
    draw = ImageDraw.Draw(img)
    pad = size * 0.08
    scale = (size - 2 * pad) / 24.0
    line_w = max(1, int(round(stroke * scale)))
    y_bias = size * 0.06
    points = [
        (pad + x * scale, pad + y * scale + y_bias) for x, y in _ACTIVITY_POINTS
    ]
    draw.line(points, fill=_hex_to_rgba(color), width=line_w, joint="curve")
    return img


def activity_photoimage(
    master: tk.Misc,
    size: int,
    color: str,
    *,
    gap: int = 0,
) -> tk.PhotoImage:
    img = render_activity_icon(size, color, gap=gap)
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    return tk.PhotoImage(master=master, data=buf.getvalue())
