const path = require("path");
const fs = require("fs");
const { runScaffold, PRESET_MANIFEST } = require("../lib/scaffold");
const { syncIdeProjections, appendIdeManifestEntries } = require("../lib/ide-sync");
const {
  listPackageSkillNames,
  listProjectSkillNames,
  pkgRoot,
  normalizeBundleMode,
  MINIMAL_BUNDLE_SKILLS
} = require("../lib/scaffold/presets");

module.exports = async function init(args, flags) {
  const rootDir = process.cwd();
  const preset = flags.preset || "minimal";
  const bundle = flags.bundle || "full";
  const projectName = flags.name || path.basename(rootDir);
  const force = Boolean(flags.force);
  const ideSync = !flags["no-ide-sync"];

  if (!normalizeBundleMode(bundle)) {
    console.error(`Unknown --bundle "${bundle}". Use full or minimal.`);
    process.exit(1);
  }

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

  let ideResult = null;
  if (ideSync) {
    ideResult = syncIdeProjections(rootDir, { dryRun: false });
    if (ideResult.errors.length === 0) {
      appendIdeManifestEntries(rootDir, ideResult, false);
    }
  }

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

  console.log("\n## CapInt Init\n");
  console.log(`Preset: ${preset}`);
  console.log(`Bundle: ${report.bundle || bundle}`);
  console.log(`Project: ${projectName}`);
  console.log(`Created: ${report.summary.created}, Updated: ${report.summary.updated}, Skipped: ${report.summary.skipped}, Conflicts: ${report.summary.conflict}`);
  const projectSkills = listProjectSkillNames(rootDir).length;
  const workflowCount = fs.existsSync(path.join(rootDir, "workflows"))
    ? fs.readdirSync(path.join(rootDir, "workflows")).filter((f) => f.endsWith(".md")).length
    : 0;
  const pkgSkills = listPackageSkillNames(pkgRoot()).length;
  console.log(
    `Skills: ${projectSkills} on disk${report.bundle === "minimal" ? ` (minimal stub; package has ${pkgSkills})` : ""}, ${workflowCount} workflows\n`
  );
  for (const r of report.results) {
    const extra = r.sidecar ? ` -> see ${r.sidecar}` : r.reason ? ` (${r.reason})` : "";
    console.log(`  [${r.action}] ${r.path}${extra}`);
  }
  if (ideSync && ideResult) {
    if (ideResult.errors.length) {
      console.log(`\nIDE sync skipped: ${ideResult.errors.join("; ")}`);
    } else {
      console.log(`\nIDE sync: ${ideResult.written.length} projection(s) written`);
    }
  } else if (!ideSync) {
    console.log("\nIDE sync skipped (--no-ide-sync). Run: capint ide sync");
  }
  console.log("\nNext: open GUNLUK.md — then chat your first task (no terminal needed)");
  console.log("       capint route \"i18n\"  (optional preview)");
  console.log("Conflict policy: existing files without capint managed blocks are never overwritten.\n");
};
