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

// src/cli/commands/trace-filter.ts
var VALID_EVENT_TYPES = [
  // New format (detailed trace)
  "iteration:detail",
  "llm:call",
  "tool:execution",
  "memory:snapshot",
  "decision:point",
  "synthesis:forced",
  "error:captured",
  "prompt:diff",
  "tool:filter",
  "context:trim",
  "stopping:analysis",
  "llm:validation",
  // Legacy format (simple trace)
  "llm_call",
  "llm_response",
  "tool_call",
  "tool_result",
  "tool_cache_hit",
  "task_start",
  "task_end"
];
var trace_filter_default = defineCommand({
  id: "trace:filter",
  description: "Filter trace events by type for debugging",
  handler: {
    async execute(ctx, input) {
      const logger = useLogger();
      const flags = input.flags ?? input;
      const taskId = flags["task-id"] ?? flags.taskId;
      const eventType = flags.type;
      if (!eventType) {
        const err = error("INVALID_EVENT_TYPE", "Missing required --type flag");
        ctx.ui.write(JSON.stringify(err, null, 2) + "\n");
        return { exitCode: 1, response: err };
      }
      if (!VALID_EVENT_TYPES.includes(eventType)) {
        const err = error(
          "INVALID_EVENT_TYPE",
          `Invalid event type: ${eventType}. Valid types: ${VALID_EVENT_TYPES.join(", ")}`
        );
        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 { events } = loaded;
        const filtered = events.filter((e) => e.type === eventType);
        const response = {
          success: true,
          command: "trace:filter",
          taskId: taskId ?? "",
          data: {
            taskId: taskId ?? "",
            eventType,
            events: filtered,
            count: filtered.length
          },
          summary: {
            message: `Found ${filtered.length} ${eventType} events`,
            severity: "info",
            actionable: false
          }
        };
        if (flags.json) {
          ctx.ui.write(JSON.stringify(response, null, 2) + "\n");
        } else {
          printHumanReadable(ctx, eventType, filtered);
        }
        return { exitCode: 0, response };
      } catch (err) {
        logger.error("trace:filter 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 printHumanReadable(ctx, eventType, events) {
  ctx.ui.write("\n");
  ctx.ui.write(`\u{1F50D} Filtered Events: ${eventType}
`);
  ctx.ui.write(`Found ${events.length} events
`);
  ctx.ui.write("\n");
  if (events.length === 0) {
    ctx.ui.write("No events found.\n");
    return;
  }
  const showCount = Math.min(10, events.length);
  ctx.ui.write(`Showing first ${showCount}/${events.length}:
`);
  ctx.ui.write("\n");
  for (let i = 0; i < showCount; i++) {
    const event = events[i];
    if (!event) {
      continue;
    }
    ctx.ui.write(`[${event.seq}] ${event.timestamp} (iteration ${event.iteration || "N/A"})
`);
    if (event.type === "llm:call") {
      const e = event;
      ctx.ui.write(`  Model: ${e.request.model}, Tokens: ${e.response.usage.totalTokens}, Cost: $${e.cost.totalCost.toFixed(6)}
`);
    } else if (event.type === "tool:execution") {
      const e = event;
      ctx.ui.write(`  Tool: ${e.tool.name}, Success: ${e.output.success}, Duration: ${e.timing.durationMs}ms
`);
    } else if (event.type === "error:captured") {
      const e = event;
      ctx.ui.write(`  Error: ${e.error.message.substring(0, 100)}
`);
    }
    ctx.ui.write("\n");
  }
  if (events.length > showCount) {
    ctx.ui.write(`... and ${events.length - showCount} more events
`);
    ctx.ui.write("Use --json flag to see all events\n");
  }
}
function error(code, message) {
  return {
    success: false,
    command: "trace:filter",
    taskId: "",
    error: {
      code,
      message
    },
    summary: {
      message,
      severity: "error",
      actionable: true
    }
  };
}

export { trace_filter_default as default };
//# sourceMappingURL=trace-filter.js.map
//# sourceMappingURL=trace-filter.js.map