const path = require("path");
const {
  syncIdeProjections,
  checkIdeProjection,
  appendIdeManifestEntries,
  DEFAULT_TARGETS,
  CAPINT_SYNC_MARKER
} = require("../lib/ide-sync");

module.exports = async function ide(args, flags) {
  const sub = args[0];
  const rootDir = process.cwd();
  const dryRun = Boolean(flags["dry-run"]);

  if (sub === "check") {
    const checks = checkIdeProjection(rootDir);
    if (flags.json) {
      console.log(JSON.stringify({ marker: CAPINT_SYNC_MARKER, checks }, null, 2));
      return;
    }
    console.log("\n## CapInt IDE check\n");
    for (const c of checks) {
      console.log(`  ${c.ok ? "✓" : "✗"} ${c.name} (${c.path})`);
    }
    console.log("");
    return;
  }

  if (sub !== "sync") {
    console.error("Usage: capint ide sync|check [--dry-run] [--json] [--targets cursor,claude,...]");
    process.exit(1);
  }

  const targets = flags.targets
    ? flags.targets.split(",").map((t) => t.trim())
    : DEFAULT_TARGETS;

  const result = syncIdeProjections(rootDir, { targets, dryRun });
  if (result.errors.length) {
    console.error(result.errors.join("; "));
    process.exit(1);
  }

  if (!dryRun) {
    appendIdeManifestEntries(rootDir, result, dryRun);
  }

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

  console.log("\n## CapInt IDE sync\n");
  if (dryRun) console.log("(dry-run — no files written)\n");
  for (const w of result.written) {
    console.log(`  wrote ${path.relative(rootDir, w) || w}`);
  }
  for (const s of result.skipped) {
    console.log(`  skipped: ${s}`);
  }
  console.log("");
};
