"""Offline contract validator for invented responses. Python 3.10+, stdlib only."""
import argparse
import json
from pathlib import Path

KEYS = {"request_id", "priority", "labels", "needs_review"}
LABELS = {"billing", "scheduling", "access"}


class ContractError(ValueError):
    pass


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ContractError("duplicate_key")
        result[key] = value
    return result


def reject_constant(value):
    raise ContractError("nonfinite_number")


def first_error(raw):
    try:
        obj = json.loads(raw, object_pairs_hook=unique_object,
                         parse_constant=reject_constant)
    except json.JSONDecodeError:
        return "invalid_json"
    except ContractError as exc:
        return str(exc)
    if type(obj) is not dict:
        return "top_level_object"
    if set(obj) != KEYS:
        return "keys_mismatch"
    name = obj["request_id"]
    if type(name) is not str or not 1 <= len(name) <= 24 or name.strip() != name:
        return "request_id_format"
    priority = obj["priority"]
    # bool subclasses int: isinstance(True, int) would incorrectly accept it.
    if type(priority) is not int or not 0 <= priority <= 3:
        return "priority_type_or_range"
    labels = obj["labels"]
    if type(labels) is not list or len(labels) > 3:
        return "labels_shape"
    if any(type(label) is not str or label not in LABELS for label in labels):
        return "labels_value"
    if len(set(labels)) != len(labels):
        return "labels_duplicates"
    if type(obj["needs_review"]) is not bool:
        return "needs_review_type"
    return "ok"


def evaluate(data):
    results = []
    for case in data["candidates"]:
        reason = first_error(case["raw"])
        results.append({"id": case["id"], "accepted": reason == "ok", "reason": reason})
    accepted = sum(row["accepted"] for row in results)
    return {"total": len(results), "accepted": accepted,
            "rejected": len(results) - accepted, "results": results}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("--check", type=Path, help="Compare with an answer JSON file")
    args = parser.parse_args()
    result = evaluate(json.loads(args.input.read_text(encoding="utf-8")))
    print(json.dumps(result, indent=2, allow_nan=False))
    if args.check and result != json.loads(args.check.read_text(encoding="utf-8")):
        parser.exit(1, "Answer mismatch: compare the printed fields with your answer.\n")


if __name__ == "__main__":
    main()
