import {
  AnthropicRequestSchema,
  AnthropicResponseSchema,
} from "../../../proxy/formats/anthropic/schemas";
import type { LogFormatAdapter } from "./types";
import { emptyRequestAnalysis, EMPTY_RESPONSE_ANALYSIS } from "./types";

export const anthropicLogFormatAdapter: LogFormatAdapter = {
  format: "anthropic",

  analyzeRequest(rawBody) {
    if (rawBody === null) return emptyRequestAnalysis(rawBody);
    try {
      const result = AnthropicRequestSchema.safeParse(JSON.parse(rawBody));
      if (!result.success) return emptyRequestAnalysis(rawBody);
      return {
        parsed: result.data,
        comparisonValue: result.data,
        messageCount: result.data.messages.length,
        toolCount:
          result.data.tools !== undefined && result.data.tools.length > 0
            ? result.data.tools.length
            : null,
      };
    } catch {
      return emptyRequestAnalysis(rawBody);
    }
  },

  analyzeResponse(responseText) {
    if (responseText === null) return EMPTY_RESPONSE_ANALYSIS;
    try {
      let json: unknown = JSON.parse(responseText);
      if (typeof json === "string") json = JSON.parse(json);
      const result = AnthropicResponseSchema.safeParse(json);
      if (!result.success) return EMPTY_RESPONSE_ANALYSIS;
      const toolNames = result.data.content
        .filter((block) => block.type === "tool_use")
        .map((block) => block.name);
      return {
        parsed: result.data,
        toolNames: toolNames.length > 0 ? toolNames : null,
      };
    } catch {
      return EMPTY_RESPONSE_ANALYSIS;
    }
  },
};
