#!/usr/bin/env python3
"""Generate the DSH.app icon (1024px rounded blue square with a white "D").

Requires: python3 + Pillow (pip3 install Pillow). Outputs an iconset dir
and a .icns file for macOS.
"""
import os
import subprocess
import sys

try:
    from PIL import Image, ImageDraw, ImageFont
except ImportError:
    sys.exit("Pillow not found: pip3 install Pillow")

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "build", "dsh-icon.iconset")
os.makedirs(OUT, exist_ok=True)

SIZE = 1024
img = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
d = ImageDraw.Draw(img)
margin = 40
d.rounded_rectangle([margin, margin, SIZE - margin, SIZE - margin],
                    radius=200, fill=(20, 90, 220, 255))

overlay = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
do = ImageDraw.Draw(overlay)
do.rounded_rectangle([margin, margin, SIZE - margin, SIZE - margin],
                     radius=200, fill=(255, 255, 255, 40))
img = Image.alpha_composite(img, overlay)

try:
    font = ImageFont.truetype("/System/Library/Fonts/Supplemental/Arial Bold.ttf", 560)
except Exception:
    font = ImageFont.load_default()
d = ImageDraw.Draw(img)
bbox = d.textbbox((0, 0), "D", font=font)
w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
d.text(((SIZE - w) / 2 - bbox[0], (SIZE - h) / 2 - bbox[1]), "D",
       font=font, fill=(255, 255, 255, 255))

img.save(os.path.join(OUT, "icon_1024x1024.png"))
for s in (16, 32, 128, 256, 512):
    img.resize((s, s), Image.LANCZOS).save(os.path.join(OUT, f"icon_{s}x{s}.png"))
    img.resize((s * 2, s * 2), Image.LANCZOS).save(os.path.join(OUT, f"icon_{s}x{s}@2x.png"))

icns = os.path.join(os.path.dirname(OUT), "DSH.icns")
subprocess.run(["iconutil", "-c", "icns", OUT, "-o", icns], check=True)
print(f"icon ready: {icns}")
