#!/usr/bin/env python3
"""
Generate a 1 024×1 024 BIBIVIDI source icon (PNG, stdlib only).

Outputs: bvd/ui/src-tauri/icons/icon.png
The Tauri CLI's `tauri icon` command then expands this into all
platform-specific formats (32×32, 128×128, .ico, .icns, etc.)
"""
import struct
import zlib
from pathlib import Path

SIZE = 1024
GREEN = (34, 197, 94)   # BIBIVIDI brand green  #22c55e
WHITE = (255, 255, 255)


# ── Pure-stdlib PNG encoder ────────────────────────────────────────────────────

def _png(pixels: list[list[tuple[int, int, int]]]) -> bytes:
    h, w = len(pixels), len(pixels[0])

    def _chunk(name: bytes, data: bytes) -> bytes:
        c = struct.pack(">I", len(data)) + name + data
        return c + struct.pack(">I", zlib.crc32(name + data) & 0xFFFFFFFF)

    raw = b"".join(
        b"\x00" + b"".join(bytes(p) for p in row) for row in pixels
    )
    return (
        b"\x89PNG\r\n\x1a\n"
        + _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
        + _chunk(b"IDAT", zlib.compress(raw, 6))
        + _chunk(b"IEND", b"")
    )


# ── Icon design ────────────────────────────────────────────────────────────────

def _draw(size: int = SIZE) -> list[list[tuple[int, int, int]]]:
    """
    Green background with a white rounded rectangle (30% margin, 12% radius).
    Simple, scalable, brand-appropriate.
    """
    grid = [[GREEN] * size for _ in range(size)]

    margin = int(size * 0.22)
    radius = int(size * 0.14)
    x0, y0 = margin, margin
    x1, y1 = size - margin, size - margin
    corners = [(x0 + radius, y0 + radius), (x1 - radius, y0 + radius),
               (x0 + radius, y1 - radius), (x1 - radius, y1 - radius)]

    for y in range(size):
        for x in range(size):
            # Is (x, y) inside the rounded rectangle?
            in_h = x0 + radius <= x <= x1 - radius and y0 <= y <= y1
            in_v = x0 <= x <= x1 and y0 + radius <= y <= y1 - radius
            in_corner = any(
                (x - cx) ** 2 + (y - cy) ** 2 <= radius ** 2
                for cx, cy in corners
            )
            if in_h or in_v or in_corner:
                grid[y][x] = WHITE

    return grid


# ── Entry point ────────────────────────────────────────────────────────────────

def main() -> None:
    out = (
        Path(__file__).resolve().parent.parent
        / "bvd" / "ui" / "src-tauri" / "icons" / "icon.png"
    )
    out.parent.mkdir(parents=True, exist_ok=True)
    data = _png(_draw())
    out.write_bytes(data)
    print(f"Icon written → {out}  ({len(data):,} bytes)")


if __name__ == "__main__":
    main()
