import { OpenAIRequestSchema, parseOpenAIResponse } from "../../../proxy/formats/openai/schemas";
import type { LogFormatAdapter } from "./types";
import { emptyRequestAnalysis, EMPTY_RESPONSE_ANALYSIS } from "./types";

export const openAILogFormatAdapter: LogFormatAdapter = {
  format: "openai",

  analyzeRequest(rawBody) {
    if (rawBody === null) return emptyRequestAnalysis(rawBody);
    try {
      const result = OpenAIRequestSchema.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;
    const parsed = parseOpenAIResponse(responseText);
    if (parsed === null) return EMPTY_RESPONSE_ANALYSIS;
    const toolNames =
      parsed.choices[0]?.message?.tool_calls
        ?.map((toolCall) => toolCall.function?.name ?? "")
        .filter((name) => name !== "") ?? [];
    return {
      parsed,
      toolNames: toolNames.length > 0 ? toolNames : null,
    };
  },
};
