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

interface InterpreterInput {
  main_prompt: string;
  liked_shows: string;
  disliked_shows: string;
  themes: string;
  feedback_context?: string;
}

export async function runInterpreter(input: InterpreterInput): Promise<InterpreterOutput> {
  const feedbackSection = input.feedback_context
    ? `\n\nUser Feedback Context (incorporate into preferences):\n${input.feedback_context}`
    : '';

  const response = await openai.chat.completions.create({
    model: 'gpt-5.4-mini',
    temperature: 0.2,
    service_tier: 'flex',
    response_format: { type: 'json_object' },
    messages: [
      {
        role: 'system',
        content: `You are a TV show preference interpreter. Transform raw user input into structured, normalized preferences.

Your output MUST be valid JSON matching this schema:
{
  "liked": string[],        // shows the user likes
  "disliked": string[],     // shows the user dislikes
  "themes": string[],       // normalized themes (e.g. "spy" -> "espionage")
  "character_preferences": string[], // character types they prefer
  "tone": string[],         // tone descriptors (e.g. "serious", "grounded", "dark")
  "avoid": string[]         // things to explicitly avoid
}

Rules:
- Extract implicit preferences from the main prompt
- Normalize terminology (e.g. "spy" → "espionage", "cop show" → "police procedural")
- Detect and resolve contradictions (prefer explicit over implicit)
- Do NOT assume anything not stated or clearly implied
- Be specific and concrete, not vague`,
      },
      {
        role: 'user',
        content: `Main prompt: ${input.main_prompt}
Liked shows: ${input.liked_shows || '(none)'}
Disliked shows: ${input.disliked_shows || '(none)'}
Themes and requirements: ${input.themes || '(none)'}${feedbackSection}`,
      },
    ],
  });

  const content = response.choices[0]?.message?.content ?? '{}';
  return JSON.parse(content) as InterpreterOutput;
}
