import { semanticDigest } from "@best-agent/foundation";
import type { PhaseResultPhaseName, SessionUsageOperation } from "@best-agent/protocol";
import type { ConversationMessage, ProviderToolOption } from "../../provider/model-provider.js";
import type { ProviderCorrectionTrace } from "../checkpoint-codec.js";

export function computeRequestDigest(input: {
  messages: ConversationMessage[];
  phaseResultPhaseName?: PhaseResultPhaseName;
  systemPrompt?: string;
  tools?: ProviderToolOption[];
}): string {
  return semanticDigest({
    messages: input.messages.map((message) => ({
      role: message.role,
      content: message.content,
      toolName: "toolName" in message ? message.toolName : undefined,
      toolCallId: "toolCallId" in message ? message.toolCallId : undefined,
      toolCalls: "toolCalls" in message ? message.toolCalls : undefined,
      outcome: "outcome" in message ? message.outcome : undefined,
    })),
    systemPrompt: input.systemPrompt ?? "",
    tools:
      input.tools?.map((tool) => ({
        name: tool.name,
        inputSchema: tool.inputSchema,
      })) ?? [],
    phaseResultPhaseName: input.phaseResultPhaseName,
  }).slice(0, 16);
}

export function createStableCorrectionTraceId(input: {
  code: ProviderCorrectionTrace["code"];
  operation: SessionUsageOperation;
  requestDigest: string;
}): string {
  return semanticDigest({
    code: input.code,
    operation: input.operation,
    requestDigest: input.requestDigest,
    type: "provider-correction-trace",
  }).slice(0, 16);
}
