# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""The checks for users' implementations are correct and actually catch porting bugs.

1. checks/cases.json matches what the reference implementation computes now.
2. The reference implementation passes checks/check_port.py.
3. An independent port written with lists passes as well.
4. Each deliberately broken port, a typical porting mistake, fails at least one fixed case.
"""

import json
import math
import sys
from pathlib import Path
from types import SimpleNamespace

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "reference"))
sys.path.insert(0, str(ROOT / "checks"))
import check_port  # noqa: E402
import make_cases  # noqa: E402
import processed_dkd as ref  # noqa: E402

failures = []


def verdict(ok, text):
    print(f"{'PASS' if ok else 'FAIL'} {text}")
    if not ok:
        failures.append(text)


stored = json.loads((ROOT / "checks" / "cases.json").read_text())
verdict(stored == json.loads(json.dumps(make_cases.build())), "checks/cases.json equals the output of checks/make_cases.py")


def reference_port():
    def modified_gradient(q, h, mass, theta):
        return ref.modified_gradient(tuple(q), h, tuple(mass), make_cases.poly_grad(theta), make_cases.poly_hvp(theta))

    def loss_and_derivative(qs, forces, h, mass, theta):
        samples = list(zip(map(tuple, qs), map(tuple, forces)))
        loss = ref.force_loss(samples, h, tuple(mass), make_cases.poly_grad(theta), make_cases.poly_hvp(theta))
        return loss, make_cases.loss_derivative(qs, forces, h, mass, theta)

    return SimpleNamespace(
        modified_gradient=modified_gradient,
        loss_and_derivative=loss_and_derivative,
        process=lambda q, p, h, mass, grad, post: ref.process(tuple(q), tuple(p), h, tuple(mass), grad, post=post),
        rollout=lambda q0, p0, h, n, every, mass, grad: ref.rollout(q0, p0, h, n, mass, grad, every=every),
    )


log = []
verdict(check_port.run_checks(reference_port(), out=log.append) == 0, f"reference implementation passes all {len(log)} port checks")


def make_port(*, coeff=1 / 12, deriv_coeff=1 / 6, swap_processors=False, s_scale=1 / math.sqrt(48), use_mass=True,
              write_back=False, kick_sign=1.0, modified_kicks=False, drop_final=False):
    """Processed-leapfrog MEAL written with lists, with one typical mistake switched on."""

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

    def b1(q, v):
        x, y = q
        return [(1.2 + 0.6 * x * x) * v[0] + 0.18 * v[1], 0.18 * v[0] + (0.8 + 0.3 * y * y) * v[1]]

    def corrected(q, h, mass, theta):
        g = [theta * a for a in g1(q)]
        bmg = [theta * c for c in b1(q, [gi / mi for gi, mi in zip(g, mass)])]
        return [a + coeff * h * h * c for a, c in zip(g, bmg)], g, bmg

    def modified_gradient(q, h, mass, theta):
        return corrected(q, h, mass, theta)[0]

    def loss_and_derivative(qs, forces, h, mass, theta):
        loss = dloss = 0.0
        for q, f in zip(qs, forces):
            gm, g, bmg = corrected(q, h, mass, theta)
            # d(g~)/d(theta) = g1 + (h^2/6) theta B1 M^-1 g1 when both copies of grad V depend on theta;
            # a detached copy gives h^2/12 instead of h^2/6.
            dg = [a / theta + deriv_coeff * h * h * c / theta for a, c in zip(g, bmg)]
            loss += sum((a + b) ** 2 for a, b in zip(gm, f))
            dloss += sum(2 * (a + b) * d for a, b, d in zip(gm, f, dg))
        return loss / len(qs), dloss / len(qs)

    def shears(h, post):
        s = abs(h) * s_scale
        seq = [("D", s), ("K", s), ("D", -s), ("K", -s), ("D", -s), ("K", -s), ("D", s), ("K", s)]
        if post == swap_processors:
            seq = [(k, -t) for k, t in reversed(seq)]
        return seq

    def apply(q, p, seq, mass, grad):
        m = mass if use_mass else [1.0] * len(mass)
        q, p = list(q), list(p)
        for kind, t in seq:
            if kind == "D":
                q = [qi + t * pi / mi for qi, pi, mi in zip(q, p, m)]
            else:
                p = [pi - kick_sign * t * gi for pi, gi in zip(p, grad(q))]
        return q, p

    def process(q, p, h, mass, grad, post):
        return apply(q, p, shears(h, post), mass, grad)

    def rollout(q0, p0, h, n, every, mass, grad):
        kick_grad = grad
        if modified_kicks:  # uses the training-time corrected gradient in the kicks
            def kick_grad(q):
                g = grad(q)
                eps = 1e-6
                gp = grad([qi + eps * gi / mi for qi, gi, mi in zip(q, g, mass)])
                return [a + h * h / 12 * (b - a) / eps for a, b in zip(g, gp)]
        out = [(0, list(q0), list(p0))]
        q, p = process(q0, p0, h, mass, kick_grad, False)
        for step in range(1, n + 1):
            q, p = apply(q, p, [("D", h / 2), ("K", h), ("D", h / 2)], mass, kick_grad)
            if step % every == 0 or (step == n and not drop_final):
                yq, yp = process(q, p, h, mass, kick_grad, True)
                out.append((step, yq, yp))
                if write_back:
                    q, p = yq, yp
        return out

    return SimpleNamespace(modified_gradient=modified_gradient, loss_and_derivative=loss_and_derivative,
                           process=process, rollout=rollout)


verdict(check_port.run_checks(make_port(), out=lambda _: None) == 0, "a correct independent port (lists, hand-written Hessian product) passes")

MUTANTS = {
    "1/24 instead of 1/12 in the corrected gradient": make_port(coeff=1 / 24, deriv_coeff=1 / 12),
    "one copy of grad V detached in the loss derivative": make_port(deriv_coeff=1 / 12),
    "preprocessor and postprocessor swapped": make_port(swap_processors=True),
    "processor step s = |h|/sqrt(24) instead of |h|/sqrt(48)": make_port(s_scale=1 / math.sqrt(24)),
    "momentum used as velocity (mass ignored in drifts)": make_port(use_mass=False),
    "physical output written back into the auxiliary state": make_port(write_back=True),
    "kick sign flipped (p += t grad V)": make_port(kick_sign=-1.0),
    "corrected gradient used in the simulation kicks": make_port(modified_kicks=True),
    "final state not emitted when the output interval does not divide the step count": make_port(drop_final=True),
}
for name, port in MUTANTS.items():
    log = []
    check_port.run_checks(port, out=log.append)
    fixed = [line for line in log if line.startswith("FAIL case")]
    verdict(len(fixed) > 0, f"broken port caught by the fixed cases: {name} (fails {len(fixed)} fixed case(s))")

sys.exit(1 if failures else 0)
