#!/usr/bin/env python3
"""
PWA Apple Icon Converter
Converts apple image to optimal sizes for PWA applications (iOS and Android)
"""
import os
import sys

# Try to import PIL/Pillow
try:
    from PIL import Image
except ImportError:
    print("Installing Pillow...")
    os.system('python3 -m pip install --user Pillow')
    from PIL import Image

# Create output directory
output_dir = 'public/icons/apple'
os.makedirs(output_dir, exist_ok=True)

# PWA Icon Specifications
icon_specs = {
    # PWA Standard Sizes (Web Manifest)
    'apple-192.png': 192,
    'apple-256.png': 256,
    'apple-384.png': 384,
    'apple-512.png': 512,
    
    # iOS Home Screen Icons
    'apple-touch-icon-180.png': 180,  # iPhone 6+/7+/8+
    'apple-touch-icon-167.png': 167,  # iPad Pro (10.5-inch) / iPad Pro (12.9-inch) (1st/2nd gen)
    'apple-touch-icon-152.png': 152,  # iPad mini/4, iPad Air, iPad Air 2
    'apple-touch-icon-120.png': 120,  # iPhone 6+/7+/8+
    
    # Android and General Fallbacks
    'apple-96.png': 96,
    'apple-64.png': 64,
    'apple-32.png': 32,
}

# Load the original image
if len(sys.argv) > 1:
    input_file = sys.argv[1]
else:
    input_file = 'apple_original.jpg'

if not os.path.exists(input_file):
    print(f"Error: Input file '{input_file}' not found")
    sys.exit(1)

try:
    img = Image.open(input_file)
    print(f"Loaded image: {input_file} ({img.size})")
except Exception as e:
    print(f"Error loading image: {e}")
    sys.exit(1)

# Convert to RGB if necessary (handles RGBA, etc.)
if img.mode != 'RGB':
    img = img.convert('RGB')

# Generate all sizes
print("\nGenerating PWA icon sizes...")
for filename, size in sorted(icon_specs.items(), key=lambda x: x[1]):
    output_path = os.path.join(output_dir, filename)
    
    # Resize using high-quality resampling
    resized = img.resize((size, size), Image.Resampling.LANCZOS)
    resized.save(output_path, 'PNG', quality=95)
    
    print(f"  ✓ {filename:30s} ({size}x{size})")

print(f"\nAll icons saved to: {output_dir}/")

# Create a sample manifest.json
manifest_template = """{
  "name": "My PWA App",
  "short_name": "App",
  "description": "Progressive Web App",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "icons": [
    {
      "src": "/icons/apple/apple-192.png",
      "sizes": "192x192",
      "type": "image/png",
      "purpose": "any"
    },
    {
      "src": "/icons/apple/apple-256.png",
      "sizes": "256x256",
      "type": "image/png",
      "purpose": "any"
    },
    {
      "src": "/icons/apple/apple-384.png",
      "sizes": "384x384",
      "type": "image/png",
      "purpose": "any"
    },
    {
      "src": "/icons/apple/apple-512.png",
      "sizes": "512x512",
      "type": "image/png",
      "purpose": "any"
    }
  ]
}
"""

manifest_path = os.path.join(output_dir, 'manifest.json')
with open(manifest_path, 'w') as f:
    f.write(manifest_template)

print(f"\nSample manifest.json created at: {manifest_path}")

# Create HTML head snippet
html_snippet = """<!-- Add to your <head> section -->
<meta name="theme-color" content="#000000">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="App">

<!-- iOS App Icons -->
<link rel="apple-touch-icon" href="/icons/apple/apple-touch-icon-180.png" sizes="180x180">
<link rel="apple-touch-icon" href="/icons/apple/apple-touch-icon-167.png" sizes="167x167">
<link rel="apple-touch-icon" href="/icons/apple/apple-touch-icon-152.png" sizes="152x152">

<!-- PWA Manifest -->
<link rel="manifest" href="/manifest.json">

<!-- Fallback Icons -->
<link rel="icon" type="image/png" href="/icons/apple/apple-192.png" sizes="192x192">
<link rel="icon" type="image/png" href="/icons/apple/apple-512.png" sizes="512x512">
"""

html_path = os.path.join(output_dir, 'html-head-snippet.html')
with open(html_path, 'w') as f:
    f.write(html_snippet)

print(f"HTML head snippet created at: {html_path}")
print("\nDone! Your PWA is ready for mobile deployment.")
