const aiFollowupQuestion = async (req, res) => {

  const { MongoClient } = require('mongodb');
  // const fetch = require('node-fetch');
  const { v4: uuidv4 } = require('uuid');
  const url = process.env.MONGODB_URL;
  const dbName = process.env.MONGO_DB_NAME;
  const client = new MongoClient(url);
  
  await client.connect();
  const database = client.db(dbName); // Replace with your database name
  const conversationsCollection = database.collection('conversations'); // Replace with your collection name
  
  async function fetchOpenAICompletion(prompt, messages, model = "gpt-3.5-turbo-16k", max_tokens = 600) {
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.OPENAI_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: model,
        messages: messages,
        max_tokens: max_tokens,
      }),
    });
  
    const data = await response.json();
    return data;
    // return data.choices[0].message.content;
  }
  
  
    try {
      const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 600 } = req.body;
      if (!conversationsCollection) {
        return res.status(500).json({
          success: false,
          error: 'MongoDB is not connected yet. Please try again later.',
        });
      }
      let conversation;
  
      if (!sessionId) {
        const newSessionId = uuidv4();
  
        conversation = {
          sessionId: newSessionId,
          conversationHistory: [
            { role: 'system', content: 'You are a helpful assistant.' },
            // { role: 'user', content: prompt },
            { role: 'user', content: JSON.stringify(req.body.score) + "   -  is the students report card. " + req.body.instruction },
          ],
        };
        // console.log(req.body.score[0])
        await conversationsCollection.insertOne(conversation);
      } else {
        conversation = await conversationsCollection.findOne({ sessionId: sessionId });
        if (!conversation) {
          return res.status(400).json({
            success: false,
            error: 'Invalid session ID.',
          });
        }
        conversation.conversationHistory.push({ role: 'user', content: prompt });
      }
  
      // Call OpenAI API with the conversation history
      const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
  
      // Add the AI's response to the conversation history
      conversation.conversationHistory.push({ role: 'assistant', content: aiResponse });
  
      // Update the conversation in MongoDB
      await conversationsCollection.updateOne(
        { sessionId: conversation.sessionId },
        { $set: { conversationHistory: conversation.conversationHistory } }
      );
  
      // Send the AI's response and session ID back to the frontend
      res.json({
        success: true,
        data: aiResponse,
        sessionId: conversation.sessionId,  // Return the session ID for subsequent queries
      });
    } catch (error) {
      console.error('Error generating response:', error.message);
      res.status(500).json({
        success: false,
        error: 'Something went wrong. Please try again later.',
      });
    }
  
  
  }
  
  module.exports = aiFollowupQuestion;