#!/bin/bash
# gen-icon.sh — Generate PRE Desktop.app icon from favicon.svg
# Tries rsvg-convert (brew install librsvg) first, falls back to qlmanage.

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SVG="$SCRIPT_DIR/../web/public/favicon.svg"
ICONSET_DIR="$SCRIPT_DIR/AppIcon.iconset"
ICNS_OUT="$SCRIPT_DIR/PRE Desktop.app/Contents/Resources/AppIcon.icns"

if [ ! -f "$SVG" ]; then
    echo "Error: favicon.svg not found at $SVG"
    exit 1
fi

mkdir -p "$ICONSET_DIR"

render_svg() {
    local size=$1
    local output=$2

    if command -v rsvg-convert &>/dev/null; then
        rsvg-convert -w "$size" -h "$size" --background-color="#0a0a0a" "$SVG" -o "$output"
    elif command -v python3 &>/dev/null && python3 -c "import cairosvg" 2>/dev/null; then
        python3 -c "
import cairosvg
cairosvg.svg2png(url='$SVG', write_to='$output', output_width=$size, output_height=$size, background_color='#0a0a0a')
"
    else
        # Fallback: use sips on a qlmanage-generated preview
        if [ ! -f "/tmp/pre-icon-base.png" ]; then
            qlmanage -t -s 1024 -o /tmp "$SVG" 2>/dev/null || true
            if [ -f "/tmp/favicon.svg.png" ]; then
                mv "/tmp/favicon.svg.png" "/tmp/pre-icon-base.png"
            else
                # Last resort: generate a simple icon with sips from a placeholder
                echo "Warning: Could not render SVG. Install librsvg: brew install librsvg"
                return 1
            fi
        fi
        sips -z "$size" "$size" "/tmp/pre-icon-base.png" --out "$output" 2>/dev/null
    fi
}

echo "Generating icon sizes..."

for SIZE in 16 32 128 256 512; do
    render_svg "$SIZE" "$ICONSET_DIR/icon_${SIZE}x${SIZE}.png"
    RETINA=$((SIZE * 2))
    render_svg "$RETINA" "$ICONSET_DIR/icon_${SIZE}x${SIZE}@2x.png"
done

echo "Building .icns..."
mkdir -p "$(dirname "$ICNS_OUT")"
iconutil -c icns "$ICONSET_DIR" -o "$ICNS_OUT"

rm -rf "$ICONSET_DIR"
rm -f "/tmp/pre-icon-base.png"

echo "Done: $ICNS_OUT"
