const knowledgeService = require('../services/knowledgeService');
const searchService = require('../services/searchService');
const promptService = require('../services/promptService');
const aiService = require('../services/aiService');

/**
 * Controller for chatbot requests.
 * Coordinates knowledge loading, search, prompt building, and AI response generation.
 * @param {import('express').Request} req
 * @param {import('express').Response} res
 */
async function chatController(req, res) {
  try {
    const userMessage = typeof req.body?.message === 'string' ? req.body.message.trim() : '';

    if (!userMessage) {
      return res.status(400).json({
        success: false,
        answer: 'Please provide a valid message in req.body.message.'
      });
    }

    console.log('chatController: received message:', userMessage);
  const knowledgeBase = knowledgeService.getKnowledgeBase();
  console.log('chatController: loaded knowledge count:', Array.isArray(knowledgeBase) ? knowledgeBase.length : 0);

    if (!Array.isArray(knowledgeBase) || knowledgeBase.length === 0) {
      return res.json({
        success: true,
        answer: 'I am sorry, I do not have any knowledge available to answer that question right now.'
      });
    }

    const searchResults = searchService.searchKnowledge(userMessage, knowledgeBase);
    console.log('chatController: searchResults count:', Array.isArray(searchResults) ? searchResults.length : 0);

    if (!Array.isArray(searchResults) || searchResults.length === 0) {
      return res.json({
        success: true,
        answer: 'I could not find information that matches your question. Please try asking in a different way.'
      });
    }

    const prompt = promptService.buildPrompt(userMessage, searchResults);
    console.log('chatController: prompt built, length:', prompt.length);
    const answer = await aiService.generateAIResponse(prompt);
    console.log('chatController: aiService response length:', answer ? answer.length : 0);

    return res.json({
      success: true,
      answer
    });
  } catch (error) {
    console.error('Chat controller error:', error);
    return res.status(500).json({
      success: false,
      answer: 'Sorry, something went wrong while processing your request.'
    });
  }
}

module.exports = {
  chatController
};
