import OpenAI from 'openai';
import { AIResponse, Language } from '@/types';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

// Educational prompts for AI to guide thinking instead of giving direct answers
const EDUCATIONAL_PROMPTS = {
  en: {
    systemPrompt: "You are an educational assistant for children. Instead of giving direct answers, ask 2-3 guiding questions that help children think through the problem themselves. Be encouraging and use simple language. Focus on the thinking process, not the answer.",
    prefix: "That's a great question! Let me help you think through this step by step. Instead of telling you the answer, here are some questions to guide your thinking:"
  },
  de: {
    systemPrompt: "Du bist ein Lernassistent für Kinder. Anstatt direkte Antworten zu geben, stelle 2-3 Leitfragen, die Kindern helfen, das Problem selbst zu durchdenken. Sei ermutigend und verwende einfache Sprache. Konzentriere dich auf den Denkprozess, nicht auf die Antwort.",
    prefix: "Das ist eine tolle Frage! Lass mich dir helfen, Schritt für Schritt darüber nachzudenken. Anstatt dir die Antwort zu sagen, hier sind einige Fragen, die dein Denken leiten:"
  }
};

// Fallback questions for when AI is not available
const FALLBACK_QUESTIONS = {
  en: [
    "What do you already know about this topic?",
    "What do you think might be the reason for this?",
    "Where could you look to find more information?",
    "Can you think of any examples or similar situations?"
  ],
  de: [
    "Was weißt du bereits über dieses Thema?",
    "Was denkst du, könnte der Grund dafür sein?",
    "Wo könntest du nachschauen, um mehr Informationen zu finden?",
    "Kannst du an Beispiele oder ähnliche Situationen denken?"
  ]
};

export async function getAIResponse(question: string, language: Language): Promise<AIResponse> {
  try {
    const prompt = EDUCATIONAL_PROMPTS[language];
    
    const completion = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: prompt.systemPrompt
        },
        {
          role: "user",
          content: question
        }
      ],
      max_tokens: 300,
      temperature: 0.7
    });

    const aiMessage = completion.choices[0]?.message?.content || '';
    
    return {
      message: `${prompt.prefix}\n\n${aiMessage}`,
      thinking_steps: extractThinkingSteps(aiMessage, language),
      research_ideas: generateResearchIdeas(question, language),
      experiment_ideas: generateExperimentIdeas(question, language),
      discussion_ideas: generateDiscussionIdeas(question, language)
    };
  } catch (error) {
    console.error('AI service error:', error);
    
    // Fallback to local guidance
    return {
      message: EDUCATIONAL_PROMPTS[language].prefix,
      thinking_steps: FALLBACK_QUESTIONS[language],
      research_ideas: generateResearchIdeas(question, language),
      experiment_ideas: generateExperimentIdeas(question, language),
      discussion_ideas: generateDiscussionIdeas(question, language)
    };
  }
}

function extractThinkingSteps(aiMessage: string, language: Language): string[] {
  // Extract numbered or bulleted questions from AI response
  const lines = aiMessage.split('\n').filter(line => line.trim());
  const steps = lines.filter(line => 
    line.match(/^\d+\./) || line.match(/^-/) || line.match(/^\*/) || line.includes('?')
  );
  
  return steps.length > 0 ? steps : FALLBACK_QUESTIONS[language];
}

function generateResearchIdeas(question: string, language: Language): string[] {
  const ideas = language === 'en' ? [
    "Look up the topic in a children's encyclopedia",
    "Ask a teacher or parent about it",
    "Watch educational videos about the subject",
    "Visit a library to find books about this topic"
  ] : [
    "Schau das Thema in einer Kinderlexikon nach",
    "Frag einen Lehrer oder Elternteil danach",
    "Schau dir Lehrvideos zu dem Thema an",
    "Besuche eine Bibliothek und finde Bücher zu diesem Thema"
  ];
  
  return ideas;
}

function generateExperimentIdeas(question: string, language: Language): string[] {
  const ideas = language === 'en' ? [
    "Try a simple, safe experiment with adult supervision",
    "Observe examples of this in your daily life",
    "Draw or write down what you notice",
    "Compare different examples to see patterns"
  ] : [
    "Probiere ein einfaches, sicheres Experiment mit erwachsener Aufsicht",
    "Beobachte Beispiele davon in deinem täglichen Leben",
    "Zeichne oder schreibe auf, was dir auffällt",
    "Vergleiche verschiedene Beispiele, um Muster zu erkennen"
  ];
  
  return ideas;
}

function generateDiscussionIdeas(question: string, language: Language): string[] {
  const ideas = language === 'en' ? [
    "Talk to your family about what they think",
    "Ask friends if they've wondered about this too",
    "Share your discoveries with your class",
    "Discuss what you learned with a teacher"
  ] : [
    "Sprich mit deiner Familie darüber, was sie denken",
    "Frag Freunde, ob sie sich das auch schon gefragt haben",
    "Teile deine Entdeckungen mit deiner Klasse",
    "Besprich, was du gelernt hast, mit einem Lehrer"
  ];
  
  return ideas;
}
