#!/usr/bin/env node

/**
 * Build and minify inline scripts extracted from SSR app.rs
 *
 * Usage:
 *   node scripts/build-inline-scripts.js
 *
 * This minifies:
 *   - public/js/theme-init.js -> public/js/theme-init.min.js
 *   - public/js/highlight-utils.js -> public/js/highlight-utils.min.js
 *   - public/js/leptos-hydration.js -> public/js/leptos-hydration.min.js
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Simple JavaScript minifier (removes comments, whitespace, unnecessary chars)
function minifyJs(code) {
  return code
    // Remove single line comments
    .replace(/\/\/.*$/gm, '')
    // Remove multi-line comments
    .replace(/\/\*[\s\S]*?\*\//g, '')
    // Remove excessive whitespace
    .replace(/\s+/g, ' ')
    // Remove whitespace around operators and punctuation
    .replace(/\s*([{}();,=+\-*/<>!&|])\s*/g, '$1')
    // Remove leading/trailing whitespace
    .trim();
}

async function buildInlineScripts() {
  try {
    const sourceDir = path.join(__dirname, '../../site/assets/scripts');
    const publicJsDir = path.join(__dirname, '../../site/public/js');

    if (!fs.existsSync(publicJsDir)) {
      fs.mkdirSync(publicJsDir, { recursive: true });
    }

    const scripts = [
      {
        source: 'theme-init.js',
        target: 'theme-init.min.js',
        description: 'Theme initialization script'
      },
      {
        source: 'highlight-utils.js',
        target: 'highlight-utils.min.js',
        description: 'Highlight.js utilities'
      }
    ];

    console.log('🔨 Building inline scripts...');

    for (const script of scripts) {
      const sourcePath = path.join(sourceDir, script.source);
      const targetPath = path.join(publicJsDir, script.target);

      if (!fs.existsSync(sourcePath)) {
        console.log(`⚠️  Warning: ${script.source} not found, skipping...`);
        continue;
      }

      // Read source
      const sourceCode = fs.readFileSync(sourcePath, 'utf8');

      // Minify
      const minified = minifyJs(sourceCode);

      // Write minified version
      fs.writeFileSync(targetPath, minified);

      // Copy unminified source alongside minified (for development/source mode)
      const unminifiedPath = path.join(publicJsDir, script.source);
      fs.copyFileSync(sourcePath, unminifiedPath);

      // Get file sizes
      const originalSize = sourceCode.length;
      const minifiedSize = minified.length;
      const savings = Math.round(((originalSize - minifiedSize) / originalSize) * 100);

      console.log(`✅ ${script.description}:`);
      console.log(`   📁 ${script.source} -> ${script.target}`);
      console.log(`   📊 ${originalSize} bytes -> ${minifiedSize} bytes (${savings}% reduction)`);
    }

    console.log('');
    console.log('🚀 Inline scripts built successfully!');
    console.log('💡 Scripts are now ready to be loaded as external files');

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

buildInlineScripts();
