"""
PRIOR-SENSITIVITY of the Laplace Bayes factor (DFD vs LCDM).
The Laplace ln B depends on the assumed FLAT-prior widths of the genuinely FITTED knobs. The honest
question: is the LCDM lead (ln B ~ -1.2 from laplace_evidence.py) robust, or an artifact of arbitrary
prior choices for DFD's theta_i and A_s-coefficient? Scan the two DFD-specific prior widths over
physically defensible ranges and report ln B each time. chi^2 fixed at the joint values (no re-run).
"""
import numpy as np

# frozen joint chi^2 (from laplace_evidence.py / joint_fit.py)
CHI_DFD, CHI_LCDM = 1999.7, 1994.8

# --- LCDM Occam total (6 params), fixed (Planck chains + standard priors) ---
# per-param ln(sqrt(2pi) sigma/Delta):
LCDM_OCCAM = -16.302   # from laplace_evidence.py

# --- DFD shared-input Occam (ombh2 + tau), identical to LCDM's two of those ---
DFD_SHARED_OCCAM = -2.770 + -1.881   # ombh2, tau

# DFD posterior sigmas for the two contested knobs (data-driven, fixed):
SIG_THETA_I = 0.001362     # from omch2 CMB sigma propagated through Omega_chi h^2 = 1.62 theta_i^2
SIG_ASCOEFF = 1.407        # from ln(As) posterior sigma * 32pi


def occ(sig, Delta): return np.log(np.sqrt(2*np.pi)*sig/Delta)


def lnB(theta_i_prior, ascoeff_prior_factor):
    """theta_i_prior = flat-prior width for the misalignment angle (rad).
       ascoeff_prior_factor = multiplicative range for the A_s coeff prior (e.g. 16 = 8pi..128pi)."""
    occ_theta = occ(SIG_THETA_I, theta_i_prior)
    ascoeff0 = 32*np.pi
    Delta_asc = ascoeff0*(ascoeff_prior_factor-1.0/ascoeff_prior_factor)  # symmetric-ish in log: [coeff/f, coeff*f]
    occ_asc = occ(SIG_ASCOEFF, Delta_asc)
    occ_dfd = DFD_SHARED_OCCAM + occ_theta + occ_asc
    lnZ_dfd = -0.5*CHI_DFD + occ_dfd
    lnZ_lcdm = -0.5*CHI_LCDM + LCDM_OCCAM
    return lnZ_dfd-lnZ_lcdm, occ_dfd


print("="*80)
print("PRIOR SENSITIVITY OF LAPLACE ln B (DFD/LCDM).  ln B>0 favours DFD.")
print("="*80)
print(f"  Frozen: chi^2 DFD {CHI_DFD}, LCDM {CHI_LCDM} (Delta=+{CHI_DFD-CHI_LCDM:.1f}); LCDM Occam {LCDM_OCCAM}")
print("\n  theta_i is a misalignment ANGLE: natural prior [0,1] rad (or [0,pi] if maximal).")
print("  A_s coeff: 32pi asserted; prior factor f means coeff in [32pi/f, 32pi*f].")
print("\n  scan:")
print(f"  {'theta_i prior':>14s} {'As-coeff factor':>16s} {'Occam_DFD':>11s} {'ln B':>8s}   verdict")
scen = [
    (1.0, 16.0, "broad (laplace_evidence.py default)"),
    (1.0, 4.0,  "moderate As prior"),
    (1.0, 2.0,  "tight As prior (coeff known to ~2x)"),
    (np.pi, 16.0, "theta_i in [0,pi]"),
    (0.5, 4.0,  "theta_i half-range, moderate As"),
    (1.0, 1.3,  "As coeff ~derived (factor 1.3)"),
    (0.5, 2.0,  "both tight (most DFD-favourable defensible)"),
]
for tp, af, lab in scen:
    b, od = lnB(tp, af)
    verd = "DFD" if b > 0 else "LCDM"
    print(f"  {tp:14.3f} {af:16.1f} {od:11.2f} {b:+8.2f}   {verd}: {lab}")

print("\n  "+"-"*76)
print("  Threshold: ln B flips to DFD-favoured when the DFD Occam penalty shrinks enough to beat")
print(f"  the +{CHI_DFD-CHI_LCDM:.1f} chi^2 deficit + LCDM's lighter Occam. Solve for the A_s-coeff prior factor")
print("  that gives ln B=0 at theta_i prior=1.0:")
# find break-even As factor at theta_i prior=1
from scipy.optimize import brentq
f_be = brentq(lambda f: lnB(1.0, f)[0], 1.001, 100)
print(f"    break-even A_s-coeff prior factor = {f_be:.2f}  (tighter than this -> DFD wins; broader -> LCDM)")
print("\n  HONEST: the Laplace verdict is PRIOR-SENSITIVE. With broad, agnostic priors on DFD's two")
print("  fitted knobs (theta_i, A_s coeff), LCDM is mildly preferred (ln B ~ -1.2, 'substantial').")
print("  With physically tight priors (the coeff IS argued to be ~32pi; theta_i ~O(0.3)), DFD draws")
print("  level or ahead. The robust statement: DFD and LCDM are within ~1 e-fold of evidence either")
print("  way -- a STATISTICAL TIE at the evidence level, NOT a decisive BIC-style DFD win.")
