"""Separated Kerr spin −2, l=m=2 mode check. Run python3 -I check.py offline."""
import json
import math
from pathlib import Path

S = -2
M = 2  # azimuthal mode index (black-hole mass units are set to one)


def x_element(ell, other):
    """Matrix of cos(theta) on normalized spin-weighted spherical harmonics."""
    if ell == other:
        return -M * S / (ell * (ell + 1))
    if abs(ell - other) == 1:
        j = max(ell, other)
        return math.sqrt((j*j - M*M) * (j*j - S*S) / (j*j * (4*j*j - 1)))
    return 0.0


def angular_matrix(c, lmax):
    # Project x² after multiplying: the intermediate ell=lmax+1 contributes
    # to the last diagonal. Cook & Zalutskiy Eqs. (52)–(56).
    matrix = []
    for ell in range(2, lmax + 1):
        row = []
        for other in range(2, lmax + 1):
            x2 = sum(x_element(ell, j) * x_element(j, other)
                     for j in range(max(2, ell - 1), ell + 2))
            value = 2*S*c*x_element(ell, other) - c*c*x2
            if ell == other:
                value += ell*(ell + 1) - S*(S + 1)
            row.append(value)
        matrix.append(row)
    return matrix


def angular_eigenvalue(c, lmax):
    """Follow the eigenvalue attached to ell=2; eliminate the higher harmonics."""
    h = angular_matrix(c, lmax)
    value = h[0][0]
    for _ in range(30):
        # After elimination, the lowest row gives A = H00 - H0h (Hhh-AI)^-1 Hh0.
        reduced = [row.copy() for row in h]
        for j in range(1, len(h)):
            reduced[j][j] -= value
        for j in range(len(h) - 1, 0, -1):
            # The original matrix has bandwidth two; eliminating from the end preserves it.
            for k in range(max(0, j - 2), j):
                factor = reduced[k][j] / reduced[j][j]
                for i in range(max(0, j - 2), j):
                    reduced[k][i] -= factor * reduced[j][i]
        updated = reduced[0][0]
        if abs(updated - value) < 1e-14:
            return updated
        value = updated
    raise ArithmeticError("Angular eigenvalue iteration failed")


def radial_residual(w, spin, overtone, depth, lmax):
    """n-inverted Leaver fraction, zero tail, M=1; Eqs. (23)–(32), (42)–(44)."""
    d = math.sqrt((1 - spin)*(1 + spin))
    outer = (2*w*(1 + d) - M*spin) / (2*d)
    inner = (2*w*(1 - d) - M*spin) / (2*d)
    zeta = 1j*w
    xi = -S - 1j*outer
    eta = -1j*inner
    p = d*zeta
    alpha = 1 + 2*S + xi + eta - 2*zeta
    gamma = 1 + S + 2*eta
    delta = 1 + S + 2*xi
    mean = (gamma + delta) / 2
    separation = angular_eigenvalue(spin*w, lmax)
    sigma = (separation + (spin*w)**2 - 8*w*w + p*(2*alpha + gamma - delta)
             + (1 + S - mean)*(S + mean))
    d0 = delta
    d1 = 4*p - 2*alpha + gamma - delta - 2
    d2 = 2*alpha - gamma + 2
    d3 = alpha*(4*p - delta) - sigma
    d4 = alpha*(alpha - gamma + 1)

    def a(j):
        return (j + 1)*(j + d0)

    def b(j):
        return -2*j*j + (d1 + 2)*j + d3

    def g(j):
        return j*j + (d2 - 3)*j + d4 - d2 + 2

    left = 0j
    for j in range(overtone):
        left = a(j)*g(j + 1) / (b(j) - left)
    right = 0j
    for j in range(depth, overtone, -1):
        right = a(j - 1)*g(j) / (b(j) - right)
    return b(overtone) - left - right


def solve(seed, spin, overtone, depth, lmax):
    w = seed
    step = 1e-7
    for _ in range(24):
        residual = radial_residual(w, spin, overtone, depth, lmax)
        deriv = (radial_residual(w + step, spin, overtone, depth, lmax)
                 - radial_residual(w - step, spin, overtone, depth, lmax)) / (2*step)
        delta = residual / deriv
        w -= delta
        if abs(delta) < 2e-14:
            return w, abs(radial_residual(w, spin, overtone, depth, lmax))
    raise ArithmeticError("Frequency iteration failed")


SPINS = (0, .2, .4, .6, .8, .9, .94, .96, .97, .98, .986, .992, .996, .998,
         .999, .9993, .9995, .99965, .99975, .9998)
STARTS = (.37367 - .08896j, .34671 - .27391j, .30105 - .47828j)
DEPTH = 6000
LMAX = 20


def track_branch(overtone):
    """Start at Schwarzschild and extrapolate earlier roots to seed the next spin."""
    roots = []
    selected = {}
    for index, spin in enumerate(SPINS):
        seed = roots[-1] if roots else STARTS[overtone]
        if index >= 2:
            span = (spin - SPINS[index - 1]) / (SPINS[index - 1] - SPINS[index - 2])
            seed += span * (roots[-1] - roots[-2])
        w, residual = solve(seed, spin, overtone, DEPTH, LMAX)
        if w.real <= 0 or w.imag >= 0 or residual >= 1e-10:
            raise ArithmeticError("Unconverged or incorrectly signed root")
        roots.append(w)
        if spin in (.8, .9998):
            selected[spin, overtone] = (w, residual)
    return selected


def compare_component(value, reference, label, half_unit, half_percent):
    # Signed components enter Eq. (30). The image of a frequency rounding cell
    # under |(p-r)/r| may include zero if the cell contains r.
    distance = abs(value - reference)
    scale = 100 / abs(reference)
    lo = max(0., distance - half_unit)*scale
    hi = (distance + half_unit)*scale
    if label == "<0.001":
        bin_lo, bin_hi = 0., half_percent  # Table 1 caption uses 0.0005%.
    else:
        bin_lo = max(0., float(label) - half_percent)
        bin_hi = float(label) + half_percent
    if lo >= bin_lo and hi < bin_hi:
        relation = "contained"
    elif hi >= bin_lo and lo < bin_hi:
        relation = "overlaps"
    else:
        relation = "disjoint"
    return round(distance*scale, 8), [round(lo, 8), round(hi, 8)], relation


def refinement_checks(roots):
    # Each solve changes exactly one cutoff relative to the fine run.
    diagnostics = []
    for depth, lmax in [(100, LMAX), (250, LMAX), (600, LMAX), (3000, LMAX),
                        (DEPTH, 4), (DEPTH, 5), (DEPTH, 6), (DEPTH, 10)]:
        largest = 0.
        for (spin, n), (w, _) in roots.items():
            coarse, _ = solve(w, spin, n, depth, lmax)
            largest = max(largest, abs(coarse - w))
        diagnostics.append({
            "N": depth, "L": lmax,
            "maxAbsFrequencyShift": None if largest < 1e-12 else float(f"{largest:.3g}"),
            "below1eMinus12": largest < 1e-12,
        })
    return diagnostics


def run(data):
    if (data["spinWeight"], data["ell"], data["m"]) != (S, 2, M):
        raise ValueError("This benchmark uses spin weight −2 and ell=m=2")
    cases = [(row["spin"], row["n"]) for row in data["rows"]]
    if cases != [(spin, n) for spin in (.8, .9998) for n in range(3)]:
        raise ValueError("Expected six ordered Table 1 mode/spin pairs")
    roots = {}
    for n in range(3):
        roots.update(track_branch(n))
    rows = []
    compatible = 0
    contained = 0
    reversed_damping_rejections = 0
    swapped_overtone_rejections = 0
    for sample in data["rows"]:
        spin, n = sample["spin"], sample["n"]
        w, _ = roots[spin, n]
        real, imag = float(sample["real"]), float(sample["imag"])
        precision = (data["frequencyHalfUnit"], data["percentHalfUnit"])
        re_pct, re_cell, re_match = compare_component(real, w.real, sample["realPct"], *precision)
        im_pct, im_cell, im_match = compare_component(imag, w.imag, sample["imagPct"], *precision)
        compatible += int(re_match != "disjoint") + int(im_match != "disjoint")
        contained += int(re_match == "contained") + int(im_match == "contained")
        reversed_damping_rejections += (
            compare_component(-imag, w.imag, sample["imagPct"], *precision)[2] == "disjoint")
        other_root = roots[spin, (n + 1) % 3][0]
        swapped_overtone_rejections += (
            compare_component(imag, other_root.imag, sample["imagPct"], *precision)[2] == "disjoint")
        rows.append({
            "spin": spin, "mode": [2, 2, n],
            "reference": {"real": round(w.real, 12), "imag": round(w.imag, 12)},
            "pinn": {"real": real, "imag": imag},
            "errorPercent": {"real": re_pct, "imag": im_pct},
            "realErrorIntervalPct": re_cell, "imagErrorIntervalPct": im_cell,
            "reportedErrorPercent": {"real": sample["realPct"], "imag": sample["imagPct"]},
            "printedCellVsReportedBin": {"real": re_match, "imag": im_match},
        })
    refinement = refinement_checks(roots)
    residual_limit = 1e-11
    residuals_pass = all(residual < residual_limit for _, residual in roots.values())
    fine_cuts_pass = all(row["below1eMinus12"] for row in refinement if row["N"] == 3000 or row["L"] == 10)
    passed = (compatible == 12 and residuals_pass and fine_cuts_pass
              and reversed_damping_rejections == 6 and swapped_overtone_rejections == 6)
    return {
        "status": "passed" if passed else "failed",
        "source": data["source"], "referenceSource": data["referenceSource"],
        "spinWeight": S, "fineN": DEPTH, "fineL": LMAX, "continuationSpins": list(SPINS),
        "rows": rows,
        "rounding": {"components": 12, "contained": contained, "overlapsOnly": compatible - contained,
                     "disjoint": 12 - compatible},
        "convergence": refinement,
        "residual": {"equation": "n-inverted radial continued fraction", "absoluteTolerance": residual_limit,
                     "allSixBelowTolerance": residuals_pass},
        "controls": {"imaginarySignRejections": reversed_damping_rejections,
                     "cyclicOvertoneSwapRejections": swapped_overtone_rejections},
    }


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