import { defineCommand, useLogger } from '@kb-labs/sdk';
import { loadTrace, formatTraceLoadError } from '@kb-labs/agent-tracing';

// src/cli/commands/trace-iteration.ts

// src/cli/commands/trace-event-normalizer.ts
function normalizeTraceEvents(events) {
  const out = [];
  let currentIteration = 0;
  for (const raw of events) {
    const type = String(raw.type ?? "");
    const data = getEventData(raw);
    const explicitIteration = asNumber(raw.iteration) ?? asNumber(data.iteration);
    if (type === "iteration:start") {
      currentIteration = explicitIteration ?? Math.max(1, currentIteration + 1);
    }
    const iteration = explicitIteration ?? currentIteration;
    out.push({ raw, type, data, iteration });
  }
  return out;
}
function getEventData(event) {
  const data = event.data;
  if (data && typeof data === "object") {
    return data;
  }
  return {};
}
function asNumber(value) {
  if (typeof value === "number" && Number.isFinite(value)) {
    return value;
  }
  if (typeof value === "string") {
    const n = Number(value);
    if (Number.isFinite(n)) {
      return n;
    }
  }
  return void 0;
}

// src/cli/commands/trace-iteration.ts
var trace_iteration_default = defineCommand({
  id: "trace:iteration",
  description: "View all events for a specific iteration",
  handler: {
    async execute(ctx, input) {
      const logger = useLogger();
      const flags = input.flags ?? input;
      const taskId = flags["task-id"] ?? flags.taskId;
      const iteration = typeof flags.iteration === "string" ? parseInt(flags.iteration, 10) : flags.iteration;
      if (iteration === void 0 || iteration < 1) {
        const err = error("INVALID_ITERATION", "Missing or invalid --iteration flag (must be >= 1)");
        ctx.ui.write(JSON.stringify(err, null, 2) + "\n");
        return { exitCode: 1, response: err };
      }
      try {
        const loaded = await loadTrace(taskId);
        if (!loaded.ok) {
          const code = loaded.error.kind === "invalid_task_id" ? "INVALID_TASK_ID" : loaded.error.kind === "not_found" ? "TRACE_NOT_FOUND" : loaded.error.kind === "too_large" ? "FILE_TOO_LARGE" : "CORRUPTED_TRACE";
          const err = error(code, formatTraceLoadError(loaded.error));
          ctx.ui.write(JSON.stringify(err, null, 2) + "\n");
          return { exitCode: 1, response: err };
        }
        const normalized = normalizeTraceEvents(loaded.events);
        const filtered = normalized.filter((e) => e.iteration === iteration).map((e) => e.raw);
        if (filtered.length === 0) {
          const err = error("INVALID_ITERATION", `No events found for iteration ${iteration}`);
          ctx.ui.write(JSON.stringify(err, null, 2) + "\n");
          return { exitCode: 1, response: err };
        }
        const summary = calculateIterationSummary(filtered);
        const response = {
          success: true,
          command: "trace:iteration",
          taskId: taskId ?? "",
          data: {
            taskId: taskId ?? "",
            iteration,
            events: filtered,
            summary
          },
          summary: {
            message: `Iteration ${iteration}: ${summary.eventCount} events, ${summary.llmCalls} LLM calls, ${summary.toolCalls} tool calls`,
            severity: summary.errors > 0 ? "warning" : "info",
            actionable: summary.errors > 0
          }
        };
        if (flags.json) {
          ctx.ui.write(JSON.stringify(response, null, 2) + "\n");
        } else {
          printHumanReadable(ctx, iteration, filtered, summary);
        }
        return { exitCode: 0, response };
      } catch (err) {
        logger.error("trace:iteration error:", err instanceof Error ? err : void 0);
        const errResponse = error("IO_ERROR", err instanceof Error ? err.message : String(err));
        ctx.ui.write(JSON.stringify(errResponse, null, 2) + "\n");
        return { exitCode: 1, response: errResponse };
      }
    }
  }
});
function calculateIterationSummary(events) {
  const llmEvents = events.filter((e) => {
    const type = String(e.type ?? "");
    return type === "llm:start" || type === "llm:call" || type === "llm_call";
  });
  const toolEvents = events.filter((e) => {
    const type = String(e.type ?? "");
    return type === "tool:start" || type === "tool:execution" || type === "tool_call";
  });
  const errorEvents = events.filter((e) => {
    const type = String(e.type ?? "");
    return type === "error:captured" || type === "agent:error" || type === "tool:error";
  });
  const timestamps = events.map((e) => new Date(e.timestamp).getTime());
  const durationMs = timestamps.length > 0 ? Math.max(...timestamps) - Math.min(...timestamps) : 0;
  return {
    eventCount: events.length,
    llmCalls: llmEvents.length,
    toolCalls: toolEvents.length,
    errors: errorEvents.length,
    durationMs
  };
}
function printHumanReadable(ctx, iteration, events, summary) {
  ctx.ui.write("\n");
  ctx.ui.write(`\u{1F504} Iteration ${iteration}
`);
  ctx.ui.write("\n");
  ctx.ui.write("\u{1F4CA} Summary:\n");
  ctx.ui.write(`  Total events: ${summary.eventCount}
`);
  ctx.ui.write(`  LLM calls: ${summary.llmCalls}
`);
  ctx.ui.write(`  Tool calls: ${summary.toolCalls}
`);
  ctx.ui.write(`  Errors: ${summary.errors}
`);
  ctx.ui.write(`  Duration: ${summary.durationMs}ms
`);
  ctx.ui.write("\n");
  ctx.ui.write("\u{1F4DD} Events Timeline:\n");
  ctx.ui.write("\n");
  const grouped = /* @__PURE__ */ new Map();
  for (const event of events) {
    const existing = grouped.get(event.type) || [];
    existing.push(event);
    grouped.set(event.type, existing);
  }
  for (const [type, typeEvents] of grouped) {
    ctx.ui.write(`  ${type}: ${typeEvents.length}
`);
    if ((type === "llm:end" || type === "llm:call") && typeEvents.length > 0) {
      const llmEvent = typeEvents[0];
      const tokens = llmEvent?.data?.tokensUsed ?? llmEvent?.response?.usage?.totalTokens ?? 0;
      ctx.ui.write(`    Tokens: ${tokens}
`);
    } else if (type === "tool:end" || type === "tool:start" || type === "tool:execution") {
      const toolNames = typeEvents.map((e) => e?.data?.toolName || e?.tool?.name || "unknown");
      ctx.ui.write(`    Tools: ${[...new Set(toolNames)].join(", ")}
`);
    } else if (type === "error:captured" && typeEvents.length > 0) {
      const errorEvent = typeEvents[0];
      ctx.ui.write(`    \u26A0\uFE0F  ${errorEvent.error.message.substring(0, 100)}
`);
    }
  }
  ctx.ui.write("\n");
  ctx.ui.write("Use --json flag to see full event details\n");
}
function error(code, message) {
  return {
    success: false,
    command: "trace:iteration",
    taskId: "",
    error: {
      code,
      message
    },
    summary: {
      message,
      severity: "error",
      actionable: true
    }
  };
}

export { trace_iteration_default as default };
//# sourceMappingURL=trace-iteration.js.map
//# sourceMappingURL=trace-iteration.js.map