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

import json
import math
import sys
from pathlib import Path


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


def callbacks(problem):
    if problem == "manufactured":
        return (lambda t, y: (math.cos(t)-y[0]+math.sin(t),),
                lambda t, y: ((-1,),))
    if problem == "coupled":
        return (lambda t, y: (-4*y[0]+2*y[1]+t, -y[0]-3*y[1]+t*t),
                lambda t, y: ((-4, 2), (-1, -3)))
    if problem == "nonlinear":
        return lambda t, y: (t-y[0]*y[0],), lambda t, y: ((-2*y[0],),)
    if problem == "fast":
        return lambda t, y: (-1e6*y[0],), lambda t, y: ((-1e6,),)
    if problem == "damped":
        return lambda t, y: (-y[0],), lambda t, y: ((-1,),)
    raise ValueError("unknown problem")


def advance(start, step, problem, t, y, h, n, previous=None):
    fun, jac = callbacks(problem)
    for i in range(n):
        if i == 0 and previous is None:
            next_state = start(fun, jac, t, y, h)
        else:
            next_state = step(fun, jac, t+i*h, previous, y, h)
        previous, y = y, tuple(next_state)
    return tuple(y)


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


def convergence(start, step):
    errors = []
    baseline = []
    for n in (32, 64, 128, 256):
        h = 1/n
        y = advance(start, step, "damped", 0, (1,), h, n)[0]
        errors.append(abs(y-math.exp(-1)))
        baseline.append(abs((1+h)**(-n)-math.exp(-1)))
    orders = [math.log2(a/b) for a, b in zip(errors, errors[1:])]
    return all(1.95 < p < 2.09 for p in orders) and errors[-1] < baseline[-1]/100, (
        "orders " + ", ".join(f"{p:.3f}" for p in orders)
        + f"; finest BDF2/backward Euler errors {errors[-1]:.2e}/{baseline[-1]:.2e}")


def damping(start, step):
    h = 0.1
    previous, current = (1,), advance(start, step, "fast", 0, (1,), h, 1)
    values = [current[0]]
    for n in range(1, 5):
        next_state = advance(start, step, "fast", n*h, current, h, 1, previous)
        values.append(next_state[0])
        previous, current = current, next_state
    rho = 1/math.sqrt(3 + 2*h*1e6)
    ok = max(map(abs, values)) < 1.1e-5 and abs(values[-1]) < 2e-12
    return ok, f"h*lambda=-1e5, root radius {rho:.3e}; y1..y5 " + ", ".join(f"{x:.2e}" for x in values)


def mixed_scale(start, 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))
    initial = (scale, passive)
    try:
        starter_active, starter_passive = start(f, jac, 0, initial, 1)
        next_active, next_passive = step(f, jac, 1, initial, (scale/2, passive), 1)
    except Exception as exc:
        return False, f"mixed-scale solve: {type(exc).__name__}: {exc}"
    # Solve the backward Euler and BDF2 endpoint equations in units of scale.
    starter_error = abs(starter_active/scale - (math.sqrt(5)-1)/2)
    step_error = abs(next_active/scale - (math.sqrt(17)-3)/4)
    ok = (starter_error < 1e-12 and step_error < 1e-12
          and abs(starter_passive-passive) <= 1e-10 and abs(next_passive-passive) <= 1e-10)
    return ok, (f"mixed-scale active errors in normalized units: "
                f"startup {starter_error:.2e}, BDF2 {step_error:.2e}")


def run_checks(start, step, out=print):
    results = [*fixed_cases(start, step), convergence(start, step), damping(start, step), mixed_scale(start, 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 start, step
    sys.exit(bool(run_checks(start, step)))
