# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Validate fixtures and show which errors they reject."""

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT / "reference"), str(ROOT / "checks")]
from check_port import fixed_cases, load_fixtures, run_checks
from make_cases import build
from rattle import step


def no_tangent_correction(q, v, h, mass, force, g, G):
    q_next, _ = step(q, v, h, mass, force, g, G)
    v_free = tuple((b-a)/h+h*f/(2*m)
                   for a, b, f, m in zip(q, q_next, force(q_next), mass, strict=True))
    return q_next, v_free


def ignore_mass(q, v, h, mass, force, g, G):
    return step(q, v, h, [1]*len(mass), force, g, G)


def ignore_step_sign(q, v, h, mass, force, g, G):
    return step(q, v, abs(h), mass, force, g, G)


if __name__ == "__main__":
    actual, stored = json.loads(json.dumps(build())), load_fixtures()
    # Metadata must regenerate exactly. run_checks compares endpoints at their fixture tolerances.
    for record in (actual, stored):
        for case in record["cases"]:
            del case["expected"]
    assert actual == stored
    assert run_checks(step) == 0
    for wrong in (no_tangent_correction, ignore_mass, ignore_step_sign):
        failures = sum(not ok for ok, _ in fixed_cases(wrong))
        assert failures, wrong.__name__
        print(f"PASS {wrong.__name__}: rejected by {failures} fixed case(s)")
    try:
        step((1, 0), (0, 1), 1.2, (1, 1), lambda q: (0, 0),
             lambda q: (sum(x*x for x in q)-1,), lambda q: (tuple(2*x for x in q),))
    except RuntimeError:
        print("PASS infeasible drift reports constraint solve failure")
    else:
        raise AssertionError("expected infeasible drift to be rejected")
