"""Step 6. [HP] section 2 and 4: the free single-letter Hagedorn equation, solved independently.

(1) single-letter partition functions from an explicit enumeration of the S^3 modes of [HP] Table 1 (no closed form),
    truncation sweep in the mode cut-off, root of z(x) = 1 by bisection;
(2) closed forms [HP] eq. (zBzF), (z), the cubic, x_H, beta_0, T_H, x z'(x) = 3/2, w'' = -(3/2) sqrt 3;
(3) [HP] eq. (d1), (d1H): one-loop mass coefficient, its series, its value and beta-derivative at x_H;
(4) Harmark-Wilhelm two-loop coefficient (closed form quoted in [HP] eq. HW) and the target d_4 of [HP] eq. (target);
    independent closure test: solve m_1^2(T) = 0 numerically and recover the g^4 coefficient of T_H;
(5) temperature sweep of z_n and of the masses of the moments u_n; Hagedorn growth of the confined partition function.
Outputs: results/hp_hagedorn.json, results/hp_modesum_convergence.csv, results/hp_temperature_sweep.csv, results/hp_growth.csv
"""
from fractions import Fraction
import mpmath as mp
import sympy as sy
from common import Tee, event, save_json, save_csv, check

mp.mp.dps = 40


def z_modes(x, nmax):
    """Sum of x^E over the modes of [HP] Table 1 with n = 2j+1 <= nmax.  Returns (zB, zF)."""
    zB = mp.mpf(0); zF = mp.mpf(0)
    for n in range(1, nmax + 1):
        zB += 6 * n * n * x**n                                  # 6 scalars, harmonics (j,j): (2j+1)^2 states, E = 2j+1
        zB += 2 * n * (n + 2) * x ** (n + 1)                    # gauge field, (j+1,j)+(j,j+1): 2(2j+1)(2j+3) states, E = 2j+2
        zF += 4 * 2 * n * (n + 1) * x ** (n + mp.mpf(1) / 2)    # 4 Weyl fermions, (j+1/2,j)+(j,j+1/2): 2(2j+1)(2j+2), E = 2j+3/2
    return zB, zF


def zB_cf(x):
    return (6 * x + 12 * x**2 - 2 * x**3) / (1 - x) ** 3


def zF_cf(x):
    return 16 * x ** mp.mpf(1.5) / (1 - x) ** 3


def z_cf(x):
    y = mp.sqrt(x)
    return 2 * y**2 * (3 - y) / (1 - y) ** 3


def zn(x, n):
    return zB_cf(x**n) + (-1) ** (n + 1) * zF_cf(x**n)


def d1(x):
    y = mp.sqrt(x)
    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 bisect(fun, a, b, tol):
    fa = fun(a)
    while b - a > tol:
        m = (a + b) / 2; fm = fun(m)
        if (fa > 0) == (fm > 0):
            a, fa = m, fm
        else:
            b = m
    return (a + b) / 2


def main():
    R = {"checks": []}; C = R["checks"]
    print("== (1) mode enumeration and root of z(x) = 1")
    rows = []
    for nmax in (1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96):
        xr = bisect(lambda x: sum(z_modes(x, nmax)) - 1, mp.mpf("0.01"), mp.mpf("0.5"), mp.mpf(10) ** (-35))
        rows.append([nmax, mp.nstr(xr, 30), float(xr - (7 - 4 * mp.sqrt(3))), float(-1 / mp.log(xr))])
        print(f"  modes n=2j+1 <= {nmax:3d}: x_root = {mp.nstr(xr, 22)}  (x_root - (7-4 sqrt3) = {float(xr-(7-4*mp.sqrt(3))):+.3e})  T = {float(-1/mp.log(xr)):.10f}")
    save_csv("hp_modesum_convergence.csv", ["n_max", "x_root", "x_root_minus_closed_form", "T_root"], rows)
    xH_modes = bisect(lambda x: sum(z_modes(x, 200)) - 1, mp.mpf("0.01"), mp.mpf("0.5"), mp.mpf(10) ** (-36))
    xH = 7 - 4 * mp.sqrt(3); yH = 2 - mp.sqrt(3); b0 = -mp.log(xH)
    R.update(x_H_modesum=mp.nstr(xH_modes, 34), x_H=mp.nstr(xH, 34), y_H=mp.nstr(yH, 34), beta_0=mp.nstr(b0, 34), T_H0=mp.nstr(1 / b0, 34))
    C.append(check("x_H from mode sum (n<=200) vs 7-4 sqrt3", xH_modes, xH, 1e-30, "[HP] eq. (xH)"))
    C.append(check("x_H", xH, 0.07180, 5e-6, "[HP] eq. (xH)"))
    C.append(check("beta_0 = -ln x_H", b0, 2.6339158, 5e-8, "[HP] eq. (xH)"))
    C.append(check("T_H^(0) = 1/ln(7+4 sqrt3)", 1 / mp.log(7 + 4 * mp.sqrt(3)), 0.37966, 5e-6, "[HP] eq. (TH0)"))
    xt = mp.mpf("0.123")
    zBm, zFm = z_modes(xt, 400)
    C.append(check("z_B: mode sum vs closed form at x=0.123", zBm, zB_cf(xt), 1e-30, "[HP] eq. (zBzF)"))
    C.append(check("z_F: mode sum vs closed form at x=0.123", zFm, zF_cf(xt), 1e-30, "[HP] eq. (zBzF)"))
    C.append(check("z_B+z_F vs 2y^2(3-y)/(1-y)^3 at x=0.123", zB_cf(xt) + zF_cf(xt), z_cf(xt), 1e-30, "[HP] eq. (z)"))

    print("== (2) closed forms (sympy, exact)")
    y = sy.symbols("y", positive=True)
    zsym = 2 * y**2 * (3 - y) / (1 - y) ** 3
    num = sy.factor(sy.numer(sy.together(zsym - 1)))
    roots = sy.solve(sy.Eq(y**3 - 3 * y**2 - 3 * y + 1, 0), y)
    print(f"  numerator of z-1: {num};  roots of y^3-3y^2-3y+1: {sy.solve(y**3 - 3*y**2 - 3*y + 1)}")
    yHs = 2 - sy.sqrt(3)
    x = sy.symbols("x", positive=True)
    zx = zsym.subs(y, sy.sqrt(x))
    xdz = sy.simplify((x * sy.diff(zx, x)).subs(x, yHs**2))
    print(f"  x z'(x) at x_H = {xdz}   (paper: 3/2)")
    R["x_dz_dx_exact"] = str(xdz)
    C.append(check("x z'(x) at x_H", float(xdz), 1.5, 1e-14, "[HP] eq. (slope)"))
    C.append(check("cubic factorisation (y+1)(y^2-4y+1) = y^3-3y^2-3y+1", float(sy.expand((y + 1) * (y**2 - 4 * y + 1) - (y**3 - 3 * y**2 - 3 * y + 1)).subs(y, 0.3)), 0, 1e-15, "[HP] section 2.3"))
    w = lambda b: 1 - z_cf(mp.exp(-b))
    C.append(check("w'(beta_0)", mp.diff(w, b0), 1.5, 1e-25, "[HP] eq. (target) text"))
    C.append(check("w''(beta_0) = -(3/2) sqrt3", mp.diff(w, b0, 2), -1.5 * mp.sqrt(3), 1e-20, "[HP] eq. (target) text"))
    A2 = 1 - zB_cf(xH**2) + zF_cf(xH**2)
    C.append(check("A_2(x_H) = 1 - z_B(x^2) + z_F(x^2)", A2, 0.9742786, 5e-8, "[HP] eq. (master) text"))
    R["A2"] = mp.nstr(A2, 20)

    print("== (3) one-loop coefficient d_1")
    C.append(check("d_1(x_H)", d1(xH), 1.5, 1e-25, "[HP] eq. (d1H)"))
    dd1 = mp.diff(lambda b: d1(mp.exp(-b)), b0)
    C.append(check("d d_1/d beta at beta_0 = -(8 sqrt3 - 9)", dd1, -(8 * mp.sqrt(3) - 9), 1e-20, "[HP] eq. (target) text"))
    d1s = 2 * (1 + y) ** 2 / (1 - y) ** 6 * (-(1 - 4 * y + y**2) ** 2 * sy.log(1 - y**2) - y**2 * (1 - 8 * y + 2 * y**2))
    ser = sy.series(d1s, y, 0, 8).removeO()
    lead = sy.Poly(ser, y).all_coeffs()[::-1]
    print(f"  d_1 series in y: {sy.series(d1s, y, 0, 8)}")
    C.append(check("leading coefficient of d_1 (y^4 = x^2)", float(lead[4]), 33, 1e-12, "[HP] section 4.3 ('begins 33 x^2')"))
    R["d1_series_low_orders_zero"] = bool(all(c == 0 for c in lead[:4]))
    for nm, val, ref in (("(1+y_H)^2 = 6 y_H", (1 + yH) ** 2, 6 * yH), ("(1-y_H)^2 = 2 y_H", (1 - yH) ** 2, 2 * yH), ("1-8y_H+2y_H^2 = -1", 1 - 8 * yH + 2 * yH**2, -1)):
        C.append(check(nm, val, ref, 1e-30, "[HP] section 4.3"))
    C.append(check("one-loop shift: T_H/T_H0 - 1 = 2 g^2 (coefficient)", (mp.mpf(3) / 2 * 2 * b0) / (mp.mpf(3) / 2 * b0), 2, 1e-30, "[HP] eq. (TH1)"))

    print("== (4) Harmark-Wilhelm coefficient and the target d_4 ([HP] eq. HW, target, d4target)")
    hw = b0 * (-86 / mp.sqrt(3) + 24 * mp.log(12) / mp.log(2 + mp.sqrt(3)))
    C.append(check("two-loop T_H coefficient, closed form", hw, -11.50399, 5e-6, "[HP] eq. (HW)"))
    C41 = mp.mpf("8.353829")                    # paper input, [HP] section 8.3
    beta1 = -2 * b0; beta2 = b0 * (4 - hw)
    terms = [mp.mpf(3) / 2 * beta2, mp.mpf(1) / 2 * (-1.5 * mp.sqrt(3)) * beta1**2, 2 * beta1 * mp.mpf(3) / 2, 2 * b0 * beta1 * (-(8 * mp.sqrt(3) - 9))]
    first = 2 * b0**2 * C41
    d4 = (first - sum(terms)) / b0
    for nm, v, ref in (("w' beta_2", terms[0], 61.25), ("w'' beta_1^2/2", terms[1], -36.05), ("2 beta_1 d_1", terms[2], -15.80), ("2 beta_0 beta_1 d d_1", terms[3], 134.77), ("2 beta_0^2 C_41", first, 115.91)):
        C.append(check(f"target term {nm}", v, ref, 6e-3, "[HP] section 8.3"))
    C.append(check("d_4(x_H) target", d4, -10.7287, 6e-5, "[HP] eq. (d4target)"))
    C.append(check("beta_2 = beta_0 (4 + 11.50399)", beta2, b0 * (4 + mp.mpf("11.50399")), 1e-4, "[HP] section 8.3"))
    R["d4_target"] = mp.nstr(d4, 12); R["HW_two_loop_coefficient"] = mp.nstr(hw, 15)
    C.append(check("direct d_4 sum -0.156-5.65-0.017-4.476-0.41", -0.156 - 5.65 - 0.017 - 4.476 - 0.41, -10.71, 5e-3, "[HP] eq. (d4)"))
    # closure: solve m_1^2(beta) = 0 with m_1^2 = w + 2 g^2 beta d_1 + g^4 (beta d_4 - 2 beta^2 C_41) and read off the g^4 coefficient
    def TH_num(g2):
        m1 = lambda b: w(b) + 2 * g2 * b * d1(mp.exp(-b)) + g2**2 * (b * d4 - 2 * b**2 * C41)
        return 1 / mp.findroot(m1, b0)
    ks = []
    for g2 in (mp.mpf("1e-3"), mp.mpf("5e-4"), mp.mpf("2.5e-4")):
        ks.append((TH_num(g2) * b0 - 1 - 2 * g2) / g2**2)
    k_rich = 2 * ks[2] - ks[1]
    print(f"  numerical g^4 coefficient of T_H/T_H0 from the zero of m_1^2: {[mp.nstr(k, 9) for k in ks]} -> Richardson {mp.nstr(k_rich, 9)}")
    C.append(check("g^4 coefficient of T_H recovered from m_1^2 = 0 (closure of eq. target)", k_rich, hw, 2e-3, "[HP] eq. (m1-twoloop), (target)"))
    R["TH_g4_coefficient_closure"] = mp.nstr(k_rich, 10)

    print("== (5) temperature sweep and Hagedorn growth")
    sweep = []
    for i in range(0, 121):
        T = mp.mpf("0.20") + mp.mpf(i) * mp.mpf("0.0025")
        xx = mp.exp(-1 / T)
        sweep.append([float(T), float(xx), float(zn(xx, 1)), float(zn(xx, 2)), float(zn(xx, 3)), float(1 - zn(xx, 1)), float((1 - zn(xx, 2)) / 2), float(d1(xx))])
    save_csv("hp_temperature_sweep.csv", ["T", "x", "z1", "z2", "z3", "m1sq_free", "m2sq_free", "d1"], sweep)
    for n in (1, 2, 3, 4):
        print(f"  z_{n}(x_H) = {float(zn(xH, n)):+.7f}   mass^2 of u_{n}: (1-z_n)/n = {float((1-zn(xH,n))/n):+.7f}")
    R["zn_at_xH"] = [float(zn(xH, n)) for n in (1, 2, 3, 4, 5)]
    C.append(check("m_2^2 = (1 - z_2)/2 at x_H ('about 1/2')", (1 - zn(xH, 2)) / 2, 0.5, 0.02, "[HP] section 3.1"))
    # growth: coefficients of prod_n 1/(1 - z_n) as an exact integer series in y
    N = 90
    def ser_z(n):
        """integer coefficients of z_n in y up to y^N."""
        co = [0] * (N + 1)
        for m in range(0, N + 1):
            binom = (m + 2) * (m + 1) // 2                     # coefficient of X^m in 1/(1-X)^3, X = x^n = y^(2n)
            for (pw, cf) in ((2 * n, 6), (4 * n, 12), (6 * n, -2)):
                k = pw + 2 * n * m
                if k <= N:
                    co[k] += cf * binom
            k = 3 * n + 2 * n * m
            if k <= N:
                co[k] += (-1) ** (n + 1) * 16 * binom
        return co
    def mul(a, b):
        r = [0] * (N + 1)
        for i, ai in enumerate(a):
            if ai:
                for j in range(0, N + 1 - i):
                    r[i + j] += ai * b[j]
        return r
    Z = [1] + [0] * N
    for n in range(1, N // 2 + 1):
        zc = ser_z(n)
        inv = [1] + [0] * N                                    # 1/(1 - z_n)
        for k in range(1, N + 1):
            inv[k] = sum(zc[j] * inv[k - j] for j in range(1, k + 1))
        Z = mul(Z, inv)
    grow = [[k, str(Z[k]), float(Fraction(Z[k], Z[k - 1])) if Z[k - 1] else ""] for k in range(2, N + 1)]
    save_csv("hp_growth.csv", ["power_of_y", "multi_trace_states_coefficient", "ratio_to_previous"], grow)
    ratio = float(Fraction(Z[N], Z[N - 1]))
    print(f"  confined partition function prod 1/(1-z_n): first coefficients in y: {Z[:9]}")
    print(f"  ratio of consecutive coefficients at y^{N}: {ratio:.6f}   (1/y_H = 2+sqrt3 = {float(1/yH):.6f})")
    C.append(check("growth ratio of state counting at y^90 vs 1/y_H", ratio, 1 / yH, 0.02, "[HP] section 2.3 (Hagedorn growth)"))
    C.append(check("first coefficients of Z: 6 scalars at y^2", Z[2], 6, 0, "[HP] Table 1"))
    R["n_checks"] = len(C); R["n_pass"] = sum(c["pass"] for c in C)
    print(f"SUMMARY: {R['n_pass']}/{R['n_checks']} checks pass")
    save_json("hp_hagedorn.json", R)
    event("compute", "Free Hagedorn equation solved from explicit S^3 mode sums",
          f"x_H(mode sum) - (7-4 sqrt3) = {float(xH_modes-xH):.1e}; beta_0 = {mp.nstr(b0,10)}; x z' = 3/2; d_4 target {mp.nstr(d4,7)}; {R['n_pass']}/{R['n_checks']} checks pass",
          outputs=["results/hp_hagedorn.json", "results/hp_modesum_convergence.csv"])


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