# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check an independent implementation exposed by 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 agrees(got, expected, tolerance):
    if isinstance(expected, list):
        return isinstance(got, (list, tuple)) and len(got) == len(expected) and all(
            agrees(a, b, tolerance) for a, b in zip(got, expected, strict=True)
        )
    if isinstance(expected, dict):
        return isinstance(got, dict) and got.keys() == expected.keys() and all(
            agrees(got[key], value, tolerance) for key, value in expected.items()
        )
    if isinstance(expected, float):
        return isinstance(got, (float, int)) and math.isclose(got, expected, rel_tol=0, abs_tol=tolerance)
    return got == expected


def run_checks(port, out=print):
    failures = 0
    for case in load_cases()["cases"]:
        try:
            result = getattr(port, case["operation"])(*case["args"])
            ok = agrees(result, case["expected"], case["tol"])
        except Exception as exc:
            out(f"FAIL {case['name']}: {type(exc).__name__}: {exc}")
            failures += 1
            continue
        out(f"{'PASS' if ok else 'FAIL'} {case['name']}")
        failures += not ok
    return failures


if __name__ == "__main__":
    sys.path.insert(0, str(Path.cwd()))
    import port_adapter

    failed = run_checks(port_adapter)
    print(f"{failed} failed port check(s)")
    sys.exit(bool(failed))
