# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check an independent Gauss–Legendre adapter on fixed and geometric tests."""

import json
from math import cos, dist, isfinite, log2, sin
from pathlib import Path
import sys


def read_cases():
    return json.loads(Path(__file__).with_name("cases.json").read_text())


def callbacks(problem):
    if problem == "canonical":
        def f(t, y):
            q, p = y
            P = p + q*q/2
            return P, -q-q*P

        def J(t, y):
            q, p = y
            P = p + q*q/2
            return (q, 1), (-1-P-q*q, -q)

        return f, J
    if problem == "rotation":
        return (lambda t, y: (-y[1]*y[2]/6, 2*y[0]*y[2]/3, -y[0]*y[1]/2),
                lambda t, y: ((0,-y[2]/6,-y[1]/6),(2*y[2]/3,0,2*y[0]/3),(-y[1]/2,-y[0]/2,0)))
    if problem == "forced":
        return (lambda t, y: (t-y[0]*y[1], t*t-y[1]+y[0]),
                lambda t, y: ((-y[1],-y[0]), (1,-1)))
    if problem == "imaginary":
        return lambda t, y: (-40*y[1], 40*y[0]), lambda t, y: ((0,-40),(40,0))
    raise ValueError(problem)


def advance(step, problem, t, y, h, count):
    f, J = callbacks(problem)
    for n in range(count):
        y = tuple(step(f, J, t+n*h, y, h))
    return tuple(y)


def fixed_cases(step):
    for case in read_cases()["cases"]:
        try:
            y = advance(step, case["problem"], case["t"], case["y"], case["h"], case["steps"])
            error = [abs(a-b) for a,b in zip(y, case["expected"], strict=True)]
            yield all(isfinite(d) and d <= case["tol"] for d in error), (
                f'{case["problem"]}: endpoint difference {max(error):.2e}')
        except Exception as exc:
            yield False, f'{case["problem"]}: {type(exc).__name__}: {exc}'


def exact(t, y):
    q, p = y
    P = p+q*q/2
    qt = q*cos(t)+P*sin(t)
    Pt = P*cos(t)-q*sin(t)
    return qt, Pt-qt*qt/2


def nonseparable_errors(step):
    y0 = (0.7, 0.3)
    return [dist(advance(step, "canonical", 0, y0, 2/n, n), exact(2, y0))
            for n in (10, 20, 40, 80)]


def convergence(step):
    errors = nonseparable_errors(step)
    orders = [log2(a/b) for a,b in zip(errors, errors[1:])]
    return all(3.85 < p < 4.15 for p in orders), (
        "nonseparable errors " + ", ".join(f"{e:.2e}" for e in errors)
        + "; orders " + ", ".join(f"{p:.3f}" for p in orders))


def quadratic(step):
    f, J = callbacks("rotation")
    y = (0.7, 0.4, 0.8)

    def invariants(y):
        x, y, z = y
        return x*x+y*y+z*z, x*x+y*y/2+z*z/3

    initial = invariants(y)
    peak = 0.0
    for n in range(200):
        y = tuple(step(f, J, n*0.2, y, 0.2))
        peak = max(peak, *(abs(a-b) for a,b in zip(invariants(y), initial)))
    return peak < 2e-12, f"two quadratic invariants over 200 steps: peak drift {peak:.2e}"


def reversal(step):
    y = (0.7, 0.3)
    forward = advance(step, "canonical", 0, y, 0.24, 50)
    gap = dist(advance(step, "canonical", 12, forward, -0.24, 50), y)
    return gap < 2e-11, f"canonical forward/backward error {gap:.2e}"


def mixed_scale(step):
    f = lambda t, y: (-y[0]*y[0],)
    jac = lambda t, y: ((-2*y[0],),)
    scale, passive = 1e-9, 1e5
    f_scaled = lambda t, y: (-y[0]*y[0]/scale, 0)
    jac_scaled = lambda t, y: ((-2*y[0]/scale, 0), (0, 0))
    try:
        expected, = step(f, jac, 0, (1,), 1)
        active, constant = step(f_scaled, jac_scaled, 0, (scale, passive), 1)
    except Exception as exc:
        return False, f"mixed-scale solve: {type(exc).__name__}: {exc}"
    error = abs(active/scale-expected)
    ok = error < 1e-12 and abs(constant-passive) <= 1e-10
    return ok, f"mixed-scale active error in normalized units: {error:.2e}"


def run_checks(step, out=print):
    results = [*fixed_cases(step), convergence(step), quadratic(step), reversal(step), mixed_scale(step)]
    for ok, detail in results:
        out(f"{'PASS' if ok else 'FAIL'} {detail}")
    return sum(not ok for ok, _ in results)


if __name__ == "__main__":
    sys.path.insert(0, str(Path.cwd()))
    from port_adapter import step
    sys.exit(bool(run_checks(step)))
