#!/usr/bin/env node

/**
 * Critical Resource Preloading Script
 * Generates preload hints for critical resources to improve performance
 */

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

const BUILD_DIR = path.join(__dirname, '..', 'build');
const INDEX_HTML = path.join(BUILD_DIR, 'index.html');

console.log('🚀 Generating critical resource preload hints...');

try {
  // Check if build directory exists
  if (!fs.existsSync(BUILD_DIR)) {
    console.error('❌ Build directory not found. Run npm run build first.');
    process.exit(1);
  }

  // Read the built index.html
  let indexHtml = fs.readFileSync(INDEX_HTML, 'utf8');

  // Find critical CSS and JS files
  const staticDir = path.join(BUILD_DIR, 'static');
  const cssFiles = [];
  const jsFiles = [];

  // Get CSS files
  if (fs.existsSync(path.join(staticDir, 'css'))) {
    const cssDir = fs.readdirSync(path.join(staticDir, 'css'));
    cssDir.forEach(file => {
      if (file.endsWith('.css') && !file.includes('.map')) {
        cssFiles.push(`/static/css/${file}`);
      }
    });
  }

  // Get JS files (prioritize main chunk)
  if (fs.existsSync(path.join(staticDir, 'js'))) {
    const jsDir = fs.readdirSync(path.join(staticDir, 'js'));
    const mainFiles = [];
    const chunkFiles = [];
    
    jsDir.forEach(file => {
      if (file.endsWith('.js') && !file.includes('.map')) {
        if (file.includes('main.')) {
          mainFiles.push(`/static/js/${file}`);
        } else if (file.includes('react') || file.includes('vendor')) {
          chunkFiles.push(`/static/js/${file}`);
        }
      }
    });
    
    // Prioritize main files, then vendor chunks
    jsFiles.push(...mainFiles, ...chunkFiles);
  }

  // Generate preload hints
  let preloadHints = '';

  // Preload critical CSS
  cssFiles.slice(0, 2).forEach(file => {
    preloadHints += `  <link rel="preload" href="${file}" as="style" onload="this.onload=null;this.rel='stylesheet'">\n`;
    preloadHints += `  <noscript><link rel="stylesheet" href="${file}"></noscript>\n`;
  });

  // Preload critical JS (main bundle)
  jsFiles.slice(0, 1).forEach(file => {
    preloadHints += `  <link rel="preload" href="${file}" as="script">\n`;
  });

  // Preload vendor chunks with lower priority
  jsFiles.slice(1, 3).forEach(file => {
    preloadHints += `  <link rel="prefetch" href="${file}" as="script">\n`;
  });

  // Add DNS prefetch for API calls
  preloadHints += `  <link rel="dns-prefetch" href="/api">\n`;

  // Add preconnect for same-origin API
  preloadHints += `  <link rel="preconnect" href="/api">\n`;

  // Insert preload hints into head
  const headEndIndex = indexHtml.indexOf('</head>');
  if (headEndIndex !== -1) {
    indexHtml = indexHtml.slice(0, headEndIndex) + 
                preloadHints + 
                indexHtml.slice(headEndIndex);
  }

  // Add resource hints for better performance
  const resourceHints = `
  <!-- Performance optimizations -->
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <meta name="theme-color" content="#2e7d32">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="default">
  <meta name="format-detection" content="telephone=no">
  
  <!-- Preload critical fonts if any -->
  <link rel="preload" href="/static/media/fonts.woff2" as="font" type="font/woff2" crossorigin>
  
  <!-- Critical resource hints -->
  <link rel="prefetch" href="/api/auth/me">
  <link rel="prefetch" href="/api/projects">
  `;

  // Insert resource hints after charset
  const charsetIndex = indexHtml.indexOf('<meta charset="utf-8"');
  if (charsetIndex !== -1) {
    const afterCharset = indexHtml.indexOf('>', charsetIndex) + 1;
    indexHtml = indexHtml.slice(0, afterCharset) + 
                resourceHints + 
                indexHtml.slice(afterCharset);
  }

  // Write the optimized index.html
  fs.writeFileSync(INDEX_HTML, indexHtml);

  console.log('✅ Critical resource preload hints generated successfully!');
  console.log(`📊 Preloaded resources:`);
  console.log(`   - CSS files: ${cssFiles.length}`);
  console.log(`   - JS files: ${jsFiles.length}`);
  console.log(`   - Critical preloads: ${cssFiles.slice(0, 2).length + jsFiles.slice(0, 1).length}`);
  console.log(`   - Prefetch hints: ${jsFiles.slice(1, 3).length}`);

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