"""Execute exact validators using independent literal, type-sensitive outcomes."""

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

from validator import (validate_port_accept_all, validate_port_baseline,
                       validate_port_corrected, validate_port_reject_all)

ROOT = Path(__file__).resolve().parent
IMPLEMENTATIONS = {"baseline": validate_port_baseline,
                   "corrected": validate_port_corrected,
                   "accept-all": validate_port_accept_all,
                   "reject-all": validate_port_reject_all}


def same_typed_structure(actual, expected):
    # Python True == 1 is not sufficient for this declared typed contract.
    if type(actual) is not type(expected):
        return False
    if type(expected) is dict:
        return actual.keys() == expected.keys() and all(
            same_typed_structure(actual[key], expected[key]) for key in expected)
    return actual == expected


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--implementation", required=True, choices=IMPLEMENTATIONS)
    parser.add_argument("--selection", required=True,
                        choices=["representatives", "six-neighbors", "refined-eight"])
    args = parser.parse_args()
    authored = json.loads((ROOT / "cases.json").read_text())
    cases = [row for row in authored["cases"] if args.selection in row["selections"]]
    results = []
    for case in cases:
        # Enforce fixture construction, not a type-validation claim about SUT.
        if type(case["port"]) is not int:
            raise SystemExit("Fixture violates exact-int incoming-domain precondition")
        try:
            actual = IMPLEMENTATIONS[args.implementation](case["port"])
            error = None
        except Exception as caught:
            actual = None
            error = {"type": type(caught).__name__, "message": str(caught)}
        passed = error is None and same_typed_structure(actual, case["expected"])
        results.append({"case_id": case["id"], "authored_class": case["class"],
                        "input_port": case["port"], "input_type": type(case["port"]).__name__,
                        "expected": case["expected"], "actual": actual,
                        "expected_field_types": {key: type(value).__name__ for key, value in case["expected"].items()},
                        "actual_field_types": {key: type(value).__name__ for key, value in actual.items()} if type(actual) is dict else None,
                        "error": error, "passed": passed})
    report = {
        "implementation": args.implementation, "selection": args.selection,
        "oracle": "Independent literal whole response with exact types and keys; no expected calculation copied from validator.",
        "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 ["validator.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),
                   "authored_classes_sampled": dict(sorted(Counter(row["authored_class"] for row in results).items()))},
        "class_count_interpretation": "Counts identify selected witnesses from authored classes; they do not prove all members behave equivalently.",
        "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())
