/* global window */
// ============================================================================
// MELR · Étiquetage budgétaire climat — moteur d'agrégation (window.CLIMTAG).
// ----------------------------------------------------------------------------
// Marque les lignes budgétaires selon les Rio Markers de l'OCDE (0 = non ciblé,
// 1 = significatif, 2 = principal), sur deux objectifs — ATTÉNUATION et
// ADAPTATION — avec un marqueur d'alignement CDN (Contribution déterminée au
// niveau national). Agrège en dépenses « pertinentes climat » pondérées.
//
// ⚠ AUCUNE NORME NE FAIT AUTORITÉ pour les coefficients : la méthodologie OCDE
// (Rio Markers, 2021) est le repère le plus proche, sans coefficients officiels.
// Les POIDS sont donc PARAMÉTRÉS (règle transversale n°1) : défaut « OCDE-like »
// significatif 40 % / principal 100 %, modifiables. Pour éviter le double
// comptage des lignes transversales (atténuation ET adaptation), la pertinence
// climat totale prend le poids MAXIMAL des deux objectifs ; la ventilation
// atténuation/adaptation est fournie séparément.
//
// SORTIES : alimentent PEFA-Climat CRPFM-2 (suivi des dépenses liées au climat,
// budgété) et CRPFM-14 (dépenses exécutées pour l'action climatique).
// ============================================================================

(function () {
  const num = (v) => { const n = Number(v); return v == null || v === "" || Number.isNaN(n) ? null : n; };

  // Poids par Rio Marker (part de pertinence climat). Configurable.
  const DEFAULT_WEIGHTS = { 0: 0, 1: 0.40, 2: 1.0 };

  const MARKERS = [
    { code: 0, fr: "Non ciblé",    en: "Not targeted", es: "No orientado" },
    { code: 1, fr: "Significatif", en: "Significant",  es: "Significativo" },
    { code: 2, fr: "Principal",    en: "Principal",    es: "Principal" },
  ];

  const weightOf = (weights, m) => {
    const w = weights || DEFAULT_WEIGHTS;
    const k = m == null ? 0 : m;
    return w[k] != null ? w[k] : 0;
  };

  // Agrège des lignes budgétaires étiquetées.
  // lines = [{ label, amount, executed?, mitig:0|1|2, adapt:0|1|2, ndc?:bool, sector? }]
  function aggregate(lines, weights) {
    let total = 0, executedTotal = 0, mitig = 0, adapt = 0, climate = 0, ndcAmt = 0, climExec = 0;
    for (const ln of (lines || [])) {
      const a = num(ln && ln.amount);
      if (a == null || a <= 0) continue;
      const ex = num(ln.executed) || 0;
      const wm = weightOf(weights, ln.mitig || 0);
      const wa = weightOf(weights, ln.adapt || 0);
      const wmax = Math.max(wm, wa);          // évite le double comptage transversal
      total += a; executedTotal += ex;
      mitig += a * wm; adapt += a * wa;
      climate += a * wmax; climExec += ex * wmax;
      if (ln.ndc) ndcAmt += a * wmax;
    }
    if (total <= 0) return null;
    return {
      total, executedTotal,
      mitigation:      mitig,                       // budgété pondéré (atténuation)
      adaptation:      adapt,                       // budgété pondéré (adaptation)
      climateRelevant: climate,                     // pertinence climat totale (max) → CRPFM-2
      ndcAligned:      ndcAmt,                       // part alignée CDN
      climateExecuted: climExec,                    // exécuté pondéré → CRPFM-14
      shareClimate:    climate / total,             // % du budget pertinent climat (CRPFM-2)
      shareExecuted:   executedTotal > 0 ? climExec / executedTotal : null, // % exécuté (CRPFM-14)
    };
  }

  window.CLIMTAG = { num, DEFAULT_WEIGHTS, MARKERS, weightOf, aggregate };
})();
