const express = require('express');
const router = express.Router();
const axios = require('axios');
const config = require('../config');
const db = require('../db');

router.post('/', async (req, res) => {
  const message = req.body.message || '';
  const history = req.body.history || [];
  
  let sysPrompt = 'You are Peak AI, an intelligent assistant for the Peak workflow platform.';
  let model = 'groq-compound';
  let temperature = 0.7;
  let maxTokens = 1024;
  let knowledge = '';
  
  try {
    const rows = await db.query('SELECT setting_key, setting_value FROM settings WHERE setting_key IN (?, ?, ?, ?, ?)', 
      ['ai_system_prompt', 'ai_model', 'ai_temperature', 'ai_max_tokens', 'ai_knowledge']);
    rows.forEach(r => {
      switch (r.setting_key) {
        case 'ai_system_prompt': sysPrompt = r.setting_value; break;
        case 'ai_model': model = r.setting_value; break;
        case 'ai_temperature': temperature = parseFloat(r.setting_value) || 0.7; break;
        case 'ai_max_tokens': maxTokens = parseInt(r.setting_value) || 1024; break;
        case 'ai_knowledge': knowledge = r.setting_value; break;
      }
    });
  } catch (err) {}
  
  if (knowledge) sysPrompt += "\n\nPlatform knowledge:\n" + knowledge;
  
  const messages = [{ role: 'system', content: sysPrompt }];
  history.forEach(h => messages.push({ role: h.role, content: h.content }));
  messages.push({ role: 'user', content: message });
  
  try {
    if (model.startsWith('gemini') || model.startsWith('gemma')) {
      const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent?key=${config.GEMINI_API_KEY}`;
      const geminiContents = messages.filter(m => m.role !== 'system').map(m => ({
        role: m.role === 'assistant' ? 'model' : 'user',
        parts: [{ text: m.content }]
      }));
      const payload = {
        contents: geminiContents,
        generationConfig: { temperature, maxOutputTokens: maxTokens },
        systemInstruction: { parts: [{ text: sysPrompt }] }
      };
      const response = await axios.post(url, payload);
      res.json({ reply: response.data.candidates[0].content.parts[0].text });
    } else {
      const apiModel = model === 'groq-compound' ? 'llama-3.3-70b-versatile' : model;
      const response = await axios.post('https://api.groq.com/openai/v1/chat/completions', {
        model: apiModel,
        messages: messages,
        temperature,
        max_tokens: maxTokens
      }, { headers: { 'Authorization': `Bearer ${config.GROQ_API_KEY}` } });
      res.json({ reply: response.data.choices[0].message.content });
    }
  } catch (err) {
    res.json({ reply: 'I understand you are asking something. (Fallback logic invoked due to API error: ' + err.message + ')' });
  }
});

module.exports = router;
