# -*- coding: utf-8 -*-
"""
Observatoire des Carrières Enseignantes (1950–2026+)
====================================================
Reconstitution historique, année par année, de la rémunération totale sur cycle de vie
(salaires + pensions, en euros constants de 2026, nets avant IR ET super-nets après IR)
pour deux corps de l'enseignement secondaire en France :
  1. Professeur agrégé (15 h de cours/semaine, soit 540 h/an)
  2. Professeur certifié / CAPES (18 h de cours/semaine, soit 648 h/an)

Cohortes simulées :
  - Grille quinquennale (1950, 1955, ..., 2015 — 14 cohortes)
  - Grille annuelle intégrale (1950 à 2015 — 66 cohortes)
  (Âge d'entrée : 24 ans, service plein sans HSA, carrière complète sans interruption,
   avancement moyen, accès à la Hors Classe dès sa création, exclusion de la Classe Exceptionnelle.)

Entrées : series_historiques.csv, baremes_ir_historiques.json
Sorties : resultats_agreges.csv, resultats_certifies.csv,
          resultats_annuels_agreges_1950_2015.csv, resultats_annuels_certifies_1950_2015.csv,
          01_cumul_vie_agreges_vs_certifies.png,
          02_gain_horaire_cours.png,
          03_ecart_agrege_certifie.png,
          04_infographie_choc_vie_entiere.png,
          05_trajectoire_annuelle_supernet_ir.png
"""

from pathlib import Path
import json
import math
import os
import tempfile
import numpy as np
import pandas as pd

os.environ.setdefault("MPLCONFIGDIR", tempfile.gettempdir())
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.patches import FancyBboxPatch, Rectangle

# ---------------------------------------------------------------------------
# 1. CONSTANTES, HYPOTHÈSES STRUCTURELLES ET PARAMÈTRES FISCAUX (IR 1950–2026)
# ---------------------------------------------------------------------------
BASE_DIR = Path(__file__).resolve().parent
SERIES_CSV = BASE_DIR / "series_historiques.csv"
IR_JSON = BASE_DIR / "baremes_ir_historiques.json"

COHORTES = list(range(1950, 2020, 5))     # 1950, 1955, ..., 2015 (14 cohortes)
COHORTES_ANNUELLES = list(range(1950, 2016))  # 1950 à 2015 année par année (66 cohortes)
AGE_ENTREE = 24
HEURES_ANNUELLES = {
    "agrege": 540.0,   # 15 h/semaine x 36 semaines
    "certifie": 648.0, # 18 h/semaine x 36 semaines
}
HEURES_ETP = 1607.0    # Base annuelle légale équivalent temps plein (FP)

with open(IR_JSON, encoding="utf-8") as _f:
    _IR_RAW = json.load(_f)
IR_PAR_ANNEE = _IR_RAW["ir_par_annee"]
INSEE_E65_ENSEMBLE_HF = {int(k): float(v) for k, v in _IR_RAW["insee_e65_ensemble_hf"].items()}


def trimestres_et_age_legal(annee_naissance: int) -> tuple[int, float]:
    """
    Durée de cotisation requise (en trimestres) pour le taux plein (75 %) et âge légal
    d'ouverture des droits par année de naissance (générations 1926 à 2005).
    Sources : Barèmes IPP (TRIMTP-FP), Loi 2003-775 (Fillon), Loi 2010-1330 (Woerth),
              Loi 2014-40 (Touraine), Loi 2023-270 (réforme des retraites 2023).
    """
    by = annee_naissance
    if by <= 1943:
        return 150, 60.0    # 37,5 ans (avant loi Fillon 2003)
    if by == 1944:
        return 152, 60.0    # 38,0 ans
    if by == 1945:
        return 154, 60.0    # 38,5 ans
    if by == 1946:
        return 156, 60.0    # 39,0 ans
    if by == 1947:
        return 158, 60.0    # 39,5 ans
    if by == 1948:
        return 160, 60.0    # 40,0 ans
    if by == 1949:
        return 161, 60.0    # 40,25 ans
    if by == 1950:
        return 162, 60.0    # 40,5 ans
    if by == 1951:
        return 163, 60.2    # 40,75 ans (Woerth)
    if by == 1952:
        return 164, 60.75   # 41,0 ans
    if by == 1953:
        return 165, 61.2    # 41,25 ans
    if by == 1954:
        return 165, 61.6    # 41,25 ans
    if by in (1955, 1956, 1957):
        return 166, 62.0    # 41,5 ans (Touraine)
    if by in (1958, 1959, 1960):
        return 167, 62.0    # 41,75 ans
    if by == 1961:
        return 168, 62.25   # 42,0 ans (Touraine / Borne)
    if by == 1962:
        return 169, 62.5    # 42,25 ans
    if by == 1963:
        return 170, 62.75   # 42,5 ans
    if by == 1964:
        return 171, 63.0    # 42,75 ans
    if by == 1965:
        return 172, 63.25   # 43,0 ans (Borne 2023 : 172 trim dès gén. 1965)
    if by == 1966:
        return 172, 63.5
    if by == 1967:
        return 172, 63.75
    return 172, 64.0


def esperance_vie_retraite_cadre_fp(annee_naissance: int, age_depart: float) -> float:
    """
    Calcule l'espérance de vie résiduelle à l'âge effectif de départ à la retraite
    pour un cadre de la fonction publique (moyenne H/F) :
      - Socle générationnel e_65(Ensemble H/F) : INSEE Première n° 1927 (ip1927.xlsx, Fig. 3).
      - Sur-longévité des cadres de la fonction publique vs Ensemble à 65 ans :
        +1,92 an (INSEE Première n° 2005, juil. 2024, ip2005.xlsx Tableaux compl. 1 & 2).
      - Translation d'âge (de 65 ans vers age_depart) issue de la table de survie
        des cadres (ip2005.xlsx) : +0,89 an par année d'écart avant 65 ans,
        et gradient de sur-longévité sociale de +0,07 an par année avant 65 ans.
    """
    e65_ens = INSEE_E65_ENSEMBLE_HF[annee_naissance]
    ecart_age = 65.0 - age_depart
    prime_cadre_fp = 1.92 + 0.07 * ecart_age
    e_depart = e65_ens + 0.89 * ecart_age + prime_cadre_fp
    return round(e_depart, 2)


def calcul_ir_annuel_eur(rev_net_imposable_eur: float, annee: int, est_pension: bool = False) -> float:
    """
    Calcule l'impôt sur le revenu annuel (en EUR courants de l'année si <=2026,
    ou en EUR constants de 2026 si >2026 sous hypothèse d'indexation du barème 2026
    sur l'inflation) pour un contribuable célibataire sans enfant (1 part fiscale).
    Remarque : le taux moyen d'IR est strictement identique pour un couple marié/pacsé
    de deux enseignants percevant le même revenu (2 parts fiscales).

    Intègre les paramètres officiels OpenFisca-France / Barèmes IPP / LF 2026 / PLF 2027 :
      - Abattement 10 % pour frais professionnels (salaires) et abattement 10 % pensions (dès 1977)
      - Abattement supplémentaire historique (10 % en 1953, 15 % 1954-58, 19 % 1959, 20 % 1960-2005)
      - Barème progressif annuel 1950–2026
      - Décote célibataire 1 part (1981–2026)
      - Minorations exceptionnelles (1966–1972 et 1984–1992, intégrées au barème en 1993)
      - Majorations exceptionnelles (1955–1965 décime/demi-décime, 1967–1971, 1980–1984).
    """
    if rev_net_imposable_eur <= 0.0:
        return 0.0

    y_ref = min(annee, 2026)
    cfg = IR_PAR_ANNEE[str(y_ref)]

    # 1. Abattement 10 % (frais pro salaires / abattement pensions dès 1977)
    if not est_pension:
        ab10 = rev_net_imposable_eur * cfg["abatpro_taux"]
        if cfg["abatpro_min_eur"] is not None:
            ab10 = max(ab10, min(cfg["abatpro_min_eur"], rev_net_imposable_eur))
        if cfg["abatpro_max_eur"] is not None:
            ab10 = min(ab10, cfg["abatpro_max_eur"])
    else:
        if cfg["abatpen_taux"] > 0.0:
            ab10 = rev_net_imposable_eur * cfg["abatpen_taux"]
            if cfg["abatpen_min_eur"] is not None:
                ab10 = max(ab10, min(cfg["abatpen_min_eur"], rev_net_imposable_eur))
            if cfg["abatpen_max_eur"] is not None:
                ab10 = min(ab10, cfg["abatpen_max_eur"])
        else:
            ab10 = 0.0

    r_apres_10 = max(0.0, rev_net_imposable_eur - ab10)

    # 2. Abattement supplémentaire historique (1953–2005)
    t_supp = cfg["abat_supp_taux"]
    if t_supp > 0.0:
        ab20 = r_apres_10 * t_supp
        if cfg["abat_supp_max_eur"] is not None:
            ab20 = min(ab20, cfg["abat_supp_max_eur"])
        rni = max(0.0, r_apres_10 - ab20)
    else:
        rni = r_apres_10

    # 3. Barème progressif (1 part)
    tranches = cfg["tranches_eur"]
    ir_brut = 0.0
    for i in range(len(tranches)):
        lo, rate = tranches[i]
        hi = tranches[i + 1][0] if i + 1 < len(tranches) else float("inf")
        if rni > lo:
            ir_brut += (min(rni, hi) - lo) * rate

    # 4. Décote (1 part, 1981–2026+)
    seuil = cfg["decote_seuil_1part_eur"]
    t_dec = cfg["decote_taux"]
    if seuil is not None and t_dec is not None and ir_brut > 0.0:
        dec = max(0.0, seuil - t_dec * ir_brut)
        ir_net = max(0.0, ir_brut - dec)
    else:
        ir_net = ir_brut

    # 5. Minorations exceptionnelles historiques (OpenFisca / IPP)
    m = cfg["minoration"]
    if m is not None and ir_net > 0.0:
        if y_ref in (1966, 1967):
            s2, s3, s4 = m["s2"], m["s3"], m["s4"]
            t1, t5 = m["t1"], m["t5"]
            if rni <= s2:
                ir_net *= (1.0 - t1)
            elif rni <= s3:
                frac = (rni - s2) / (s3 - s2)
                ir_net *= (1.0 - (t1 - frac * (t1 - t5)))
            elif rni <= s4:
                ir_net *= (1.0 - t5)
        elif 1968 <= y_ref <= 1972:
            s2, s3, s4 = m["s2"], m["s3"], m["s4"]
            t1, t5 = m["t1"], m["t5"]
            if ir_net <= s2:
                ir_net *= (1.0 - t1)
            elif ir_net <= s3:
                frac = (ir_net - s2) / (s3 - s2)
                ir_net *= (1.0 - (t1 - frac * (t1 - t5)))
            elif ir_net <= s4:
                ir_net *= (1.0 - t5)
        elif y_ref == 1984:
            s2 = m["s2"]
            s_mid = s2 * 1.25
            s_hi = 32080.0 / 6.55957
            if ir_net <= s2:
                ir_net *= 0.95
            elif ir_net <= s_mid:
                frac = (ir_net - s2) / (s_mid - s2)
                ir_net *= (1.0 - (0.05 - 0.02 * frac))
            elif ir_net <= s_hi:
                ir_net *= 0.97
        elif y_ref == 1985:
            s2, s3, s4 = m["s2"], m["s3"], m["s4"]
            if ir_net <= s2:
                ir_net *= (1.0 - m["t1"])
            elif ir_net <= s3:
                min_amt = max(0.0, m["f2"] - m["ft"] * ir_net)
                ir_net = max(0.0, ir_net - min_amt)
            elif ir_net <= s4:
                ir_net *= (1.0 - m["t3"])
        elif 1986 <= y_ref <= 1992:
            s2, s3, s4, s5 = m["s2"], m["s3"], m["s4"], m["s5"]
            if ir_net <= s2:
                ir_net *= (1.0 - m["t1"])
            elif ir_net <= s3:
                min_amt = max(0.0, m["f2"] - m["ft"] * ir_net)
                ir_net = max(0.0, ir_net - min_amt)
            elif ir_net <= s4:
                ir_net *= (1.0 - m["t3"])
            elif ir_net <= s5:
                min_amt = max(0.0, m["f4"] - m["ft"] * ir_net)
                ir_net = max(0.0, ir_net - min_amt)
            elif m["rni_sup"] is None or rni <= m["rni_sup"]:
                ir_net *= (1.0 - m["t5"])

    # 6. Majorations exceptionnelles historiques (OpenFisca / IPP)
    mj = cfg["majoration"]
    if mj is not None and ir_net > 0.0:
        if 1955 <= y_ref <= 1965:
            if mj["srev"] is not None and rni > mj["srev"]:
                ir_net *= (1.0 + mj["t1"])
        elif y_ref == 1967:
            if ir_net > mj["s3"]:
                ir_net *= (1.0 + mj["t3"])
            elif ir_net > mj["s2"]:
                ir_net *= (1.0 + 0.15)
            elif ir_net > mj["s1"]:
                ir_net *= (1.0 + mj["t1"])
        elif y_ref in (1968, 1969):
            if ir_net > mj["s3"]:
                ir_net *= (1.0 + mj["t3"])
            elif ir_net > mj["s2"]:
                ir_net *= (1.0 + mj["t2"])
            elif ir_net > mj["s1"]:
                frac = (ir_net - mj["s1"]) / (mj["s2"] - mj["s1"])
                ir_net *= (1.0 + mj["t1"] + frac * (mj["t2"] - mj["t1"]))
        elif y_ref in (1970, 1971):
            if mj["s3"] is not None and ir_net > mj["s3"]:
                ir_net *= (1.0 + mj["t3"])
            elif mj["s2"] is not None and ir_net > mj["s2"]:
                ir_net *= (1.0 + mj["t2"])
            elif mj["s1"] is not None and ir_net > mj["s1"]:
                ir_net *= (1.0 + mj["t1"])
        elif y_ref == 1980:
            if ir_net > mj["s1"]:
                ir_net += (ir_net - mj["s1"]) * mj["t1"]
        elif y_ref == 1981:
            if ir_net > (25000.0 / 6.55957):
                ir_net += max(0.0, ir_net - (15000.0 / 6.55957)) * 0.10
        elif y_ref == 1982:
            if ir_net > mj["s1"]:
                ir_net += (ir_net - mj["s1"]) * mj["t1"]
        elif y_ref == 1983:
            if ir_net > mj["s2"]:
                ir_net *= (1.0 + mj["t2"])
            elif ir_net > mj["s1"]:
                ir_net *= (1.0 + mj["t1"])
        elif y_ref == 1984:
            if ir_net > mj["s1"]:
                ir_net *= (1.0 + mj["t1"])

    return ir_net


# ---------------------------------------------------------------------------
# 2. GRILLES INDICIAIRES HISTORIQUES (1950–2026+) ET PROGRESSION DE CARRIÈRE
# ---------------------------------------------------------------------------
SEUILS_CN_PRE_PPCR = [0.0, 0.25, 1.0, 2.0, 4.0, 6.5, 9.5, 12.5, 16.0, 20.0, 24.5]
SEUILS_CN_PPCR = [0.0, 1.0, 2.0, 4.0, 6.0, 8.5, 11.5, 14.5, 18.0, 22.0, 26.0]
SEUIL_ACCES_HC = 27.0

AGREGE_IB_1950 = [370, 440, 510, 565, 620, 680, 740, 795, 860, 930, 1000]
CERTIFIE_IB_1950 = [300, 345, 405, 450, 490, 530, 575, 625, 680, 735, 785]

AGREGE_IM_1982 = [356, 405, 459, 495, 534, 577, 619, 658, 703, 750, 821]
CERTIFIE_IM_1982 = [320, 349, 385, 412, 435, 458, 488, 524, 560, 608, 658]

AGREGE_IM_1989 = [379, 436, 489, 526, 561, 593, 635, 684, 734, 783, 821]
CERTIFIE_IM_1989 = [349, 376, 432, 445, 458, 467, 495, 531, 567, 612, 658]

AGREGE_IM_2020 = [450, 498, 513, 542, 579, 618, 659, 710, 757, 800, 830]
CERTIFIE_IM_2020 = [390, 441, 448, 461, 476, 492, 519, 557, 590, 629, 673]

AGREGE_IM_2024 = [455, 503, 518, 547, 584, 623, 664, 715, 762, 805, 835]
CERTIFIE_IM_2024 = [395, 446, 453, 466, 481, 497, 524, 562, 595, 634, 678]

AGREGE_HC_DUREES = [3.0, 1.0, 1.0, 99.0]
AGREGE_HC_IM_1982 = [821, 881, 916, 963]
AGREGE_HC_IM_2020 = [830, 890, 925, 972]
AGREGE_HC_IM_2024 = [835, 895, 930, 977]

CERTIFIE_HC_PRE_PPCR_DUREES = [3.0, 3.0, 99.0]
CERTIFIE_HC_PRE_PPCR_IM = [695, 741, 783]
CERTIFIE_HC_PPCR_DUREES = [3.0, 3.0, 3.0, 99.0]
CERTIFIE_HC_PPCR_IM_2020 = [715, 763, 785, 821]
CERTIFIE_HC_PPCR_IM_2024 = [720, 768, 790, 826]


def echelon_cn_depuis_anciennete(anciennete: float, annee: int) -> int:
    seuils = SEUILS_CN_PPCR if annee >= 2017 else SEUILS_CN_PRE_PPCR
    ech = 1
    for i, s in enumerate(seuils):
        if anciennete >= s:
            ech = i + 1
    return ech


def indice_effectif(corps: str, annee: int, anciennete: float,
                    facteur_echelle_in: float, taux_ir: float) -> tuple[float, int, bool]:
    hc_existe = (corps == "agrege" and annee >= 1978) or (corps == "certifie" and annee >= 1989)
    est_hc = hc_existe and (anciennete >= SEUIL_ACCES_HC)

    if not est_hc:
        ech = echelon_cn_depuis_anciennete(anciennete, annee)
        idx = ech - 1

        if annee <= 1981:
            ib_list = AGREGE_IB_1950 if corps == "agrege" else CERTIFIE_IB_1950
            im82_list = AGREGE_IM_1982 if corps == "agrege" else CERTIFIE_IM_1982
            ib = float(ib_list[idx])
            if corps == "agrege" and idx == 10 and annee >= 1977:
                ib = 1015.0
            if corps == "certifie" and idx == 10 and annee >= 1978:
                ib = 801.0

            if annee <= 1960:
                return ib, ech, False
            elif annee in (1961, 1962):
                return 0.76 * ib * facteur_echelle_in, ech, False
            elif annee <= 1967:
                return 0.76 * ib, ech, False
            else:
                alpha = max(0.0, min(1.0, (0.20 - taux_ir) / (0.20 - 0.03)))
                in_67 = 0.76 * ib
                im_82 = float(im82_list[idx])
                return in_67 + alpha * (im_82 - in_67), ech, False

        elif annee <= 1988:
            im = AGREGE_IM_1982[idx] if corps == "agrege" else CERTIFIE_IM_1982[idx]
            return float(im), ech, False
        elif annee <= 2016:
            im = AGREGE_IM_1989[idx] if corps == "agrege" else CERTIFIE_IM_1989[idx]
            return float(im), ech, False
        elif annee <= 2019:
            w = {2017: 1.0 / 3.0, 2018: 0.5, 2019: 0.75}[annee]
            im_old = AGREGE_IM_1989[idx] if corps == "agrege" else CERTIFIE_IM_1989[idx]
            im_new = AGREGE_IM_2020[idx] if corps == "agrege" else CERTIFIE_IM_2020[idx]
            return im_old + w * (im_new - im_old), ech, False
        elif annee <= 2023:
            im = AGREGE_IM_2020[idx] if corps == "agrege" else CERTIFIE_IM_2020[idx]
            return float(im), ech, False
        else:
            im = AGREGE_IM_2024[idx] if corps == "agrege" else CERTIFIE_IM_2024[idx]
            return float(im), ech, False

    annee_creation_hc = 1978 if corps == "agrege" else 1989
    annee_entree_approx = annee - anciennete
    anc_entree_hc = max(SEUIL_ACCES_HC, annee_creation_hc - annee_entree_approx)
    anc_hc = max(0.0, anciennete - anc_entree_hc)

    if corps == "agrege":
        cum = 0.0
        pos = 0
        for i, d in enumerate(AGREGE_HC_DUREES):
            if anc_hc >= cum:
                pos = i
            cum += d

        if annee <= 1981:
            alpha = max(0.0, min(1.0, (0.20 - taux_ir) / (0.20 - 0.03)))
            im_82 = float(AGREGE_HC_IM_1982[pos])
            im_67_eq = im_82 * (760.0 / 810.0)
            return im_67_eq + alpha * (im_82 - im_67_eq), 0, True
        elif annee <= 2016:
            return float(AGREGE_HC_IM_1982[pos]), 0, True
        elif annee <= 2019:
            w = {2017: 1.0 / 3.0, 2018: 0.5, 2019: 0.75}[annee]
            return AGREGE_HC_IM_1982[pos] + w * (AGREGE_HC_IM_2020[pos] - AGREGE_HC_IM_1982[pos]), 0, True
        elif annee <= 2023:
            return float(AGREGE_HC_IM_2020[pos]), 0, True
        else:
            return float(AGREGE_HC_IM_2024[pos]), 0, True

    else:
        if annee <= 2016:
            cum = 0.0
            pos = 0
            for i, d in enumerate(CERTIFIE_HC_PRE_PPCR_DUREES):
                if anc_hc >= cum:
                    pos = i
                cum += d
            im = CERTIFIE_HC_PRE_PPCR_IM[pos]
            if annee <= 1992:
                im = min(im, 741)
            return float(im), 0, True
        else:
            cum = 0.0
            pos = 0
            for i, d in enumerate(CERTIFIE_HC_PPCR_DUREES):
                if anc_hc >= cum:
                    pos = i
                cum += d
            if annee <= 2019:
                w = {2017: 1.0 / 3.0, 2018: 0.5, 2019: 0.75}[annee]
                old_im = CERTIFIE_HC_PRE_PPCR_IM[min(pos, 2)]
                new_im = min(CERTIFIE_HC_PPCR_IM_2020[pos], 785)
                return old_im + w * (new_im - old_im), 0, True
            elif annee == 2020:
                return float(min(CERTIFIE_HC_PPCR_IM_2020[pos], 785)), 0, True
            elif annee <= 2023:
                return float(CERTIFIE_HC_PPCR_IM_2020[pos]), 0, True
            else:
                return float(CERTIFIE_HC_PPCR_IM_2024[pos]), 0, True


# ---------------------------------------------------------------------------
# 3. PRIME D'ATTRACTIVITÉ (2021–2026+, Décrets 2021-276 & 2023-627)
# ---------------------------------------------------------------------------
PRIME_ATT_2021 = {2: 1400, 3: 1250, 4: 900, 5: 700, 6: 500, 7: 500}
PRIME_ATT_2022 = {2: 2200, 3: 2050, 4: 1500, 5: 1100, 6: 900, 7: 900, 8: 400, 9: 400}
PRIME_ATT_2023 = {1: 2130, 2: 2980, 3: 3370, 4: 3180, 5: 2880, 6: 2500, 7: 1500, 8: 400, 9: 400}


def prime_attractivite_eur_courant(annee: int, ech_cn: int, est_hc: bool) -> float:
    if est_hc or ech_cn <= 0 or annee < 2021:
        return 0.0
    if annee == 2021:
        return PRIME_ATT_2021.get(ech_cn, 0.0) * (8.0 / 12.0)
    elif annee == 2022:
        return (PRIME_ATT_2021.get(ech_cn, 0.0) + 11.0 * PRIME_ATT_2022.get(ech_cn, 0.0)) / 12.0
    elif annee == 2023:
        return (8.0 * PRIME_ATT_2022.get(ech_cn, 0.0) + 4.0 * PRIME_ATT_2023.get(ech_cn, 0.0)) / 12.0
    else:
        return float(PRIME_ATT_2023.get(ech_cn, 0.0))


# ---------------------------------------------------------------------------
# 4. MOTEUR DE SIMULATION COHORTE PAR COHORTE (AVANT IR + SUPER-NET APRÈS IR)
# ---------------------------------------------------------------------------
def simuler_carriere(df_hist: pd.DataFrame, corps: str, annee_entree: int,
                     g_override: float | None = None) -> dict:
    """
    Simule l'intégralité de la vie professionnelle et de la retraite d'une cohorte.
    Calcule simultanément les flux nets avant impôt sur le revenu (IR) et les flux
    super-nets après IR (célibataire 1 part / couple de 2 enseignants à 2 parts),
    tous exprimés en euros constants de 2026.
    """
    hist = df_hist.set_index("annee").to_dict("index")
    row_2026 = hist[2026]
    pt_real_2026 = row_2026["valeur_point_reel_2026_equiv_im"]

    annee_naissance = annee_entree - AGE_ENTREE
    trim_req, age_legal = trimestres_et_age_legal(annee_naissance)
    duree_carriere = trim_req / 4.0
    age_depart = AGE_ENTREE + duree_carriere
    annee_depart_exact = annee_entree + duree_carriere
    ev_retraite = esperance_vie_retraite_cadre_fp(annee_naissance, age_depart)

    # Taux annuel moyen d'évolution réelle du point d'indice subi par CETTE cohorte
    if g_override is not None:
        g_point_reel = g_override
    elif annee_depart_exact > 2026.0 and annee_entree < 2026:
        pt_real_entree = hist[annee_entree]["valeur_point_reel_2026_equiv_im"]
        n_obs = 2026 - annee_entree
        g_point_reel = (pt_real_2026 / pt_real_entree) ** (1.0 / n_obs) - 1.0
    else:
        g_point_reel = 0.0

    def get_params_annee(y: int) -> dict:
        if y <= 2026:
            return hist[y]
        facteur_post = (1.0 + g_point_reel) ** (y - 2026)
        p = dict(row_2026)
        p["ipc_base_2026"] = 100.0
        p["coeff_euro_2026"] = 1.0
        p["valeur_point_eur_courant"] = row_2026["valeur_point_eur_courant"] * facteur_post
        p["valeur_point_reel_2026_equiv_im"] = pt_real_2026 * facteur_post
        p["isoe_fixe_eur_courant"] = row_2026["isoe_fixe_eur_courant"] * facteur_post
        p["abattement_tpp_eur_courant"] = row_2026["abattement_tpp_eur_courant"]
        p["rafp_val_acquisition_eur"] = row_2026["rafp_val_acquisition_eur"]
        p["rafp_val_service_eur"] = row_2026["rafp_val_service_eur"]
        p["_facteur_primes_post2026"] = facteur_post
        return p

    # --- PHASE 1 : ACTIVITÉ ---
    n_annees_pleines = int(math.floor(duree_carriere))
    frac_derniere = duree_carriere - n_annees_pleines

    total_salaires_net_2026 = 0.0
    total_ir_salaires_2026 = 0.0
    points_rafp_cumules = 0.0
    tib_terminal_2026 = 0.0

    tranches_actives = [(annee_entree + k, k, 1.0) for k in range(n_annees_pleines)]
    if frac_derniere > 1e-9:
        tranches_actives.append(
            (annee_entree + n_annees_pleines, n_annees_pleines, frac_derniere)
        )

    # Bonification d'ancienneté Chatel (+1 an dès l'entrée en 2010–2013, Décret 2010-1006 :
    # stage temps plein directement classé à l'échelon 3)
    bonus_anc_chatel = 1.0 if 2010 <= annee_entree <= 2013 else 0.0

    for y, k_an, poids in tranches_actives:
        p = get_params_annee(y)
        coeff26 = p["coeff_euro_2026"]

        # --- MODÉLISATION EXACTE DE L'ANNÉE DE STAGE (k_an == 0) ---
        # Avant PPCR (1950–2016, hors bonification Chatel 2010–2013) : 3 mois à l'échelon 1
        # (anc 0,0–0,25) + 9 mois à l'échelon 2 (anc 0,25–1,0), Décrets 72-580 & 72-581.
        # Depuis PPCR (2017–2026) : 12 mois entiers à l'échelon 1.
        if k_an == 0 and annee_entree <= 2016 and bonus_anc_chatel == 0.0:
            sous_tranches = [(0.125, 0.25), (0.625, 0.75)]
        elif k_an == 0 and bonus_anc_chatel > 0.0:
            # Stage Chatel 2010–2013 : bonification +1 an -> échelon 3 dès le stage
            sous_tranches = [(1.5, 1.0)]
        else:
            anc_mid = k_an + (0.5 * poids) + bonus_anc_chatel
            sous_tranches = [(anc_mid, 1.0)]

        # Proratisation réglementaire de l'ISOE part fixe durant l'année de stage (Décret 93-55) :
        # - 1993–2009 (IUFM / PLC2 ~6 h/18 h) : 1/3
        # - 2010–2013 (Chatel temps plein)    : 100 %
        # - 2014–2021 (ESPE/INSPÉ mi-temps)   : 50 %
        # - 2022–2026 (stage M2 temps plein)  : 100 %
        if k_an == 0:
            if 1993 <= annee_entree <= 2009:
                quotite_isoe = 1.0 / 3.0
            elif 2014 <= annee_entree <= 2021:
                quotite_isoe = 0.50
            else:
                quotite_isoe = 1.0
        else:
            quotite_isoe = 1.0

        tib = 0.0
        ir_zone = 0.0
        isoe = 0.0
        p_att = 0.0
        for anc_st, w_st in sous_tranches:
            ind_mult, ech_cn, est_hc = indice_effectif(
                corps, y, anc_st, p["facteur_echelle_in_equiv"], p["taux_ir_zone1"]
            )
            tib_st = ind_mult * p["valeur_point_eur_courant"]
            tib += w_st * tib_st
            ir_zone += w_st * (tib_st * p["taux_ir_zone1"])
            isoe += w_st * (p["isoe_fixe_eur_courant"] * quotite_isoe)
            # Prime d'attractivité : stagiaires exclus avant sept. 2023 (ouverte éch. 1 au 01/09/2023)
            if k_an == 0 and y < 2023:
                pa_st = 0.0
            else:
                pa_st = prime_attractivite_eur_courant(y, ech_cn, est_hc)
            if y > 2026:
                pa_st *= p["_facteur_primes_post2026"]
            p_att += w_st * pa_st

        abatt_tpp = p["abattement_tpp_eur_courant"]

        brut_avant_ic = tib + ir_zone + isoe + p_att + abatt_tpp
        ind_comp_csg = brut_avant_ic * p["taux_ind_comp_csg"]
        brut_total = brut_avant_ic + ind_comp_csg

        ret_pc = tib * p["taux_retenue_pc"]
        maladie_sp = min(tib, p["pss_annuel_eur_courant"]) * p["taux_maladie_actif_sous_pss"]
        maladie_tt = tib * p["taux_maladie_actif_tout"]
        maladie = maladie_sp + maladie_tt

        assiette_ces = max(0.0, min(brut_total - ret_pc - maladie, 4.0 * p["pss_annuel_eur_courant"]))
        ces = assiette_ces * p["taux_ces_solidarite"]

        primes_rafp = max(0.0, ir_zone + isoe + p_att + ind_comp_csg + abatt_tpp)
        assiette_rafp = min(primes_rafp, 0.20 * tib)
        rafp_sal = assiette_rafp * p["taux_rafp_salarie"]
        if y >= 2005 and p["rafp_val_acquisition_eur"] > 0:
            points_rafp_cumules += (0.10 * assiette_rafp * poids) / p["rafp_val_acquisition_eur"]

        assiette_csg = brut_total * (1.0 - p["abattement_csg_actif"])
        csg = assiette_csg * p["taux_csg_actif"]
        crds = assiette_csg * p["taux_crds_actif"]

        salaire_net_y = brut_total - ret_pc - maladie - ces - rafp_sal - csg - crds
        # Revenu net imposable = salaire net + CSG non déductible + CRDS
        t_csg_nd = IR_PAR_ANNEE[str(min(y, 2026))]["csg_non_deductible"]
        net_imposable_y = salaire_net_y + assiette_csg * t_csg_nd + crds
        ir_sal_y = calcul_ir_annuel_eur(net_imposable_y, y, est_pension=False)

        total_salaires_net_2026 += salaire_net_y * coeff26 * poids
        total_ir_salaires_2026 += ir_sal_y * coeff26 * poids
        tib_terminal_2026 = tib * coeff26

    # --- PHASE 2 : RETRAITE ---
    pension_base_brut_init_2026 = 0.75 * tib_terminal_2026

    y_dep_int = int(math.floor(annee_depart_exact))
    p_dep = get_params_annee(y_dep_int)
    vs_dep_2026 = p_dep["rafp_val_service_eur"] * p_dep["coeff_euro_2026"] if y_dep_int >= 2005 else 0.0
    delai_age = max(0.0, age_depart - age_legal)
    coeff_maj_rafp = min(1.13, 1.0 + 0.04 * delai_age)
    pension_rafp_brut_2026 = points_rafp_cumules * vs_dep_2026 * coeff_maj_rafp

    pt_real_dep = p_dep["valeur_point_reel_2026_equiv_im"]
    pt_real_2003 = hist[2003]["valeur_point_reel_2026_equiv_im"]

    t_debut_ret = annee_depart_exact
    t_fin_ret = annee_depart_exact + ev_retraite
    y_curr = int(math.floor(t_debut_ret))

    total_retraite_net_2026 = 0.0
    total_rafp_net_2026 = 0.0
    total_ir_retraite_2026 = 0.0

    while y_curr < t_fin_ret - 1e-9:
        seg_start = max(t_debut_ret, float(y_curr))
        seg_end = min(t_fin_ret, float(y_curr + 1))
        w_ret = seg_end - seg_start
        if w_ret > 1e-9:
            py = get_params_annee(y_curr)
            coeff26 = py["coeff_euro_2026"]
            if y_curr <= 2003:
                pen_base_brut = pension_base_brut_init_2026 * (
                    py["valeur_point_reel_2026_equiv_im"] / pt_real_dep
                )
            elif annee_depart_exact < 2004.0:
                pen_base_brut = pension_base_brut_init_2026 * (pt_real_2003 / pt_real_dep)
            else:
                pen_base_brut = pension_base_brut_init_2026

            taux_prel_ret = (
                py["taux_maladie_retraite"]
                + py["taux_csg_retraite"]
                + py["taux_crds_retraite"]
                + py["taux_casa_retraite"]
            )
            pen_base_nette = pen_base_brut * (1.0 - taux_prel_ret)
            pen_rafp_nette = pension_rafp_brut_2026 * (1.0 - taux_prel_ret)
            pen_tot_brut_26 = pen_base_brut + pension_rafp_brut_2026

            # Net imposable pension = pension nette + CSG non déductible + CRDS + CASA
            t_csg_nd = IR_PAR_ANNEE[str(min(y_curr, 2026))]["csg_non_deductible"]
            t_non_ded_ret = (
                min(py["taux_csg_retraite"], t_csg_nd)
                + py["taux_crds_retraite"]
                + py["taux_casa_retraite"]
            )
            pen_net_imp_cour = (pen_tot_brut_26 / coeff26) * (1.0 - taux_prel_ret + t_non_ded_ret)
            ir_ret_cour = calcul_ir_annuel_eur(pen_net_imp_cour, y_curr, est_pension=True)

            total_retraite_net_2026 += (pen_base_nette + pen_rafp_nette) * w_ret
            total_rafp_net_2026 += pen_rafp_nette * w_ret
            total_ir_retraite_2026 += (ir_ret_cour * coeff26) * w_ret

        y_curr += 1

    # --- INDICATEURS DE SYNTHÈSE (AVANT IR & SUPER-NET APRÈS IR) ---
    total_vie = total_salaires_net_2026 + total_retraite_net_2026
    total_ir_vie = total_ir_salaires_2026 + total_ir_retraite_2026
    total_salaires_supernet = total_salaires_net_2026 - total_ir_salaires_2026
    total_retraite_supernet = total_retraite_net_2026 - total_ir_retraite_2026
    total_vie_supernet = total_vie - total_ir_vie

    salaire_mensuel_moy = total_salaires_net_2026 / (duree_carriere * 12.0)
    pension_mensuelle_moy = total_retraite_net_2026 / (ev_retraite * 12.0)
    salaire_mensuel_supernet_moy = total_salaires_supernet / (duree_carriere * 12.0)
    pension_mensuelle_supernette_moy = total_retraite_supernet / (ev_retraite * 12.0)

    heures_cours_tot = HEURES_ANNUELLES[corps] * duree_carriere
    heures_etp_tot = HEURES_ETP * duree_carriere

    return {
        "annee_entree": annee_entree,
        "annee_naissance": annee_naissance,
        "duree_carriere_ans": round(duree_carriere, 2),
        "age_depart": round(age_depart, 2),
        "annee_depart": round(annee_depart_exact, 2),
        "esperance_vie_retraite_ans": round(ev_retraite, 2),
        "taux_evol_reel_point_post_2026_pct": round(g_point_reel * 100.0, 3),
        "total_salaires_eur_2026": round(total_salaires_net_2026, 0),
        "total_retraite_eur_2026": round(total_retraite_net_2026, 0),
        "dont_rafp_net_eur_2026": round(total_rafp_net_2026, 0),
        "total_vie_eur_2026": round(total_vie, 0),
        "salaire_mensuel_net_moyen_eur_2026": round(salaire_mensuel_moy, 0),
        "pension_mensuelle_nette_moyenne_eur_2026": round(pension_mensuelle_moy, 0),
        "heures_cours_totales": round(heures_cours_tot, 0),
        "salaire_horaire_net_cours_eur_2026": round(total_salaires_net_2026 / heures_cours_tot, 2),
        "gain_horaire_global_cours_eur_2026": round(total_vie / heures_cours_tot, 2),
        "gain_horaire_global_etp_1607h_eur_2026": round(total_vie / heures_etp_tot, 2),
        # Colonnes Impôt sur le Revenu & Super-net (1 part fiscale / couple de 2 enseignants)
        "total_ir_salaires_eur_2026": round(total_ir_salaires_2026, 0),
        "total_ir_retraite_eur_2026": round(total_ir_retraite_2026, 0),
        "total_ir_vie_eur_2026": round(total_ir_vie, 0),
        "taux_moyen_ir_vie_pct": round(total_ir_vie / total_vie * 100.0, 2),
        "total_salaires_supernet_eur_2026": round(total_salaires_supernet, 0),
        "total_retraite_supernet_eur_2026": round(total_retraite_supernet, 0),
        "total_vie_supernet_eur_2026": round(total_vie_supernet, 0),
        "salaire_mensuel_supernet_moyen_eur_2026": round(salaire_mensuel_supernet_moy, 0),
        "pension_mensuelle_supernette_moyenne_eur_2026": round(pension_mensuelle_supernette_moy, 0),
        "gain_horaire_global_supernet_cours_eur_2026": round(total_vie_supernet / heures_cours_tot, 2),
        "gain_horaire_global_supernet_etp_eur_2026": round(total_vie_supernet / heures_etp_tot, 2),
    }


# ---------------------------------------------------------------------------
# 5. OUTILS DE FORMATAGE FRANÇAIS & GRAPHIQUES HAUTE DÉFINITION (300 DPI)
# ---------------------------------------------------------------------------
def fmt_eur(val: float) -> str:
    return f"{int(round(val)):,}".replace(",", "\u00a0") + "\u00a0€"


def fmt_keur(val: float) -> str:
    return f"{int(round(val / 1000.0)):,}".replace(",", "\u00a0") + "\u00a0k€"


def fmt_meur(val: float, dec: int = 2) -> str:
    return f"{val / 1e6:.{dec}f}".replace(".", ",") + "\u00a0M€"


def fmt_fr(val: float, dec: int = 1) -> str:
    return f"{val:.{dec}f}".replace(".", ",")


def configurer_style_graphique():
    plt.rcParams.update({
        "font.family": "sans-serif",
        "font.sans-serif": ["Segoe UI", "DejaVu Sans", "Arial", "Helvetica"],
        "axes.edgecolor": "#CBD5E1",
        "axes.linewidth": 0.8,
        "axes.facecolor": "#FDFDFB",
        "figure.facecolor": "#FDFDFB",
        "grid.color": "#E2E8F0",
        "grid.linestyle": "--",
        "grid.linewidth": 0.7,
        "xtick.color": "#334155",
        "ytick.color": "#334155",
        "text.color": "#1E293B",
    })


SOURCE_FOOTER = (
    "Sources : INSEE (IPC 011813530 / 011814056 ; Tables de mortalité IP n° 1927 & IP n° 2005), "
    "Barèmes IPP / OpenFisca (point d'indice, cotisations FP, PSS), DGAFP, ERAFP, Décrets statutaires (1950–2024).\n"
    "Hypothèses : entrée à 24 ans, carrière complète au taux plein sans HSA, Zone 1 (IR), "
    "Hors Classe dès sa création (1978 agrégés, 1989 certifiés), hors Classe Exceptionnelle, € constants 2026 nets avant IR."
)

SOURCE_FOOTER_IR = (
    "Sources : INSEE (IPC 1950–2026 ; mortalité générationnelle IP n° 1927 & cadres FP IP n° 2005), "
    "OpenFisca-France / Barèmes IPP (point d'indice, cotisations FP, barèmes IR, décotes, abattements, minorations & majorations 1950–2025), LF 2026 & PLF 2027.\n"
    "Hypothèses : entrée à 24 ans, service plein sans HSA, avancement moyen + Hors Classe (hors Classe Exceptionnelle), "
    "IR calculé pour 1 part fiscale (taux moyen identique pour un couple de 2 professeurs à 2 parts), barème 2026 indexé sur l'inflation après 2026."
)


def generer_graphiques(df_agr: pd.DataFrame, df_cer: pd.DataFrame,
                       df_agr_an: pd.DataFrame, df_cer_an: pd.DataFrame):
    configurer_style_graphique()

    # Palette pastel sobre et lisible
    COL_AGR_SAL = "#5B82A6"   # Bleu ardoise doux
    COL_AGR_RET = "#AFCBE3"   # Bleu ciel pastel
    COL_AGR_LINE = "#3B6289"  # Bleu ardoise soutenu
    COL_CER_SAL = "#C9826B"   # Terracotta pastel
    COL_CER_RET = "#ECC7B8"   # Pêche poudré
    COL_CER_LINE = "#B05D44"  # Terracotta soutenu
    COL_RATIO = "#5F8575"     # Vert sauge sobre
    COL_PEAK = "#C68B2C"      # Or vieilli pour le sommet absolu

    # =======================================================================
    # GRAPHIQUE 1 : 01_cumul_vie_agreges_vs_certifies.png
    # =======================================================================
    cohortes_cles = [1950, 1965, 1970, 1990, 2010]
    a_sub = df_agr[df_agr["annee_entree"].isin(cohortes_cles)].set_index("annee_entree").loc[cohortes_cles]
    c_sub = df_cer[df_cer["annee_entree"].isin(cohortes_cles)].set_index("annee_entree").loc[cohortes_cles]

    fig, ax = plt.subplots(figsize=(11.5, 6.8), dpi=300)
    x = np.arange(len(cohortes_cles))
    w = 0.34

    agr_sal = a_sub["total_salaires_eur_2026"].values / 1e6
    agr_ret = a_sub["total_retraite_eur_2026"].values / 1e6
    ax.bar(x - w / 2 - 0.02, agr_sal, width=w, color=COL_AGR_SAL, edgecolor="white", linewidth=0.8,
           label="Agrégés — Salaires nets")
    ax.bar(x - w / 2 - 0.02, agr_ret, width=w, bottom=agr_sal, color=COL_AGR_RET, edgecolor="white", linewidth=0.8,
           label="Agrégés — Retraite nette")

    cer_sal = c_sub["total_salaires_eur_2026"].values / 1e6
    cer_ret = c_sub["total_retraite_eur_2026"].values / 1e6
    ax.bar(x + w / 2 + 0.02, cer_sal, width=w, color=COL_CER_SAL, edgecolor="white", linewidth=0.8,
           label="Certifiés — Salaires nets")
    ax.bar(x + w / 2 + 0.02, cer_ret, width=w, bottom=cer_sal, color=COL_CER_RET, edgecolor="white", linewidth=0.8,
           label="Certifiés — Retraite nette")

    for i in range(len(cohortes_cles)):
        tot_a = agr_sal[i] + agr_ret[i]
        tot_c = cer_sal[i] + cer_ret[i]
        ax.text(x[i] - w / 2 - 0.02, tot_a + 0.045, f"{tot_a:.2f} M€",
                ha="center", va="bottom", fontsize=9.2, fontweight="bold", color=COL_AGR_LINE)
        ax.text(x[i] + w / 2 + 0.02, tot_c + 0.045, f"{tot_c:.2f} M€",
                ha="center", va="bottom", fontsize=9.2, fontweight="bold", color=COL_CER_LINE)
        ax.text(x[i] - w / 2 - 0.02, agr_sal[i] / 2, f"{agr_sal[i]:.2f}",
                ha="center", va="center", fontsize=8, color="white", fontweight="bold")
        ax.text(x[i] - w / 2 - 0.02, agr_sal[i] + agr_ret[i] / 2, f"{agr_ret[i]:.2f}",
                ha="center", va="center", fontsize=8, color="#1E3A5F", fontweight="bold")
        ax.text(x[i] + w / 2 + 0.02, cer_sal[i] / 2, f"{cer_sal[i]:.2f}",
                ha="center", va="center", fontsize=8, color="white", fontweight="bold")
        ax.text(x[i] + w / 2 + 0.02, cer_sal[i] + cer_ret[i] / 2, f"{cer_ret[i]:.2f}",
                ha="center", va="center", fontsize=8, color="#6B2F1D", fontweight="bold")

    ax.set_xticks(x)
    xlabels = [
        f"Cohorte {yr}\n({str(round(a_sub.loc[yr, 'duree_carriere_ans'], 1)).replace('.', ',')} ans actif)"
        for yr in cohortes_cles
    ]
    ax.set_xticklabels(xlabels, fontsize=9.5)
    ax.set_ylabel("Rémunération nette cumulée sur la vie entière (millions d'€ 2026)", fontsize=10, labelpad=8)
    ax.set_ylim(0, max(agr_sal + agr_ret) * 1.18)
    ax.yaxis.set_major_formatter(mtick.FormatStrFormatter("%.1f M€"))
    ax.yaxis.grid(True)
    ax.set_axisbelow(True)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.legend(loc="upper right", ncol=2, frameon=True, facecolor="white", edgecolor="#E2E8F0", fontsize=8.8)

    fig.suptitle(
        "Cumul net sur la vie entière : l'âge d'or des cohortes 1965–1970 face à l'érosion contemporaine",
        fontsize=12.8, fontweight="bold", x=0.08, ha="left", y=0.955
    )
    ax.set_title(
        "Somme des salaires nets et pensions nettes (en millions d'euros constants 2026, avant IR) — Agrégés vs Certifiés",
        fontsize=9.6, color="#475569", loc="left", pad=12
    )
    fig.text(0.08, 0.015, SOURCE_FOOTER, fontsize=7.3, color="#64748B", va="bottom", ha="left")
    plt.subplots_adjust(left=0.08, right=0.97, top=0.86, bottom=0.17)
    fig.savefig(BASE_DIR / "01_cumul_vie_agreges_vs_certifies.png", dpi=300)
    plt.close(fig)

    # =======================================================================
    # GRAPHIQUE 2 : 02_gain_horaire_cours.png
    # =======================================================================
    fig, ax = plt.subplots(figsize=(11.5, 6.8), dpi=300)

    yrs = df_agr["annee_entree"].values
    g_agr = df_agr["gain_horaire_global_cours_eur_2026"].values
    g_cer = df_cer["gain_horaire_global_cours_eur_2026"].values

    ax.plot(yrs, g_agr, marker="o", linewidth=2.6, markersize=6.5, color=COL_AGR_LINE,
            markerfacecolor=COL_AGR_RET, markeredgewidth=1.8, label="Professeur agrégé (15 h/sem., 540 h/an)")
    ax.plot(yrs, g_cer, marker="s", linewidth=2.6, markersize=6.2, color=COL_CER_LINE,
            markerfacecolor=COL_CER_RET, markeredgewidth=1.8, label="Professeur certifié / CAPES (18 h/sem., 648 h/an)")
    ax.fill_between(yrs, g_cer, g_agr, color="#CBD5E1", alpha=0.22)

    idx_max_a = int(np.argmax(g_agr))
    idx_max_c = int(np.argmax(g_cer))
    yr_max_a, val_max_a = int(yrs[idx_max_a]), g_agr[idx_max_a]
    yr_max_c, val_max_c = int(yrs[idx_max_c]), g_cer[idx_max_c]

    ax.scatter([yr_max_a], [val_max_a], s=145, color=COL_PEAK, edgecolor="white", linewidth=1.8, zorder=6)
    ax.scatter([yr_max_c], [val_max_c], s=145, color=COL_PEAK, edgecolor="white", linewidth=1.8, zorder=6)

    ax.annotate(
        f"Sommet absolu Agrégés (« le haut du haut »)\nCohorte {yr_max_a} : {val_max_a:.2f} €/h de cours",
        xy=(yr_max_a, val_max_a), xytext=(yr_max_a + 10, val_max_a + 14),
        fontsize=9.0, fontweight="bold", color="#7A4F0B",
        bbox=dict(boxstyle="round,pad=0.4", facecolor="#FEF7E6", edgecolor=COL_PEAK, linewidth=1.2),
        arrowprops=dict(arrowstyle="->", color=COL_PEAK, lw=1.6, connectionstyle="arc3,rad=-0.15"),
        zorder=7
    )
    ax.annotate(
        f"Sommet absolu Certifiés (« le haut du haut »)\nCohorte {yr_max_c} : {val_max_c:.2f} €/h de cours",
        xy=(yr_max_c, val_max_c), xytext=(1950.5, 76),
        fontsize=9.0, fontweight="bold", color="#7A4F0B",
        bbox=dict(boxstyle="round,pad=0.4", facecolor="#FEF7E6", edgecolor=COL_PEAK, linewidth=1.2),
        arrowprops=dict(arrowstyle="->", color=COL_PEAK, lw=1.6, connectionstyle="arc3,rad=-0.18"),
        zorder=7
    )

    ax.annotate(f"{g_agr[0]:.1f} €", (1950, g_agr[0]), xytext=(0, 9), textcoords="offset points",
                fontsize=8.6, fontweight="bold", color=COL_AGR_LINE, ha="center")
    ax.annotate(f"{g_cer[0]:.1f} €", (1950, g_cer[0]), xytext=(-2, 9), textcoords="offset points",
                fontsize=8.6, fontweight="bold", color=COL_CER_LINE, ha="center")

    chute_a = (g_agr[-1] / val_max_a - 1.0) * 100.0
    chute_c = (g_cer[-1] / val_max_c - 1.0) * 100.0
    ax.annotate(f"{g_agr[-1]:.1f} €\n({chute_a:.1f} % vs pic)", (2015, g_agr[-1]),
                xytext=(4, 14), textcoords="offset points",
                fontsize=8.5, fontweight="bold", color=COL_AGR_LINE, ha="center")
    ax.annotate(f"{g_cer[-1]:.1f} €\n({chute_c:.1f} % vs pic)", (2015, g_cer[-1]),
                xytext=(4, -26), textcoords="offset points",
                fontsize=8.5, fontweight="bold", color=COL_CER_LINE, ha="center")

    ax.axvspan(1985, 2018.5, color="#94A3B8", alpha=0.08, label="Cohortes partiellement extrapolées post-2026")
    ax.axvline(1985, color="#94A3B8", linestyle=":", linewidth=1.2)
    ax.text(2017.5, val_max_a * 1.19, "Actives après 2026\n(tendance réelle prolongée)",
            fontsize=8.2, color="#64748B", va="top", ha="right")

    ax.set_xticks(yrs)
    ax.set_xlim(1947, 2019)
    ax.set_ylim(38, val_max_a * 1.24)
    ax.set_xlabel("Année d'entrée dans le métier (âge d'entrée : 24 ans)", fontsize=10, labelpad=8)
    ax.set_ylabel("Gain horaire global net (€ 2026 / heure de cours)", fontsize=10, labelpad=8)
    ax.yaxis.set_major_formatter(mtick.FormatStrFormatter("%.0f €"))
    ax.grid(True)
    ax.set_axisbelow(True)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.legend(loc="lower left", frameon=True, facecolor="white", edgecolor="#E2E8F0", fontsize=8.8)

    fig.suptitle(
        "Gain horaire global par heure de cours : un sommet historique en 1965, suivi d'un repli de plus de 40 %",
        fontsize=12.6, fontweight="bold", x=0.08, ha="left", y=0.955
    )
    ax.set_title(
        "(Salaires nets + Retraite nette sur toute la vie) / Heures de cours totales effectuées — en € constants 2026 avant IR",
        fontsize=9.6, color="#475569", loc="left", pad=12
    )
    fig.text(0.08, 0.015, SOURCE_FOOTER, fontsize=7.3, color="#64748B", va="bottom", ha="left")
    plt.subplots_adjust(left=0.08, right=0.97, top=0.86, bottom=0.17)
    fig.savefig(BASE_DIR / "02_gain_horaire_cours.png", dpi=300)
    plt.close(fig)

    # =======================================================================
    # GRAPHIQUE 3 : 03_ecart_agrege_certifie.png
    # =======================================================================
    fig, ax = plt.subplots(figsize=(11.5, 6.7), dpi=300)

    ratio_cours = g_agr / g_cer
    ratio_etp = (
        df_agr["gain_horaire_global_etp_1607h_eur_2026"].values
        / df_cer["gain_horaire_global_etp_1607h_eur_2026"].values
    )

    ax.plot(yrs, ratio_cours, marker="o", linewidth=2.6, markersize=6.8, color=COL_RATIO,
            markerfacecolor="#B8D5C7", markeredgewidth=1.8,
            label="Ratio gain horaire par heure de cours (Agrégé 15 h / Certifié 18 h)")
    ax.plot(yrs, ratio_etp, marker="^", linewidth=2.0, linestyle="--", markersize=5.8, color="#7C8594",
            markerfacecolor="#DCE1E7", markeredgewidth=1.4,
            label="Ratio revenu global vie entière ou ETP 1 607 h (hors effet horaire 18/15)")

    ax.axhline(1.20, color="#CBD5E1", linestyle=":", linewidth=1.3)
    ax.text(2017.2, 1.176, "Seul effet service (18 h / 15 h = 1,20×)", fontsize=8.1,
            color="#64748B", ha="right", va="top")

    for i, yr in enumerate(yrs):
        if yr in (1950, 1955, 1965, 1975, 1985, 1995, 2005, 2015):
            ax.annotate(f"{ratio_cours[i]:.2f}×", (yr, ratio_cours[i]),
                        xytext=(0, 9), textcoords="offset points",
                        ha="center", fontsize=8.5, fontweight="bold", color=COL_RATIO)
            y_off = 9 if yr in (1965, 1975, 2005, 2015) else -14
            ax.annotate(f"{ratio_etp[i]:.2f}×", (yr, ratio_etp[i]),
                        xytext=(0, y_off), textcoords="offset points",
                        ha="center", fontsize=8.1, color="#475569")

    ax.annotate(
        "Cohorte 1950 : Certifiés retraités en 1987\navant la Hors Classe (1989) ; Agrégés y accèdent dès 1978",
        xy=(1950, ratio_cours[0]), xytext=(1955, 1.685),
        fontsize=8.3, color="#334155",
        bbox=dict(boxstyle="round,pad=0.38", facecolor="#F1F5F9", edgecolor="#94A3B8", linewidth=0.9),
        arrowprops=dict(arrowstyle="->", color="#64748B", lw=1.2, connectionstyle="arc3,rad=0.10")
    )
    ax.annotate(
        "Convergence partielle après 1989 :\nHors Classe Certifiés (1989) + 7e éch. HC (2021)\n+ primes forfaitaires identiques (ISOE, attractivité)",
        xy=(2005, ratio_cours[yrs.tolist().index(2005)]), xytext=(1980, 1.32),
        fontsize=8.3, color="#334155",
        bbox=dict(boxstyle="round,pad=0.38", facecolor="#F1F5F9", edgecolor="#94A3B8", linewidth=0.9),
        arrowprops=dict(arrowstyle="->", color="#64748B", lw=1.2, connectionstyle="arc3,rad=-0.12")
    )

    ax.set_xticks(yrs)
    ax.set_xlim(1947, 2018)
    ax.set_ylim(1.09, 1.77)
    ax.set_xlabel("Année d'entrée dans le métier", fontsize=10, labelpad=8)
    ax.set_ylabel("Ratio Agrégé / Certifié (multiplicateur)", fontsize=10, labelpad=8)
    ax.yaxis.set_major_formatter(mtick.FormatStrFormatter("%.2f×"))
    ax.grid(True)
    ax.set_axisbelow(True)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.legend(loc="lower left", frameon=True, facecolor="white", edgecolor="#E2E8F0", fontsize=8.8)

    fig.suptitle(
        "Prime d'agrégation : un avantage horaire structurel qui se tasse lentement après la création de la Hors Classe certifiée",
        fontsize=11.7, fontweight="bold", x=0.08, ha="left", y=0.955
    )
    ax.set_title(
        "Évolution du ratio de gain horaire global (Agrégé / Certifié) par heure de cours et en équivalent temps plein (1950–2015)",
        fontsize=9.5, color="#475569", loc="left", pad=12
    )
    fig.text(0.08, 0.015, SOURCE_FOOTER, fontsize=7.3, color="#64748B", va="bottom", ha="left")
    plt.subplots_adjust(left=0.08, right=0.97, top=0.86, bottom=0.17)
    fig.savefig(BASE_DIR / "03_ecart_agrege_certifie.png", dpi=300)
    plt.close(fig)

    # =======================================================================
    # GRAPHIQUE 4 : 04_infographie_choc_vie_entiere.png
    # Affiche éditoriale grand public : L'année la plus généreuse (1966) vs la plus pingre (2015)
    # =======================================================================
    generer_infographie_choc(df_agr_an, df_cer_an)

    # =======================================================================
    # GRAPHIQUE 5 : 05_trajectoire_annuelle_supernet_ir.png
    # Trajectoire annuelle 1950–2015 : Avant IR vs Super-net + Ciseau travail / retraite
    # =======================================================================
    generer_trajectoire_annuelle_ir(df_agr_an, df_cer_an)


def generer_infographie_choc(df_agr_an: pd.DataFrame, df_cer_an: pd.DataFrame):
    """
    Infographie éditoriale grand public comparant l'année d'entrée la plus généreuse
    et l'année la plus pingre (1950–2015), en euros constants 2026 SUPER-NETS APRÈS IR,
    avec mise en scène explicite des années travaillées et des années moyennes à la retraite.
    """
    # Extraction exacte des sommets et planchers (super-net après IR)
    a_best = df_agr_an.loc[df_agr_an["total_vie_supernet_eur_2026"].idxmax()]
    a_worst = df_agr_an.loc[df_agr_an["total_vie_supernet_eur_2026"].idxmin()]
    c_best = df_cer_an.loc[df_cer_an["total_vie_supernet_eur_2026"].idxmax()]
    c_worst = df_cer_an.loc[df_cer_an["total_vie_supernet_eur_2026"].idxmin()]

    fig = plt.figure(figsize=(15.0, 9.6), dpi=300, facecolor="#F8FAFC")
    ax = fig.add_axes([0, 0, 1, 1], facecolor="#F8FAFC")
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)
    ax.axis("off")

    # Palette éditoriale sobre et lisible
    INK_DARK = "#0F172A"
    INK_MUTED = "#475569"
    INK_LIGHT = "#64748B"
    CARD_BG = "#FFFFFF"
    BORDER = "#CBD5E1"

    GREEN_DARK = "#1E5645"
    GREEN_MED = "#3E8E75"
    GREEN_SOFT = "#98CBB8"
    GREEN_PILL = "#EAF5F0"

    CORAL_DARK = "#993424"
    CORAL_MED = "#C96A52"
    CORAL_SOFT = "#EBB4A2"
    CORAL_PILL = "#FCEEEB"

    LOSS_BG = "#FDF2F2"
    LOSS_BORDER = "#E5A3A3"
    LOSS_TXT = "#9B1C1C"

    # --- BANDEAU SUPÉRIEUR ---
    ax.add_patch(Rectangle((0, 88.2), 100, 11.8, facecolor="#1E293B", edgecolor="none"))
    ax.text(
        3.2, 95.3,
        "Combien touche un professeur sur toute sa vie, impôts déduits ?",
        fontsize=20.5, fontweight="bold", color="#FFFFFF", va="center", ha="left"
    )
    ax.text(
        3.2, 90.8,
        "Salaires + retraite cumulés sur une carrière complète à temps plein (entrée à 24 ans, sans heures sup.) — "
        "en euros constants de 2026, super-net après impôt sur le revenu*",
        fontsize=10.3, color="#CBD5E1", va="center", ha="left"
    )

    # Échelle commune des barres horizontales (en M€) : max = 3.55 M€ (Agrégé 1966 avant IR = 3.37 M€)
    BAR_MAX_EUR = 3.55e6

    def draw_column(x0: float, width: float, corps_titre: str, corps_sous: str,
                    best: pd.Series, worst: pd.Series, accent_title: str):
        # En-tête de colonne
        ax.add_patch(FancyBboxPatch(
            (x0, 81.6), width, 4.6,
            boxstyle="round,pad=0.35,rounding_size=0.8",
            facecolor="#FFFFFF", edgecolor=accent_title, linewidth=1.6
        ))
        ax.text(x0 + 1.6, 84.55, corps_titre, fontsize=13.5, fontweight="bold",
                color=accent_title, va="center", ha="left")
        ax.text(x0 + 1.6, 82.6, corps_sous, fontsize=9.2, color=INK_MUTED, va="center", ha="left")

        # --- CARTE 1 : ANNÉE LA PLUS GÉNÉREUSE (1966) ---
        y_top_card = 52.8
        h_card = 27.2
        ax.add_patch(FancyBboxPatch(
            (x0, y_top_card), width, h_card,
            boxstyle="round,pad=0.35,rounding_size=1.0",
            facecolor=CARD_BG, edgecolor=GREEN_SOFT, linewidth=1.5
        ))
        # Ruban supérieur vert pastel
        ax.add_patch(FancyBboxPatch(
            (x0 + 0.6, y_top_card + h_card - 4.3), width - 1.2, 3.6,
            boxstyle="round,pad=0.1,rounding_size=0.6",
            facecolor=GREEN_PILL, edgecolor="none"
        ))
        ax.text(
            x0 + 1.8, y_top_card + h_card - 2.5,
            f"L'ANNÉE LA PLUS GÉNÉREUSE  ·  ENTRÉE EN {int(best['annee_entree'])}",
            fontsize=9.6, fontweight="bold", color=GREEN_DARK, va="center", ha="left"
        )
        ax.text(
            x0 + width - 1.6, y_top_card + h_card - 2.5,
            f"Né en {int(best['annee_naissance'])} · Retraité à {fmt_fr(best['age_depart'])} ans",
            fontsize=8.6, color=GREEN_DARK, va="center", ha="right"
        )

        # Gros chiffre super-net
        ax.text(
            x0 + 1.8, y_top_card + 18.6,
            fmt_eur(best["total_vie_supernet_eur_2026"]),
            fontsize=22.5, fontweight="bold", color=GREEN_DARK, va="center", ha="left"
        )
        ax.text(
            x0 + 1.8, y_top_card + 15.1,
            f"touchés en poche sur toute sa vie (super-net après IR)  ·  "
            f"soit {fmt_eur(best['total_vie_eur_2026'])} avant IR  (IR : {fmt_fr(best['taux_moyen_ir_vie_pct'])} %)",
            fontsize=8.3, color=INK_MUTED, va="center", ha="left"
        )

        # Barre horizontale proportionnelle (Salaires super-nets + Retraite super-nette + IR payé en hachuré)
        bx = x0 + 1.8
        bw_max = width - 3.6
        by = y_top_card + 9.4
        bh = 3.5
        w_sal = bw_max * (best["total_salaires_supernet_eur_2026"] / BAR_MAX_EUR)
        w_ret = bw_max * (best["total_retraite_supernet_eur_2026"] / BAR_MAX_EUR)
        w_ir = bw_max * (best["total_ir_vie_eur_2026"] / BAR_MAX_EUR)

        ax.add_patch(Rectangle((bx, by), bw_max, bh, facecolor="#F1F5F9", edgecolor="none"))
        ax.add_patch(Rectangle((bx, by), w_sal, bh, facecolor=GREEN_MED, edgecolor="white", linewidth=0.8))
        ax.add_patch(Rectangle((bx + w_sal, by), w_ret, bh, facecolor=GREEN_SOFT, edgecolor="white", linewidth=0.8))
        ax.add_patch(Rectangle((bx + w_sal + w_ret, by), w_ir, bh, facecolor="#E2E8F0",
                               edgecolor="#94A3B8", linewidth=0.6, hatch="///"))

        ax.text(bx + w_sal / 2, by + bh / 2,
                f"Salaires : {fmt_meur(best['total_salaires_supernet_eur_2026'])}",
                fontsize=7.9, fontweight="bold", color="white", va="center", ha="center")
        ax.text(bx + w_sal + w_ret / 2, by + bh / 2,
                f"Retraite : {fmt_meur(best['total_retraite_supernet_eur_2026'])}",
                fontsize=7.7, fontweight="bold", color=GREEN_DARK, va="center", ha="center")
        ax.text(bx + w_sal + w_ret + w_ir / 2, by + bh / 2,
                f"IR\n{fmt_keur(best['total_ir_vie_eur_2026'])}",
                fontsize=6.5, fontweight="bold", color="#334155", va="center", ha="center",
                bbox=dict(boxstyle="round,pad=0.14", facecolor="white", edgecolor="none", alpha=0.88))

        # 3 pastilles temps de vie & gain horaire (formulations demandées par l'utilisateur !)
        py = y_top_card + 1.8
        ph = 5.8
        gap = 1.0
        pw1 = (bw_max - 2 * gap) * 0.36
        pw2 = (bw_max - 2 * gap) * 0.39
        pw3 = (bw_max - 2 * gap) * 0.25

        for px, pw, lbl1, lbl2 in [
            (bx, pw1, "A travaillé pendant", f"{fmt_fr(best['duree_carriere_ans'])} années"),
            (bx + pw1 + gap, pw2, "A passé en moyenne", f"{fmt_fr(best['esperance_vie_retraite_ans'])} ans à la retraite"),
            (bx + pw1 + pw2 + 2 * gap, pw3, "Soit par h de cours", f"{fmt_fr(best['gain_horaire_global_supernet_cours_eur_2026'])} €/h"),
        ]:
            ax.add_patch(FancyBboxPatch(
                (px, py), pw, ph,
                boxstyle="round,pad=0.1,rounding_size=0.55",
                facecolor="#F8FAFC", edgecolor="#CBD5E1", linewidth=0.9
            ))
            ax.text(px + pw / 2, py + ph * 0.69, lbl1, fontsize=7.9, color=INK_MUTED, va="center", ha="center")
            ax.text(px + pw / 2, py + ph * 0.30, lbl2, fontsize=10.0, fontweight="bold",
                    color=GREEN_DARK, va="center", ha="center")

        # --- CARTE 2 : ANNÉE LA PLUS PINGRE (2015) ---
        y_bot_card = 23.6
        ax.add_patch(FancyBboxPatch(
            (x0, y_bot_card), width, h_card,
            boxstyle="round,pad=0.35,rounding_size=1.0",
            facecolor=CARD_BG, edgecolor=CORAL_SOFT, linewidth=1.5
        ))
        ax.add_patch(FancyBboxPatch(
            (x0 + 0.6, y_bot_card + h_card - 4.3), width - 1.2, 3.6,
            boxstyle="round,pad=0.1,rounding_size=0.6",
            facecolor=CORAL_PILL, edgecolor="none"
        ))
        ax.text(
            x0 + 1.8, y_bot_card + h_card - 2.5,
            f"L'ANNÉE LA PLUS PINGRE  ·  ENTRÉE EN {int(worst['annee_entree'])}",
            fontsize=9.6, fontweight="bold", color=CORAL_DARK, va="center", ha="left"
        )
        ax.text(
            x0 + width - 1.6, y_bot_card + h_card - 2.5,
            f"Né en {int(worst['annee_naissance'])} · Retraité à {int(worst['age_depart'])} ans",
            fontsize=8.6, color=CORAL_DARK, va="center", ha="right"
        )

        ax.text(
            x0 + 1.8, y_bot_card + 18.6,
            fmt_eur(worst["total_vie_supernet_eur_2026"]),
            fontsize=22.5, fontweight="bold", color=CORAL_DARK, va="center", ha="left"
        )
        ax.text(
            x0 + 1.8, y_bot_card + 15.1,
            f"touchés en poche sur toute sa vie (super-net après IR)  ·  "
            f"soit {fmt_eur(worst['total_vie_eur_2026'])} avant IR  (IR : {fmt_fr(worst['taux_moyen_ir_vie_pct'])} %)",
            fontsize=8.3, color=INK_MUTED, va="center", ha="left"
        )

        # Barre horizontale SUR LA MÊME ÉCHELLE + zone pointillée de richesse perdue !
        by2 = y_bot_card + 9.4
        w_sal2 = bw_max * (worst["total_salaires_supernet_eur_2026"] / BAR_MAX_EUR)
        w_ret2 = bw_max * (worst["total_retraite_supernet_eur_2026"] / BAR_MAX_EUR)
        w_ir2 = bw_max * (worst["total_ir_vie_eur_2026"] / BAR_MAX_EUR)
        w_tot1_sn = w_sal + w_ret
        w_tot2_sn = w_sal2 + w_ret2

        ax.add_patch(Rectangle((bx, by2), bw_max, bh, facecolor="#F1F5F9", edgecolor="none"))
        ax.add_patch(Rectangle((bx, by2), w_sal2, bh, facecolor=CORAL_MED, edgecolor="white", linewidth=0.8))
        ax.add_patch(Rectangle((bx + w_sal2, by2), w_ret2, bh, facecolor=CORAL_SOFT, edgecolor="white", linewidth=0.8))
        ax.add_patch(Rectangle((bx + w_tot2_sn, by2), w_ir2, bh, facecolor="#E2E8F0",
                               edgecolor="#94A3B8", linewidth=0.6, hatch="///"))
        # Repère vertical du niveau super-net de 1966 + flèche rouge de perte sèche
        ax.plot([bx + w_tot1_sn, bx + w_tot1_sn], [by2 - 0.55, by2 + bh + 0.55],
                color=LOSS_TXT, linestyle="--", linewidth=1.4)
        perte_sn = worst["total_vie_supernet_eur_2026"] - best["total_vie_supernet_eur_2026"]
        ax.annotate(
            "", xy=(bx + w_tot2_sn, by2 + bh / 2), xytext=(bx + w_tot1_sn, by2 + bh / 2),
            arrowprops=dict(arrowstyle="<->", color=LOSS_TXT, lw=1.3)
        )
        ax.text(bx + w_tot1_sn + 0.8, by2 + bh / 2,
                f"−{fmt_keur(abs(perte_sn))} vs 1966",
                fontsize=7.9, fontweight="bold", color=LOSS_TXT, va="center", ha="left")

        ax.text(bx + w_sal2 / 2, by2 + bh / 2,
                f"Salaires : {fmt_meur(worst['total_salaires_supernet_eur_2026'])}",
                fontsize=7.9, fontweight="bold", color="white", va="center", ha="center")
        ax.text(bx + w_sal2 + w_ret2 / 2, by2 + bh / 2,
                f"Ret. : {fmt_meur(worst['total_retraite_supernet_eur_2026'])}",
                fontsize=7.5, fontweight="bold", color=CORAL_DARK, va="center", ha="center")

        # 3 pastilles temps de vie & gain horaire (avec écarts rouges)
        py2 = y_bot_card + 1.8
        d_trav = worst["duree_carriere_ans"] - best["duree_carriere_ans"]
        d_ret = worst["esperance_vie_retraite_ans"] - best["esperance_vie_retraite_ans"]
        pct_gh = (worst["gain_horaire_global_supernet_cours_eur_2026"]
                  / best["gain_horaire_global_supernet_cours_eur_2026"] - 1.0) * 100.0

        for px, pw, lbl1, lbl2, delta in [
            (bx, pw1, "Travaillera pendant", f"{int(worst['duree_carriere_ans'])} années",
             f"(+{fmt_fr(d_trav)} ans)"),
            (bx + pw1 + gap, pw2, "Passera en moyenne", f"{fmt_fr(worst['esperance_vie_retraite_ans'])} ans à la retraite",
             f"(−{fmt_fr(abs(d_ret))} an)"),
            (bx + pw1 + pw2 + 2 * gap, pw3, "Soit par h de cours",
             f"{fmt_fr(worst['gain_horaire_global_supernet_cours_eur_2026'])} €/h",
             f"(−{fmt_fr(abs(pct_gh))} %)"),
        ]:
            ax.add_patch(FancyBboxPatch(
                (px, py2), pw, ph,
                boxstyle="round,pad=0.1,rounding_size=0.55",
                facecolor="#FFF8F6", edgecolor="#ECC7B8", linewidth=0.9
            ))
            ax.text(px + pw / 2, py2 + ph * 0.74, lbl1, fontsize=7.6, color=INK_MUTED, va="center", ha="center")
            ax.text(px + pw / 2, py2 + ph * 0.42, lbl2, fontsize=9.6, fontweight="bold",
                    color=CORAL_DARK, va="center", ha="center")
            ax.text(px + pw / 2, py2 + ph * 0.14, delta, fontsize=7.7, fontweight="bold",
                    color=LOSS_TXT, va="center", ha="center")

        # --- BANDEAU PERTE SÈCHE DE LA COLONNE ---
        pct_vie = (worst["total_vie_supernet_eur_2026"] / best["total_vie_supernet_eur_2026"] - 1.0) * 100.0
        perte_av_ir = worst["total_vie_eur_2026"] - best["total_vie_eur_2026"]
        ax.add_patch(FancyBboxPatch(
            (x0, 15.2), width, 6.7,
            boxstyle="round,pad=0.35,rounding_size=0.8",
            facecolor=LOSS_BG, edgecolor=LOSS_BORDER, linewidth=1.4
        ))
        ax.text(
            x0 + width / 2, 19.8,
            f"PERTE SÈCHE EN POCHE :  −{fmt_eur(abs(perte_sn))}  (−{fmt_fr(abs(pct_vie))} %)",
            fontsize=12.0, fontweight="bold", color=LOSS_TXT, va="center", ha="center"
        )
        ax.text(
            x0 + width / 2, 16.9,
            f"Pour 5,5 années de travail en PLUS et 1,1 an de retraite en MOINS  ·  "
            f"(Perte avant IR : −{fmt_eur(abs(perte_av_ir))})",
            fontsize=8.3, color="#7F1D1D", va="center", ha="center"
        )

    # Colonne GAUCHE : Certifié | Colonne DROITE : Agrégé
    draw_column(
        3.0, 45.2,
        "PROFESSEUR CERTIFIÉ (CAPES)",
        "18 heures de cours / semaine (648 h/an) · Hors Classe dès sa création (1989)",
        c_best, c_worst, "#A24F38"
    )
    draw_column(
        51.8, 45.2,
        "PROFESSEUR AGRÉGÉ",
        "15 heures de cours / semaine (540 h/an) · Hors Classe dès sa création (1978)",
        a_best, a_worst, "#2D5275"
    )

    # --- ENCART SYNTHÈSE CHOC EN BAS ---
    ecart_croise = c_best["total_vie_supernet_eur_2026"] - a_worst["total_vie_supernet_eur_2026"]
    ax.add_patch(FancyBboxPatch(
        (3.0, 7.6), 94.0, 5.7,
        boxstyle="round,pad=0.3,rounding_size=0.8",
        facecolor="#FFFBEB", edgecolor="#D97706", linewidth=1.3
    ))
    ax.text(
        50.0, 11.4,
        f"LE DÉCLASSEMENT EN UN CHIFFRE : un Certifié entré en 1966 a touché {fmt_eur(c_best['total_vie_supernet_eur_2026'])} après impôt (37,5 ans travaillés) —",
        fontsize=10.3, fontweight="bold", color="#78350F", va="center", ha="center"
    )
    ax.text(
        50.0, 9.0,
        f"soit {fmt_eur(ecart_croise)} DE PLUS qu'un Agrégé entré en 2015 ({fmt_eur(a_worst['total_vie_supernet_eur_2026'])}) alors même que l'agrégé a réussi un concours plus sélectif et travaillera 5,5 ans de plus.",
        fontsize=9.6, color="#92400E", va="center", ha="center"
    )

    # --- PIED DE PAGE SOURCES ---
    g_worst_str = fmt_fr(abs(a_worst["taux_evol_reel_point_post_2026_pct"]), 2)
    ax.text(
        3.0, 5.4,
        "* IR calculé année par année (législation réelle 1950–2026, 1 part fiscale ; taux moyen identique pour un couple de 2 enseignants à 2 parts). "
        "La baisse historique de l'IR (bascule vers la CSG + chute du revenu réel)\n"
        f"  amortit ~1/3 de la perte brute, mais laisse une perte sèche de −639 k€ à −804 k€ en poche. "
        f"Pour 2015, le point d'indice post-2026 prolonge sa tendance réelle observée depuis 2015 (−{g_worst_str} %/an).",
        fontsize=7.2, color=INK_MUTED, va="top", ha="left", linespacing=1.35
    )
    ax.text(
        3.0, 2.35,
        SOURCE_FOOTER_IR,
        fontsize=6.7, color=INK_LIGHT, va="top", ha="left", linespacing=1.3
    )

    fig.savefig(BASE_DIR / "04_infographie_choc_vie_entiere.png", dpi=300)
    plt.close(fig)


def generer_trajectoire_annuelle_ir(df_agr_an: pd.DataFrame, df_cer_an: pd.DataFrame):
    """
    Graphique éditorial double panneau (1950–2015 année par année — 66 cohortes) :
      - Panneau haut : Total vie entière (€ constants 2026) Avant IR vs Super-net Après IR
        avec mise en évidence de l'amortisseur fiscal et du croisement Agrégé 2000 < Certifié 1966.
      - Panneau bas : Le double ciseau du temps de vie (« A travaillé pendant X années »
        vs « A passé en moyenne X années à la retraite »).
    """
    configurer_style_graphique()
    fig, (ax1, ax2) = plt.subplots(
        2, 1, figsize=(13.0, 10.2), dpi=300, sharex=True,
        gridspec_kw={"height_ratios": [1.55, 1.0], "hspace": 0.14}
    )

    yrs = df_agr_an["annee_entree"].values

    agr_av = df_agr_an["total_vie_eur_2026"].values / 1e6
    agr_sn = df_agr_an["total_vie_supernet_eur_2026"].values / 1e6
    cer_av = df_cer_an["total_vie_eur_2026"].values / 1e6
    cer_sn = df_cer_an["total_vie_supernet_eur_2026"].values / 1e6

    COL_AGR = "#2D5A87"
    COL_AGR_FADE = "#8FB4D8"
    COL_CER = "#B8553B"
    COL_CER_FADE = "#E5A591"
    COL_TRAV = "#B8553B"
    COL_RET = "#2F7D63"

    # ---- PANNEAU HAUT : ARGENT SUR TOUTE LA VIE (AVANT IR vs SUPER-NET APRÈS IR) ----
    ax1.fill_between(yrs, agr_sn, agr_av, color=COL_AGR_FADE, alpha=0.25,
                     label="Impôt sur le revenu payé sur la vie (Agrégé)")
    ax1.fill_between(yrs, cer_sn, cer_av, color=COL_CER_FADE, alpha=0.25,
                     label="Impôt sur le revenu payé sur la vie (Certifié)")

    ax1.plot(yrs, agr_av, color=COL_AGR, linestyle="--", linewidth=1.6, alpha=0.75,
             label="Agrégé — Net avant IR")
    ax1.plot(yrs, agr_sn, color=COL_AGR, linestyle="-", linewidth=3.0,
             label="Agrégé — Super-net après IR (en poche)")

    ax1.plot(yrs, cer_av, color=COL_CER, linestyle="--", linewidth=1.6, alpha=0.75,
             label="Certifié — Net avant IR")
    ax1.plot(yrs, cer_sn, color=COL_CER, linestyle="-", linewidth=3.0,
             label="Certifié — Super-net après IR (en poche)")

    # Sommets 1966 & planchers 2015 (super-net)
    idx_pa = int(np.argmax(agr_sn))
    idx_pc = int(np.argmax(cer_sn))
    yr_pa, val_pa = int(yrs[idx_pa]), agr_sn[idx_pa]
    yr_pc, val_pc = int(yrs[idx_pc]), cer_sn[idx_pc]

    # Ligne repère horizontale : niveau du Certifié 1966 (2,35 M€) -> montre le croisement de l'Agrégé en 2000 !
    ax1.axhline(val_pc, color=COL_CER, linestyle=":", linewidth=1.2, alpha=0.75)
    ax1.scatter([2000], [val_pc], s=48, color="#9A3412", edgecolor="white", lw=1.2, zorder=6)
    ax1.annotate(
        "Dès 2000, un Agrégé gagne moins après IR\nqu'un Certifié entré en 1966 (2,35 M€)",
        xy=(2000, val_pc), xytext=(1990.5, 3.22),
        fontsize=8.2, fontweight="bold", color="#8A341E", ha="left", va="center",
        bbox=dict(boxstyle="round,pad=0.33", facecolor="#FFF7F5", edgecolor="#E5A591", lw=0.95),
        arrowprops=dict(arrowstyle="->", color="#9A3412", lw=1.25, connectionstyle="arc3,rad=0.14"),
        zorder=7
    )

    ax1.scatter([yr_pa, 2015], [val_pa, agr_sn[-1]], s=75, color=COL_AGR, edgecolor="white", lw=1.6, zorder=6)
    ax1.scatter([yr_pc, 2015], [val_pc, cer_sn[-1]], s=75, color=COL_CER, edgecolor="white", lw=1.6, zorder=6)

    # Annotations claires et espacées (zéro chevauchement)
    ax1.annotate(
        f"Sommet super-net : {yr_pa}\nAgrégé : {fmt_meur(val_pa * 1e6)}  (IR : 16,8 %)",
        xy=(yr_pa, val_pa), xytext=(1972.8, 3.04),
        fontsize=8.6, fontweight="bold", color=COL_AGR,
        bbox=dict(boxstyle="round,pad=0.35", facecolor="#EFF6FF", edgecolor=COL_AGR, lw=1.0),
        arrowprops=dict(arrowstyle="->", color=COL_AGR, lw=1.4, connectionstyle="arc3,rad=0.14"),
        zorder=7
    )
    ax1.annotate(
        f"Sommet super-net : {yr_pc}\nCertifié : {fmt_meur(val_pc * 1e6)}  (IR : 13,8 %)",
        xy=(yr_pc, val_pc), xytext=(1950.0, 1.80),
        fontsize=8.6, fontweight="bold", color=COL_CER,
        bbox=dict(boxstyle="round,pad=0.35", facecolor="#FFF5F2", edgecolor=COL_CER, lw=1.0),
        arrowprops=dict(arrowstyle="->", color=COL_CER, lw=1.4, connectionstyle="arc3,rad=-0.16"),
        zorder=7
    )
    # Avant IR en 1963/1964 : bien dégagés des courbes
    ax1.text(1963.0, 3.43, "3,37 M€ avant IR (1963)", fontsize=7.9, color=COL_AGR, ha="center", fontweight="bold")
    ax1.annotate(
        "2,72 M€ avant IR (1964)",
        xy=(1964.0, 2.724), xytext=(1963.8, 2.52),
        fontsize=7.9, color=COL_CER, ha="center", fontweight="bold",
        arrowprops=dict(arrowstyle="->", color=COL_CER, lw=1.0, alpha=0.85)
    )

    # Planchers 2015 : placés dans les zones 100 % dégagées
    ax1.annotate(
        f"2015 : {fmt_meur(agr_sn[-1] * 1e6)}\n(−804 k€ vs 1966 | IR : 6,5 %)",
        xy=(2015, agr_sn[-1]), xytext=(2014.5, 2.74),
        fontsize=8.3, fontweight="bold", color=COL_AGR, ha="right",
        bbox=dict(boxstyle="round,pad=0.32", facecolor="#EFF6FF", edgecolor=COL_AGR, lw=0.95),
        arrowprops=dict(arrowstyle="->", color=COL_AGR, lw=1.3, connectionstyle="arc3,rad=-0.14"),
        zorder=7
    )
    ax1.annotate(
        f"2015 : {fmt_meur(cer_sn[-1] * 1e6)}\n(−639 k€ vs 1966 | IR : 4,1 %)",
        xy=(2015, cer_sn[-1]), xytext=(2004.0, 1.56),
        fontsize=8.3, fontweight="bold", color=COL_CER, ha="right",
        bbox=dict(boxstyle="round,pad=0.32", facecolor="#FFF5F2", edgecolor=COL_CER, lw=0.95),
        arrowprops=dict(arrowstyle="->", color=COL_CER, lw=1.3),
        zorder=7
    )

    # Repères verticaux communs aux 2 panneaux
    for ax in (ax1, ax2):
        ax.axvline(1967.5, color="#94A3B8", linestyle=":", linewidth=1.2)
        ax.axvspan(1985, 2017.5, color="#94A3B8", alpha=0.07)
        ax.axvline(1985, color="#94A3B8", linestyle="--", linewidth=0.9, alpha=0.6)
        ax.grid(True)
        ax.set_axisbelow(True)
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)

    ax1.text(1968.2, 3.55, "Loi Fillon 2003 :\nfin des 37,5 annuités\n(entrées ≥ 1968)",
             fontsize=7.9, color="#475569", va="top", ha="left")
    ax1.text(2016.8, 3.55, "Partiellement extrapolées\naprès 2026",
             fontsize=7.9, color="#64748B", va="top", ha="right")

    ax1.set_ylim(1.42, 3.65)
    ax1.set_ylabel("Cumul sur toute la vie (millions d'€ 2026)", fontsize=10.2, labelpad=8)
    ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter("%.1f M€"))
    ax1.legend(loc="lower left", ncol=2, frameon=True, facecolor="white", edgecolor="#E2E8F0", fontsize=8.0)
    ax1.set_title(
        "A. Rémunération totale sur la vie entière (salaires + retraite) : net avant IR vs super-net en poche après IR",
        fontsize=10.4, fontweight="bold", color="#1E293B", loc="left", pad=8
    )

    # ---- PANNEAU BAS : LE DOUBLE CISEAU DU TEMPS DE VIE (TRAVAIL vs RETRAITE) ----
    duree_trav = df_agr_an["duree_carriere_ans"].values
    duree_ret = df_agr_an["esperance_vie_retraite_ans"].values

    ax2.plot(yrs, duree_trav, color=COL_TRAV, linewidth=2.9,
             label="A travaillé pendant X années (carrière au taux plein)")
    ax2.plot(yrs, duree_ret, color=COL_RET, linewidth=2.9,
             label="A passé en moyenne X années à la retraite (cadres FP, H/F)")
    ax2.fill_between(yrs, duree_ret, duree_trav, color="#E2E8F0", alpha=0.35)

    # Points & annotations clés du temps de vie
    idx_rmax = int(np.argmax(duree_ret))
    idx_rmin = int(np.argmin(duree_ret))
    yr_rmax, val_rmax = int(yrs[idx_rmax]), duree_ret[idx_rmax]
    yr_rmin, val_rmin = int(yrs[idx_rmin]), duree_ret[idx_rmin]

    ax2.scatter([1966, 2015], [duree_trav[16], duree_trav[-1]], s=55, color=COL_TRAV, edgecolor="white", lw=1.3, zorder=6)
    ax2.scatter([yr_rmax, yr_rmin, 2015], [val_rmax, val_rmin, duree_ret[-1]],
                s=55, color=COL_RET, edgecolor="white", lw=1.3, zorder=6)

    ax2.text(1958.5, 38.7, "37,5 années travaillées\n(départ à 61,5 ans)",
             fontsize=8.5, fontweight="bold", color=COL_TRAV, ha="center", va="bottom")
    ax2.text(2002.0, 44.0, "43 années travaillées (+5,5 ans, départ à 67 ans)",
             fontsize=8.6, fontweight="bold", color=COL_TRAV, ha="center", va="bottom")

    ax2.annotate(
        f"Sommet retraite : {fmt_fr(val_rmax)} ans\n(entrées 1966–1967)",
        xy=(yr_rmax, val_rmax), xytext=(1955.5, 29.8),
        fontsize=8.3, fontweight="bold", color=COL_RET,
        bbox=dict(boxstyle="round,pad=0.28", facecolor="#ECFDF5", edgecolor=COL_RET, lw=0.9),
        arrowprops=dict(arrowstyle="->", color=COL_RET, lw=1.2)
    )
    ax2.annotate(
        f"Creux : {fmt_fr(val_rmin)} ans à la retraite\n(entrée {yr_rmin} : −{fmt_fr(val_rmax - val_rmin)} ans vs 1966)",
        xy=(yr_rmin, val_rmin), xytext=(1978.0, 20.1),
        fontsize=8.2, fontweight="bold", color=COL_RET,
        bbox=dict(boxstyle="round,pad=0.28", facecolor="#ECFDF5", edgecolor=COL_RET, lw=0.9),
        arrowprops=dict(arrowstyle="->", color=COL_RET, lw=1.2)
    )
    ax2.text(2015.0, duree_ret[-1] + 1.3, f"{fmt_fr(duree_ret[-1])} ans\n(−1,1 an vs 1966)",
             fontsize=8.2, fontweight="bold", color=COL_RET, ha="right", va="bottom")

    ax2.set_ylim(18.5, 47.8)
    ax2.set_xlim(1948, 2017.5)
    ax2.set_xticks(range(1950, 2020, 5))
    ax2.set_xlabel("Année d'entrée dans le métier (âge d'entrée : 24 ans)", fontsize=10.2, labelpad=8)
    ax2.set_ylabel("Durée en années", fontsize=10.2, labelpad=8)
    ax2.yaxis.set_major_formatter(mtick.FormatStrFormatter("%.0f ans"))
    ax2.legend(loc="center left", bbox_to_anchor=(0.01, 0.56), frameon=True,
               facecolor="white", edgecolor="#E2E8F0", fontsize=8.5)
    ax2.set_title(
        "B. Le double ciseau du temps de vie : +5,5 années de travail, pour moins d'années à la retraite qu'en 1966",
        fontsize=10.4, fontweight="bold", color="#1E293B", loc="left", pad=8
    )

    fig.suptitle(
        "De 1950 à 2015 : même après impôt sur le revenu, la chute sur la vie entière atteint −639 k€ à −804 k€",
        fontsize=13.5, fontweight="bold", x=0.075, ha="left", y=0.968
    )
    fig.text(
        0.075, 0.938,
        "Reconstitution annuelle exacte (66 cohortes) en euros constants de 2026 — intégration de la législation fiscale historique (1950–2026)",
        fontsize=9.6, color="#475569", ha="left"
    )
    fig.text(0.075, 0.012, SOURCE_FOOTER_IR, fontsize=6.6, color="#64748B", va="bottom", ha="left", linespacing=1.35)
    plt.subplots_adjust(left=0.075, right=0.97, top=0.90, bottom=0.115)
    fig.savefig(BASE_DIR / "05_trajectoire_annuelle_supernet_ir.png", dpi=300)
    plt.close(fig)


def simuler_table_1950_2026(df_hist: pd.DataFrame, corps: str) -> pd.DataFrame:
    """
    Reconstruit toutes les cohortes annuelles jusqu'à aujourd'hui (1950–2026, 77 années),
    en distinguant explicitement la part de carrière déjà observée en 2026 de la part anticipée,
    et en publiant trois conventions transparentes post-2026 (méthode multi-scénarios type COR) :
      1. Maintien du pouvoir d'achat dès 2027 (g = 0,00 %/an — borne haute / optimiste)
      2. Tendance de long terme 2000–2026 (g = −1,106 %/an — scénario central tendanciel)
      3. Tendance décennale 2016–2026 (g = −1,514 %/an — scénario bas / poursuite récente)
    Pour les cohortes déjà retraitées en 2026 (1950–1984), les trois scénarios sont strictement identiques.
    """
    idx = df_hist.set_index("annee")
    pt_col = "valeur_point_reel_2026_equiv_im"
    g_25 = (idx.loc[2026, pt_col] / idx.loc[2000, pt_col]) ** (1.0 / 26.0) - 1.0
    g_10 = (idx.loc[2026, pt_col] / idx.loc[2016, pt_col]) ** (1.0 / 10.0) - 1.0

    rows = []
    for yr in range(1950, 2027):
        r0 = simuler_carriere(df_hist, corps, yr, g_override=0.0)
        r25 = simuler_carriere(df_hist, corps, yr, g_override=g_25)
        r10 = simuler_carriere(df_hist, corps, yr, g_override=g_10)

        duree = r0["duree_carriere_ans"]
        ans_obs = max(0.0, min(duree, 2026.0 - yr))
        pct_obs = round(ans_obs / duree * 100.0, 1)
        if pct_obs >= 99.9:
            statut = "100% observee"
        elif pct_obs <= 0.1:
            statut = "100% anticipee"
        else:
            statut = "Partiellement anticipee"

        rows.append({
            "annee_entree": yr,
            "annee_naissance": r0["annee_naissance"],
            "duree_carriere_ans": duree,
            "age_depart": r0["age_depart"],
            "annee_depart": r0["annee_depart"],
            "esperance_vie_retraite_ans": r0["esperance_vie_retraite_ans"],
            "part_carriere_observee_2026_pct": pct_obs,
            "statut_carriere_2026": statut,
            # Scénario 1 : Maintien pouvoir d'achat (g = 0 %/an dès 2027)
            "salaires_supernet_g0_eur_2026": r0["total_salaires_supernet_eur_2026"],
            "retraite_supernet_g0_eur_2026": r0["total_retraite_supernet_eur_2026"],
            "vie_avant_ir_g0_eur_2026": r0["total_vie_eur_2026"],
            "vie_supernet_g0_eur_2026": r0["total_vie_supernet_eur_2026"],
            "taux_ir_g0_pct": r0["taux_moyen_ir_vie_pct"],
            "gh_supernet_cours_g0_eur_2026": r0["gain_horaire_global_supernet_cours_eur_2026"],
            # Scénario 2 : Tendance long terme 2000–2026 (-1,11 %/an)
            "salaires_supernet_tendance25_eur_2026": r25["total_salaires_supernet_eur_2026"],
            "retraite_supernet_tendance25_eur_2026": r25["total_retraite_supernet_eur_2026"],
            "vie_avant_ir_tendance25_eur_2026": r25["total_vie_eur_2026"],
            "vie_supernet_tendance25_eur_2026": r25["total_vie_supernet_eur_2026"],
            "taux_ir_tendance25_pct": r25["taux_moyen_ir_vie_pct"],
            "gh_supernet_cours_tendance25_eur_2026": r25["gain_horaire_global_supernet_cours_eur_2026"],
            # Scénario 3 : Tendance décennale 2016–2026 (-1,51 %/an)
            "salaires_supernet_tendance10_eur_2026": r10["total_salaires_supernet_eur_2026"],
            "retraite_supernet_tendance10_eur_2026": r10["total_retraite_supernet_eur_2026"],
            "vie_avant_ir_tendance10_eur_2026": r10["total_vie_eur_2026"],
            "vie_supernet_tendance10_eur_2026": r10["total_vie_supernet_eur_2026"],
            "taux_ir_tendance10_pct": r10["taux_moyen_ir_vie_pct"],
            "gh_supernet_cours_tendance10_eur_2026": r10["gain_horaire_global_supernet_cours_eur_2026"],
        })
    return pd.DataFrame(rows)


# ---------------------------------------------------------------------------
# 6. POINT D'ENTRÉE PRINCIPAL
# ---------------------------------------------------------------------------
def main():
    df_hist = pd.read_csv(SERIES_CSV)

    # 1. Simulation quinquennale (1950–2015, 14 cohortes)
    df_agr = pd.DataFrame([simuler_carriere(df_hist, "agrege", yr) for yr in COHORTES])
    df_cer = pd.DataFrame([simuler_carriere(df_hist, "certifie", yr) for yr in COHORTES])

    df_agr.to_csv(BASE_DIR / "resultats_agreges.csv", index=False, encoding="utf-8-sig")
    df_cer.to_csv(BASE_DIR / "resultats_certifies.csv", index=False, encoding="utf-8-sig")

    # 2. Simulation annuelle intégrale (1950–2015, 66 cohortes, règle d'extrapolation par cohorte)
    df_agr_an = pd.DataFrame([simuler_carriere(df_hist, "agrege", yr) for yr in COHORTES_ANNUELLES])
    df_cer_an = pd.DataFrame([simuler_carriere(df_hist, "certifie", yr) for yr in COHORTES_ANNUELLES])

    df_agr_an.to_csv(BASE_DIR / "resultats_annuels_agreges_1950_2015.csv", index=False, encoding="utf-8-sig")
    df_cer_an.to_csv(BASE_DIR / "resultats_annuels_certifies_1950_2015.csv", index=False, encoding="utf-8-sig")

    # 3. Simulation complète jusqu'à aujourd'hui (1950–2026, 77 cohortes, 3 scénarios type COR)
    df_agr_26 = simuler_table_1950_2026(df_hist, "agrege")
    df_cer_26 = simuler_table_1950_2026(df_hist, "certifie")

    df_agr_26.to_csv(BASE_DIR / "resultats_annuels_agreges_1950_2026.csv", index=False, encoding="utf-8-sig")
    df_cer_26.to_csv(BASE_DIR / "resultats_annuels_certifies_1950_2026.csv", index=False, encoding="utf-8-sig")

    # 4. Génération des 5 graphiques haute définition
    generer_graphiques(df_agr, df_cer, df_agr_an, df_cer_an)

    # 4. Affichage synthétique de contrôle
    cols_show = [
        "annee_entree", "duree_carriere_ans", "esperance_vie_retraite_ans",
        "total_vie_eur_2026", "taux_moyen_ir_vie_pct", "total_vie_supernet_eur_2026",
        "gain_horaire_global_cours_eur_2026", "gain_horaire_global_supernet_cours_eur_2026",
    ]
    print("\n================ RÉSULTATS PROFESSEURS AGRÉGÉS (1950–2015, € 2026) ================")
    print(df_agr[cols_show].to_string(index=False))
    print("\n================ RÉSULTATS PROFESSEURS CERTIFIÉS (1950–2015, € 2026) ================")
    print(df_cer[cols_show].to_string(index=False))

    for nom, df_an in [("AGRÉGÉS", df_agr_an), ("CERTIFIÉS", df_cer_an)]:
        b_av = df_an.loc[df_an["total_vie_eur_2026"].idxmax()]
        w_av = df_an.loc[df_an["total_vie_eur_2026"].idxmin()]
        b_sn = df_an.loc[df_an["total_vie_supernet_eur_2026"].idxmax()]
        w_sn = df_an.loc[df_an["total_vie_supernet_eur_2026"].idxmin()]
        print(f"\n--- {nom} (PRÉCISION ANNUELLE 1950–2015) ---")
        print(f"  AVANT IR  | Plus généreuse : {int(b_av['annee_entree'])} ({fmt_eur(b_av['total_vie_eur_2026'])}, {b_av['gain_horaire_global_cours_eur_2026']:.2f} €/h) "
              f"| Plus pingre : {int(w_av['annee_entree'])} ({fmt_eur(w_av['total_vie_eur_2026'])}, {w_av['gain_horaire_global_cours_eur_2026']:.2f} €/h)")
        print(f"  SUPER-NET | Plus généreuse : {int(b_sn['annee_entree'])} ({fmt_eur(b_sn['total_vie_supernet_eur_2026'])}, {b_sn['gain_horaire_global_supernet_cours_eur_2026']:.2f} €/h, "
              f"trav={b_sn['duree_carriere_ans']} ans, ret={b_sn['esperance_vie_retraite_ans']} ans)")
        print(f"            | Plus pingre    : {int(w_sn['annee_entree'])} ({fmt_eur(w_sn['total_vie_supernet_eur_2026'])}, {w_sn['gain_horaire_global_supernet_cours_eur_2026']:.2f} €/h, "
              f"trav={w_sn['duree_carriere_ans']} ans, ret={w_sn['esperance_vie_retraite_ans']} ans)")
        print(f"            | Perte sèche    : {fmt_eur(w_sn['total_vie_supernet_eur_2026'] - b_sn['total_vie_supernet_eur_2026'])} "
              f"({(w_sn['total_vie_supernet_eur_2026']/b_sn['total_vie_supernet_eur_2026']-1)*100:.1f} %)")


if __name__ == "__main__":
    main()
