#!/usr/bin/env node
/**
 * PWA Apple Icon Converter
 * Converts a single apple image to multiple PWA-optimized PNG formats
 * 
 * Usage: node src/convert-apple-icon.js <input-file> [output-dir]
 * Example: node src/convert-apple-icon.js apple.jpg public/icons
 */

const fs = require('fs');
const path = require('path');

// Try to use sharp if available, otherwise provide installation instructions
let sharp;
try {
  sharp = require('sharp');
} catch (e) {
  console.error('Sharp library not found.');
  console.log('\nTo install sharp, run:');
  console.log('  npm install sharp\n');
  console.log('After installation, run this script again.\n');
  process.exit(1);
}

const inputFile = process.argv[2];
const outputDir = process.argv[3] || 'public';

if (!inputFile) {
  console.error('Usage: node src/convert-apple-icon.js <input-file> [output-dir]');
  console.error('Example: node src/convert-apple-icon.js apple.jpg public');
  process.exit(1);
}

if (!fs.existsSync(inputFile)) {
  console.error(`Error: Input file not found: ${inputFile}`);
  process.exit(1);
}

// Create output directory
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

// PWA Icon Specifications
const iconSpecs = {
  // 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)
  'apple-touch-icon-152.png': 152,  // iPad mini/4, iPad Air
  'apple-touch-icon-120.png': 120,  // iPhone 6
  
  // Fallback sizes
  'apple-96.png': 96,
  'apple-64.png': 64,
  'apple-32.png': 32,
};

async function convertIcon() {
  try {
    console.log(`Loading image: ${inputFile}`);
    console.log(`Output directory: ${outputDir}\n`);
    console.log('Generating PWA icon sizes...\n');

    // Process each size
    const sizes = Object.entries(iconSpecs).sort((a, b) => a[1] - b[1]);
    
    for (const [filename, size] of sizes) {
      const outputPath = path.join(outputDir, filename);
      
      await sharp(inputFile)
        .resize(size, size, {
          fit: 'cover',
          position: 'center',
        })
        .png({ quality: 95, progressive: true })
        .toFile(outputPath);
      
      const stats = fs.statSync(outputPath);
      console.log(`  ✓ ${filename.padEnd(32)} (${size}x${size}) - ${(stats.size / 1024).toFixed(1)}KB`);
    }

    // Create manifest.json
    const manifest = {
      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-192.png",
          sizes: "192x192",
          type: "image/png",
          purpose: "any"
        },
        {
          src: "/icons/apple-256.png",
          sizes: "256x256",
          type: "image/png",
          purpose: "any"
        },
        {
          src: "/icons/apple-384.png",
          sizes: "384x384",
          type: "image/png",
          purpose: "any"
        },
        {
          src: "/icons/apple-512.png",
          sizes: "512x512",
          type: "image/png",
          purpose: "any"
        }
      ]
    };

    fs.writeFileSync(
      path.join(outputDir, 'manifest.json'),
      JSON.stringify(manifest, null, 2)
    );
    console.log(`\n  ✓ manifest.json created`);

    // Create HTML snippet
    const htmlSnippet = `<!-- PWA & iOS Home Screen Meta Tags -->
<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="My App">

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

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

<!-- Favicon Fallbacks -->
<link rel="icon" type="image/png" href="/icons/apple-192.png" sizes="192x192">
<link rel="icon" type="image/png" href="/icons/apple-512.png" sizes="512x512">
`;

    fs.writeFileSync(
      path.join(outputDir, 'html-head-snippet.html'),
      htmlSnippet
    );
    console.log(`  ✓ html-head-snippet.html created`);

    console.log(`\n✅ Done! All PWA icons generated successfully.`);
    console.log(`\n📁 Icons saved to: ${outputDir}/`);
    console.log(`\n📋 Total: ${Object.keys(iconSpecs).length} PNG files`);

  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
}

convertIcon();
