import { defineCommand, useLogger } from '@kb-labs/sdk';
import { ChangeStore } from '@kb-labs/agent-history';
import { promises } from 'fs';
import path from 'path';

// src/cli/commands/rollback.ts
var rollback_default = defineCommand({
  id: "rollback",
  description: "Rollback file changes made by agents in a session or run",
  handler: {
    async execute(ctx, input) {
      const logger = useLogger();
      const flags = input.flags ?? input;
      const sessionId = flags["session-id"] ?? flags["sessionId"];
      const runId = flags["run-id"] ?? flags["runId"];
      const filePath = flags["file"];
      const dryRun = Boolean(flags["dry-run"] ?? flags["dryRun"]);
      const asJson = Boolean(flags["json"]);
      if (!sessionId) {
        return output(ctx, asJson, { success: false, error: "Missing --session-id" }, 1);
      }
      const workingDir = process.cwd();
      const store = new ChangeStore(workingDir);
      try {
        let changes;
        if (runId && !filePath) {
          changes = await store.listRun(sessionId, runId);
        } else if (filePath) {
          changes = await store.listFile(sessionId, filePath);
          if (runId) {
            changes = changes.filter((c) => c.runId === runId);
          }
        } else {
          changes = await store.listSession(sessionId);
        }
        if (changes.length === 0) {
          return output(ctx, asJson, { success: true, rolledBack: 0, message: "No changes to rollback" }, 0);
        }
        const ordered = [...changes].sort(
          (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
        );
        if (dryRun) {
          const preview = ordered.map((c) => ({
            filePath: c.filePath,
            operation: c.operation,
            action: !c.before ? "delete (was new file)" : "restore to before state"
          }));
          return output(ctx, asJson, { success: true, dryRun: true, wouldRollback: preview }, 0);
        }
        let rolledBack = 0;
        const errors = [];
        for (const change of ordered) {
          const fullPath = path.join(workingDir, change.filePath);
          try {
            if (!change.before) {
              await promises.unlink(fullPath).catch((e) => {
                if (e.code !== "ENOENT") {
                  throw e;
                }
              });
            } else {
              await promises.mkdir(path.dirname(fullPath), { recursive: true });
              await promises.writeFile(fullPath, change.before.content, "utf-8");
            }
            rolledBack++;
          } catch (e) {
            errors.push(`${change.filePath}: ${String(e)}`);
          }
        }
        return output(ctx, asJson, { success: errors.length === 0, rolledBack, errors }, errors.length > 0 ? 1 : 0);
      } catch (e) {
        logger.error("agent:rollback error", e instanceof Error ? e : void 0);
        return output(ctx, asJson, { success: false, error: String(e) }, 1);
      }
    }
  }
});
function output(ctx, asJson, data, exitCode) {
  if (asJson) {
    ctx.ui.write(JSON.stringify(data, null, 2) + "\n");
  } else {
    const d = data;
    if (d["success"]) {
      if (d["dryRun"]) {
        ctx.ui.write(`[DRY RUN] Would rollback:
`);
        for (const p of d["wouldRollback"] ?? []) {
          ctx.ui.write(`  ${p["operation"]?.toUpperCase()} ${p["filePath"]} \u2192 ${p["action"]}
`);
        }
      } else {
        ctx.ui.write(`\u2705 Rolled back ${d["rolledBack"]} change(s)
`);
        for (const e of d["errors"] ?? []) {
          ctx.ui.write(`  \u26A0\uFE0F  ${e}
`);
        }
      }
    } else {
      ctx.ui.write(`\u274C ${d["error"]}
`);
    }
  }
  return { exitCode };
}

export { rollback_default as default };
//# sourceMappingURL=rollback.js.map
//# sourceMappingURL=rollback.js.map