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

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

const projectRoot = path.join(__dirname, '..');
const standaloneDir = path.join(projectRoot, '.next', 'standalone');

// Function to copy a directory recursively
function copyDirSync(src, dest) {
  if (!fs.existsSync(src)) return;
  
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }

  const entries = fs.readdirSync(src, { withFileTypes: true });

  for (let entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);

    if (entry.isDirectory()) {
      copyDirSync(srcPath, destPath);
    } else {
      fs.copyFileSync(srcPath, destPath);
    }
  }
}

console.log('Copying static assets to standalone directory...');

// Copy 'src/mitm' directory
const mitmSrc = path.join(projectRoot, 'src', 'mitm');
const mitmDest = path.join(standaloneDir, 'src', 'mitm');
if (fs.existsSync(mitmSrc)) {
  console.log(`Copying ${mitmSrc} to ${mitmDest}`);
  copyDirSync(mitmSrc, mitmDest);
}

// Manually copy untraced dependencies for mitm
const mitmDeps = ['node-forge', 'node-machine-id'];
mitmDeps.forEach(dep => {
  const depSrc = path.join(projectRoot, 'node_modules', dep);
  const depDest = path.join(standaloneDir, 'node_modules', dep);
  if (fs.existsSync(depSrc)) {
    console.log(`Copying untraced module: ${dep}`);
    copyDirSync(depSrc, depDest);
  }
});

// Copy 'public' directory
const publicSrc = path.join(projectRoot, 'public');
const publicDest = path.join(standaloneDir, 'public');
if (fs.existsSync(publicSrc)) {
  console.log(`Copying ${publicSrc} to ${publicDest}`);
  copyDirSync(publicSrc, publicDest);
}

// Copy '.next/static' directory
const staticSrc = path.join(projectRoot, '.next', 'static');
// Important: Next.js reads static files from .next/standalone/.next/static
const staticDest = path.join(standaloneDir, '.next', 'static');
if (fs.existsSync(staticSrc)) {
  console.log(`Copying ${staticSrc} to ${staticDest}`);
  copyDirSync(staticSrc, staticDest);
}

console.log('Standalone preparation complete!');
