#!/usr/bin/env python3
"""Generate full Tauri icon set from src-tauri/icons/icon.png (1024 master)."""
import os
import subprocess
import sys
from pathlib import Path
from PIL import Image

ROOT = Path(__file__).resolve().parent.parent
ICONS = ROOT / 'src-tauri' / 'icons'
MASTER = ICONS / 'icon.png'

if not MASTER.exists():
    sys.exit(f'missing {MASTER}')

master = Image.open(MASTER).convert('RGBA')
print(f'master: {master.size}')

# Tauri canonical
png_targets = [
    ('32x32.png', 32),
    ('128x128.png', 128),
    ('128x128@2x.png', 256),
    # Windows Store tile set
    ('Square30x30Logo.png', 30),
    ('Square44x44Logo.png', 44),
    ('Square71x71Logo.png', 71),
    ('Square89x89Logo.png', 89),
    ('Square107x107Logo.png', 107),
    ('Square142x142Logo.png', 142),
    ('Square150x150Logo.png', 150),
    ('Square284x284Logo.png', 284),
    ('Square310x310Logo.png', 310),
    ('StoreLogo.png', 50),
]

for name, size in png_targets:
    out = ICONS / name
    img = master.resize((size, size), Image.LANCZOS)
    img.save(out, format='PNG', optimize=True)
    print(f'  -> {name} ({size}x{size})')

# Windows .ico (multi-size)
ico_sizes = [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
ico_path = ICONS / 'icon.ico'
master.save(ico_path, format='ICO', sizes=ico_sizes)
print(f'  -> icon.ico {ico_sizes}')

# macOS .icns via iconutil
iconset = ICONS / 'icon.iconset'
iconset.mkdir(exist_ok=True)
icns_sizes = [
    (16, 1), (16, 2),
    (32, 1), (32, 2),
    (128, 1), (128, 2),
    (256, 1), (256, 2),
    (512, 1), (512, 2),
]
for base, scale in icns_sizes:
    size = base * scale
    suffix = '' if scale == 1 else '@2x'
    out = iconset / f'icon_{base}x{base}{suffix}.png'
    master.resize((size, size), Image.LANCZOS).save(out, format='PNG')

icns_out = ICONS / 'icon.icns'
res = subprocess.run(
    ['iconutil', '-c', 'icns', str(iconset), '-o', str(icns_out)],
    capture_output=True, text=True,
)
if res.returncode != 0:
    sys.exit(f'iconutil failed: {res.stderr}')
print(f'  -> icon.icns')

# cleanup iconset dir
for f in iconset.iterdir():
    f.unlink()
iconset.rmdir()

print('done')
