import { defineHandler } from '@kb-labs/sdk';
import { SessionManager } from '@kb-labs/agent-core';
import { ChangeStore } from '@kb-labs/agent-history';
import { promises } from 'fs';
import path from 'path';

// src/rest/handlers/rollback-handler.ts
var rollback_handler_default = defineHandler({
  async execute(ctx, input) {
    const params = input.params;
    const sessionId = params?.sessionId;
    if (!sessionId) {
      throw new Error("Session ID is required");
    }
    const body = input.body ?? {};
    const sessionManager = new SessionManager(ctx.cwd);
    const session = await sessionManager.loadSession(sessionId);
    if (!session) {
      throw new Error(`Session not found: ${sessionId}`);
    }
    const workingDir = session.workingDir || ctx.cwd;
    const store = new ChangeStore(workingDir);
    let changes;
    if (body.runId) {
      changes = await store.listRun(sessionId, body.runId);
    } else if (body.changeIds?.length) {
      const ids = new Set(body.changeIds);
      const all = await store.listSession(sessionId);
      changes = all.filter((c) => ids.has(c.id));
    } else {
      changes = await store.listSession(sessionId);
    }
    if (changes.length === 0) {
      return { rolledBack: 0, skipped: 0, conflicts: [], success: true };
    }
    const sorted = [...changes].sort(
      (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
    );
    const fullHistory = await store.listSession(sessionId);
    const rollbackIds = new Set(sorted.map((c) => c.id));
    const conflicts = [];
    let rolledBack = 0;
    let skipped = 0;
    for (const change of sorted) {
      if (!body.skipConflicts) {
        const laterChanges = fullHistory.filter(
          (c) => c.filePath === change.filePath && new Date(c.timestamp).getTime() > new Date(change.timestamp).getTime() && !rollbackIds.has(c.id)
        );
        if (laterChanges.length > 0) {
          const laterAgents = [...new Set(laterChanges.map((c) => c.agentId))].join(", ");
          conflicts.push({
            filePath: change.filePath,
            changeId: change.id,
            reason: `File was modified after this change by: ${laterAgents}. Use skipConflicts: true to force.`
          });
          skipped++;
          continue;
        }
      }
      const fullPath = path.join(workingDir, change.filePath);
      try {
        if (change.before) {
          await promises.mkdir(path.dirname(fullPath), { recursive: true });
          await promises.writeFile(fullPath, change.before.content, "utf-8");
        } else {
          await promises.unlink(fullPath).catch((e) => {
            if (e.code !== "ENOENT") {
              throw e;
            }
          });
        }
        rolledBack++;
      } catch (e) {
        conflicts.push({
          filePath: change.filePath,
          changeId: change.id,
          reason: `Write failed: ${e instanceof Error ? e.message : String(e)}`
        });
        skipped++;
      }
    }
    ctx.platform.logger.info(
      `[rollback-handler] Session ${sessionId}: rolled back ${rolledBack}, skipped ${skipped}`
    );
    return { rolledBack, skipped, conflicts, success: skipped === 0 };
  }
});

export { rollback_handler_default as default };
//# sourceMappingURL=rollback-handler.js.map
//# sourceMappingURL=rollback-handler.js.map