"""Call exported implementations against test-owned literal expected values."""

import argparse
import hashlib
import json
import platform
import sys
from pathlib import Path

from clamp import (workers_cap_nineteen, workers_constant_one, workers_corrected,
                   workers_interior_hole, workers_upper_only)

ROOT = Path(__file__).resolve().parent
IMPLEMENTATIONS = {"upper-only": workers_upper_only, "corrected": workers_corrected,
                   "constant-one": workers_constant_one,
                   "cap-nineteen": workers_cap_nineteen,
                   "interior-hole": workers_interior_hole}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--implementation", required=True, choices=IMPLEMENTATIONS)
    parser.add_argument("--selection", required=True,
                        choices=["existing-three", "original-zero", "six-neighbors",
                                 "selected-nine", "held-out-seven"])
    parser.add_argument("--oracle", choices=["literal", "weak-range"], default="literal")
    args = parser.parse_args()
    specification = json.loads((ROOT / "cases.json").read_text())
    cases = [case for case in specification["cases"] if args.selection in case["selections"]]
    results = []
    for case in cases:
        # The exact-int input domain is a precondition, not validation by SUT.
        if type(case["requested"]) is not int:
            raise SystemExit("Fixture input violates the declared exact-int domain")
        try:
            actual = IMPLEMENTATIONS[args.implementation](case["requested"])
            error = None
        except Exception as caught:
            actual = None
            error = {"type": type(caught).__name__, "message": str(caught)}
        if args.oracle == "literal":
            passed = error is None and type(actual) is int and actual == case["expected"]
            gate_expected = {"exact_int_value": case["expected"]}
        else:
            # Intentionally under-specified assertion: permits zero and ignores
            # the required exact answer. It is NOT the clamp contract oracle.
            passed = error is None and type(actual) is int and 0 <= actual <= 20
            gate_expected = {"weak_inclusive_range": [0, 20]}
        results.append({"case_id": case["id"], "requested": case["requested"],
                        "requirement_expected": case["expected"], "gate_expected": gate_expected,
                        "actual": actual, "error": error, "passed": passed,
                        "requirement_value_matched": error is None and type(actual) is int and actual == case["expected"]})
    report = {"implementation": args.implementation, "selection": args.selection,
              "oracle": args.oracle,
              "runtime": {"python": platform.python_version(), "python_build": sys.version,
                          "debug_assertions_enabled": __debug__, "optimize_flag": sys.flags.optimize},
              "source_sha256": {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest()
                                for name in ["clamp.py", "run_cases.py", "cases.json", "contract.json"]},
              "counts": {"function_invocations": len(results),
                         "passed": sum(row["passed"] for row in results),
                         "failed": sum(not row["passed"] for row in results),
                         "requirement_mismatches": sum(not row["requirement_value_matched"] for row in results)},
              "accepted_by_selected_gate": bool(results) and all(row["passed"] for row in results),
              "results": results}
    print(json.dumps(report, indent=2, sort_keys=True))
    return 0 if report["accepted_by_selected_gate"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
