import { openai } from '../agent.js';
import type { InterpreterOutput, RankingOutput, CuratorOutput } from '../types/agents.js';

export async function runCurator(
  ranking: RankingOutput,
  interpreter: InterpreterOutput,
): Promise<CuratorOutput[]> {
  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.chat.completions.create({
    model: 'gpt-5.4-mini',
    temperature: 0.5,
    service_tier: 'flex',
    response_format: { type: 'json_object' },
    messages: [
      {
        role: 'system',
        content: `You are a TV show recommendation curator. For each show, write a concise 1-2 sentence explanation of why it was assigned to its category based on the user's preferences.

Your output MUST be valid JSON:
{
  "shows": [
    {
      "title": string,
      "explanation": string,
      "category": "Definitely Like" | "Might Like" | "Questionable" | "Will Not Like"
    }
  ]
}

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" shows got that rating`,
      },
      {
        role: 'user',
        content: `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)}

Shows to describe:
${showList}`,
      },
    ],
  });

  const content = response.choices[0]?.message?.content ?? '{"shows":[]}';
  const result = JSON.parse(content) as { shows: CuratorOutput[] };
  return result.shows ?? [];
}
