const express = require('express');
const router = express.Router();
const nlp = require('../services/nlp');
const queryBuilder = require('../services/queryBuilder');
const responseGenerator = require('../services/responseGenerator');
const iaLogger = require('../services/iaLogger');
const { containsSqlInjection, containsXSS, sanitizeInput } = require('../middleware/security');

router.post('/query', async (req, res) => {
  try {
    const { question, userId } = req.body;

    if (!question) {
      return res.status(400).json({
        success: false,
        message: 'Question requise'
      });
    }

    const sanitizedQuestion = sanitizeInput(question);
    
    if (containsSqlInjection(sanitizedQuestion)) {
      await iaLogger.logFailedQuery(sanitizedQuestion, { typeDonnees: null }, 'SQL_INJECTION', userId);
      return res.status(400).json({
        success: false,
        message: 'Question invalide',
        code: 'INVALID_QUESTION'
      });
    }

    if (containsXSS(sanitizedQuestion)) {
      await iaLogger.logFailedQuery(sanitizedQuestion, { typeDonnees: null }, 'XSS_DETECTED', userId);
      return res.status(400).json({
        success: false,
        message: 'Contenu invalide',
        code: 'INVALID_CONTENT'
      });
    }

    const resolvedUserId = userId || req.headers['x-user-id'] || 'anonymous';

    let parsed = nlp.parse(sanitizedQuestion, resolvedUserId);
    
    if (parsed.isFollowUp && parsed.previousContext) {
      parsed = nlp.resolveFollowUp(sanitizedQuestion, resolvedUserId);
    }

    if (!parsed.typeDonnees) {
      await iaLogger.logFailedQuery(sanitizedQuestion, parsed, 'TYPE_NOT_RECOGNIZED', resolvedUserId);
      return res.status(400).json({
        success: false,
        message: 'Je n\'ai pas compris le type de données. Pouvez-vous préciser ? (recettes, fréquentations, retards, flotte, personnel)',
        suggestions: [
          'Combien de recettes cette semaine ?',
          'Les retards d\'hier',
          'État de la flotte',
          'Présence du personnel ce mois'
        ]
      });
    }

    const queryObj = queryBuilder.buildQuery(parsed);
    const queryResult = await queryBuilder.executeQuery(queryObj);

    if (queryResult.error) {
      await iaLogger.logFailedQuery(sanitizedQuestion, parsed, queryResult.error, resolvedUserId);
    } else {
      await iaLogger.logSuccessfulQuery(sanitizedQuestion, parsed, queryResult, resolvedUserId);
      await iaLogger.updateDictionary(sanitizedQuestion, parsed.typeDonnees, parsed);
    }

    let response = responseGenerator.generate(parsed, queryResult);

    if (parsed.isFollowUp && parsed.previousContext) {
      const previousQuery = queryBuilder.buildQuery(parsed.previousContext);
      const previousResult = await queryBuilder.executeQuery(previousQuery);
      const comparison = responseGenerator.generateComparison(previousResult, queryResult, parsed);
      if (comparison) {
        response.comparison = comparison;
        response.text += '\n\n' + comparison.label;
      }
    }

    res.json({
      success: true,
      data: response,
      parsed: {
        type: parsed.typeDonnees,
        periode: parsed.periode.type,
        gare: parsed.gare,
        ligne: parsed.ligne
      }
    });

  } catch (error) {
    console.error('Erreur IA Query:', error);
    await iaLogger.logFailedQuery(req.body.question, { typeDonnees: null }, error.message, req.headers['x-user-id']);
    res.status(500).json({
      success: false,
      message: error.message || 'Erreur lors du traitement de la requête'
    });
  }
});

router.get('/suggestions', (req, res) => {
  res.json({
    success: true,
    suggestions: [
      {
        category: 'Recettes',
        questions: [
          'Combien de recettes a généré la gare d\'Alger cette semaine ?',
          'Quelles sont les meilleures gares ce mois ?',
          'Recettes globales hier'
        ]
      },
      {
        category: 'Fréquentation',
        questions: [
          'Combien de voyageurs à la gare d\'Oran cette semaine ?',
          'Quelle est la fréquentation ce mois ?'
        ]
      },
      {
        category: 'Retards',
        questions: [
          'Montre-moi les retards d\'hier',
          'Lignes avec le plus de retards cette semaine',
          'Retards sur la ligne 5 ce mois'
        ]
      },
      {
        category: 'Flotte',
        questions: [
          'État de la flotte aujourd\'hui',
          'Combien de bus disponibles ?',
          'Véhicules en panne'
        ]
      },
      {
        category: 'Personnel',
        questions: [
          'Effectif par service',
          'Taux d\'absentéisme ce mois',
          'Présence du personnel aujourd\'hui'
        ]
      }
    ]
  });
});

router.get('/types', (req, res) => {
  res.json({
    success: true,
    types: queryBuilder.getAvailableTypes()
  });
});

router.get('/logs', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 50;
    const logs = await iaLogger.getTopQueries(limit);
    res.json({
      success: true,
      logs
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

router.get('/logs/failed', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 50;
    const logs = await iaLogger.getFailedQueries(limit);
    res.json({
      success: true,
      logs
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

router.get('/statistics', async (req, res) => {
  try {
    const stats = await iaLogger.getStatistics();
    res.json({
      success: true,
      statistics: stats
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

router.get('/dictionary', async (req, res) => {
  try {
    const approved = req.query.approved === 'true';
    const dictionary = await iaLogger.getDictionary(approved);
    res.json({
      success: true,
      dictionary
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

router.post('/dictionary/:id/approve', async (req, res) => {
  try {
    const { id } = req.params;
    await iaLogger.approveDictionaryEntry(id);
    res.json({
      success: true,
      message: 'Entrée approuvée'
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

module.exports = router;