module.exports = async function recover(args, flags) {
  const rootDir = process.cwd();
  const { listBackups, planRecover, applyRecover } = require("../lib/recover");

  const apply = Boolean(flags.apply);
  const latest = Boolean(flags.latest);

  if (flags.list || (!apply && !latest && !flags.stamp)) {
    const { groups, backups } = listBackups(rootDir);
    if (flags.json) {
      console.log(JSON.stringify({ groups, backups }, null, 2));
      return;
    }
    console.log("\n## CapInt backups\n");
    if (!groups.length) {
      console.log("No backups found. Run: capint upgrade --apply");
      console.log("");
      return;
    }
    for (const g of groups) {
      const when = new Date(g.mtime).toISOString();
      console.log(`  ${g.stamp}  (${when})`);
      for (const f of g.files) console.log(`    → ${f.target}  ←  ${f.file}`);
    }
    console.log("\nRestore latest (dry-run): capint recover --latest");
    console.log("Restore latest (apply):    capint recover --latest --apply\n");
    return;
  }

  const plan = planRecover(rootDir, { stamp: flags.stamp, latest: latest || Boolean(flags.stamp) });
  if (plan.error) {
    console.error(plan.error);
    if (plan.groups?.length && !flags.json) {
      console.error("Available stamps:");
      for (const g of plan.groups.slice(0, 5)) console.error(`  ${g.stamp}`);
    }
    process.exit(1);
  }

  if (!apply) {
    if (flags.json) {
      console.log(JSON.stringify({ dry_run: true, ...plan }, null, 2));
      return;
    }
    console.log("\n## Recover (dry-run)\n");
    console.log(`Stamp: ${plan.stamp}`);
    for (const a of plan.actions) {
      console.log(`  would restore ${a.target}`);
    }
    console.log("\nApply: capint recover --latest --apply\n");
    return;
  }

  const result = applyRecover(rootDir, plan);
  if (flags.json) {
    console.log(JSON.stringify(result, null, 2));
    return;
  }
  console.log("\n## Recover applied\n");
  console.log(`Stamp: ${result.stamp}`);
  console.log(`Restored: ${result.restored.join(", ") || "(none)"}\n`);
};
