import z from 'zod';
import type { ToolDef } from './types.js';

const MEDIA_SVC = process.env.MEDIA_SVC_URL?.trim() ?? 'http://localhost:3016';

const imageSchema = z.object({
  query: z.string().describe('Image search query'),
});

export const imageSearchTool: ToolDef = {
  name: 'image_search',
  description: 'Search for images by query. Use when user wants to see relevant images.',
  schema: imageSchema,
  execute: async (params, ctx) => {
    const parsed = imageSchema.parse(params);
    const chatModel = ctx?.chatModel ?? { providerId: 'env', key: process.env.LLM_CHAT_MODEL ?? 'gpt-4o-mini' };
    const url = `${MEDIA_SVC.replace(/\/$/, '')}/api/v1/media/images`;
    try {
      const res = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          query: parsed.query,
          chatHistory: ctx?.chatHistory ?? [],
          chatModel,
        }),
        signal: AbortSignal.timeout(15000),
      });
      if (!res.ok) return JSON.stringify({ error: `HTTP ${res.status}` });
      const data = (await res.json()) as { images?: { img_src: string; url: string; title: string }[] };
      return JSON.stringify({ images: data.images ?? [] }, null, 2);
    } catch (err) {
      return JSON.stringify({ error: err instanceof Error ? err.message : 'Media service unavailable' });
    }
  },
};
