const fs = require('node:fs');
const path = require('node:path');
const { getInstallEntries } = require('./asset-manifest');

function copyRecursive(source, target) {
  const stats = fs.statSync(source);

  if (stats.isDirectory()) {
    fs.mkdirSync(target, { recursive: true });
    for (const entry of fs.readdirSync(source)) {
      copyRecursive(path.join(source, entry), path.join(target, entry));
    }
    return;
  }

  fs.mkdirSync(path.dirname(target), { recursive: true });
  fs.copyFileSync(source, target);
}

async function copyPackagedAssets({ repoRoot, targetRoot, ides, allowedSkills = null }) {
  for (const entry of getInstallEntries(ides, allowedSkills)) {
    if (entry.type === 'path') {
      const sourcePath = path.join(repoRoot, entry.value);
      if (!fs.existsSync(sourcePath)) continue;
      const targetPath = path.join(targetRoot, entry.target || entry.value);
      copyRecursive(sourcePath, targetPath);
      continue;
    }

    const skillsRoot = path.join(repoRoot, entry.base);
    const targetBase = entry.targetBase || entry.base;

    if (!fs.existsSync(skillsRoot)) continue;

    // Collect skill dirs recursively — supports both flat and category-grouped layouts.
    // Direct rt-* dirs are copied as-is. Category dirs (no rt- prefix) are scanned
    // one level deep and their rt-* children are copied preserving the category path.
    const skillEntries = [];
    for (const name of fs.readdirSync(skillsRoot)) {
      const fullPath = path.join(skillsRoot, name);
      if (!fs.statSync(fullPath).isDirectory()) continue;

      if (name.startsWith(entry.prefix)) {
        // Direct skill at root level
        if (entry.excludePrefix && name.startsWith(entry.excludePrefix)) continue;
        skillEntries.push({ name, srcPath: fullPath, relPath: name });
      } else {
        // Category folder — scan one level deep for rt-* skills
        for (const child of fs.readdirSync(fullPath)) {
          if (!child.startsWith(entry.prefix)) continue;
          if (entry.excludePrefix && child.startsWith(entry.excludePrefix)) continue;
          const childPath = path.join(fullPath, child);
          if (!fs.statSync(childPath).isDirectory()) continue;
          skillEntries.push({ name: child, srcPath: childPath, relPath: path.join(name, child) });
        }
      }
    }

    for (const skill of skillEntries) {
      if (entry.allowedSkills && !entry.allowedSkills.has(skill.name)) continue;
      copyRecursive(
        skill.srcPath,
        path.join(targetRoot, targetBase, skill.relPath)
      );
    }
  }
}

module.exports = { copyPackagedAssets };
