#!/usr/bin/env python3
"""Rasterize the exact preparation icons embedded in the HTML prototype for LVGL."""

from pathlib import Path
import re

from PIL import Image
from playwright.sync_api import sync_playwright


ROOT = Path(__file__).resolve().parent.parent
PROTOTYPE = ROOT / "docs/ui-prototype/app.js"
ASSETS = ROOT / "src/display/ui/assets"
SIZE = 170
ICONS = {"wet": "wetSvg", "soap": "soapSvg"}


def prototype_svg(source: str, function_name: str) -> str:
    match = re.search(rf"function {function_name}\(\) \{{\s*return `([^`]*)`;\s*\}}", source)
    if not match:
        raise ValueError(f"Cannot find {function_name} in {PROTOTYPE}")
    return match.group(1).replace('class="prep-illustration"', "")


def write_lvgl_image(path: Path, symbol: str, image: Image.Image) -> None:
    pixels = image.convert("RGBA").tobytes("raw", "BGRA")
    with path.open("w") as output:
        output.write(
            f"/* Generated by scripts/gen_prep_icons.py from {PROTOTYPE.relative_to(ROOT)}. */\n"
            '#include "lvgl.h"\n\n'
            f"static const LV_ATTRIBUTE_MEM_ALIGN uint8_t {symbol}_map[] __attribute__((aligned(4))) = {{\n"
        )
        for offset in range(0, len(pixels), 16):
            output.write("    " + ", ".join(f"0x{byte:02x}" for byte in pixels[offset:offset + 16]) + ",\n")
        output.write(
            "};\n\n"
            f"const lv_image_dsc_t {symbol} = {{\n"
            "    .header.magic = LV_IMAGE_HEADER_MAGIC,\n"
            "    .header.cf = LV_COLOR_FORMAT_ARGB8888,\n"
            f"    .header.w = {SIZE},\n"
            f"    .header.h = {SIZE},\n"
            f"    .header.stride = {SIZE * 4},\n"
            f"    .data_size = {len(pixels)},\n"
            f"    .data = {symbol}_map,\n"
            "};\n"
        )


def main() -> None:
    source = PROTOTYPE.read_text()
    ASSETS.mkdir(parents=True, exist_ok=True)
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=True)
        page = browser.new_page(viewport={"width": SIZE, "height": SIZE}, device_scale_factor=1)
        for name, function_name in ICONS.items():
            svg = prototype_svg(source, function_name)
            page.set_content(f"<html><body style='margin:0;background:transparent'>{svg}</body></html>")
            png_path = ASSETS / f"prep_{name}.png"
            page.screenshot(path=str(png_path), omit_background=True)
            image = Image.open(png_path)
            if image.size != (SIZE, SIZE):
                raise ValueError(f"Unexpected {name} image size: {image.size}")
            write_lvgl_image(ASSETS / f"prep_{name}_argb.c", f"hw_prep_{name}_image", image)
        browser.close()


if __name__ == "__main__":
    main()
