"""Validation with separate algorithms.  Every block recomputes a headline number of s02-s08 by a method that shares
no code with the primary calculation (different library, different arithmetic, or a different mathematical route).

  V1  x*, Lambda_V          Newton iteration in Python's `decimal` with a hand-written sinh series (no mpmath)
  V2  U_0, identity (6-id)  Gauss-Legendre quadrature in float64 after removing the square-root endpoint singularity
  V3  U_s (general slit)    scipy.integrate.quad of the Poisson integral in float64 vs mpmath (s02) vs finite differences (s03)
  V4  Table 2 refit         normal equations solved in 50-digit arithmetic vs numpy least squares (s05); ratios in exact Fractions
  V5  extremal functionals  linear programming (HiGHS, float64, bisection on the gap) vs multiprecision Newton (s04);
                            Hellerman's P=2 problem from the roots of an explicit cubic
  V6  Hagedorn root         numpy.roots of the cubic; exact rational mode sum
  V7  series sums           exact Fraction coefficients x Decimal y_H; mpmath's own Pade vs the hand-written Pade of s07
  V8  Landau thresholds     brute-force scan of the potential on a (m^2, u) grid vs root solving (s08)
  V9  quartic assembly      Decimal arithmetic from the printed digits
Output: results/validation_summary.json
"""
import json, os, math
from decimal import Decimal, getcontext
from fractions import Fraction
import numpy as np
import mpmath as mp
from scipy.integrate import quad
from scipy.optimize import linprog
from common import Tee, event, save_json, load_json, read_csv, RES

OUT = []


def rec(block, label, a, b, tol, note=""):
    ok = abs(a - b) <= tol
    OUT.append(dict(block=block, label=label, method_A=float(a), method_B=float(b), absdiff=float(abs(a - b)), tol=tol, **{"pass": bool(ok)}, note=note))
    print(f"  [{'PASS' if ok else 'FAIL'}] {block} {label}: {float(a):.12g} vs {float(b):.12g}  |diff| {abs(a-b):.2e} (tol {tol:.0e}) {note}")


def v1():
    print("V1  x* by Newton in `decimal` (own Taylor series for sinh/cosh)")
    getcontext().prec = 60

    def sinh_cosh(x):
        s = c = Decimal(0); term = Decimal(1); k = 0
        while abs(term) > Decimal(10) ** -58:
            if k % 2 == 0:
                c += term
            else:
                s += term
            k += 1; term = term * x / k
        return s, c
    # pi by Machin's formula in Decimal
    def atan_inv(n):
        x = Decimal(1) / n; s = Decimal(0); t = x; k = 0
        while abs(t) > Decimal(10) ** -62:
            s += t / (2 * k + 1) * (-1) ** k; t = t * x * x; k += 1
        return s
    pi = 4 * (4 * atan_inv(5) - atan_inv(239))
    x = Decimal("0.3")
    for _ in range(12):
        s, c = sinh_cosh(pi * x)
        x = x - (s - 1) / (pi * c)
    lam = 1 / (Decimal(1) / 12 + x * x / 3)
    S = load_json("slope_constants.json")
    rec("V1", "x*", float(x), float(S["x_star"]), 1e-15)
    d = abs(x - Decimal(S["x_star"]))
    OUT.append(dict(block="V1", label="x* agreement in 40 digits (decimal vs mpmath)", method_A=float(x), method_B=float(S["x_star"]), absdiff=float(d), tol=1e-38, **{"pass": bool(d < Decimal(10) ** -38)}, note=str(x)[:45]))
    print(f"  decimal x* = {str(x)[:45]} ; |diff to mpmath| = {d:.2E}")
    rec("V1", "Lambda_V", float(lam), float(S["Lambda_V"]), 1e-14)


def v2():
    print("V2  U_0 and identity (6-identity) by Gauss-Legendre in float64")
    xs = math.asinh(1) / math.pi
    t, w = np.polynomial.legendre.leggauss(120)
    tau = (t + 1) / 2; wt = w / 2
    s = xs * (1 - tau**2)                      # s = x*(1 - tau^2): removes the sqrt singularity at the tip
    I1 = np.sum(wt * np.arcsin(np.clip(np.sinh(np.pi * s), -1, 1)) * 2 * xs * tau)
    s2 = 0.5 * (1 - tau**2)                    # same trick at s = 1/2 (regular there, harmless)
    I2 = np.sum(wt * np.arcsinh(np.sin(np.pi * s2)) * tau)
    U0 = -2 * np.pi * xs / 3 + 4 / 3 * I1
    rec("V2", "U_0", U0, -0.388747872, 2e-9, "vs mpmath value of s02")
    rec("V2", "I1 + I2 = asinh(1)/2", I1 + I2, math.asinh(1) / 2, 1e-10)
    rec("V2", "U(i/2) = 0", U0 + 4 / 3 * I2, 0.0, 1e-9)


def v3():
    print("V3  Poisson integral for a general slit in float64 (scipy.quad) vs mpmath (s02) vs finite differences (s03)")
    gt = {round(float(r["s"]), 4): r for r in read_csv("gamma_tip.csv")}
    fd = {round(float(r["s"]), 4): r for r in read_csv("fd_general_s.csv")}
    for s in (0.24, 0.26, 0.30, 0.32):
        sig = math.sinh(math.pi * s); q0 = 1 / sig
        f = lambda eta: -2 / 3 * math.asinh(math.sqrt((sig**2 * eta**2 + 1) / (eta**2 - 1))) * q0 / (q0**2 + eta**2)
        val = 2 / math.pi * (quad(f, 1, 2, limit=200)[0] + quad(f, 2, np.inf, limit=200)[0])
        rec("V3", f"U_s(0), s={s}: scipy.quad vs mpmath", val, float(gt[s]["U_s_at_0"]), 2e-7)
        rec("V3", f"U_s(0), s={s}: finite differences vs mpmath", float(fd[s]["U0_fd"]), float(gt[s]["U_s_at_0"]), 3e-4, "second-order FD, h=1/200")
    F = load_json("fd_summary.json")
    rec("V3", "tip-coefficient sign change: FD root vs x*", F["s_root_fd"], F["x_star"], 2e-3)
    rec("V3", "U(0): FD Richardson vs closed form", F["U0_richardson"], F["U0_closed_form"], 1e-6)


def v4():
    print("V4  Table 2: normal equations in 50 digits vs numpy lstsq; ratios in exact rationals")
    T = read_csv("table2_extracted.csv")
    mp.mp.dps = 50
    c = [mp.mpf(r["c"]) for r in T]; D = [mp.mpf(r["Delta_inf"]) for r in T]
    y = [(D[i] - (c[i] - 1) / 12) / c[i] for i in range(len(c))]
    basis = [lambda x: mp.mpf(1), lambda x: x ** (-mp.mpf(2) / 3), lambda x: 1 / x, lambda x: x ** (-mp.mpf(4) / 3)]
    A = mp.matrix(len(c), 4)
    for i in range(len(c)):
        for j in range(4):
            A[i, j] = basis[j](c[i])
    co = mp.lu_solve(A.T * A, A.T * mp.matrix(y))
    Rj = load_json("table2_reanalysis.json")
    rec("V4", "xi (F4, all rows, unweighted)", float(co[0]), Rj["fit_central"]["xi"], 1e-9)
    rec("V4", "coefficient of c^(-2/3)", float(co[1]), Rj["fit_central"]["A"], 1e-6)
    worst = 0
    for r in T:
        ex = Fraction(int(r["c"])) / Fraction(r["Delta_inf"])
        worst = max(worst, abs(float(ex) - float(r["ratio_printed"])) / (0.5 * 10 ** (-int(r["printed_decimals"]))))
    rec("V4", "max |c/Delta - printed| in units of half a printed digit (must be <= 1)", worst, 0.0, 1.0, "exact Fraction arithmetic")


def lag_table(x, N):
    L = np.zeros((N + 1,) + np.shape(x)); L[0] = 1.0
    if N >= 1:
        L[1] = 1 - x
    for n in range(1, N):
        L[n + 1] = ((2 * n + 1 - x) * L[n] - n * L[n - 1]) / (n + 1)
    return L


def lp_gap(c, P, tol=2e-6):
    a = (c - 1) / 12
    def phi(t):
        t = np.atleast_1d(np.asarray(t, float))
        L = lag_table(4 * np.pi * t, 2 * P - 1)
        return (L[1::2] * np.exp(-2 * np.pi * t)).T            # shape (len(t), P)
    v = (phi(-a) - 2 * phi(-a + 1) + phi(-a + 2))[0]
    vs = v / np.max(np.abs(v))

    def feasible(T):
        tg = np.concatenate([T + np.linspace(0, 6, 2401) ** 1.0, T + 6 + np.linspace(0.01, 0.8 * P + 14, 1600)])
        A = phi(tg)
        A = A / np.max(np.abs(A), axis=1, keepdims=True)
        res = linprog(-vs, A_ub=-A, b_ub=np.zeros(len(tg)), bounds=[(-1, 1)] * P, method="highs")
        return res.status == 0 and -res.fun > 1e-9
    lo, hi = 0.0, a + 3.0
    assert feasible(hi) and not feasible(lo + 1e-3)
    while hi - lo > tol:
        mid = (lo + hi) / 2
        if feasible(mid):
            hi = mid
        else:
            lo = mid
    return a + (lo + hi) / 2


def v5():
    print("V5  extremal functionals: LP (HiGHS, float64) vs multiprecision Newton; Hellerman cubic")
    def newton_val(c, P):
        for fn in (f"functional_c{c}.json", f"functional_homotopy_P{P}.json"):
            p = os.path.join(RES, fn)
            if os.path.exists(p):
                for r in json.load(open(p))["results"]:
                    if r["c"] == c and r["P"] == P:
                        return r["Delta1_float"]
        return None
    for (c, P) in ((4, 4), (4, 8), (12, 6), (12, 8), (24, 8), (48, 8), (64, 8)):
        nv = newton_val(c, P)
        if nv is None:
            continue
        rec("V5", f"Delta1^(P={P})(c={c}): LP vs Newton", lp_gap(c, P), nv, 2e-5, "LP grid + bisection tolerance")
    # P = 2 (Hellerman): g = (alpha1 L1 + alpha3 L3)(4 pi t) e^{-2 pi t}, g_vac = 0 fixes alpha1/alpha3; t1 = largest root of the cubic
    for c in (4, 12, 24, 64, 256, 1024):
        a = (c - 1) / 12
        def vac(n):
            f = lambda t: np.polynomial.laguerre.lagval(4 * np.pi * t, [0] * n + [1]) * math.exp(-2 * np.pi * t)
            return f(-a) - 2 * f(-a + 1) + f(-a + 2)
        v1_, v3_ = vac(1), vac(3)
        # p(x) = v3 L1(x) - v1 L3(x),  x = 4 pi t ; L1 = 1 - x, L3 = 1 - 3x + 3x^2/2 - x^3/6
        coef = [v1_ / 6, -1.5 * v1_, 3 * v1_ - v3_, v3_ - v1_]
        roots = np.roots(coef)
        t1 = max(r.real for r in roots if abs(r.imag) < 1e-9) / (4 * np.pi)
        eps = a + 2 / np.pi + 2 / (math.exp(2 * np.pi) - 1) - t1
        nv = newton_val(c, 2)
        if nv is not None:
            rec("V5", f"Hellerman P=2, c={c}: cubic root vs Newton", a + t1, nv, 1e-9)
        OUT.append(dict(block="V5", label=f"Hellerman eps_c at c={c}: 0 < eps_c and eps_c*c bounded", method_A=eps, method_B=eps * c, absdiff=0.0, tol=0.0, **{"pass": bool(eps > 0 and eps * c < 1.0)},
                        note=f"Delta1 = {a+t1:.6f} < c/6 + 0.4737 = {c/6+0.4737:.6f}"))
        print(f"  Hellerman c={c}: Delta1^(2) = {a+t1:.8f}, eps_c = {eps:.3e}, eps_c*c = {eps*c:.4f}, bound c/6+0.4737 = {c/6+0.4737:.6f}")


def v6():
    print("V6  Hagedorn root: numpy.roots of the cubic; exact rational mode sum")
    r = np.roots([1, -3, -3, 1])
    yH = [x.real for x in r if 0 < x.real < 1][0]
    H = load_json("hp_hagedorn.json")
    rec("V6", "y_H from numpy.roots", yH, float(H["y_H"]), 1e-14)
    rec("V6", "x_H = y_H^2 vs mode-sum bisection", yH**2, float(H["x_H_modesum"]), 1e-14)
    x = Fraction(1, 9); y = Fraction(1, 3)             # x = y^2 with rational y
    zs = Fraction(0)
    for n in range(1, 121):
        zs += 6 * n * n * x**n + 2 * n * (n + 2) * x ** (n + 1) + 8 * n * (n + 1) * x**n * y
    zc = 2 * y**2 * (3 - y) / (1 - y) ** 3
    rec("V6", "mode sum (exact rationals, n<=120) vs closed form at y=1/3", float(zs), float(zc), 1e-14, f"exact difference {float(zc - zs):.1e}")


def v7():
    print("V7  series sums with exact Fractions x Decimal; mpmath.pade vs own Pade")
    getcontext().prec = 50
    yH = Decimal(2) - Decimal(3).sqrt()
    rows = read_csv("hp_series_extracted.csv"); res = read_csv("hp_series_resum.csv")
    for w in ("a", "b"):
        tot = Decimal(0)
        for r in rows:
            if r["series"] == w:
                fr = Fraction(r["coeff_tex"])
                tot += Decimal(fr.numerator) / Decimal(fr.denominator) * yH ** int(r["n"])
        last = [float(r["partial_sum"]) for r in res if r["series"] == w][-1]
        rec("V7", f"partial sum of series {w}", float(tot), last, 1e-12)
    Q = load_json("hp_quartic.json")
    mp.mp.dps = 30
    cb = [mp.mpf(Fraction(r["coeff_tex"]).numerator) / Fraction(r["coeff_tex"]).denominator for r in rows if r["series"] == "b"]
    y = 2 - mp.sqrt(3)
    for (L, M) in ((5, 1), (4, 2), (3, 3), (2, 4)):
        p, q = mp.pade(cb, L, M)
        val = y**4 * mp.polyval(p[::-1], y) / mp.polyval(q[::-1], y)
        rec("V7", f"Pade [{L}/{M}] of series b: mpmath.pade vs own solver", float(val), Q["series"]["b"]["pade_top"][f"[{L}/{M}]"], 1e-10)


def v8():
    print("V8  Landau thresholds by brute force on a grid (|b| = 0.1)")
    b = -0.1
    u = np.linspace(0, 0.9, 90001)
    Vv = np.where(u <= 0.5, u * u, 0.25 - 0.5 * np.log(2 * (1 - np.minimum(u, 0.999999))))
    base = Vv - u * u + b * u**4
    m2_min = m2_c = None
    for m2 in np.arange(0.0700, 0.0200, -1e-5):
        Sv = base + m2 * u * u
        d = np.diff(Sv)
        has_min = np.any((d[:-1] < 0) & (d[1:] >= 0) & (u[1:-1] > 0.05))
        if has_min and m2_min is None:
            m2_min = m2
        if has_min and m2_c is None and Sv[u > 0.05].min() < 0:
            m2_c = m2
            u_c = u[u > 0.05][np.argmin(Sv[u > 0.05])]
            break
    Lj = load_json("hp_landau.json")
    rec("V8", "m^2_min (grid scan vs root solve)", m2_min, Lj["b_0p1"]["m2_min"], 3e-5)
    rec("V8", "m^2_c (grid scan vs root solve)", m2_c, Lj["b_0p1"]["m2_c"], 3e-5)
    rec("V8", "u_c (grid scan vs root solve)", u_c, Lj["b_0p1"]["u_c"], 2e-3)


def v9():
    print("V9  quartic coefficient from the printed digits in Decimal arithmetic")
    getcontext().prec = 40
    yH = Decimal(2) - Decimal(3).sqrt()
    b0 = -(yH * yH).ln()
    A2 = Decimal("0.9742786"); c3 = Decimal("0.16821"); Q4 = Decimal("2.1222"); q4 = Decimal("-0.7340") + Decimal("-1.500")
    I = Q4 / 2 + 2 * c3 * c3 / A2
    b = -4 * b0 * b0 * I + b0 * q4
    Q = load_json("hp_quartic.json")
    rec("V9", "b/g^4", float(b), Q["quartic"]["b_over_g4"], 1e-6)
    rec("V9", "b/g^4 vs the paper's -36.94(1)", float(b), -36.94, 1e-2)
    rec("V9", "critical q4 = 4 beta_0 I", float(4 * b0 * I), 11.79, 5e-3)


if __name__ == "__main__":
    with Tee("validate_all"):
        for f in (v1, v2, v3, v4, v5, v6, v7, v8, v9):
            f()
        npass = sum(o["pass"] for o in OUT)
        print(f"SUMMARY: {npass}/{len(OUT)} validation comparisons pass")
        for o in OUT:
            if not o["pass"]:
                print("  NOT PASSED:", o["block"], o["label"], o["method_A"], o["method_B"])
        save_json("validation_summary.json", {"n": len(OUT), "n_pass": npass, "comparisons": OUT})
        event("validate", "Independent-algorithm validation suite", f"{npass}/{len(OUT)} comparisons pass (decimal Newton, Gauss-Legendre, scipy.quad, LP vs Newton, exact rationals, grid scans)",
              outputs=["results/validation_summary.json"])
