const path = require("path");
const { runScaffold, PRESET_MANIFEST } = require("../lib/scaffold");

module.exports = async function scaffold(args, flags) {
  const rootDir = process.cwd();
  const preset = flags.preset || args.find((a) => !a.startsWith("--")) || "minimal";
  const projectName = flags.name || path.basename(rootDir);
  const force = Boolean(flags.force);

  if (flags.list) {
    console.log("\nAvailable presets:\n");
    for (const [id, meta] of Object.entries(PRESET_MANIFEST)) {
      console.log(`  ${id.padEnd(20)} ${meta.description}`);
    }
    console.log("");
    return;
  }

  const report = runScaffold({
    rootDir,
    preset,
    projectName,
    force,
    bundle: flags.bundle || "full"
  });
  if (report.error) {
    console.error(report.error);
    process.exit(1);
  }

  if (flags.json) {
    console.log(JSON.stringify(report, null, 2));
    return;
  }

  console.log("\n## CapInt Scaffold\n");
  console.log(`Preset: ${preset}`);
  console.log(`Summary: created=${report.summary.created} updated=${report.summary.updated} skipped=${report.summary.skipped} conflict=${report.summary.conflict}\n`);
  for (const r of report.results) {
    console.log(`  [${r.action}] ${r.path}${r.sidecar ? ` (sidecar: ${r.sidecar})` : ""}`);
  }
  console.log("");
};
