#!/usr/bin/env node

/**
 * CSS Asset Deployment Script
 *
 * Copies generated CSS files from works-pv/cache/assets/styles/ to public/styles/ for deployment.
 *
 * Files copied:
 * - *.min.css bundles (site, app, enhancements)
 * - website.css (UnoCSS generated)
 * Note: highlight-github-dark.min.css is bundled into enhancements.min.css
 *
 * Usage:
 *   node scripts/copy-css-assets.js
 */

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

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

async function copyCssAssets() {
  try {
    const assetsStylesDir = path.join(__dirname, '../../works-pv/cache/assets/styles');
    const sourceStylesDir = path.join(__dirname, '../../site/assets/styles');
    const publicStylesDir = path.join(__dirname, '../../site/public/styles');

    const copiedFiles = [];

    // Ensure public/styles directory exists
    if (!fs.existsSync(publicStylesDir)) {
      fs.mkdirSync(publicStylesDir, { recursive: true });
      console.log('📁 Created public/styles/ directory');
    }

    function shouldSkipFile(filename) {
      return filename === '.DS_Store' || filename === 'themes' || filename.endsWith('.toml');
    }

    function syncDir(srcDir, dstDir, label) {
      if (!fs.existsSync(dstDir)) {
        fs.mkdirSync(dstDir, { recursive: true });
      }
      for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
        if (shouldSkipFile(entry.name)) continue;
        const srcPath = path.join(srcDir, entry.name);
        const dstPath = path.join(dstDir, entry.name);
        if (entry.isDirectory()) {
          syncDir(srcPath, dstPath, label);
        } else {
          fs.copyFileSync(srcPath, dstPath);
          const size = Math.round(fs.statSync(dstPath).size / 1024);
          copiedFiles.push(`${path.relative(srcDir, srcPath)} → public/styles/${label} (${size}KB)`);
        }
      }
    }

    // Sync site/assets/styles/ → public/styles/ (custom.css, design-system.css, overrides/, etc.)
    if (fs.existsSync(sourceStylesDir)) {
      console.log('📋 Copying source CSS from site/assets/styles/...');
      syncDir(sourceStylesDir, publicStylesDir, '');
    }

    // Sync works-pv/cache/assets/styles/ → public/styles/ (website.css, *.min.css bundles)
    if (fs.existsSync(assetsStylesDir)) {
      console.log('📋 Copying generated CSS from works-pv/cache/assets/styles/...');
      syncDir(assetsStylesDir, publicStylesDir, '');
    }

    console.log('📦 CSS Asset Deployment Complete!');
    console.log('');

    if (copiedFiles.length > 0) {
      console.log('✅ Copied:');
      copiedFiles.forEach(file => console.log(`   📄 ${file}`));
    }

    const totalFiles = copiedFiles.length;
    const totalSize = copiedFiles.reduce((sum, file) => {
      const sizeMatch = file.match(/\((\d+)KB\)/);
      return sum + (sizeMatch ? parseInt(sizeMatch[1]) : 0);
    }, 0);

    console.log('');
    console.log(`📊 Deployment Summary: ${totalFiles} files, ${totalSize}KB total`);
    console.log('🚀 Ready for Leptos deployment to target/site/');

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

copyCssAssets();
