// lib/comparateur/calculate-comparison.ts
import type {
  CalculatorInput,
  ComparisonResult,
  ResolvedProfil,
  RecommendedContractType,
  MarketTariff,
} from "./types";
import {
  FOURNISSEURS,
  getFournisseursForProfil,
  type Fournisseur,
} from "@/data/comparateur/fournisseurs";

// Référentiel marché 2026
// Sources : CRE Q2 2026, EPEX Spot moyen 12 mois glissants, observations courtage Acieb
// À rafraîchir trimestriellement.
export const MARKET_TARIFFS_2026: Record<ResolvedProfil, MarketTariff> = {
  C5: { min: 195, max: 245, avg: 220 }, // €/MWh HTVA
  C4: { min: 165, max: 215, avg: 190 },
  C3: { min: 135, max: 185, avg: 160 },
};

export const TVA_RATE = 0.2;
export const TURPE_AVG: Record<ResolvedProfil, number> = { C5: 35, C4: 28, C3: 18 }; // €/MWh
export const TAXES_AVG = { CSPE: 25.79, CTA: 7.21 }; // €/MWh, arrêté 18/12/2025
export const SPOT_EPEX_AVG_2026 = 78; // €/MWh, moyenne 12 mois glissants approx

// Inférer le profil tarifaire d'après MWh annuels si profil = "unknown"
export function inferProfil(mwh: number): ResolvedProfil {
  if (mwh < 100) return "C5";
  if (mwh < 1500) return "C4";
  return "C3";
}

// Score adapté par fournisseur selon profil
function scoreForProfil(f: Fournisseur, profil: ResolvedProfil): number {
  // Pondérations différenciées par segment
  const weights = profil === "C5"
    ? { prix: 50, qualiteService: 25, vert: 10, multiSites: 5, expertiseB2B: 10 }
    : profil === "C4"
    ? { prix: 40, qualiteService: 20, vert: 15, multiSites: 15, expertiseB2B: 10 }
    : { prix: 35, qualiteService: 15, vert: 10, multiSites: 20, expertiseB2B: 20 };

  const s = f.scoresQualitatifs;
  const total =
    (s.prix * weights.prix +
      s.qualiteService * weights.qualiteService +
      s.vert * weights.vert +
      s.multiSites * weights.multiSites +
      s.expertiseB2B * weights.expertiseB2B) /
    100;
  return Math.round(total);
}

function recommendContract(profil: ResolvedProfil, mwh: number): {
  typeContrat: RecommendedContractType;
  rationale: string;
} {
  if (profil === "C5") {
    return {
      typeContrat: "fixe",
      rationale:
        "Pour un profil C5 (≤ 36 kVA), un contrat à prix fixe 2-3 ans capture les prix marché actuels et offre la meilleure visibilité budgétaire. La prime de risque payée est compensée par la stabilité.",
    };
  }
  if (profil === "C4") {
    return {
      typeContrat: "hybride",
      rationale:
        "Pour un profil C4 (36-250 kVA) consommant " + mwh + " MWh/an, une offre hybride (50% fixe + 50% indexé Spot ou ARENH) optimise le ratio risque/économies. Idéal pour PME/PMI prêtes à un suivi mensuel.",
    };
  }
  return {
    typeContrat: "sur-mesure",
    rationale:
      "Pour un profil C3 (>250 kVA) à " + mwh + " MWh/an, une stratégie d'achat par clics/tranches sur un marché à terme (calendar EEX) maximise les opportunités de baisse. Un courtier avec accès direct aux salles de marché devient essentiel.",
  };
}

export function calculateComparison(input: CalculatorInput): ComparisonResult {
  const inferredProfil: ResolvedProfil =
    input.profil === "unknown"
      ? inferProfil(input.consommationMwh)
      : input.profil;

  const tariff = MARKET_TARIFFS_2026[inferredProfil];
  const turpe = TURPE_AVG[inferredProfil];
  const taxesPerMwh = TAXES_AVG.CSPE + TAXES_AVG.CTA;

  // Budget annuel TTC = (fourniture + TURPE + taxes) × MWh × (1 + TVA)
  const minHt = (tariff.min + turpe + taxesPerMwh) * input.consommationMwh;
  const maxHt = (tariff.max + turpe + taxesPerMwh) * input.consommationMwh;
  const budgetEstimate = {
    min: Math.round(minHt * (1 + TVA_RATE)),
    max: Math.round(maxHt * (1 + TVA_RATE)),
  };

  // Économies — vs contrat actuel ou vs tarif marché moyen
  let savingsRange: { min: number; max: number };
  if (input.contratActuel) {
    const prixActuelMwhHtva = input.contratActuel.prixKwhHtva * 1000; // kWh → MWh
    const economiesMin = Math.max(0, (prixActuelMwhHtva - tariff.max) * input.consommationMwh);
    const economiesMax = Math.max(0, (prixActuelMwhHtva - tariff.min) * input.consommationMwh);
    savingsRange = { min: Math.round(economiesMin * (1 + TVA_RATE)), max: Math.round(economiesMax * (1 + TVA_RATE)) };
  } else {
    // vs tarif moyen marché
    const economiesMax = (tariff.avg - tariff.min) * input.consommationMwh * (1 + TVA_RATE);
    savingsRange = { min: 0, max: Math.round(economiesMax) };
  }

  // Ranking fournisseurs
  const candidats = getFournisseursForProfil(inferredProfil);
  const ranked = candidats
    .map((f) => ({
      id: f.id,
      score: scoreForProfil(f, inferredProfil),
      pros: f.forces,
      cons: f.faiblesses,
      estimatedAnnualPrice: Math.round(
        (f.prixUnitaire[inferredProfil] + turpe + taxesPerMwh) *
          input.consommationMwh *
          (1 + TVA_RATE)
      ),
    }))
    .sort((a, b) => b.score - a.score)
    .slice(0, 5);

  return {
    inferredProfil,
    budgetEstimate,
    savingsRange,
    rankedFournisseurs: ranked,
    recommendation: recommendContract(inferredProfil, input.consommationMwh),
    marketContext: {
      spotEpexAvg: SPOT_EPEX_AVG_2026,
      turpeApprox: turpe,
      taxesApprox: taxesPerMwh,
    },
  };
}

const EUROS_FORMATTER = new Intl.NumberFormat("fr-FR", {
  style: "currency",
  currency: "EUR",
  maximumFractionDigits: 0,
});

export function formatEuros(value: number): string {
  return EUROS_FORMATTER.format(value);
}
