# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check a Radau IIA step or an optional adaptive solve port."""

import json
from math import exp, isfinite, log2
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 == "forced":
        return lambda t, y: (t*t*t-y[0],), lambda t, y: ((-1,),)
    if problem == "damped":
        return lambda t, y: (-y[0],), lambda t, y: ((-1,),)
    if problem == "stiff":
        return lambda t, y: (-1e4*y[0],), lambda t, y: ((-1e4,),)
    if problem == "coupled":
        return (lambda t, y: (-2*y[0]+y[1]*y[1]+t,-y[0]-3*y[1]+t*t),
                lambda t, y: ((-2,2*y[1]),(-1,-3)))
    raise ValueError(problem)


def result(step, case):
    y, dense = step(*callbacks(case["problem"]), case["t"], case["y"], case["h"])
    return [tuple(y), *(tuple(dense(theta)) for theta in case["theta"])]


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


def convergence(step):
    f, J = callbacks("damped")
    errors = []
    for n in (2, 4, 8, 16):
        y = (1,)
        for i in range(n):
            y, _ = step(f, J, 2*i/n, y, 2/n)
        errors.append(abs(y[0]-exp(-2)))
    rates = [log2(a/b) for a, b in zip(errors, errors[1:])]
    return all(4.8 < p < 5.2 for p in rates), "fixed-step endpoint orders " + ", ".join(f"{p:.3f}" for p in rates)


def stiff_limit(step):
    f, J = callbacks("stiff")
    y, _ = step(f, J, 0, (1,), 10)
    z = -1e5
    pade = (1+2*z/5+z*z/20)/(1-3*z/5+3*z*z/20-z*z*z/60)
    return abs(y[0]-pade) < 1e-12 and abs(y[0]) < 3.1e-5, f"R(-1e5)={y[0]:.6e}"


def adaptive(solve):
    f = lambda t, y: (-y[0], -30*y[1])
    J = lambda t, y: ((-1, 0), (0, -30))
    y0 = (1, 1)
    sample = (0, 0.017, 0.081, 0.311, 0.997, 1.41, 2)
    stats = []
    for eps in (1e-5, 1e-9):
        y, at, accepted, rejected = solve(f, J, 0, y0, 2, h0=2, rtol=eps, atol=eps/100)
        off_grid = max(max(abs(a-exp(-k*t)) for a, k in zip(at(t), (1, 30), strict=True)) for t in sample)
        assert max(abs(a-exp(-2*k)) for a, k in zip(y, (1, 30), strict=True)) < eps
        assert max(abs(a-b) for a, b in zip(at(2), y, strict=True)) < 1e-13
        stats.append((off_grid, accepted, rejected))
    loose, tight = stats
    return tight[0] < min(2e-7, loose[0]/10) and tight[1] > loose[1] and tight[2] > 0, (
        f"adaptive dense error {loose[0]:.2e} -> {tight[0]:.2e}; "
        f"accepted/rejected loose {loose[1:]}, tight {tight[1:]}")


def stiff_initial_layer(solve):
    """Small endpoint errors alone can accept a step with spurious interior values."""
    rate = 1e6
    f = lambda t, y: (-rate*y[0],)
    J = lambda t, y: ((-rate,),)
    rtol, atol = 1e-7, 1e-10
    y, at, accepted, rejected = solve(f, J, 0, (1,), 1, h0=1, rtol=rtol, atol=atol)
    early = (1e-8, 8e-8, 3e-7, 1e-6, 4e-6, 1e-5)
    scaled = max(abs(at(t)[0]-exp(-rate*t))/(atol+rtol*exp(-rate*t)) for t in early)
    late_error = abs(at(0.05)[0])
    ok = rejected > 0 and scaled < 2 and late_error < atol and abs(y[0]) < atol
    return ok, (f"stiff initial layer: early scaled error {scaled:.2e}; "
                f"error at t=0.05 {late_error:.2e}; accepted/rejected {accepted}/{rejected}")


def nonlinear_scaling(solve):
    """The slow nonlinear state is scale/(1+t) in both sets of units."""
    rtol = 1e-8
    errors = []
    for scale in (1.0, 1e-12):
        def rhs(t, y):
            return -y[0]*y[0]/scale, -1000*y[1]

        def jac(t, y):
            return (-2*y[0]/scale, 0), (0, -1000)

        y, at, _, _ = solve(rhs, jac, 0, (scale, scale), 1, h0=1, rtol=rtol, atol=scale*1e-10)
        dense_error = max(abs(at(t)[0]*(1+t)/scale-1) for t in (0.01, 0.125, 0.38, 0.625, 0.9))
        errors.append(max(abs(2*y[0]/scale-1), dense_error))
    return max(errors) < rtol, f"nonlinear slow-mode relative errors at scales 1 and 1e-12: {errors[0]:.2e}, {errors[1]:.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, expected_dense = step(f, jac, 0, (1,), 1)
        actual, actual_dense = step(f_scaled, jac_scaled, 0, (scale, passive), 1)
        samples = [(actual, expected)]
        samples.extend((actual_dense(s), expected_dense(s)) for s in (0, 0.17, 0.5, 0.88, 1))
    except Exception as exc:
        return False, f"mixed-scale solve: {type(exc).__name__}: {exc}"
    errors = [abs(active/scale-unit) for (active, _), (unit,) in samples]
    constant_ok = all(abs(constant-passive) <= 1e-10 for (_, constant), _ in samples)
    ok = all(error < 1e-12 for error in errors) and constant_ok
    return ok, f"mixed-scale active endpoint and dense error in normalized units: {max(errors):.2e}"


def run_checks(step, solve=None, out=print):
    results = [*fixed_cases(step), convergence(step), stiff_limit(step), mixed_scale(step)]
    if solve is not None:
        results.extend((adaptive(solve), stiff_initial_layer(solve), nonlinear_scaling(solve)))
    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()))
    import port_adapter
    sys.exit(bool(run_checks(port_adapter.step, getattr(port_adapter, "solve", None))))
