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

import json
import math
import sys
from pathlib import Path

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


def callbacks(spec):
    force = tuple(spec["force"])
    if spec["constraints"] == "sphere":
        return (lambda q: force, lambda q: (sum(x*x for x in q)-1,),
                lambda q: (tuple(2*x for x in q),))
    if spec["constraints"] == "sphere-plane":
        return (lambda q: force, lambda q: (sum(x*x for x in q)-1, q[0]+q[2]-1),
                lambda q: (tuple(2*x for x in q), (1, 0, 1)))
    raise ValueError("unknown fixture constraint")


def advance(step, q, v, h, n, spec):
    args = spec["mass"], *callbacks(spec)
    for _ in range(n):
        q, v = map(tuple, step(q, v, h, *args))
    return tuple(q), tuple(v)


def fixed_cases(step):
    fixtures = load_fixtures()
    for case in fixtures["cases"]:
        try:
            spec = fixtures["problems"][case["problem"]]
            result = advance(step, case["q"], case["v"], case["h"], case["steps"], spec)
            differences = [abs(a-b) for actual, expected in zip(result, case["expected"], strict=True)
                           for a, b in zip(actual, expected, strict=True)]
            gap = max(differences)
            ok = all(math.isfinite(d) and d <= case["tol"] for d in differences)
            yield ok, f'{case["name"]}: endpoint difference {gap:.2e}'
        except Exception as exc:
            yield False, f'{case["name"]}: {type(exc).__name__}: {exc}'


def convergence(step):
    spec = load_fixtures()["problems"]["rotor"]
    q, v = (1, 0), (0, 1)
    truth = (math.cos(2), math.sin(2), -math.sin(2), math.cos(2))
    errors = []
    for n in (20, 40, 80, 160):
        coords, speed = advance(step, q, v, 2/n, n, spec)
        errors.append(math.dist(coords + speed, truth))
    orders = [math.log2(a/b) for a, b in zip(errors, errors[1:])]
    return all(1.95 < p < 2.05 for p in orders), "rotor orders " + ", ".join(f"{p:.3f}" for p in orders)


def energy_and_constraints(step):
    spec = load_fixtures()["problems"]["pendulum"]
    force, g, G = callbacks(spec)
    q, v = (0, -1), (0.9, 0)
    energy = lambda q, v: sum(u*u/2 for u in v) + q[1]
    start = energy(q, v)
    position_error = velocity_error = 0.0
    windows = []
    for _ in range(20):
        peak = 0.0
        for _ in range(2000):
            q, v = step(q, v, 0.08, spec["mass"], force, g, G)
            position_error = max(position_error, abs(g(q)[0]))
            velocity_error = max(velocity_error, abs(sum(x*u for x, u in zip(G(q)[0], v, strict=True))))
            peak = max(peak, abs(energy(q, v)-start))
        windows.append(peak)
    energy_gap = max(windows)
    return (
        position_error < 2e-12 and velocity_error < 2e-12 and energy_gap < 1e-3
        and windows[-1] <= 1.05*windows[0],
        f"40,000 pendulum steps: position {position_error:.2e}, velocity {velocity_error:.2e}, "
        f"energy peak {energy_gap:.2e}, first/last windows {windows[0]:.2e}/{windows[-1]:.2e}",
    )


def reversal(step):
    spec = load_fixtures()["problems"]["intersection"]
    q, v = (1, 0, 0), (0, 0.7, 0)
    end = advance(step, q, v, 0.08, 40, spec)
    result = advance(step, *end, -0.08, 40, spec)
    gap = math.dist(result[0] + result[1], q + v)
    return gap < 3e-10, f"forward then backward on two constraints: {gap:.2e}"


def run_checks(step, out=print):
    results = [*fixed_cases(step), convergence(step), reversal(step), energy_and_constraints(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)))
