const { applyFilePolicy, buildReport } = require("./file-policy");
const { getPresetFiles, PRESET_MANIFEST, copyBundle, normalizeBundleMode } = require("./presets");
const { writeScaffoldManifest } = require("./manifest");

function runScaffold({
  rootDir,
  preset = "minimal",
  projectName = "project",
  force = false,
  bundle = "full"
}) {
  if (!PRESET_MANIFEST[preset]) {
    return { error: `unknown preset: ${preset}. Available: ${Object.keys(PRESET_MANIFEST).join(", ")}` };
  }

  const bundleMode = normalizeBundleMode(bundle);
  if (!bundleMode) {
    return { error: `unknown bundle: ${bundle}. Use full or minimal` };
  }

  const files = getPresetFiles(
    preset,
    {
      project_name: projectName,
      date: new Date().toISOString().slice(0, 10)
    },
    { bundle: bundleMode }
  );

  const results = [];
  for (const [rel, content] of Object.entries(files)) {
    results.push(applyFilePolicy({ rootDir, relativePath: rel, content, force }));
  }

  results.push(...copyBundle({ rootDir, force, bundle: bundleMode }));

  const report = buildReport(results);
  report.preset = preset;
  report.bundle = bundleMode;
  report.manifest = PRESET_MANIFEST[preset];
  report.manifest_path = writeScaffoldManifest(rootDir, report);
  return report;
}

module.exports = { runScaffold, PRESET_MANIFEST };
