# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check structure preservation and reject common Gauss stage mistakes."""

from math import dist, log2
import json
from pathlib import Path
import sys

ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT / "checks"), str(ROOT / "reference")]
from check_port import callbacks, fixed_cases, nonseparable_errors, read_cases, run_checks
from gauss_legendre_4 import A, C, _stages, step
from make_cases import build


def midpoint(f, J, t, y, h):
    stage, = _stages(f, J, t, tuple(y), h, (0.5,), ((0.5,),), 2e-14, 12)
    return tuple(2*a-b for a,b in zip(stage, y, strict=True))


def wrong_clock(f, J, t, y, h):
    return step(lambda _, x: f(t, x), lambda _, x: J(t, x), t, y, h)


def wrong_tableau(f, J, t, y, h):
    stages = _stages(f, J, t, tuple(y), h, C, tuple(zip(*A)), 2e-14, 12)
    f1, f2 = (f(t+c*h, Y) for c,Y in zip(C, stages, strict=True))
    return tuple(x+h*(u+v)/2 for x,u,v in zip(y,f1,f2,strict=True))


def energy(y):
    q, p = y
    return (q*q+(p+q*q/2)**2)/2


def compare_midpoint():
    gauss, middle = map(nonseparable_errors, (step, midpoint))
    p = [log2(a/b) for a,b in zip(middle, middle[1:])]
    assert all(1.95 < rate < 2.05 for rate in p)
    assert gauss[0] < middle[0]/100 and gauss[-1] < middle[-1]/1000
    print(f"PASS Gauss/midpoint endpoint errors on 10 steps: {gauss[0]:.2e}/{middle[0]:.2e}")
    print(f"PASS Gauss/midpoint endpoint errors on 80 steps: {gauss[-1]:.2e}/{middle[-1]:.2e}")


def long_energy():
    f, J = callbacks("canonical")
    q0 = (0.7, 0.3)
    peaks = []
    for method in (step, midpoint):
        y = q0
        windows = []
        for k in range(20):
            peak = 0.0
            for n in range(1600):
                y = method(f, J, (1600*k+n)*0.2, y, 0.2)
                peak = max(peak, abs(energy(y)-energy(q0)))
            windows.append(peak)
        assert windows[-1] < 1.05*windows[0]
        peaks.append(max(windows))
        print(f"PASS {method.__name__}: 32,000 steps, energy first/last {windows[0]:.2e}/{windows[-1]:.2e}")
    assert peaks[0] < 1e-5 and peaks[0] < peaks[1]/100


def imaginary_map():
    f, J = callbacks("imaginary")
    h = 2.5
    z = 40j*h
    r = (1+z/2+z*z/12)/(1-z/2+z*z/12)
    y = step(f, J, 0, (1,0), h)
    error = dist(y, (r.real,r.imag))
    assert error < 2e-13
    print(f"PASS at h*lambda=100j: Padé error {error:.2e}, modulus {abs(complex(*y)):.12f}")


if __name__ == "__main__":
    actual, stored = json.loads(json.dumps(build())), read_cases()
    for record in (actual, stored):
        for case in record["cases"]:
            del case["expected"]
    assert actual == stored
    assert run_checks(step) == 0
    compare_midpoint()
    long_energy()
    imaginary_map()
    for broken in (midpoint, wrong_clock, wrong_tableau):
        count = sum(not ok for ok, _ in fixed_cases(broken))
        assert count
        print(f"PASS {broken.__name__}: rejected by {count} fixture(s)")
