"""
Iteration 4: INDUSTRIAL JOINT FIT — total chi^2 over real CMB(plik-lite) + BAO + Pantheon+ SNe + Planck
lensing, DFD (frozen derived screen A=0.0667, NO refit) vs LCDM(Planck 2018). Model comparison by AIC/BIC
accounting for DFD's fewer DERIVED parameters. Honesty-guard: real chi^2 from every probe, honest verdict.
Two CAMB calls total (each gives CMB Cl + sigma8 + lensing).

REFACTOR (2026-06-27): all per-sector chi^2 now come from the shared dfd_likelihoods.py
module (single source of truth) -- no inline copies, so joint_fit / cmb_model_comparison /
paramcount_sensitivity can never drift apart. The CMB plik-lite, BAO, Pantheon+ and the
amplitude lensing proxy all run LIVE here (CAMB + numpy). HONESTY-GUARD: numbers unchanged.
"""
import numpy as np
import dfd_likelihoods as L

print("=" * 78)
print("INDUSTRIAL JOINT FIT — DFD (frozen screen) vs LCDM, ALL real probes")
print("=" * 78)
print("\n  running 2 CAMB models (DFD, LCDM)...")

# One CAMB call per model (CMB Cl + sigma8 + Om), then live per-sector chi^2 from the shared module.
dfd_m = L.dfd_camb()
lcdm_m = L.lcdm_camb()
secs = L.per_sector_chi2(lensing="proxy", dfd_model=dfd_m, lcdm_model=lcdm_m)

# Map shared-module sector names -> the short labels this script prints.
LABELS = {
    "CMB TT/TE/EE (plik-lite cov)": "CMB TT/TE/EE (plik-lite)",
    "BAO (12 consensus pts)": "BAO (12 pts)",
    "Pantheon+ SNe (full cov)": "Pantheon+ SNe",
    "Planck lensing (sigma8 Om^0.25)": "Planck lensing",
}
print(f"\n  {'probe':28s} {'N':>5s} {'chi2 DFD':>10s} {'chi2 LCDM':>10s}")
TD = TL = NT = 0
for key, s in secs.items():
    name = LABELS.get(key, key)
    print(f"  {name:28s} {s['N']:5d} {s['dfd']:10.1f} {s['lcdm']:10.1f}")
    TD += s["dfd"]; TL += s["lcdm"]; NT += s["N"]
kD, kL = 4, 6
aicD, aicL = TD + 2 * kD, TL + 2 * kL
bicD, bicL = TD + kD * np.log(NT), TL + kL * np.log(NT)
print(f"  {'TOTAL':28s} {NT:5d} {TD:10.1f} {TL:10.1f}")
print("\n" + "-" * 78)
print(f"  Total chi^2: DFD {TD:.1f}  LCDM {TL:.1f}   Delta(DFD-LCDM) = {TD-TL:+.1f} over N={NT}")
print(f"  free params: DFD k={kD} (theta_i, ombh2, tau, As-norm; rest DERIVED)  LCDM k={kL}")
print(f"  AIC: DFD {aicD:.1f}  LCDM {aicL:.1f}   Delta AIC = {aicD-aicL:+.1f}")
print(f"  BIC: DFD {bicD:.1f}  LCDM {bicL:.1f}   Delta BIC = {bicD-bicL:+.1f}")
print(f"\n  VERDICT: |Delta AIC|={abs(aicD-aicL):.1f}, |Delta BIC|={abs(bicD-bicL):.1f}. "
      + ("Statistically INDISTINGUISHABLE (DFD with 2 fewer derived params)."
         if abs(aicD - aicL) < 2 and abs(bicD - bicL) < 2 else "see deltas."))
print("  HONEST: chi^2/AIC/BIC joint fit (frozen DFD prediction vs LCDM best-fit). Not yet a full")
print("  nested-sampling Bayesian EVIDENCE; lensing is amplitude-level (clik 8-bin pending).")
