# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check a port and its forward-Euler property on a periodic Burgers problem."""

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


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


def godunov(a, b):
    """Exact Burgers flux for left and right states a and b."""
    if a <= b:
        return 0.0 if a <= 0 <= b else min(a*a,b*b)/2
    return max(a*a,b*b)/2


def burgers(dx):
    def rhs(t, y):
        right = [godunov(a,y[(i+1)%len(y)]) for i,a in enumerate(y)]
        return tuple((right[i-1]-f)/dx for i,f in enumerate(right))
    return rhs


def callbacks(problem, dx):
    if problem == "burgers":
        return burgers(dx)
    if problem == "forced":
        return lambda t,y: (t-y[0]*y[1], y[0]-2*y[1]+t*t)
    if problem == "manufactured":
        return lambda t,y: (cos(t)+sin(t)-y[0],)
    raise ValueError(problem)


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


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


def convergence(step):
    f = callbacks("manufactured",None)
    errors = [abs(advance(step,f,0,(0,),2/n,n)[0]-sin(2)) for n in (24,48,96,192)]
    p = [log2(a/b) for a,b in zip(errors,errors[1:])]
    return all(2.9 < x < 3.1 for x in p), "smooth endpoint orders " + ", ".join(f"{x:.3f}" for x in p)


def tv(y):
    return sum(abs(y[i-1]-a) for i,a in enumerate(y))


def maximum_principle(step):
    y0 = (0,0,1,1,0.2,0.1,0.4,0)
    dx = 0.125
    f = burgers(dx)
    conditions = []
    for cfl in (0.8,1.0):
        y = y0
        increase = overshoot = mass_error = 0.0
        for n in range(24):
            updated = tuple(step(f,n*cfl*dx,y,cfl*dx))
            increase = max(increase,tv(updated)-tv(y))
            overshoot = max(overshoot,max(updated)-max(y),min(y)-min(updated))
            mass_error = max(mass_error,abs(sum(updated)-sum(y0)))
            y = updated
        conditions.append((increase,overshoot,mass_error))
    ok = all(isfinite(d) and d < 3e-13 for summary in conditions for d in summary)
    return ok, (
        f"CFL 0.8 and 1.0: max TV increase {max(c[0] for c in conditions):.2e}, "
        f"new-extremum overshoot {max(c[1] for c in conditions):.2e}, "
        f"mass error {max(c[2] for c in conditions):.2e}")


def callback_times(step):
    times = []
    def f(t,y):
        times.append(t)
        return (0,)*len(y)

    value, = step(f,2,(1.3,),0.5)
    return abs(value-1.3) < 4e-15 and times == [2,2.5,2.25], f"three callback times {times}"


def run_checks(step, out=print):
    results = [*fixtures(step), convergence(step), maximum_principle(step), callback_times(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)))
