#!/usr/bin/env python3
"""
Generate Memento Mori Study App Icon
Creates an elegant hourglass icon with dark theme
"""

import subprocess
import os

# Icon sizes needed for macOS
SIZES = [16, 32, 64, 128, 256, 512, 1024]

# SVG icon design - elegant hourglass with skull motif
SVG_ICON = '''<?xml version="1.0" encoding="UTF-8"?>
<svg width="1024" height="1024" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="bgGrad" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:#1a1a2e"/>
      <stop offset="100%" style="stop-color:#0f0f1a"/>
    </linearGradient>
    <linearGradient id="hourglassGrad" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:#ff9500"/>
      <stop offset="50%" style="stop-color:#ff6b00"/>
      <stop offset="100%" style="stop-color:#ff4500"/>
    </linearGradient>
    <linearGradient id="sandGrad" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0%" style="stop-color:#ffd700"/>
      <stop offset="100%" style="stop-color:#ff8c00"/>
    </linearGradient>
    <filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
      <feGaussianBlur stdDeviation="8" result="coloredBlur"/>
      <feMerge>
        <feMergeNode in="coloredBlur"/>
        <feMergeNode in="SourceGraphic"/>
      </feMerge>
    </filter>
    <filter id="innerShadow">
      <feOffset dx="0" dy="4"/>
      <feGaussianBlur stdDeviation="4"/>
      <feComposite operator="out" in="SourceGraphic"/>
      <feColorMatrix type="matrix" values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.3 0"/>
      <feBlend mode="normal" in2="SourceGraphic"/>
    </filter>
  </defs>

  <!-- Background -->
  <rect width="1024" height="1024" rx="220" fill="url(#bgGrad)"/>

  <!-- Subtle border -->
  <rect x="4" y="4" width="1016" height="1016" rx="216" fill="none" stroke="#ff950030" stroke-width="2"/>

  <!-- Outer glow ring -->
  <circle cx="512" cy="512" r="380" fill="none" stroke="#ff950015" stroke-width="60"/>

  <!-- Hourglass frame - top -->
  <path d="M 312 200
           L 712 200
           L 712 240
           L 312 240 Z"
        fill="url(#hourglassGrad)" filter="url(#glow)"/>

  <!-- Hourglass frame - bottom -->
  <path d="M 312 784
           L 712 784
           L 712 824
           L 312 824 Z"
        fill="url(#hourglassGrad)" filter="url(#glow)"/>

  <!-- Hourglass glass - top bulb -->
  <path d="M 340 240
           L 684 240
           C 684 240, 684 380, 560 460
           L 464 460
           C 340 380, 340 240, 340 240 Z"
        fill="#ffffff10" stroke="url(#hourglassGrad)" stroke-width="6"/>

  <!-- Hourglass glass - bottom bulb -->
  <path d="M 340 784
           L 684 784
           C 684 784, 684 644, 560 564
           L 464 564
           C 340 644, 340 784, 340 784 Z"
        fill="#ffffff10" stroke="url(#hourglassGrad)" stroke-width="6"/>

  <!-- Hourglass neck -->
  <path d="M 464 460
           L 560 460
           L 540 512
           L 484 512 Z"
        fill="#ffffff08" stroke="url(#hourglassGrad)" stroke-width="4"/>
  <path d="M 484 512
           L 540 512
           L 560 564
           L 464 564 Z"
        fill="#ffffff08" stroke="url(#hourglassGrad)" stroke-width="4"/>

  <!-- Sand in top (less sand - time passing) -->
  <path d="M 400 280
           L 624 280
           C 620 320, 580 380, 530 420
           L 494 420
           C 444 380, 404 320, 400 280 Z"
        fill="url(#sandGrad)" opacity="0.9"/>

  <!-- Falling sand stream -->
  <rect x="506" y="420" width="12" height="144" fill="url(#sandGrad)" opacity="0.8"/>

  <!-- Sand in bottom (more sand - time passed) -->
  <path d="M 360 784
           L 664 784
           C 664 700, 620 620, 540 580
           L 484 580
           C 404 620, 360 700, 360 784 Z"
        fill="url(#sandGrad)" opacity="0.9"/>

  <!-- Decorative elements - small circles -->
  <circle cx="280" cy="512" r="8" fill="#ff9500" opacity="0.6"/>
  <circle cx="744" cy="512" r="8" fill="#ff9500" opacity="0.6"/>

  <!-- Text "MM" stylized at bottom -->
  <text x="512" y="940"
        font-family="Georgia, serif"
        font-size="64"
        font-weight="bold"
        fill="#ff9500"
        text-anchor="middle"
        opacity="0.8">MEMENTO MORI</text>
</svg>'''

def main():
    base_path = os.path.dirname(os.path.abspath(__file__))
    icon_dir = os.path.join(base_path, "MementoMori-Study", "Assets.xcassets", "AppIcon.appiconset")

    # Create SVG file
    svg_path = os.path.join(base_path, "icon.svg")
    with open(svg_path, 'w') as f:
        f.write(SVG_ICON)

    print(f"Created SVG at: {svg_path}")

    # Generate PNG files using sips (macOS built-in)
    contents_images = []

    for size in SIZES:
        # For macOS we need 1x and 2x versions
        for scale in [1, 2]:
            if size * scale > 1024:
                continue

            actual_size = size * scale if scale == 2 else size
            filename = f"icon_{size}x{size}{'@2x' if scale == 2 else ''}.png"
            png_path = os.path.join(icon_dir, filename)

            # Use rsvg-convert if available, otherwise try other methods
            try:
                # Try using rsvg-convert (from librsvg)
                subprocess.run([
                    "rsvg-convert",
                    "-w", str(actual_size),
                    "-h", str(actual_size),
                    "-o", png_path,
                    svg_path
                ], check=True, capture_output=True)
                print(f"Created: {filename} ({actual_size}x{actual_size})")
            except (subprocess.CalledProcessError, FileNotFoundError):
                # Fallback: use qlmanage (QuickLook)
                try:
                    temp_png = os.path.join(base_path, "temp_icon.png")
                    subprocess.run([
                        "qlmanage", "-t", "-s", "1024", "-o", base_path, svg_path
                    ], check=True, capture_output=True)

                    # Rename and resize
                    temp_file = svg_path + ".png"
                    if os.path.exists(temp_file):
                        subprocess.run([
                            "sips", "-z", str(actual_size), str(actual_size),
                            temp_file, "--out", png_path
                        ], check=True, capture_output=True)
                        os.remove(temp_file)
                        print(f"Created (via qlmanage): {filename}")
                except:
                    print(f"Skipped: {filename} (no converter available)")
                    continue

            # Add to contents
            contents_images.append({
                "filename": filename,
                "idiom": "mac",
                "scale": f"{scale}x",
                "size": f"{size}x{size}"
            })

    # Update Contents.json
    import json
    contents_path = os.path.join(icon_dir, "Contents.json")
    contents = {
        "images": contents_images if contents_images else [
            {"idiom": "mac", "scale": "1x", "size": "16x16"},
            {"idiom": "mac", "scale": "2x", "size": "16x16"},
            {"idiom": "mac", "scale": "1x", "size": "32x32"},
            {"idiom": "mac", "scale": "2x", "size": "32x32"},
            {"idiom": "mac", "scale": "1x", "size": "128x128"},
            {"idiom": "mac", "scale": "2x", "size": "128x128"},
            {"idiom": "mac", "scale": "1x", "size": "256x256"},
            {"idiom": "mac", "scale": "2x", "size": "256x256"},
            {"idiom": "mac", "scale": "1x", "size": "512x512"},
            {"idiom": "mac", "scale": "2x", "size": "512x512"}
        ],
        "info": {"author": "xcode", "version": 1}
    }

    with open(contents_path, 'w') as f:
        json.dump(contents, f, indent=2)

    print(f"\nSVG icon created at: {svg_path}")
    print("To convert to PNG, you can use:")
    print("  brew install librsvg")
    print("  Then run this script again")
    print("\nOr open the SVG in Preview/Figma and export as PNG")

if __name__ == "__main__":
    main()
