#!/usr/bin/env python3
"""Rasterize the shared mascot SVG and package it as a native LVGL image."""

from pathlib import Path

from PIL import Image
from playwright.sync_api import sync_playwright


ROOT = Path(__file__).resolve().parent.parent
SVG = ROOT / "docs/ui-prototype/assets/mascot.svg"
PNG = ROOT / "src/display/ui/assets/mascot.png"
OUTPUT = ROOT / "src/display/ui/assets/mascot_argb.c"
WIDTH, HEIGHT = 270, 305


def main() -> None:
    PNG.parent.mkdir(parents=True, exist_ok=True)
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=True)
        page = browser.new_page(
            viewport={"width": WIDTH, "height": HEIGHT}, device_scale_factor=1
        )
        page.goto(SVG.as_uri())
        page.screenshot(path=str(PNG), omit_background=True)
        browser.close()

    image = Image.open(PNG).convert("RGBA")
    if image.size != (WIDTH, HEIGHT):
        raise ValueError(f"Unexpected mascot size: {image.size}")
    pixels = image.tobytes("raw", "BGRA")
    with OUTPUT.open("w") as output:
        output.write(
            "/* Generated by scripts/gen_home_mascot.py from "
            "docs/ui-prototype/assets/mascot.svg. */\n"
            '#include "lvgl.h"\n\n'
            "static const LV_ATTRIBUTE_MEM_ALIGN uint8_t mascot_map[] = {\n"
        )
        for offset in range(0, len(pixels), 16):
            chunk = pixels[offset : offset + 16]
            output.write("    " + ", ".join(f"0x{byte:02x}" for byte in chunk) + ",\n")
        output.write(
            "};\n\n"
            "const lv_image_dsc_t hw_mascot_image = {\n"
            "    .header.magic = LV_IMAGE_HEADER_MAGIC,\n"
            "    .header.cf = LV_COLOR_FORMAT_ARGB8888,\n"
            f"    .header.w = {WIDTH},\n"
            f"    .header.h = {HEIGHT},\n"
            f"    .header.stride = {WIDTH * 4},\n"
            f"    .data_size = {len(pixels)},\n"
            "    .data = mascot_map,\n"
            "};\n"
        )


if __name__ == "__main__":
    main()
