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

// src/cli/commands/diff.ts
var diff_default = defineCommand({
  id: "diff",
  description: "Show diff for specific file change",
  handler: {
    async execute(ctx, input) {
      const logger = useLogger();
      const flags = input.flags ?? input;
      const changeId = flags["change-id"] ?? flags.changeId;
      if (!changeId) {
        const err = { success: false, error: "Missing required --change-id flag" };
        ctx.ui.write(JSON.stringify(err, null, 2) + "\n");
        return { exitCode: 1, response: err };
      }
      try {
        const basePath = path.join(process.cwd(), ".kb", "agents", "sessions");
        const sessions = await promises.readdir(basePath);
        let snapshot = null;
        let foundSessionId = null;
        for (const sessionId of sessions) {
          const snapshotPath = path.join(basePath, sessionId, "snapshots", `${changeId}.json`);
          try {
            const content = await promises.readFile(snapshotPath, "utf-8");
            snapshot = JSON.parse(content);
            foundSessionId = sessionId;
            break;
          } catch {
            continue;
          }
        }
        if (!snapshot) {
          const err = { success: false, error: `Change not found: ${changeId}` };
          ctx.ui.write(JSON.stringify(err, null, 2) + "\n");
          return { exitCode: 1, response: err };
        }
        const diff = calculateDiff(snapshot);
        const response = {
          success: true,
          changeId,
          sessionId: foundSessionId,
          data: {
            ...snapshot,
            diff
          }
        };
        if (flags.json) {
          ctx.ui.write(JSON.stringify(response, null, 2) + "\n");
        } else {
          printDiff(ctx, snapshot, diff);
        }
        return { exitCode: 0, response };
      } catch (err) {
        logger.error("agent:diff error:", err instanceof Error ? err : void 0);
        const errResponse = {
          success: false,
          error: err instanceof Error ? err.message : String(err)
        };
        ctx.ui.write(JSON.stringify(errResponse, null, 2) + "\n");
        return { exitCode: 1, response: errResponse };
      }
    }
  }
});
function calculateDiff(snapshot) {
  const beforeContent = snapshot.before?.content || "";
  const afterContent = snapshot.after?.content || "";
  const beforeLines = beforeContent.split("\n");
  const afterLines = afterContent.split("\n");
  const diff = {
    additions: 0,
    deletions: 0,
    changes: []
  };
  const maxLines = Math.max(beforeLines.length, afterLines.length);
  for (let i = 0; i < maxLines; i++) {
    const before = beforeLines[i];
    const after = afterLines[i];
    if (before === void 0 && after !== void 0) {
      diff.additions++;
      diff.changes.push({
        type: "add",
        line: i + 1,
        content: after
      });
    } else if (before !== void 0 && after === void 0) {
      diff.deletions++;
      diff.changes.push({
        type: "delete",
        line: i + 1,
        content: before
      });
    } else if (before !== after) {
      diff.deletions++;
      diff.additions++;
      diff.changes.push({
        type: "change",
        line: i + 1,
        before,
        after
      });
    }
  }
  return diff;
}
function printDiff(ctx, snapshot, diff) {
  ctx.ui.write("\n");
  ctx.ui.write("\u{1F4DD} File Change Diff\n");
  ctx.ui.write("\n");
  const timestamp = new Date(snapshot.timestamp).toLocaleString();
  const operation = snapshot.operation.toUpperCase();
  ctx.ui.write(`Change ID: ${snapshot.id}
`);
  ctx.ui.write(`File: ${snapshot.filePath}
`);
  ctx.ui.write(`Operation: ${operation}
`);
  ctx.ui.write(`Agent: ${snapshot.agentId}
`);
  ctx.ui.write(`Timestamp: ${timestamp}
`);
  ctx.ui.write("\n");
  if (snapshot.metadata) {
    if (snapshot.metadata.startLine !== void 0) {
      ctx.ui.write(
        `Patch: lines ${snapshot.metadata.startLine}-${snapshot.metadata.endLine}
`
      );
    }
    if (snapshot.metadata.linesAdded !== void 0) {
      ctx.ui.write(
        `Changes: +${snapshot.metadata.linesAdded} -${snapshot.metadata.linesRemoved}
`
      );
    }
    if (snapshot.metadata.isOverwrite) {
      ctx.ui.write("Overwrote existing file\n");
    }
    ctx.ui.write("\n");
  }
  ctx.ui.write(`Summary: +${diff.additions} -${diff.deletions}
`);
  ctx.ui.write("\n");
  ctx.ui.write("\u2500".repeat(60) + "\n");
  if (snapshot.operation === "write" && !snapshot.before) {
    ctx.ui.write("New file created:\n");
    ctx.ui.write("\n");
    const lines = snapshot.after.content.split("\n");
    for (let i = 0; i < Math.min(lines.length, 50); i++) {
      ctx.ui.write(`+ ${(i + 1).toString().padStart(4)} | ${lines[i]}
`);
    }
    if (lines.length > 50) {
      ctx.ui.write(`... (${lines.length - 50} more lines)
`);
    }
  } else {
    for (const change of diff.changes) {
      if (change.type === "add") {
        ctx.ui.write(`+ ${change.line.toString().padStart(4)} | ${change.content}
`);
      } else if (change.type === "delete") {
        ctx.ui.write(`- ${change.line.toString().padStart(4)} | ${change.content}
`);
      } else if (change.type === "change") {
        ctx.ui.write(`- ${change.line.toString().padStart(4)} | ${change.before}
`);
        ctx.ui.write(`+ ${change.line.toString().padStart(4)} | ${change.after}
`);
      }
    }
  }
  ctx.ui.write("\u2500".repeat(60) + "\n");
  ctx.ui.write("\n");
}

export { diff_default as default };
//# sourceMappingURL=diff.js.map
//# sourceMappingURL=diff.js.map