# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check fixed ABM histories and, optionally, a full integration adapter."""

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


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


def callback(problem):
    if problem == "time-polynomial":
        return lambda t, y: (5*t**4,)
    if problem == "coupled":
        return lambda t, y: (t-y[0]*y[1], y[0]-y[1]+t*t)
    if problem == "exponential":
        return lambda t, y: (y[0],)
    if problem == "nonautonomous":
        return lambda t, y: (cos(t)+sin(t)-y[0],)
    raise ValueError(problem)


def result(step, case):
    return step(callback(case["problem"]), case["t"], case["y"], case["h"], case["history"])


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


def milne(step):
    ratios = []
    for h in (0.02,0.01,0.005):
        history = tuple((exp(-i*h),) for i in range(4))
        y, _, estimate = step(callback("exponential"),0,(1,),h,history)
        ratios.append(estimate[0]/(exp(h)-y[0]))
    return all(0.9 < r < 1.1 for r in ratios) and abs(ratios[-1]-1) < abs(ratios[0]-1), (
        "Milne/true local error ratios " + ", ".join(f"{r:.5f}" for r in ratios))


def startup_and_order(integrate):
    errors = []
    counts = []
    for n in (40,80,160,320):
        calls = 0

        def f(t,y):
            nonlocal calls
            calls += 1
            return (cos(t)+sin(t)-y[0],)

        trajectory = list(integrate(f,0,(0,),2/n,n))
        assert len(trajectory) == n+1
        assert all(row[2] is None for row in trajectory[:4])
        assert all(row[2] is not None for row in trajectory[4:])
        assert abs(trajectory[-1][0]-2) < 1e-15
        counts.append(calls)
        errors.append(abs(trajectory[-1][1][0]-sin(2)))
    rates = [log2(a/b) for a,b in zip(errors,errors[1:])]
    return (all(3.7 < p < 4.25 for p in rates) and all(c == 7+2*n for c,n in zip(counts,(40,80,160,320))), (
        "global orders " + ", ".join(f"{p:.3f}" for p in rates)
        + f"; {counts[-1]} RHS calls for 320 steps, compared with 1280 for RK4"))


def run_checks(step, integrate=None, out=print):
    results = [*fixed_cases(step), milne(step)]
    if integrate is not None:
        results.append(startup_and_order(integrate))
    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,"integrate",None))))
