import { semanticDigest } from "@best-agent/foundation";
import type { ToolInputValue } from "@best-agent/protocol";
import type { ConversationMessage } from "../../provider/provider-conversation.js";
import type { CompletedProviderToolCall } from "../checkpoint-codec.js";

export function countToolErrorsSinceLastUser(messages: ConversationMessage[]): number {
  let count = 0;
  for (const message of messages) {
    if (message.role === "user") {
      count = 0;
      continue;
    }
    if (message.role === "tool" && message.outcome === "error") {
      count += 1;
    }
  }
  return count;
}

export function semanticToolInputDigest(value: ToolInputValue): string {
  return semanticDigest(value);
}

export function completedToolCallStableInputDigest(
  call: CompletedProviderToolCall,
): string | undefined {
  return call.inputStableDigest ?? call.inputDigest;
}
