# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Run from the directory containing port_adapter.py; see SKILL.md."""

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


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


def callbacks(kind):
    if kind == "nonautonomous":
        return lambda t,y: (cos(t)+sin(t)-y[0],), lambda t,y: ((-1,),)
    if kind == "affine":
        return (lambda t,y: (-4*y[0]+2*y[1]+1,-y[0]-3*y[1]-2),
                lambda t,y: ((-4,2),(-1,-3)))
    if kind == "rotation":
        return (lambda t,y: (-(1+y[0]/2)*y[1],(1+y[0]/2)*y[0]),
                lambda t,y: ((-y[1]/2,-1-y[0]/2),(1+y[0],0)))
    if kind == "fast":
        return lambda t,y: (-1000*y[0],), lambda t,y: ((-1000,),)
    raise ValueError(kind)


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


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


def convergence(step):
    errors = [abs(advance(step,"nonautonomous",0,(0,),2/n,n)[0]-sin(2)) for n in (16,32,64,128)]
    rates = [log2(a/b) for a,b in zip(errors,errors[1:])]
    return all(1.95 < p < 2.05 for p in rates), "global orders " + ", ".join(f"{p:.3f}" for p in rates)


def ringing(step):
    plain = [advance(step,"fast",0,(1,),1,n)[0] for n in (1,2,3,4)]
    # Replace the first full step by two backward Euler half steps.
    damped = advance(step,"fast",1,(1/(1+500)**2,),1,3)[0]
    z = -1000
    factor = (1+z/2)/(1-z/2)
    return (
        max(abs(y-factor**(k+1)) for k,y in enumerate(plain)) < 5e-12
        and abs(damped) < 4e-6,
        f"h*lambda=-1000: plain y1={plain[0]:.6f}, y4={plain[-1]:.6f}; "
        f"y4 with backward Euler startup={damped:.3e}; exact y4={exp(-4000):.0f}",
    )


def mixed_scale(step):
    scale, passive = 1e-9, 1e5
    f = lambda t, y: (-y[0]*y[0]/scale, 0)
    jac = lambda t, y: ((-2*y[0]/scale, 0), (0, 0))
    try:
        active, constant = step(f, jac, 0, (scale, passive), 1)
    except Exception as exc:
        return False, f"mixed-scale solve: {type(exc).__name__}: {exc}"
    # The normalized endpoint satisfies u = (1 - u*u)/2.
    error = abs(active/scale - (sqrt(2)-1))
    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 = [*fixtures(step), convergence(step), ringing(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)))
