/**
 * AI-driven content generation. Produces child-friendly Bangla MCQs.
 *
 * In DEMO_MODE (or when AI_API_KEY is missing) this returns the hand-written
 * fallback questions instead of calling any external API.
 *
 * Server-only.
 */
import { env, canUseAi } from './env';
import type { AgeGroup, Question } from './types';
import { SUBJECT_NAME } from './types';
import fallback from '../data/lessons.json';

function fallbackQuestions(subjectId: string, count: number): Question[] {
  const lessons = (fallback as unknown as Record<string, { questions: Question[] }[]>)[subjectId] ?? [];
  const all = lessons.flatMap((l) => l.questions);
  if (all.length === 0) return [];
  // repeat/trim to the requested count
  const out: Question[] = [];
  for (let i = 0; i < count; i += 1) out.push(all[i % all.length]);
  return out.slice(0, count);
}

function buildPrompt(subjectId: string, ageGroup: AgeGroup, count: number): string {
  const subjectName = SUBJECT_NAME[subjectId] ?? subjectId;
  return [
    `তুমি বাংলাদেশি শিশুদের জন্য শিক্ষামূলক কুইজ প্রশ্ন বানাও।`,
    `বিষয়: ${subjectName}। বয়স গ্রুপ: ${ageGroup} বছর।`,
    `${count} টা multiple-choice প্রশ্ন বানাও।`,
    `নিয়ম:`,
    `- সহজ, দৈনন্দিন বাংলা ব্যবহার করবে; ইংরেজি শব্দ কম।`,
    `- প্রতিটা প্রশ্নে ঠিক ৪টা option থাকবে, একটাই সঠিক।`,
    `- তথ্য অবশ্যই সঠিক হতে হবে; বয়স অনুযায়ী কঠিনতা ঠিক রাখবে।`,
    `- explanation এক লাইনে, উৎসাহমূলক টোনে।`,
    `শুধু নিচের JSON array ফরম্যাটে উত্তর দাও, আর কিছু লিখবে না:`,
    `[{"question":"...","options":["..","..","..",".."],"correctIndex":0,"explanation":".."}]`,
  ].join('\n');
}

function coerceQuestions(data: any, subjectId: string): Question[] {
  if (!Array.isArray(data)) return [];
  const out: Question[] = [];
  data.forEach((q: any, i: number) => {
    if (
      q &&
      typeof q.question === 'string' &&
      Array.isArray(q.options) &&
      q.options.length === 4 &&
      typeof q.correctIndex === 'number'
    ) {
      out.push({
        id: `${subjectId}-gen-${i + 1}`,
        question: q.question,
        options: q.options.slice(0, 4) as [string, string, string, string],
        correctIndex: Math.max(0, Math.min(3, q.correctIndex)),
        explanation: typeof q.explanation === 'string' ? q.explanation : 'দারুণ চেষ্টা!',
      });
    }
  });
  return out;
}

async function callAnthropic(prompt: string): Promise<string> {
  const res = await fetch('https://api.anthropic.com/v1/messages', {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'x-api-key': env.aiApiKey,
      'anthropic-version': '2023-06-01',
    },
    body: JSON.stringify({
      model: env.aiModel,
      max_tokens: 2000,
      messages: [{ role: 'user', content: prompt }],
    }),
  });
  const json = await res.json();
  return json?.content?.[0]?.text ?? '';
}

async function callOpenai(prompt: string): Promise<string> {
  const res = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      authorization: `Bearer ${env.aiApiKey}`,
    },
    body: JSON.stringify({
      model: env.aiModel,
      messages: [{ role: 'user', content: prompt }],
      temperature: 0.7,
    }),
  });
  const json = await res.json();
  return json?.choices?.[0]?.message?.content ?? '';
}

function extractJson(text: string): any {
  // Models sometimes wrap JSON in prose/backticks; grab the first array.
  const match = text.match(/\[[\s\S]*\]/);
  if (!match) return null;
  try {
    return JSON.parse(match[0]);
  } catch {
    return null;
  }
}

/**
 * Generate `count` MCQ questions for a subject + age group.
 * Falls back to hand-written questions when AI is unavailable.
 */
export async function generateLessons(
  subjectId: string,
  ageGroup: AgeGroup,
  count = 6,
): Promise<Question[]> {
  if (!canUseAi()) {
    return fallbackQuestions(subjectId, count);
  }

  try {
    const prompt = buildPrompt(subjectId, ageGroup, count);
    const text =
      env.aiProvider === 'openai' ? await callOpenai(prompt) : await callAnthropic(prompt);
    const parsed = extractJson(text);
    const questions = coerceQuestions(parsed, subjectId);
    if (questions.length > 0) return questions;
  } catch (err) {
    console.error('[ai] generateLessons failed, using fallback:', err);
  }
  return fallbackQuestions(subjectId, count);
}
