# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check component-level NMFk behavior in port_adapter.py."""

import json
import math
import sys
from pathlib import Path


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


def _diff(got, want):
    if isinstance(want, list):
        if not isinstance(got, (list, tuple)) or len(got) != len(want):
            return float("inf")
        return max((_diff(g, w) for g, w in zip(got, want, strict=True)), default=0.0)
    value = float(got)
    if not math.isfinite(value):
        return float("inf")
    if type(want) is int:
        return 0.0 if value == want else float("inf")
    return abs(value - float(want))


def run_checks(port, out=print):
    failures = 0
    for case in load_cases()["cases"]:
        try:
            result = getattr(port, case["operation"])(*case["args"])
            diff = _diff(result, case["expected"])
            ok = math.isfinite(diff) and diff <= case["tol"]
            detail = f"max difference {diff:.2e}"
        except Exception as exc:
            ok, detail = False, f"{type(exc).__name__}: {exc}"
        failures += not ok
        out(f"{'PASS' if ok else 'FAIL'} case {case['name']} ({detail})")
    return failures


if __name__ == "__main__":
    sys.path.insert(0, str(Path.cwd()))
    try:
        import port_adapter
    except ModuleNotFoundError as exc:
        if exc.name != "port_adapter":
            raise
        print(__doc__)
        sys.exit(2)
    failures = run_checks(port_adapter)
    print(f"{failures} failed port check(s)")
    sys.exit(bool(failures))
