# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Verify dense interpolation, damping, convergence and adaptive control."""

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 fixed_cases, read_cases, run_checks
from make_cases import build
from radau_iia_5 import C, solve, step


def interpolation_check():
    f = lambda t, y: (3*t*t,)
    J = lambda t, y: ((0,),)
    _, poly = step(f, J, 0.3, (0.3**3,), 0.8)
    error = max(abs(poly(theta)[0]-(0.3+0.8*theta)**3) for theta in (0, *C, 0.23, 0.73, 1))
    assert error < 3e-15
    print(f"PASS exact dense cubic reproduction within {error:.2e}")


def straight_line(f, J, t, y, h):
    end, _ = step(f, J, t, y, h)
    return end, lambda theta: tuple(a+theta*(b-a) for a, b in zip(y, end))


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


def wrong_endpoint(f, J, t, y, h):
    _, dense = step(f, J, t, y, h)
    return dense(C[1]), dense


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, solve) == 0
    interpolation_check()
    for wrong in (straight_line, freeze_time, wrong_endpoint):
        failures = sum(not ok for ok, _ in fixed_cases(wrong))
        assert failures
        print(f"PASS {wrong.__name__}: rejected by {failures} fixture(s)")
