import { imageResult, imagesResult } from '../common.js';
import type { ImageGenerationResult } from '../../image_providers/types.js';
import type { ImageStorageService } from '../../service/image_storage.js';

export function clampDimension(value: number | undefined, max: number): number | undefined {
  if (value === undefined) return undefined;
  return Math.min(value, max);
}

export async function persistImages(result: ImageGenerationResult, storage: ImageStorageService): Promise<ImageGenerationResult> {
  const persisted = await Promise.all(
    result.images.map(async img => {
      if (!img.url) return img;
      const permanentUrl = await storage.persist(img.url);
      return { ...img, url: permanentUrl };
    })
  );
  return { ...result, images: persisted };
}

export function formatImageToolResult(result: ImageGenerationResult) {
  if (result.images.length === 1) {
    const img = result.images[0];
    return imageResult(img.url!, undefined, {
      width: img.width,
      height: img.height,
      text: `图片已生成并自动展示给用户（无需再用 markdown 或 URL 重复展示）。图片 URL: ${img.url}`,
    });
  }
  const urls = result.images.map((img, i) => `[图${i + 1}] ${img.url}`).join('\n');
  return imagesResult(
    result.images.map(img => ({ url: img.url!, width: img.width, height: img.height })),
    `已生成 ${result.images.length} 张图片并自动展示给用户（无需再用 markdown 或 URL 重复展示）。\n${urls}`,
  );
}
