#!/usr/bin/env python3
"""
InsuRo Icon Converter
Converts favicon.svg → PNG variants + favicon.ico
"""

import os
import sys
import cairosvg
from PIL import Image
import io

SVG_PATH = "/home/jay/projects/InsuRo/public/favicon.svg"
OUT_DIR  = "/home/jay/projects/InsuRo/public"

TARGETS = [
    ("pwa-512.png",          512, 512),
    ("pwa-192.png",          192, 192),
    ("apple-touch-icon.png", 180, 180),
    ("favicon-32.png",        32,  32),
    ("favicon-16.png",        16,  16),
]

ICO_SIZES = [(16, 16), (32, 32), (48, 48)]


def svg_to_png(svg_path: str, out_path: str, width: int, height: int) -> None:
    cairosvg.svg2png(
        url=svg_path,
        write_to=out_path,
        output_width=width,
        output_height=height,
    )
    size = os.path.getsize(out_path)
    print(f"  [OK] {os.path.basename(out_path):30s}  {width}x{height}  {size:,} bytes")


def build_ico(svg_path: str, out_path: str, sizes: list) -> None:
    """Render each size from SVG then pack into multi-size ICO."""
    images = []
    for w, h in sizes:
        raw = cairosvg.svg2png(url=svg_path, output_width=w, output_height=h)
        img = Image.open(io.BytesIO(raw)).convert("RGBA")
        images.append(img)

    # Pillow requires the largest image first for ICO
    images.sort(key=lambda i: i.size[0], reverse=True)

    images[0].save(
        out_path,
        format="ICO",
        sizes=[(img.size[0], img.size[1]) for img in images],
        append_images=images[1:],
    )
    size = os.path.getsize(out_path)
    labels = "+".join(f"{s[0]}x{s[1]}" for s in sorted(sizes))
    print(f"  [OK] {'favicon.ico':30s}  [{labels}]  {size:,} bytes")


def main():
    print(f"\nInsuRo Icon Conversion")
    print(f"  SVG   : {SVG_PATH}")
    print(f"  OutDir: {OUT_DIR}\n")

    if not os.path.isfile(SVG_PATH):
        print(f"[ERROR] SVG not found: {SVG_PATH}")
        sys.exit(1)

    os.makedirs(OUT_DIR, exist_ok=True)

    print("Generating PNG files...")
    for name, w, h in TARGETS:
        out = os.path.join(OUT_DIR, name)
        svg_to_png(SVG_PATH, out, w, h)

    print("\nGenerating favicon.ico...")
    ico_path = os.path.join(OUT_DIR, "favicon.ico")
    build_ico(SVG_PATH, ico_path, ICO_SIZES)

    print("\nAll files generated successfully.\n")

    # Summary
    print("Output summary:")
    for f in os.listdir(OUT_DIR):
        p = os.path.join(OUT_DIR, f)
        if os.path.isfile(p) and f.endswith((".png", ".ico", ".svg")):
            print(f"  {f:35s}  {os.path.getsize(p):>10,} bytes")


if __name__ == "__main__":
    main()
