import { openai } from '../agent.js';
import type { InterpreterOutput, RankingOutput, CuratorOutput, MediaType } from '../types/agents.js';
import { z } from 'zod';
import { zodTextFormat } from 'openai/helpers/zod';

const CuratorSchema = z.object({
  shows: z.array(z.object({
    title: z.string(),
    explanation: z.string(),
    category: z.enum(["Definitely Like", "Might Like", "Questionable", "Will Not Like"])
  }))
});

export async function runCurator(
  ranking: RankingOutput,
  interpreter: InterpreterOutput,
  mediaType: MediaType = 'tv_show',
  useWebSearch = false,
): Promise<CuratorOutput[]> {
  const mediaLabel = mediaType === 'movie' ? 'movie' : 'TV show';

  const allShows = [
    ...ranking.definitely_like.map((t) => ({ title: t, category: 'Definitely Like' as const })),
    ...ranking.might_like.map((t) => ({ title: t, category: 'Might Like' as const })),
    ...ranking.questionable.map((t) => ({ title: t, category: 'Questionable' as const })),
    ...ranking.will_not_like.map((t) => ({ title: t, category: 'Will Not Like' as const })),
  ];

  if (allShows.length === 0) return [];

  const showList = allShows
    .map((s) => `- "${s.title}" (${s.category})`)
    .join('\n');

  const response = await openai.responses.parse({
    model: 'gpt-5.4',
    temperature: 0.5,
    service_tier: 'flex',
    ...(useWebSearch ? { tools: [{ type: 'web_search' as const }] } : {}),
    text: { format: zodTextFormat(CuratorSchema, "shows") },
    instructions: `You are a ${mediaLabel} recommendation curator. For each ${mediaLabel}, write a concise 1-2 sentence explanation of why it was assigned to its category based on the user's preferences.${useWebSearch ? '\n\nUse web search to verify details and enrich explanations with accurate information.' : ''}

Rules:
- Preserve the exact title and category as given
- Keep explanations concise (1-2 sentences max)
- Reference specific user preferences in the explanation
- Be honest — explain why "Questionable" or "Will Not Like" ${mediaLabel}s got that rating`,
    input: `User preferences summary:
Liked: ${JSON.stringify(interpreter.liked)}
Themes: ${JSON.stringify(interpreter.themes)}
Tone: ${JSON.stringify(interpreter.tone)}
Character preferences: ${JSON.stringify(interpreter.character_preferences)}
Avoid: ${JSON.stringify(interpreter.avoid)}

${mediaLabel}s to describe:
${showList}`,
  });

  return response.output_parsed?.shows ?? [];
}
