# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check YOUR implementation of Störmer–Verlet against this skill.

1. In the directory you run from, create `port_adapter.py` with

       SCHEMES = ("kdk",)          # the forms you implemented: "kdk", "dkd" or both

       def integrate(q0, p0, h, n_steps, mass, force, scheme):
           # Call your code. q0, p0, mass are lists of floats; force(q) takes and
           # returns a list of floats; h may be negative. Use canonical momentum
           # p = mass * v (convert if your code stores velocities).
           # Return the final (q, p) after n_steps steps, as sequences of floats.
           ...

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 q and p with "expected" within "tol".

Checks: the fixed cases in cases.json, convergence order 2, bounded energy over
1,000 periods (unit mass) and with different masses, and returning to the start
after integrating with -h. 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 _force(problem):
    spec = CASES["problems"][problem]
    if problem == "kepler":
        def f(q):
            r3 = (q[0] * q[0] + q[1] * q[1]) ** 1.5
            return [-q[0] / r3, -q[1] / r3]
        return f
    k = spec["k"]
    return lambda q: [-ki * qi for ki, qi in zip(k, q)]


def _final(integrate, problem, q0, p0, h, n, scheme):
    q, p = integrate(list(q0), list(p0), h, n, list(CASES["problems"][problem]["mass"]), _force(problem), scheme)
    return [float(x) for x in q], [float(x) for x in p]


def run_checks(integrate, schemes=("kdk", "dkd"), out=print):
    """Run every check; return the number of failures."""
    failures = 0

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

    # 1. Fixed cases: same algorithm, so only rounding differences are allowed.
    for i, case in enumerate(CASES["cases"]):
        if case["scheme"] not in schemes:
            continue
        try:
            q, p = _final(integrate, case["problem"], case["q0"], case["p0"], case["h"], case["n_steps"], case["scheme"])
            err = max(abs(a - b) for a, b in zip(q + p, case["expected"]["q"] + case["expected"]["p"]))
            ok = len(q) == len(case["expected"]["q"]) and len(p) == len(case["expected"]["p"]) and err <= case["tol"]
            detail = f"max difference {err:.1e}"
        except Exception as exc:  # report, keep going
            ok, detail = False, f"raised {type(exc).__name__}: {exc}"
        verdict(ok, f"case {i}: {case['problem']}, {case['scheme']}, h={case['h']:+.4f}, {case['n_steps']} steps ({detail})")

    for scheme in schemes:
        # 2. Convergence order on the two-mass oscillator (exact solution known).
        k, mass = CASES["problems"]["two-mass"]["k"], CASES["problems"]["two-mass"]["mass"]
        omega = [math.sqrt(ki / mi) for ki, mi in zip(k, mass)]
        exact = [math.cos(w * 5.0) for w in omega] + [-m * w * math.sin(w * 5.0) for m, w in zip(mass, omega)]
        errs = []
        for n in (200, 400, 800):
            q, p = _final(integrate, "two-mass", [1.0, 1.0], [0.0, 0.0], 5.0 / n, n, scheme)
            errs.append(max(abs(a - b) for a, b in zip(q + p, exact)))
        orders = [math.log2(a / b) for a, b in zip(errs, errs[1:])]
        verdict(all(1.9 < o < 2.1 for o in orders), f"{scheme}: convergence order " + ", ".join(f"{o:.2f}" for o in orders) + " (expected 2)")

        # 3. Energy stays bounded on the harmonic oscillator over 1,000 periods.
        h, per = 0.1, round(2 * math.pi / 0.1)
        q, p = [1.0], [0.0]
        energies = []
        for _ in range(1000):
            q, p = _final(integrate, "harmonic", q, p, h, per, scheme)
            energies.append(abs(0.5 * (p[0] ** 2 + q[0] ** 2) - 0.5))
        first, last = max(energies[:100]), max(energies[-100:])
        verdict(last <= 1.5 * first + 1e-12 and last < h * h / 4, f"{scheme}: energy error over 1,000 periods {first:.2e} -> {last:.2e} (must not grow)")

        # 3b. Energy also stays bounded with different masses (catches momentum used as velocity).
        k2, m2 = CASES["problems"]["two-mass"]["k"], CASES["problems"]["two-mass"]["mass"]

        def energy2(q, p):
            return sum(pi * pi / (2 * mi) for pi, mi in zip(p, m2)) + sum(0.5 * ki * qi * qi for ki, qi in zip(k2, q))

        q, p = [1.0, -0.5], [0.3, 0.2]
        e0 = energy2(q, p)
        errs2 = []
        for _ in range(400):
            q, p = _final(integrate, "two-mass", q, p, 0.02, 50, scheme)
            errs2.append(abs(energy2(q, p) - e0) / e0)
        first2, last2 = max(errs2[:40]), max(errs2[-40:])
        verdict(last2 <= 1.5 * first2 + 1e-12 and last2 < 1e-2, f"{scheme}: energy error with masses {m2}: {first2:.2e} -> {last2:.2e} (must stay small and not grow)")

        # 4. Integrating forward and then with -h returns to the start.
        kepler = next(c for c in CASES["cases"] if c["problem"] == "kepler")
        kq0, kp0 = kepler["q0"], kepler["p0"]
        q, p = _final(integrate, "kepler", kq0, kp0, 0.03, 500, scheme)
        q, p = _final(integrate, "kepler", q, p, -0.03, 500, scheme)
        gap = max(abs(a - b) for a, b in zip(q + p, kq0 + kp0))
        verdict(gap < 1e-9, f"{scheme}: forward then backward over 500 steps returns 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)
    schemes = tuple(getattr(port_adapter, "SCHEMES", ("kdk", "dkd")))
    failed = run_checks(port_adapter.integrate, schemes)
    print(f"{'All checks passed' if not failed else f'{failed} check(s) failed'} for schemes {', '.join(schemes)}.")
    sys.exit(1 if failed else 0)
