"""Quartic reconstruction and two canonical saddle calculations. Python 3, offline."""
import json
import math
from pathlib import Path


def bisect(f, lo, hi):
    left, right = f(lo), f(hi)
    if left * right >= 0:
        raise ValueError("Root must be strictly bracketed")
    for _ in range(70):
        mid = (lo + hi) / 2
        value = f(mid)
        if value == 0 or mid in (lo, hi):
            return mid
        if (value < 0) == (left < 0):
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2


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


def z_fermion(x):
    return 16*x**1.5 / (1-x)**3


def one_loop_invariant(inputs, a2):
    return float(inputs["Q4"])/2 + 2*float(inputs["c3"])**2/a2


def reconstruct(one_loop, two_loop, beta, a2):
    if one_loop["scheme"] != two_loop["scheme"]:
        raise ValueError("Use inputs from one Hamiltonian scheme")
    tree, loop = float(two_loop["q4Tree"]), float(two_loop["q4Loop"])
    q4 = tree + loop
    invariant = one_loop_invariant(one_loop, a2)
    pieces = {"oneLoopSquare": -2*beta**2*float(one_loop["Q4"]),
              "secondMomentExchange": -8*beta**2*float(one_loop["c3"])**2/a2,
              "twoLoopTree": beta*tree, "twoLoopLoop": beta*loop}
    return invariant, q4, pieces, -4*beta**2*invariant + beta*q4


def weak_limit(data):
    # Eq. (8) gives the Hagedorn root. The n=2 fermion sign differs from n=1.
    x = bisect(lambda x: z_boson(x) + z_fermion(x) - 1, 1e-6, 0.5)
    beta = -math.log(x)
    a2 = 1 - z_boson(x*x) + z_fermion(x*x)
    y = math.sqrt(x)
    slope = 6*y*y/(1-y)**4  # x dz/dx by differentiation of Eq. (9)
    literal = data["roundedHamiltonianInputs"]
    other = data["alternateOneLoopInputs"]
    invariant, q4, pieces, b_g4 = reconstruct(literal, literal, beta, a2)
    b_lambda2 = b_g4 / (256*math.pi**4)
    # At small B=|b| the emerging deconfined saddle lies at u=1/2.
    edge = 0.5
    critical_m_over_B = edge**2   # m u²−B u⁴=0 at the edge
    fold_m_over_B = 2*edge**2     # 2m u−4B u³=0 at the edge
    gap_scale = abs(b_lambda2) / (slope*beta)
    latent = slope * edge**2     # R d(S/N²)/d(beta_physical) at fixed saddle
    barrier_per_B = critical_m_over_B**2 / 4  # unstable u²=m/(2B)
    return {"xH": x, "beta0": beta, "freeHagedornRT": 1/beta, "zSlope": slope,
            "A2": a2, "I": invariant, "commutatorI": one_loop_invariant(other, a2),
            "q4": q4, "q4SignThreshold": 4*beta*invariant, "piecesOverG4": pieces,
            "bOverG4": b_g4, "bOverLambda2": b_lambda2,
            "criticalMassPerB": critical_m_over_B, "foldMassPerB": fold_m_over_B,
            "relativeCriticalGapPerLambda2": critical_m_over_B*gap_scale,
            "relativeLowerGapPerLambda2": (fold_m_over_B-critical_m_over_B)*gap_scale,
            "relativeFullGapPerLambda2": fold_m_over_B*gap_scale,
            "latentHeatRoverN2": latent, "leadingBarrierPerN2B": barrier_per_B,
            "leadingBarrierActionPerN2Lambda2": barrier_per_B*abs(b_lambda2)}


def wall(u):
    # Subtract u² from the Haar potential in Eq. (19); log1p resolves the join.
    if u <= 0.5:
        return 0.
    t = u - 0.5
    return -t - t*t - 0.5*math.log1p(-2*t)


def action(u, mass, B):
    return wall(u) + mass*u*u - B*u**4


def derivative(u, mass, B):
    wall_prime = 0. if u <= 0.5 else (2*u-1)**2 / (2*(1-u))
    return wall_prime + 2*mass*u - 4*B*u**3


def curvature(u, mass, B):
    wall_second = 0. if u <= 0.5 else 1/(2*(1-u)**2) - 2
    return wall_second + 2*mass - 12*B*u*u


def saddles(B):
    # Solve S'=0 for m on the gapped branch. The fold is dm/du=0;
    # coexistence requires S=0 on the stable branch after the fold.
    if not 0 < B <= 0.1:
        raise ValueError("This small-B saddle comparison uses 0 < B <= 0.1")

    def mass(u):
        return 2*B*u*u - (2*u-1)**2 / (4*u*(1-u))

    def mass_slope(u):
        return 4*B*u + (1-2*u)/(4*u*u*(1-u)**2)

    fold = bisect(mass_slope, 0.5, 0.99)
    coexist = bisect(lambda u: action(u, mass(u), B), fold, 0.99)
    m_fold, m_c = mass(fold), mass(coexist)
    unstable = math.sqrt(m_c/(2*B))
    actions = [action(u, m_c, B) for u in (0, unstable, coexist)]
    residuals = [derivative(fold, m_fold, B), curvature(fold, m_fold, B),
                 derivative(coexist, m_c, B), derivative(unstable, m_c, B), actions[2]-actions[0]]
    if max(map(abs, residuals)) >= 1e-12:
        raise ArithmeticError("Saddle equation residual too large")
    if not (0 < m_c < m_fold and 0 < unstable < 0.5 < fold < coexist
            and curvature(0, m_c, B) > 0 > curvature(unstable, m_c, B)
            and curvature(coexist, m_c, B) > 0 and actions[1] > actions[0]):
        raise ArithmeticError("Unexpected saddle ordering or stability")
    return {"B": B, "foldU": fold, "foldMass": m_fold, "transitionU": coexist,
            "transitionMass": m_c, "unstableU": unstable, "barrierPerN2": actions[1]-actions[0]}


def gravity_saddles():
    # Uniform Schwarzschild–AdS5; rho=r_h/L. Subtract the thermal-AdS vacuum
    # before comparing F or E; t=RT in the same boundary-sphere units.
    def energy(rho):
        return 3*rho*rho*(1+rho*rho)/4

    def entropy(rho):
        return math.pi*rho**3

    def temperature(rho):
        return (1+2*rho*rho)/(2*math.pi*rho)

    def temperature_slope(rho):
        return (2-1/rho**2)/(2*math.pi)

    def free_energy(rho):
        return energy(rho) - temperature(rho)*entropy(rho)

    fold = bisect(temperature_slope, 0.2, 1.5)
    large = bisect(free_energy, fold, 2)
    t_c = temperature(large)
    small = bisect(lambda rho: temperature(rho)-t_c, 0.1, fold)
    barrier = free_energy(small)
    if not (temperature_slope(small) < 0 < temperature_slope(large)
            and barrier > 0 and abs(free_energy(large)) < 1e-12
            and abs(energy(large) - t_c*entropy(large)) < 1e-12):
        raise ArithmeticError("Gravity coexistence or stability check failed")
    return {"minimumRT": temperature(fold), "transitionRT": t_c, "foldRadius": fold,
            "smallRadius": small, "largeRadius": large,
            "relativeLowerGap": (t_c - temperature(fold))/t_c,
            "latentHeatRoverN2": energy(large), "barrierRFoverN2": barrier,
            "barrierActionPerN2": barrier/t_c}


def printed_cell(actual, text):
    places = len(text.split(".")[1])
    return abs(actual-float(text)) <= 0.5 * 10**(-places)


def compact(values):
    if isinstance(values, dict):
        return {key: compact(value) for key, value in values.items()}
    if isinstance(values, list):
        return [compact(value) for value in values]
    if isinstance(values, float):
        return float(f"{values:.12g}")
    return values


def run(data):
    weak = weak_limit(data)
    gravity = gravity_saddles()
    examples = [saddles(B) for B in data["illustrativeB"]]
    figure = data["figure2"]
    example = next(row for row in examples if row["B"] == figure["B"])
    ref = data["reported"]
    printed_ok = all(printed_cell(weak[key], ref[key]) for key in
                     ("beta0", "A2", "bOverLambda2", "relativeCriticalGapPerLambda2"))
    quoted_ok = all(abs(weak[key] - float(ref[target])) <= float(ref[target+"Tolerance"])
                    for key, target in (("I","literalI"), ("commutatorI","commutatorI"), ("bOverG4","bOverG4")))
    figure_ok = all(printed_cell(example[key], figure[key]) for key in ("foldMass", "transitionMass"))
    scheme_blocked = False
    try:
        reconstruct(data["alternateOneLoopInputs"], data["roundedHamiltonianInputs"], weak["beta0"], weak["A2"])
    except ValueError:
        scheme_blocked = True
    # A sign reversal at the former nonzero coexisting minimum lifts that
    # minimum above the confined action. This tests the sign used in Eq. (21).
    lifted = action(example["transitionU"], example["transitionMass"], -example["B"])
    limit = []
    for B in data["leadingLimitControlB"]:
        row = saddles(B)
        limit.append({"B": B, "foldMassOverB": row["foldMass"]/B,
                      "transitionMassOverB": row["transitionMass"]/B,
                      "barrierActionOverN2B": row["barrierPerN2"]/B})
    ratios = (("foldMassOverB", "foldMassPerB"), ("transitionMassOverB", "criticalMassPerB"),
              ("barrierActionOverN2B", "leadingBarrierPerN2B"))
    approach = all(abs(limit[1][key]-weak[target]) < abs(limit[0][key]-weak[target])
                   for key, target in ratios)
    consistency = abs(sum(weak["piecesOverG4"].values()) - weak["bOverG4"]) < 1e-12
    gravity_ok = (abs(gravity["transitionRT"] - 3/(2*math.pi)) < 1e-12
                  and abs(gravity["minimumRT"] - math.sqrt(2)/math.pi) < 1e-12
                  and abs(gravity["barrierActionPerN2"] - math.pi/32) < 1e-12)
    controls = {"matchesPrintedQuarticInputsAndOutputs": printed_ok and quoted_ok,
                "matchesFigure2RoundedMasses": figure_ok, "mixedSchemesRejected": scheme_blocked,
                "signReversalLiftsCoexistingAction": lifted > 0,
                "signReversedActionPerN2": lifted, "smallBConvergence": limit,
                "approachesLeadingRatios": approach, "fourPiecesSumToQuartic": consistency,
                "classicalRootsMatchAnalyticValues": gravity_ok}
    passed = all([printed_ok, quoted_ok, figure_ok, scheme_blocked, lifted > 0, approach, consistency, gravity_ok])
    return compact({"source": data["source"], "status": "passed" if passed else "failed",
                    "weak": weak, "illustrations": examples, "gravity": gravity, "controls": controls})


if __name__ == "__main__":
    inputs = json.loads(Path(__file__).with_name("inputs.json").read_text(encoding="utf-8"))
    result = run(inputs)
    print(json.dumps(result, indent=2))
    raise SystemExit(0 if result["status"] == "passed" else 1)
