"""Step 8. [HP] section 3 and 7.2: the Landau analysis on the paper's actual restricted holonomy domain.

Domain and potential ([HP] eq. V, Sfull):  u = |u_1| in [0, 1),
    V(u) = u^2 (u <= 1/2),   V(u) = 1/4 - (1/2) ln[2(1-u)]  (1/2 <= u < 1, gapped branch),
    S(u)/N^2 = V(u) - u^2 + m^2 u^2 + b u^4 .
(1) the gapped branch itself: Legendre transform of the Gross-Witten-Wadia free energy, and a finite-N check of that
    free energy from the exact Toeplitz determinant  Z_N(beta) = det[ I_{j-k}(2 N beta) ]  (independent of the paper);
(2) exact saddles of S(u) and the three thresholds m^2_min (saddle-node), m^2_c (degeneracy), 0 (Hagedorn) versus the
    leading-order values |b|/2, |b|/4 of [HP] eq. (us), (eps), Table (regimes) and the caption of Fig. (potential);
(3) temperatures: exact inversion of m_1^2(T) through two loops versus the series [HP] eq. (three-T); ordering;
(4) b > 0: second-order point and Gross-Witten-Wadia point;  (5) comparison with the AdS_5 black-hole thermodynamics
    quoted in [HP] section 1 (T_min = sqrt2/(pi R), T_HP = 3/(2 pi R)).
Outputs: results/hp_landau.json, results/hp_landau_scan.csv, results/hp_potential_curves.csv, results/hp_temperatures.csv,
         results/hp_gww_finiteN.csv, results/hp_gravity_branches.csv
"""
import numpy as np
import mpmath as mp
from scipy.optimize import brentq
from common import Tee, event, save_json, save_csv, load_json, check

mp.mp.dps = 30


def V(u):
    return u * u if u <= 0.5 else 0.25 - 0.5 * np.log(2 * (1 - u))


def dV(u):
    return 2 * u if u <= 0.5 else 0.5 / (1 - u)


def d2V(u):
    return 2.0 if u <= 0.5 else 0.5 / (1 - u) ** 2


def S(u, m2, b):
    return V(u) - u * u + m2 * u * u + b * u**4


def dS(u, m2, b):
    return dV(u) - 2 * u + 2 * m2 * u + 4 * b * u**3


def d2S(u, m2, b):
    return d2V(u) - 2 + 2 * m2 + 12 * b * u * u


def saddles(m2, b, n=40001):
    """All stationary points of S on (0, 1) by sign changes of S' on a fine grid, refined with brentq."""
    us = np.linspace(1e-9, 1 - 1e-7, n)
    f = np.array([dS(u, m2, b) for u in us])
    out = []
    for i in np.where(np.sign(f[:-1]) * np.sign(f[1:]) < 0)[0]:
        r = brentq(dS, us[i], us[i + 1], args=(m2, b), xtol=1e-15)
        out.append((r, S(r, m2, b), "min" if d2S(r, m2, b) > 0 else "max"))
    return out


def thresholds(b):
    """Exact m^2_min (birth of the second minimum) and m^2_c (degenerate with u=0) for b < 0."""
    ab = -b
    # saddle-node: S' = 0 and S'' = 0.  From S'=0: m2(u) = [2u - V'(u) - 4 b u^3]/(2u); the pair is born at the maximum of m2(u).
    m2_of_u = lambda u: (2 * u - dV(u) - 4 * b * u**3) / (2 * u)
    uu = np.linspace(0.5, 0.999, 200001)
    vals = np.array([m2_of_u(u) for u in uu])
    i = int(np.argmax(vals))
    from scipy.optimize import minimize_scalar
    res = minimize_scalar(lambda u: -m2_of_u(u), bounds=(uu[max(i - 2, 0)], uu[min(i + 2, len(uu) - 1)]), method="bounded", options={"xatol": 1e-14})
    u_sn, m2_min = res.x, -res.fun
    # degeneracy: S(u) = 0 on the branch of minima u_min(m2)
    def gap(m2):
        mins = [s for s in saddles(m2, b, 4001) if s[2] == "min"]
        return mins[-1][1]
    m2_c = brentq(gap, 1e-9 * ab, m2_min * (1 - 1e-9), xtol=1e-14)
    mins = [s for s in saddles(m2_c, b) if s[2] == "min"][-1]
    maxs = [s for s in saddles(m2_c, b) if s[2] == "max"]
    return dict(m2_min=m2_min, u_saddle_node=u_sn, m2_c=m2_c, u_c=mins[0], barrier_at_c=maxs[0][1] if maxs else None, u_s_at_c=maxs[0][0] if maxs else None)


def main():
    R = {"checks": []}; C = R["checks"]
    H = load_json("hp_hagedorn.json"); Q = load_json("hp_quartic.json")
    b0 = float(H["beta_0"]); b_g4 = Q["quartic"]["b_over_g4"]; hw = float(H["HW_two_loop_coefficient"]); d4 = float(H["d4_target"]); C41 = 8.353829

    print("== (1) the gapped branch: junction at u = 1/2 and Gross-Witten-Wadia origin ([HP] eq. V, Vcubic)")
    e = 1e-6
    C.append(check("V continuous at 1/2", V(0.5 + 1e-12), 0.25, 1e-10, "[HP] eq. (V)"))
    C.append(check("V' continuous at 1/2 (gapped branch value)", 0.5 / (1 - 0.5), 1.0, 1e-14, "[HP] eq. (V)"))
    C.append(check("V'' continuous at 1/2 (gapped branch value)", 0.5 / (1 - 0.5) ** 2, 2.0, 1e-14, "[HP] eq. (V)"))
    C.append(check("jump of V''' at 1/2", 1 / (1 - 0.5) ** 3 - 0.0, 8.0, 1e-14, "[HP] section 3.2"))
    for eps in (0.01, 0.001):
        C.append(check(f"(V(u)-u^2)/eps^3 at eps={eps} -> 4/3", (V(0.5 + eps) - (0.5 + eps) ** 2) / eps**3, 4 / 3, 5 * eps, "[HP] eq. (Vcubic)"))
    # Legendre transform of the GWW free energy F(beta) = beta^2 (beta<=1/2), 2 beta - 3/4 - (1/2) ln(2 beta) (beta>=1/2)
    Fg = lambda be: be * be if be <= 0.5 else 2 * be - 0.75 - 0.5 * np.log(2 * be)
    from scipy.optimize import minimize_scalar
    worst = 0
    for u in (0.1, 0.3, 0.5, 0.6, 0.75, 0.9, 0.97):
        res = minimize_scalar(lambda be: -(2 * be * u - Fg(be)), bounds=(0, 200), method="bounded", options={"xatol": 1e-13})
        worst = max(worst, abs(-res.fun - V(u)))
    C.append(check("V(u) = sup_beta [2 beta u - F_GWW(beta)] at 7 values of u (max abs deviation)", worst, 0, 1e-9, "[HP] section 3.2 (Legendre transform of Gross-Witten-Wadia)"))
    # finite-N Toeplitz determinant check of F_GWW
    rows = []
    for be in (0.25, 0.5, 0.75, 1.0, 1.5):
        for N in (2, 4, 8, 16, 32):
            M = mp.matrix(N, N)
            for j in range(N):
                for k in range(N):
                    M[j, k] = mp.besseli(abs(j - k), 2 * N * be)
            FN = float(mp.log(mp.det(M)) / N**2)
            rows.append([be, N, FN, Fg(be), FN - Fg(be)])
    save_csv("hp_gww_finiteN.csv", ["beta", "N", "F_N", "F_GWW_largeN", "difference"], rows)
    for be in (0.25, 0.75, 1.5):
        rr = [r for r in rows if r[0] == be]
        print(f"  Toeplitz det, beta={be}: F_N - F_inf at N=2,4,8,16,32: " + ", ".join(f"{r[4]:+.2e}" for r in rr))
    C.append(check("finite-N GWW free energy, N=32, beta=1.5 (gapped phase)", [r for r in rows if r[0] == 1.5 and r[1] == 32][0][2], Fg(1.5), 2e-3, "Gross-Witten, Wadia as cited in [HP] section 3.2"))
    C.append(check("finite-N GWW free energy, N=32, beta=0.25 (ungapped phase)", [r for r in rows if r[0] == 0.25 and r[1] == 32][0][2], Fg(0.25), 1e-6, "Gross-Witten, Wadia as cited in [HP] section 3.2"))

    print("== (2) exact saddles and thresholds on the restricted domain")
    th = thresholds(-0.1)
    print(f"  |b| = 0.1 (the exaggerated value of [HP] Fig. potential): m^2_min = {th['m2_min']:.5f} (caption: 0.053; leading order 0.05), "
          f"m^2_c = {th['m2_c']:.5f} (caption: 0.032; leading order 0.025); u_c = {th['u_c']:.4f} (leading 1/2+sqrt|b|/4 = {0.5+0.1**0.5/4:.4f})")
    C.append(check("m^2 at which the second minimum appears, |b|=0.1", th["m2_min"], 0.053, 6e-4, "[HP] Fig. (potential) caption"))
    C.append(check("m^2 at which the minima are degenerate, |b|=0.1", th["m2_c"], 0.032, 6e-4, "[HP] Fig. (potential) caption"))
    R["b_0p1"] = th
    scan = []
    for ab in np.logspace(-6, np.log10(0.3), 28):
        t = thresholds(-ab)
        scan.append([ab, t["m2_min"], t["m2_c"], t["m2_min"] / ab, t["m2_c"] / ab, t["u_c"], t["u_c"] - 0.5, np.sqrt(ab) / 4, t["u_saddle_node"] - 0.5,
                     t["barrier_at_c"], t["barrier_at_c"] / ab, 1.5 * t["u_c"] ** 2])
    save_csv("hp_landau_scan.csv", ["abs_b", "m2_min", "m2_c", "m2_min_over_b", "m2_c_over_b", "u_c", "u_c_minus_half", "sqrt_b_over_4", "u_saddle_node_minus_half",
                                    "barrier_height_at_Tc", "barrier_over_b", "latent_heat_over_N2"], scan)
    sc = np.array(scan)
    # leading corrections: fit (m2_c/|b| - 1/4) ~ k |b|^p on small |b|
    msk = sc[:, 0] < 1e-3
    p_c = np.polyfit(np.log(sc[msk, 0]), np.log(sc[msk, 4] - 0.25), 1)
    p_m = np.polyfit(np.log(sc[msk, 0]), np.log(sc[msk, 3] - 0.5), 1)
    print(f"  small-|b| scan: m^2_c/|b| - 1/4 ~ {np.exp(p_c[1]):.3f} |b|^{p_c[0]:.3f};  m^2_min/|b| - 1/2 ~ {np.exp(p_m[1]):.3f} |b|^{p_m[0]:.3f}")
    print(f"  at |b| = 1e-6: m^2_min/|b| = {sc[0,3]:.6f}, m^2_c/|b| = {sc[0,4]:.6f}, (u_c - 1/2)/(sqrt|b|/4) = {sc[0,6]/sc[0,7]:.5f}, barrier/|b| = {sc[0,10]:.6f} (leading 1/64 = {1/64:.6f})")
    C.append(check("m^2_min/|b| -> 1/2 as |b| -> 0", sc[0, 3], 0.5, 2e-3, "[HP] eq. (us),(eps), Table (regimes)"))
    C.append(check("m^2_c/|b| -> 1/4 as |b| -> 0", sc[0, 4], 0.25, 2e-3, "[HP] section 3.3"))
    C.append(check("(u_c - 1/2)/(sqrt|b|/4) -> 1", sc[0, 6] / sc[0, 7], 1.0, 5e-3, "[HP] section 3.3"))
    C.append(check("latent heat (3/2) u_c^2 -> 3/8 as |b| -> 0", sc[0, 11], 0.375, 2e-3, "[HP] eq. (latent)"))
    C.append(check("correction exponent of m^2_c/|b| (expected 1/2: O(|b|^(3/2)) terms from the wall)", p_c[0], 0.5, 0.05, "[HP] section 3.3 ('up to terms of order |b|^(3/2)')"))
    R["scan_fit"] = dict(exp_c=float(p_c[0]), coef_c=float(np.exp(p_c[1])), exp_min=float(p_m[0]), coef_min=float(np.exp(p_m[1])))
    # potential curves for the figure (|b| = 0.1)
    curves = []
    for lab, m2 in (("m2=0.08 (T<T_min)", 0.08), ("m2=m2_min", th["m2_min"]), ("m2=0.042", 0.042), ("m2=m2_c (T_c)", th["m2_c"]), ("m2=0.015", 0.015), ("m2=0 (T_H)", 0.0), ("m2=-0.02 (T>T_H)", -0.02)):
        for u in np.linspace(0, 0.8, 321):
            curves.append([lab, m2, u, S(u, m2, -0.1), m2 * u * u - 0.1 * u**4])
    save_csv("hp_potential_curves.csv", ["label", "m2", "u", "S_full_restricted_domain", "S_truncated_quartic_no_wall"], curves)
    # regime table check at |b| = 0.1 with exact thresholds
    reg = []
    for m2 in (0.08, 0.045, 0.02, -0.02):
        sd = saddles(m2, -0.1)
        gmin = min([(0.0, 0.0)] + [(s[1], s[0]) for s in sd if s[2] == "min"])
        reg.append(dict(m2=m2, saddles=[(round(s[0], 5), round(s[1], 6), s[2]) for s in sd], global_minimum_u=gmin[1], origin_is_minimum=bool(m2 > 0)))
        print(f"  m^2 = {m2:+.3f}: interior saddles {[(round(s[0],4), s[2]) for s in sd]}; global minimum at u = {gmin[1]:.4f}; u=0 is {'a local minimum' if m2>0 else 'unstable'}")
    R["regimes_b_0p1"] = reg
    ok_reg = (len(reg[0]["saddles"]) == 0 and len(reg[1]["saddles"]) == 2 and reg[1]["global_minimum_u"] == 0.0 and len(reg[2]["saddles"]) == 2
              and reg[2]["global_minimum_u"] > 0.5 and len(reg[3]["saddles"]) == 1 and reg[3]["global_minimum_u"] > 0.5)
    C.append({"label": "four regimes of [HP] Table (regimes) reproduced with exact saddles (|b|=0.1)", "computed": int(ok_reg), "paper": 1, "absdiff": 0, "tol": 0, "pass": bool(ok_reg), "source": "[HP] Table (regimes)", "unit": ""})
    # truncated potential without the wall is unbounded below on the unrestricted domain
    print(f"  truncated quartic without the gapped branch at m^2=0.02, b=-0.1: S(0.8) = {0.02*0.64-0.1*0.8**4:+.4f}, S(2) = {0.02*4-0.1*16:+.3f} -> unbounded below; the wall is essential")

    print("== (3) temperatures through two loops: exact inversion of m_1^2(T) versus the series of [HP] eq. (three-T)")
    zc = lambda be: (lambda y: 2 * y**2 * (3 - y) / (1 - y) ** 3)(mp.exp(-be / 2))
    def d1f(be):
        y = mp.exp(-be / 2)
        return 2 * (1 + y) ** 2 / (1 - y) ** 6 * (-(1 - 4 * y + y**2) ** 2 * mp.log(1 - y**2) - y**2 * (1 - 8 * y + 2 * y**2))
    def m1sq(be, g2):
        return 1 - zc(be) + 2 * g2 * be * d1f(be) + g2**2 * (be * d4 - 2 * be**2 * C41)
    trow = []
    for lam in (0.01, 0.1, 0.5, 1.0, 2.0, 5.0):
        g2 = lam / (16 * np.pi**2); ab = -b_g4 * g2**2
        t = thresholds(-ab)
        sol = {}
        for nm, target in (("T_H", 0.0), ("T_c", t["m2_c"]), ("T_min", t["m2_min"])):
            be = mp.findroot(lambda x: m1sq(x, g2) - target, b0)
            sol[nm] = float(1 / be)
        ser = dict(T_H=(1 + 2 * g2 + hw * g2**2) / b0, T_c=(1 + 2 * g2 + (hw + b_g4 / (6 * b0)) * g2**2) / b0, T_min=(1 + 2 * g2 + (hw + b_g4 / (3 * b0)) * g2**2) / b0)
        ordered = sol["T_min"] < sol["T_c"] < sol["T_H"]
        trow.append([lam, g2, ab, sol["T_min"], sol["T_c"], sol["T_H"], ser["T_min"], ser["T_c"], ser["T_H"], (sol["T_H"] - sol["T_c"]) / sol["T_H"], ab / (6 * b0),
                     (sol["T_H"] - sol["T_min"]) / sol["T_H"], ab / (3 * b0), t["u_c"], 0.5 + np.sqrt(ab) / 4, bool(ordered)])
        print(f"  lambda={lam:5.2f} (g^2={g2:.2e}, |b|={ab:.2e}): exact T_min={sol['T_min']:.9f} < T_c={sol['T_c']:.9f} < T_H={sol['T_H']:.9f}  ordered={ordered}; "
              f"(T_H-T_c)/T_H = {trow[-1][9]:.3e} (leading |b|/6beta0 = {trow[-1][10]:.3e}); jump u_c = {t['u_c']:.5f}")
    save_csv("hp_temperatures.csv", ["lambda", "g2", "abs_b", "T_min_exact", "T_c_exact", "T_H_exact", "T_min_series", "T_c_series", "T_H_series",
                                     "window_c_exact", "window_c_leading", "window_min_exact", "window_min_leading", "u_c_exact", "u_c_leading", "ordering_Tmin<Tc<TH"], trow)
    C.append({"label": "ordering T_min < T_c < T_H for lambda in {0.01,...,5}", "computed": sum(r[-1] for r in trow), "paper": len(trow), "absdiff": 0, "tol": 0, "pass": all(r[-1] for r in trow),
              "source": "[HP] section 7.2", "unit": ""})
    l1 = [r for r in trow if r[0] == 1.0][0]
    C.append(check("window (T_H-T_c)/T_H at lambda=1 ('one part in ten thousand')", l1[9], 9.37e-5, 4e-6, "[HP] eq. (window), section 7.2"))
    C.append(check("ratio of windows (T_H-T_min)/(T_H-T_c) at lambda=0.01 -> 2", [r for r in trow if r[0] == 0.01][0][11] / [r for r in trow if r[0] == 0.01][0][9], 2.0, 0.02, "[HP] eq. (Tc)"))
    R["temperatures"] = trow

    print("== (4) b > 0: continuous transition and Gross-Witten-Wadia point")
    bp = 0.1
    for m2 in (-0.02, -0.05, -0.08):
        sd = saddles(m2, bp)
        print(f"  b=+0.1, m^2={m2:+.3f}: minimum at u = {sd[-1][0]:.5f} (ungapped formula sqrt(-m^2/2b) = {np.sqrt(-m2/(2*bp)):.5f}; gapped: {sd[-1][0] > 0.5})")
    C.append(check("b>0: minimum reaches u=1/2 at m^2 = -b/2", saddles(-bp / 2, bp)[-1][0], 0.5, 1e-4, "[HP] section 3.4"))
    C.append(check("b>0: free energy -m^4/4b at m^2=-0.02", saddles(-0.02, bp)[-1][1], -(0.02**2) / (4 * bp), 1e-10, "[HP] section 3.4"))

    print("== (5) gravity side quoted in [HP] section 1: Schwarzschild-AdS_5 (R = 1)")
    # f(r) = 1 + r^2 - mu/r^2:  T(r+) = (2 r+^2 + 1)/(2 pi r+),  F(r+) proportional to r+^2 (1 - r+^2)
    Tg = lambda r: (2 * r * r + 1) / (2 * np.pi * r)
    rmin = brentq(lambda r: (Tg(r + 1e-7) - Tg(r - 1e-7)), 0.3, 1.5)
    C.append(check("T_min of AdS_5 black holes = sqrt2/pi", Tg(rmin), np.sqrt(2) / np.pi, 1e-9, "[HP] section 1.1"))
    C.append(check("T_HP = T(r+ = R) = 3/(2 pi)", Tg(1.0), 3 / (2 * np.pi), 1e-14, "[HP] eq. (THP)"))
    grav = [[r, Tg(r), r * r * (1 - r * r), "small" if r < rmin else "large"] for r in np.linspace(0.15, 1.6, 146)]
    save_csv("hp_gravity_branches.csv", ["r_plus_over_R", "T_times_R", "F_in_units_pi_over_8G_R2", "branch"], grav)
    R["gravity"] = dict(T_min=float(Tg(rmin)), T_HP=float(Tg(1.0)), ratio_Tmin_over_THP=float(Tg(rmin) / Tg(1.0)))
    print(f"  gravity: T_min/T_HP = {Tg(rmin)/Tg(1.0):.4f} (= 2 sqrt2/3); weak coupling: T_min/T_c = 1 - {abs(b_g4)/(6*b0):.3f} g^4 -> 1; no classical counterpart of T_H")
    R["n_checks"] = len(C); R["n_pass"] = sum(bool(c["pass"]) for c in C)
    print(f"SUMMARY: {R['n_pass']}/{R['n_checks']} checks pass")
    for c in C:
        if not c["pass"]:
            print("  NOT PASSED:", c["label"], c["computed"], c["paper"])
    save_json("hp_landau.json", R)
    event("compute", "Landau analysis on the restricted holonomy domain",
          f"|b|=0.1: m2_min={th['m2_min']:.4f}, m2_c={th['m2_c']:.4f} (caption 0.053, 0.032); ordering T_min<T_c<T_H holds for all tested couplings; {R['n_pass']}/{R['n_checks']} checks pass",
          outputs=["results/hp_landau.json", "results/hp_landau_scan.csv", "results/hp_temperatures.csv"])


if __name__ == "__main__":
    with Tee("s08_hp_landau"):
        main()
