import type { ContentPart, Message } from '../../llm/openai-compat.js';
import { logger } from '../../logger.js';
import { IMAGE_CONTENT_TOKENS } from '../context/token-estimate.js';
import type { DispatchedImage } from './tool-dispatcher.js';

const MAX_IMAGE_CONTEXT_TOKENS = 8_000;

export const injectPendingImages = (opts: {
  pendingImages: DispatchedImage[];
  messages: Message[];
  availableTokens: number;
}): void => {
  const { pendingImages, messages, availableTokens } = opts;
  if (pendingImages.length === 0) return;

  const imageTokens = pendingImages.length * IMAGE_CONTENT_TOKENS;
  const imageBudget = Math.min(MAX_IMAGE_CONTEXT_TOKENS, Math.floor(availableTokens * 0.25));
  if (imageTokens > imageBudget) {
    const labels = pendingImages.map(i => i.label ?? 'image').join(', ');
    messages.push({
      role: 'user',
      content: `[Image omitted from LLM context: ${labels}. Estimated image context cost ${imageTokens.toLocaleString()} tokens exceeds image budget ${imageBudget.toLocaleString()} tokens. Use ReadImage on a smaller/cropped image if visual inspection is required.]`,
    });
    logger.warn(`[agent-loop] omitted ${pendingImages.length} image(s) from context: estimated=${imageTokens} budget=${imageBudget}`);
    return;
  }

  const parts: ContentPart[] = [
    { type: 'text', text: pendingImages.map(i => `[Image: ${i.label ?? 'image'}]`).join('\n') },
    ...pendingImages.map(i => ({ type: 'image_url' as const, image_url: { url: i.dataUrl } })),
  ];
  messages.push({ role: 'user', content: parts });
  logger.info(`[agent-loop] injected ${pendingImages.length} image(s) into context`);
};
