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

const sourceDir = path.resolve(__dirname, '..', '..', '..', 'routebox');
const targetDir = path.resolve(__dirname, '..', 'frontDev');

const EXCLUDED_DIRS = new Set(['node_modules', 'dist', '.git']);
const EXCLUDED_FILES = new Set([
  'npm-debug.log',
  'yarn-error.log',
  // Keep frontDev build output settings local to backend workspace.
  'vue.config.js',
  'vite.config.mjs'
]);

function shouldSkip(name, fullPath) {
  if (EXCLUDED_DIRS.has(name)) {
    return true;
  }

  if (EXCLUDED_FILES.has(name)) {
    return true;
  }

  if (fullPath.includes(path.join(sourceDir, '.git'))) {
    return true;
  }

  return false;
}

function ensureDir(dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
}

function removeStale(targetPath, sourcePath) {
  if (!fs.existsSync(targetPath)) {
    return;
  }

  for (const entry of fs.readdirSync(targetPath, { withFileTypes: true })) {
    const targetEntryPath = path.join(targetPath, entry.name);
    const sourceEntryPath = path.join(sourcePath, entry.name);

    if (shouldSkip(entry.name, sourceEntryPath)) {
      continue;
    }

    if (!fs.existsSync(sourceEntryPath)) {
      fs.rmSync(targetEntryPath, { recursive: true, force: true });
      continue;
    }

    if (entry.isDirectory()) {
      removeStale(targetEntryPath, sourceEntryPath);
    }
  }
}

function copyRecursive(currentSource, currentTarget) {
  ensureDir(currentTarget);

  for (const entry of fs.readdirSync(currentSource, { withFileTypes: true })) {
    const sourceEntryPath = path.join(currentSource, entry.name);
    const targetEntryPath = path.join(currentTarget, entry.name);

    if (shouldSkip(entry.name, sourceEntryPath)) {
      continue;
    }

    if (entry.isDirectory()) {
      copyRecursive(sourceEntryPath, targetEntryPath);
      continue;
    }

    fs.copyFileSync(sourceEntryPath, targetEntryPath);
  }
}

if (!fs.existsSync(sourceDir)) {
  console.error(`Source folder not found: ${sourceDir}`);
  process.exit(1);
}

ensureDir(targetDir);
removeStale(targetDir, sourceDir);
copyRecursive(sourceDir, targetDir);

console.log(`Synced frontend source from ${sourceDir} to ${targetDir}`);
