# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check YOUR implementation of processed-leapfrog MEAL against this skill.

1. In the directory you run from, create `port_adapter.py` with the parts you
   implemented ("training", "simulation" or both):

       PARTS = ("training", "simulation")

       # Training. Implement V_theta(q) = theta * V1(q) in your framework, with
       #   V1(x, y) = 0.6*x**2 + 0.4*y**2 + 0.18*x*y + 0.05*x**4 + 0.025*y**4,
       # and call your own code for the corrected gradient and the loss.
       def modified_gradient(q, h, mass, theta):
           # Return g~(q) = grad V + (h^2/12) (grad^2 V) M^-1 grad V as floats.
           ...

       def loss_and_derivative(qs, forces, h, mass, theta):
           # L = mean over i of |g~(q_i) + F_i|^2; return (L, dL/dtheta) as floats,
           # with dL/dtheta from your backpropagation.
           ...

       # Simulation. grad(q) takes and returns a list of floats (+grad V); mass is a
       # list with one mass per coordinate; h may be negative. Use canonical momentum
       # p = mass * v (convert if your code stores velocities).
       def process(q, p, h, mass, grad, post):
           # post=True: postprocessor (auxiliary -> physical); False: preprocessor.
           ...

       def rollout(q0, p0, h, n_steps, every, mass, grad):
           # Return [(step, q, p), ...] of physical states at step 0, every `every`
           # steps and at the final step.
           ...

2. Run this file with the Python environment in which your code works, so your own
   dependencies are importable:

       python <path-to-skill>/checks/check_port.py

Non-Python implementations: use checks/cases.json directly. Run each case with your
code and compare with "expected" within "tol".

Checks: the fixed cases in cases.json; for training, that dL/dtheta agrees with a
finite difference of your own loss (catches a detached gradient); for simulation,
convergence order 4 on the quartic double well with the analytic step-specific
potential, preprocessor and postprocessor inverting each other, returning to the start
after integrating with -h, output frequency not changing the trajectory, and the number
of gradient evaluations. Keep this file and cases.json in the same folder, and run it
from the directory that contains port_adapter.py.
"""

import json
import math
import os
import sys
from pathlib import Path

CASES = json.loads((Path(__file__).resolve().parent / "cases.json").read_text())


def poly_grad(theta):
    def grad(q):
        x, y = q
        return [theta * (1.2 * x + 0.18 * y + 0.2 * x ** 3), theta * (0.8 * y + 0.18 * x + 0.1 * y ** 3)]
    return grad


class Counter:
    """Wrap a gradient and count its calls."""

    def __init__(self, grad):
        self.grad, self.calls = grad, 0

    def __call__(self, q):
        self.calls += 1
        return self.grad(list(q))


def _floats(v):
    return [float(x) for x in v]


def _diff(a, b):
    return max(abs(x - y) for x, y in zip(a, b)) if len(a) == len(b) else math.inf


def _outputs(raw):
    return [(int(s), _floats(q), _floats(p)) for s, q, p in raw]


def _double_well_error(port, h, T=6.0):
    """Global error of the port at T on V0 = q^4/4 - q^2/2 with V*_h (paper Table 7 setup)."""
    def grad(q):
        x = q[0]
        return [(x ** 3 - x) * (1 - h * h * (3 * x * x - 1) / 12)]

    n = round(T / h)
    _, q, p = _outputs(port.rollout([0.3], [0.9], h, n, n, [1.0], grad))[-1]
    qr, pr, dt = 0.3, 0.9, T / 24000
    for _ in range(24000):  # RK4 reference on the physical system
        f = lambda q, p: (p, q - q ** 3)  # noqa: E731
        a = f(qr, pr)
        b = f(qr + dt / 2 * a[0], pr + dt / 2 * a[1])
        c = f(qr + dt / 2 * b[0], pr + dt / 2 * b[1])
        d = f(qr + dt * c[0], pr + dt * c[1])
        qr += dt / 6 * (a[0] + 2 * b[0] + 2 * c[0] + d[0])
        pr += dt / 6 * (a[1] + 2 * b[1] + 2 * c[1] + d[1])
    return math.hypot(q[0] - qr, p[0] - pr)


def run_checks(port, parts=("training", "simulation"), out=print):
    """Run every check for the given parts of `port`; return the number of failures."""
    failures = 0

    def verdict(ok, text):
        nonlocal failures
        out(f"{'PASS' if ok else 'FAIL'} {text}")
        failures += not ok

    def attempt(fn):
        try:
            return fn(), None
        except Exception as exc:  # report, keep going
            return None, f"raised {type(exc).__name__}: {exc}"

    mass = CASES["problems"]["poly2"]["mass"]

    # 1. Fixed cases: same algorithm, so only rounding differences are allowed.
    for i, case in enumerate(CASES["cases"]):
        kind, exp, tol = case["kind"], case["expected"], case["tol"]
        if kind in ("modified_gradient", "loss") and "training" not in parts:
            continue
        if kind in ("process", "rollout") and "simulation" not in parts:
            continue
        grad = Counter(poly_grad(case["theta"]))
        if kind == "modified_gradient":
            res, err = attempt(lambda: _floats(port.modified_gradient(list(case["q"]), case["h"], list(mass), case["theta"])))
            d = _diff(res, exp) if res is not None else math.inf
            label = f"modified gradient at q={case['q']}"
        elif kind == "loss":
            res, err = attempt(lambda: _floats(port.loss_and_derivative([list(q) for q in case["q"]], [list(f) for f in case["forces"]], case["h"], list(mass), case["theta"])))
            d = _diff(res, [exp["loss"], exp["dloss_dtheta"]]) if res is not None else math.inf
            label = f"loss and dL/dtheta on {len(case['q'])} configurations"
        elif kind == "process":
            res, err = attempt(lambda: port.process(list(case["q"]), list(case["p"]), case["h"], list(mass), grad, case["post"]))
            d = _diff(_floats(res[0]) + _floats(res[1]), exp["q"] + exp["p"]) if res is not None else math.inf
            label = f"{'postprocessor' if case['post'] else 'preprocessor'}"
        else:
            res, err = attempt(lambda: _outputs(port.rollout(list(case["q0"]), list(case["p0"]), case["h"], case["n_steps"], case["every"], list(mass), grad)))
            d = math.inf
            if res is not None:
                want = exp["outputs"]
                if [s for s, _, _ in res] == [o["step"] for o in want]:
                    d = max(_diff(q + p, o["q"] + o["p"]) for (_, q, p), o in zip(res, want))
                else:
                    err = f"emitted steps {[s for s, _, _ in res]}, expected {[o['step'] for o in want]}"
            label = f"rollout h={case['h']:+.2f}, {case['n_steps']} steps, output every {case['every']}"
        detail = err or f"max difference {d:.1e}"
        verdict(err is None and d <= tol, f"case {i}: {label} ({detail})")
        if kind == "rollout" and res is not None:
            if grad.calls == 0:
                out(f"SKIP case {i}: gradient count (your rollout did not call the grad it was given)")
            else:
                want = exp["gradient_evaluations"]
                verdict(grad.calls == want, f"case {i}: {grad.calls} gradient evaluations (expected {want} = N + 4 + 4 ceil(N/k))")

    if "training" in parts:
        # 2. dL/dtheta must be the derivative of L: a detached copy of grad V breaks this.
        case = next(c for c in CASES["cases"] if c["kind"] == "loss")
        args = ([list(q) for q in case["q"]], [list(f) for f in case["forces"]], case["h"], list(mass))
        res, err = attempt(lambda: (
            _floats(port.loss_and_derivative(*args, case["theta"])),
            float(port.loss_and_derivative(*args, case["theta"] + 1e-5)[0]),
            float(port.loss_and_derivative(*args, case["theta"] - 1e-5)[0]),
        ))
        if res is None:
            verdict(False, f"dL/dtheta against a finite difference of your loss ({err})")
        else:
            (_, deriv), lp, lm = res
            fd = (lp - lm) / 2e-5
            verdict(abs(deriv - fd) < 1e-7 * max(1.0, abs(fd)), f"dL/dtheta {deriv:.10f} against finite difference {fd:.10f}")

    if "simulation" in parts:
        # 3. Order 4 with the step-specific potential (V*_h of paper Eq. (39)).
        res, err = attempt(lambda: [_double_well_error(port, h) for h in (0.1, 0.05, 0.025)])
        if res is None:
            verdict(False, f"convergence order on the double well ({err})")
        else:
            orders = [math.log2(a / b) for a, b in zip(res, res[1:])]
            verdict(all(3.8 < o < 4.2 for o in orders), "convergence order " + ", ".join(f"{o:.2f}" for o in orders) + " on the double well (expected 4)")

        q0, p0, h = [0.4, -0.35], [0.1, 0.3], 0.12
        grad = poly_grad(1.07)
        # 4. Preprocessor then postprocessor returns the input.
        res, err = attempt(lambda: port.process(*port.process(q0, p0, h, mass, grad, False), h, mass, grad, True))
        gap = _diff(_floats(res[0]) + _floats(res[1]), q0 + p0) if res is not None else math.inf
        verdict(gap < 1e-13, f"preprocessor then postprocessor returns the input within {gap:.1e}" + (f" ({err})" if err else ""))

        # 5. Forward, then with -h, returns to the start.
        def back():
            _, q, p = _outputs(port.rollout(q0, p0, h, 200, 200, mass, grad))[-1]
            return _outputs(port.rollout(q, p, -h, 200, 200, mass, grad))[-1]
        res, err = attempt(back)
        gap = _diff(res[1] + res[2], q0 + p0) if res is not None else math.inf
        verdict(gap < 1e-12, f"forward then backward over 200 steps returns within {gap:.1e}" + (f" ({err})" if err else ""))

        # 6. Output frequency does not change the states at shared steps.
        def strides():
            a = {s: q + p for s, q, p in _outputs(port.rollout(q0, p0, h, 24, 1, mass, grad))}
            b = {s: q + p for s, q, p in _outputs(port.rollout(q0, p0, h, 24, 8, mass, grad))}
            return a, b
        res, err = attempt(strides)
        if res is None:
            verdict(False, f"output every 1 and every 8 steps ({err})")
        else:
            a, b = res
            gap = max((_diff(a[s], b[s]) for s in b), default=math.inf) if set(b) <= set(a) else math.inf
            verdict(sorted(b) == [0, 8, 16, 24] and gap < 1e-14, f"output every 1 and every 8 steps agree at shared steps within {gap:.1e}")
    return failures


if __name__ == "__main__":
    sys.path.insert(0, os.getcwd())
    try:
        import port_adapter  # noqa: E402  (created by you, see the docstring)
    except ModuleNotFoundError:
        print(__doc__)
        sys.exit(2)
    parts = tuple(getattr(port_adapter, "PARTS", ("training", "simulation")))
    failed = run_checks(port_adapter, parts)
    print(f"{'All checks passed' if not failed else f'{failed} check(s) failed'} for parts {', '.join(parts)}.")
    sys.exit(1 if failed else 0)
