import { defineCommand } from '@kb-labs/sdk';
import { SessionManager } from '@kb-labs/agent-core';

// src/cli/commands/history.ts
var history_default = defineCommand({
  id: "history",
  description: "Show file change history for agent sessions",
  handler: {
    async execute(ctx, input) {
      const flags = "flags" in input && typeof input.flags === "object" && input.flags !== null ? input.flags : input;
      const manager = new SessionManager(process.cwd());
      try {
        const sessionId = flags["session-id"] ?? flags.sessionId;
        const agentId = flags["agent-id"] ?? flags.agentId;
        if (sessionId) {
          return showSessionHistory(ctx, manager, String(sessionId), Boolean(flags.json));
        }
        if (flags.file) {
          return showFileHistory(ctx, manager, String(flags.file), Boolean(flags.json));
        }
        if (agentId) {
          return showAgentHistory(ctx, manager, String(agentId), Boolean(flags.json));
        }
        return listAllSessions(ctx, manager, Boolean(flags.json));
      } catch (error) {
        const response = {
          success: false,
          error: error instanceof Error ? error.message : String(error)
        };
        ctx.ui.write(JSON.stringify(response, null, 2) + "\n");
        return { exitCode: 1, response };
      }
    }
  }
});
async function showSessionHistory(ctx, manager, sessionId, asJson) {
  const info = await manager.getSessionInfo(sessionId);
  if (!info) {
    const err = { success: false, error: `Session not found: ${sessionId}` };
    ctx.ui.write(JSON.stringify(err, null, 2) + "\n");
    return { exitCode: 1, response: err };
  }
  const turns = await manager.getTurns(sessionId);
  const changes = collectChanges(sessionId, turns);
  changes.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
  const response = {
    success: true,
    sessionId,
    runCount: info.runCount,
    changes: changes.length,
    data: changes
  };
  if (asJson) {
    ctx.ui.write(JSON.stringify(response, null, 2) + "\n");
  } else {
    ctx.ui.write(`Session: ${sessionId}
`);
    ctx.ui.write(`Runs: ${info.runCount} | Changes: ${changes.length}

`);
    for (const c of changes) {
      const ts = new Date(c.timestamp).toLocaleString();
      ctx.ui.write(`[${ts}] ${c.operation.toUpperCase()} ${c.filePath}
`);
      ctx.ui.write(`  Agent: ${c.agentId} | Turn: #${c.turnSequence}
`);
      ctx.ui.write(`  Change ID: ${c.changeId}

`);
    }
  }
  return { exitCode: 0, response };
}
async function showFileHistory(ctx, manager, filePath, asJson) {
  const sessions = await manager.listSessions({ limit: 1e3, offset: 0 });
  const allChanges = [];
  for (const s of sessions.sessions) {
    const turns = await manager.getTurns(s.id);
    const changes = collectChanges(s.id, turns).filter((c) => c.filePath === filePath);
    allChanges.push(...changes);
  }
  allChanges.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
  const response = {
    success: true,
    filePath,
    changes: allChanges.length,
    data: allChanges
  };
  if (asJson) {
    ctx.ui.write(JSON.stringify(response, null, 2) + "\n");
  } else {
    ctx.ui.write(`File: ${filePath}
`);
    ctx.ui.write(`Changes: ${allChanges.length}

`);
    for (const c of allChanges) {
      const ts = new Date(c.timestamp).toLocaleString();
      ctx.ui.write(`[${ts}] ${c.operation.toUpperCase()} (${c.sessionId})
`);
      ctx.ui.write(`  Agent: ${c.agentId} | Change ID: ${c.changeId}

`);
    }
  }
  return { exitCode: 0, response };
}
async function showAgentHistory(ctx, manager, agentId, asJson) {
  const sessions = await manager.listSessions({ limit: 1e3, offset: 0 });
  const allChanges = [];
  for (const s of sessions.sessions) {
    const turns = await manager.getTurns(s.id);
    const changes = collectChanges(s.id, turns).filter((c) => c.agentId === agentId);
    allChanges.push(...changes);
  }
  allChanges.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
  const response = {
    success: true,
    agentId,
    changes: allChanges.length,
    data: allChanges
  };
  if (asJson) {
    ctx.ui.write(JSON.stringify(response, null, 2) + "\n");
  } else {
    ctx.ui.write(`Agent: ${agentId}
`);
    ctx.ui.write(`Changes: ${allChanges.length}

`);
    for (const c of allChanges) {
      const ts = new Date(c.timestamp).toLocaleString();
      ctx.ui.write(`[${ts}] ${c.operation.toUpperCase()} ${c.filePath} (${c.sessionId})
`);
    }
    ctx.ui.write("\n");
  }
  return { exitCode: 0, response };
}
async function listAllSessions(ctx, manager, asJson) {
  const sessions = await manager.listSessions({ limit: 1e3, offset: 0 });
  const uniqueSessions = dedupeSessionsById(sessions.sessions);
  const data = await Promise.all(
    uniqueSessions.map(async (s) => {
      const turns = await manager.getTurns(s.id);
      return {
        sessionId: s.id,
        status: s.status,
        runCount: s.runCount,
        lastActivityAt: s.lastActivityAt,
        changes: collectChanges(s.id, turns).length
      };
    })
  );
  const response = {
    success: true,
    sessions: data.length,
    data
  };
  if (asJson) {
    ctx.ui.write(JSON.stringify(response, null, 2) + "\n");
  } else {
    ctx.ui.write(`Sessions: ${data.length}

`);
    for (const s of data) {
      ctx.ui.write(`${s.sessionId}
`);
      ctx.ui.write(`  Runs: ${s.runCount} | Changes: ${s.changes} | Status: ${s.status}
`);
      ctx.ui.write(`  Last activity: ${new Date(s.lastActivityAt).toLocaleString()}

`);
    }
  }
  return { exitCode: 0, response };
}
function dedupeSessionsById(sessions) {
  const byId = /* @__PURE__ */ new Map();
  for (const session of sessions) {
    const existing = byId.get(session.id);
    if (!existing) {
      byId.set(session.id, session);
      continue;
    }
    const existingTs = Date.parse(existing.lastActivityAt);
    const incomingTs = Date.parse(session.lastActivityAt);
    if (incomingTs > existingTs || incomingTs === existingTs && session.runCount > existing.runCount) {
      byId.set(session.id, session);
    }
  }
  return Array.from(byId.values()).sort((a, b) => Date.parse(b.lastActivityAt) - Date.parse(a.lastActivityAt));
}
function collectChanges(sessionId, turns) {
  const rows = [];
  for (const turn of turns) {
    if (turn.type !== "assistant") {
      continue;
    }
    const changes = turn.metadata.fileChanges ?? [];
    for (const change of changes) {
      rows.push({
        ...change,
        sessionId,
        turnId: turn.id,
        turnSequence: turn.sequence,
        agentId: turn.metadata.agentId
      });
    }
  }
  return rows;
}

export { history_default as default };
//# sourceMappingURL=history.js.map
//# sourceMappingURL=history.js.map