import type { Message } from '../../llm/openai-compat.js';
import { toolResultMessage } from '../../llm/openai-compat.js';
import type { AgentLoopCallbacks } from './types.js';
import type { ToolCallResult } from './tool-execution.js';
import type { DispatchedImage } from './tool-dispatcher.js';

// Records a single tool result: fires callbacks, pushes the tool-result message,
// and collects any images — preserving the exact order of side effects.
// Returns the updated `regularToolsUsed` count.
export const recordToolResult = (
  toolName: string,
  result: ToolCallResult,
  messages: Message[],
  callbacks: AgentLoopCallbacks | undefined,
  pendingImages: DispatchedImage[],
  regularToolsUsed: number,
): number => {
  const isError = result.result.startsWith('Error: ');
  callbacks?.onToolResult?.(toolName, {
    isError,
    result: result.result,
    durationMs: result.durationMs ?? 0,
    cacheHit: result.cacheHit ?? false,
  }, result.toolCallId);
  let updated = regularToolsUsed;
  if (result.countedAsRegularToolUse) {
    updated++;
    callbacks?.onMemoryCheckpoint?.(updated);
  }
  messages.push(toolResultMessage(result.toolCallId, result.result));
  if (result.images) pendingImages.push(...result.images);
  return updated;
};
