// nouvelle version avec les communes dans generateDepartmentAveragesAndColors en commentaires dessous


const fs = require("fs");
const path = require("path");
const csv = require("csv-parser");

// Fonction de couleur selon le score
const getColorForScore = (score) => {
    if (score >= 0.99) return "#1a9850";
    if (score >= 0.95) return "#66bd63";
    if (score >= 0.9) return "#a6d96a";
    if (score >= 0.85) return "#d9ef8b";
    if (score >= 0.8) return "#fee08b";
    if (score >= 0.7) return "#fdae61";
    if (score >= 0.6) return "#f46d43";
    if (score >= 0.5) return "#d73027";
    if (score >= 0.4) return "#a50026";
    return "#6a3d9a";
};

// Fonction pour générer les moyennes et couleurs par département
const generateDepartmentAveragesAndColors = (scoreType, year) => {
    // Dictionnaire de correspondance scoreType -> colonne CSV
    let dictCorr = {
        "indicateurs": "score_global",
        "indicateursPH": "score_pH",
        "indicateursChlore": "score_Chlore",
        "indicateursNitritesNitrates": "score_Nitrites_Nitrates",
        "indicateursMetauxLourds": "score_Metaux_Lourds",
        "indicateursPesticides": "score_Pesticides"
    };
    let columnName = dictCorr[scoreType];

    return new Promise((resolve, reject) => {
        const filePath = path.join(__dirname, `data/sigmoid_scores_${year}.csv`);

        if (!fs.existsSync(filePath)) {
            return reject(new Error(`Fichier introuvable : sigmoid_scores_${year}.csv`));
        }

        const departmentScores = {};
        const departmentCounts = {};

        fs.createReadStream(filePath)
            .pipe(csv())
            .on('data', (row) => {
                let dept = row.cddept_x.replace('.0', '');

                if (dept.startsWith('02A') || dept.startsWith('02B')) {
                    dept = dept.substring(1);
                } else {
                    dept = dept.padStart(2, '0');
                }

                const score = parseFloat(row[columnName]);
                if (!isNaN(score)) {
                    if (!departmentScores[dept]) {
                        departmentScores[dept] = 0;
                        departmentCounts[dept] = 0;
                    }
                    departmentScores[dept] += score;
                    departmentCounts[dept]++;
                }
            })
            .on('end', () => {
                const results = {
                    averages: {},
                    exactAvg: {},
                    colors: {},
                    top5dept: [],
                    flop5dept: []
                };
                for (const dept in departmentScores) {
                    const avgScore = departmentScores[dept] / departmentCounts[dept];
                    results.exactAvg[dept] = avgScore;
                    results.averages[dept] = avgScore.toFixed(2);
                    results.colors[dept] = getColorForScore(avgScore);
                }

                // Calcul du top 5 et flop 5 des départements par moyenne
                const excludedDepts = new Set(["971", "972", "973", "974", "976", "025", "026", "027", "028", "029", "030", "031", "032", "033", "034", "035"]);

                const sortedDepts = Object.keys(results.exactAvg)
                    .filter(dept => !excludedDepts.has(dept)) // Exclure les départements spécifiés
                    .sort((a, b) => results.exactAvg[b] - results.exactAvg[a]);

                results.top5dept = sortedDepts.slice(0, 5).map(dept => ({
                    department: dept,
                    departmentName: require('./data/departments.json')[dept],
                    average: results.exactAvg[dept]
                }));
                results.flop5dept = sortedDepts.slice(-5).map(dept => ({
                    department: dept,
                    departmentName: require('./data/departments.json')[dept],
                    average: results.exactAvg[dept]
                }));
                // enlever exactAvg de results
                delete results.exactAvg;

                resolve(results);
            })
            .on('error', (err) => reject(err));
    });
};

module.exports = { generateDepartmentAveragesAndColors };