import OpenAI from 'openai';
import { env } from '../config/env.js';

let client = null;

function keyLooksReal(key) {
  return Boolean(key) && key.startsWith('sk-') && !key.includes('your');
}

function getClient() {
  if (!keyLooksReal(env.openaiApiKey)) return null;
  if (!client) client = new OpenAI({ apiKey: env.openaiApiKey });
  return client;
}

export function isAiConfigured() {
  return keyLooksReal(env.openaiApiKey);
}

/**
 * Generate a clear explanation for a question given its options and correct answer(s).
 */
export async function explainQuestion({ question, options, correctTexts, existingExplanation }) {
  const ai = getClient();
  if (!ai) {
    return {
      explanation:
        existingExplanation ||
        'AI explanations are not configured yet. Add OPENAI_API_KEY to the backend .env to enable them.',
      generated: false,
    };
  }

  const optionList = options.map((o, i) => `${String.fromCharCode(65 + i)}. ${o}`).join('\n');
  const prompt = `You are an expert certification exam tutor. Explain the following multiple-choice question clearly and concisely.

Question:
${question}

Options:
${optionList}

Correct answer(s): ${correctTexts.join(', ')}

Provide:
1. A short explanation of why the correct answer is right.
2. A brief note on why the other key options are wrong.
Keep it under 180 words, use plain language.`;

  const completion = await ai.chat.completions.create({
    model: env.openaiModel,
    messages: [
      { role: 'system', content: 'You are a helpful, accurate certification exam tutor.' },
      { role: 'user', content: prompt },
    ],
    temperature: 0.4,
    max_tokens: 400,
  });

  return {
    explanation: completion.choices[0]?.message?.content?.trim() || existingExplanation || '',
    generated: true,
  };
}
