class ResponseGenerator {
  constructor() {
    this.graphConfig = {
      recettes: {
        type: 'bar',
        title: 'Recettes',
        colors: ['#4CAF50', '#2196F3', '#FF9800', '#E91E63', '#9C27B0'],
        yAxisLabel: 'Montant (DA)',
        xAxisLabel: 'Date/Gare'
      },
      frequentation: {
        type: 'line',
        title: 'Fréquentation',
        colors: ['#00BCD4', '#3F51B5', '#009688'],
        yAxisLabel: 'Nombre de passagers',
        xAxisLabel: 'Date'
      },
      retards: {
        type: 'bar',
        title: 'Retards par ligne',
        colors: ['#F44336', '#FF5722', '#FFC107'],
        yAxisLabel: 'Nombre de retards',
        xAxisLabel: 'Ligne'
      },
      flotte: {
        type: 'pie',
        title: 'État de la flotte',
        colors: ['#4CAF50', '#FF9800', '#F44336', '#9E9E9E'],
        yAxisLabel: 'Nombre',
        xAxisLabel: 'État'
      },
      personnel: {
        type: 'bar',
        title: 'Personnel',
        colors: ['#673AB7', '#3F51B5', '#2196F3'],
        yAxisLabel: 'Nombre',
        xAxisLabel: 'Service'
      }
    };
  }

  generate(parsed, queryResult) {
    if (queryResult.empty) {
      return this.generateEmptyResponse(parsed);
    }

    const response = {
      text: this.generateText(parsed, queryResult.data),
      data: queryResult.data,
      graphique: this.generateGraphConfig(parsed, queryResult.data),
      metadata: {
        periode: parsed.periode,
        type: parsed.typeDonnees,
        timestamp: new Date().toISOString()
      }
    };

    if (parsed.gare) {
      response.metadata.gare = parsed.gare;
    }
    if (parsed.ligne) {
      response.metadata.ligne = parsed.ligne;
    }

    return response;
  }

  generateText(parsed, data) {
    const type = parsed.typeDonnees;
    const periode = parsed.periode;
    const periodeLabel = this.getPeriodeLabel(periode.type);
    
    let text = '';

    switch (type) {
      case 'recettes':
        if (parsed.gare) {
          const total = this.calculateSum(data, 'total');
          text = `📊 **Recettes pour la gare "${parsed.gare}"**\n\n`;
          text += `Période: ${periodeLabel} (du ${periode.start} au ${periode.end})\n\n`;
          text += `💰 **Total: ${this.formatNumber(total)} DA**\n`;
          text += `📈 Nombre de transactions: ${data.length}`;
        } else if (parsed.comparateur || parsed.aggregation === 'COUNT') {
          text = `🏆 **Top ${parsed.limite} gares par recettes**\n\n`;
          text += `Période: ${periodeLabel}\n\n`;
          data.slice(0, parsed.limite).forEach((item, index) => {
            text += `${index + 1}. ${item.gare}: ${this.formatNumber(item.total)} DA\n`;
          });
        } else {
          const total = this.calculateSum(data, 'total');
          text = `📊 **Recettes globales**\n\n`;
          text += `Période: ${periodeLabel} (du ${periode.start} au ${periode.end})\n\n`;
          text += `💰 **Total: ${this.formatNumber(total)} DA**`;
        }
        break;

      case 'frequentation':
        const totalPassagers = this.calculateSum(data, 'total_passagers') || data.length;
        text = `🚶 **Fréquentation**\n\n`;
        if (parsed.gare) {
          text += `Gare: ${parsed.gare}\n`;
        }
        text += `Période: ${periodeLabel}\n\n`;
        text += `👥 **Total passengers: ${this.formatNumber(totalPassagers)}**`;
        break;

      case 'retards':
        const totalRetards = this.calculateSum(data, 'nb_retards');
        const avgRetard = data[0]?.avg_retard ? parseFloat(data[0].avg_retard).toFixed(1) : 'N/A';
        text = `🚨 **Statistiques des retards**\n\n`;
        text += `Période: ${periodeLabel}\n\n`;
        text += `⏱️ Nombre total de retards: **${totalRetards}**\n`;
        text += `📊 Retard moyen: **${avgRetard} minutes**\n\n`;
        
        if (parsed.ligne) {
          text += `Ligne: ${parsed.ligne}\n`;
        } else {
          text += `**Top lignes avec retards:**\n`;
          data.slice(0, 5).forEach((item, index) => {
            text += `${index + 1}. Ligne ${item.ligne}: ${item.nb_retards} retards (moy: ${parseFloat(item.avg_retard || 0).toFixed(1)} min)\n`;
          });
        }
        break;

      case 'flotte':
        const totalVehicules = this.calculateSum(data, 'nombre');
        const disponibles = data.find(d => d.etat === 'disponible')?.nombre || 0;
        const enService = data.find(d => d.etat === 'actif')?.nombre || 0;
        const enPanne = data.find(d => d.etat === 'panne')?.nombre || 0;
        
        text = `🚌 **État de la flotte**\n\n`;
        text += `Total véhicules: **${totalVehicules}**\n\n`;
        text += `✅ En service: **${enService}**\n`;
        text += `🔄 Disponibles: **${disponibles}**\n`;
        text += `⚠️ En panne: **${enPanne}**`;
        break;

      case 'personnel':
        if (parsed.comparateur === 'absenteisme') {
          text = `📋 **Taux d'absentéisme par service**\n\n`;
          text += `Période: ${periodeLabel}\n\n`;
          data.slice(0, 10).forEach((item, index) => {
            text += `${index + 1}. ${item.service}: ${item.taux_absence}% (${item.nb_absences}/${item.total_employes})\n`;
          });
        } else if (parsed.comparateur === 'presence') {
          const presents = this.calculateSum(data, 'presents');
          text = `👥 **Présence du personnel**\n\n`;
          text += `Période: ${periodeLabel}\n\n`;
          text += `✅ Présents aujourd'hui: **${presents}**`;
        } else {
          const totalEffectif = this.calculateSum(data, 'effectif');
          text = `👥 **Effectif par service**\n\n`;
          text += `Total: **${totalEffectif}** employés\n\n`;
          data.slice(0, 10).forEach((item, index) => {
            text += `${index + 1}. ${item.service}: ${item.effectif} (${item.actifs} actifs)\n`;
          });
        }
        break;

      default:
        text = `Données pour: ${type}`;
    }

    return text;
  }

  generateGraphConfig(parsed, data) {
    const type = parsed.typeDonnees;
    const config = this.graphConfig[type] || this.graphConfig.recettes;
    
    let chartData;

    switch (type) {
      case 'recettes':
        if (parsed.gare || !parsed.comparateur) {
          chartData = {
            labels: data.map(d => this.formatDate(d.date)),
            datasets: [{
              label: 'Recettes (DA)',
              data: data.map(d => parseFloat(d.total) || 0),
              backgroundColor: config.colors[0]
            }]
          };
        } else {
          chartData = {
            labels: data.map(d => d.gare),
            datasets: [{
              label: 'Recettes (DA)',
              data: data.map(d => parseFloat(d.total) || 0),
              backgroundColor: config.colors
            }]
          };
        }
        break;

      case 'frequentation':
        chartData = {
          labels: data.map(d => this.formatDate(d.date)),
          datasets: [{
            label: 'Passagers',
            data: data.map(d => d.total_passagers || 0),
            borderColor: config.colors[0],
            backgroundColor: 'rgba(0, 188, 212, 0.1)',
            fill: true
          }]
        };
        break;

      case 'retards':
        chartData = {
          labels: data.map(d => d.ligne || this.formatDate(d.date)),
          datasets: [{
            label: 'Nombre de retards',
            data: data.map(d => d.nb_retards || 0),
            backgroundColor: config.colors[0]
          }]
        };
        break;

      case 'flotte':
        chartData = {
          labels: data.map(d => d.etat),
          datasets: [{
            data: data.map(d => d.nombre || 0),
            backgroundColor: config.colors
          }]
        };
        break;

      case 'personnel':
        chartData = {
          labels: data.map(d => d.service),
          datasets: [{
            label: 'Effectif',
            data: data.map(d => d.effectif || d.total_employes || 0),
            backgroundColor: config.colors
          }]
        };
        break;

      default:
        chartData = {
          labels: [],
          datasets: []
        };
    }

    return {
      type: config.type,
      title: config.title,
      data: chartData,
      options: {
        responsive: true,
        plugins: {
          legend: {
            position: 'top'
          }
        },
        scales: type !== 'flotte' ? {
          y: {
            beginAtZero: true,
            title: {
              display: true,
              text: config.yAxisLabel
            }
          },
          x: {
            title: {
              display: true,
              text: config.xAxisLabel
            }
          }
        } : undefined
      }
    };
  }

  generateEmptyResponse(parsed) {
    return {
      text: `🔍 Aucune donnée disponible pour "${parsed.typeDonnees}"\n\n`,
      data: [],
      graphique: null,
      metadata: {
        periode: parsed.periode,
        type: parsed.typeDonnees,
        empty: true,
        timestamp: new Date().toISOString()
      }
    };
  }

  calculateSum(data, field) {
    return data.reduce((sum, item) => sum + (parseFloat(item[field]) || 0), 0);
  }

  formatNumber(num) {
    return new Intl.NumberFormat('fr-FR').format(num);
  }

  formatDate(dateStr) {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return date.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit' });
  }

  getPeriodeLabel(type) {
    const labels = {
      today: "Aujourd'hui",
      yesterday: 'Hier',
      week: 'Cette semaine',
      lastWeek: 'Semaine dernière',
      month: 'Ce mois',
      lastMonth: 'Mois dernier',
      year: 'Cette année',
      lastYear: 'Année dernière'
    };
    return labels[type] || type;
  }

  generateComparison(previousData, currentData, parsed) {
    if (!previousData || !currentData || previousData.empty || currentData.empty) {
      return null;
    }

    const prevTotal = this.calculateSum(previousData.data, 'total') || 
                     this.calculateSum(previousData.data, 'total_passagers') ||
                     this.calculateSum(previousData.data, 'nb_retards') ||
                     this.calculateSum(previousData.data, 'nombre') ||
                     this.calculateSum(previousData.data, 'effectif');

    const currTotal = this.calculateSum(currentData.data, 'total') ||
                      this.calculateSum(currentData.data, 'total_passagers') ||
                      this.calculateSum(currentData.data, 'nb_retards') ||
                      this.calculateSum(currentData.data, 'nombre') ||
                      this.calculateSum(currentData.data, 'effectif');

    const evolution = prevTotal > 0 ? ((currTotal - prevTotal) / prevTotal * 100).toFixed(1) : 0;
    const trend = evolution >= 0 ? '↑' : '↓';
    const emoji = evolution >= 0 ? '📈' : '📉';

    return {
      previous: prevTotal,
      current: currTotal,
      evolution: parseFloat(evolution),
      trend,
      emoji,
      label: `${emoji} ${trend === '↑' ? 'Hausse' : 'Baisse'} de ${Math.abs(evolution)}% vs période précédente`
    };
  }
}

module.exports = new ResponseGenerator();