#!/usr/bin/env python3
"""Offline, dependency-free contract checks for an educational prompt workflow.

Usage:
  python check_outputs.py golden_cases.json predictions.json

predictions.json format: {"results": [{"id": "consistent", "output": {...}}, ...]}
A reference prediction example is provided in predictions_example.json.
This checks structure, arithmetic and status consistency; it does NOT validate an LLM
or verify documents, supplier conduct or real-world facts.
"""
import json
import sys
from pathlib import Path

KEYS = {"ordered", "received", "delivery_note", "difference", "status", "confidence_note", "next_check"}
STATUSES = {"consistent", "requires_review", "insufficient_data"}


def quantity(value):
    return value is None or (type(value) is int and value >= 0)


def check_contract(original, output):
    issues = []
    if not isinstance(output, dict):
        return ["output must be a JSON object"]
    if set(output) != KEYS:
        issues.append("output keys must exactly match the contract")
    for key in ("ordered", "received", "delivery_note"):
        if not quantity(output.get(key)):
            issues.append(f"{key}: must be a non-negative integer or null")
    delta = output.get("difference")
    if delta is not None and type(delta) is not int:
        issues.append("difference: must be an integer (negative values allowed) or null")
    for key in ("ordered", "received", "delivery_note"):
        if output.get(key) != original.get(key) or type(output.get(key)) != type(original.get(key)):
            issues.append(f"{key}: must faithfully match source data")
    if output.get("status") not in STATUSES:
        issues.append("status: not in approved enum")
    for key in ("confidence_note", "next_check"):
        if not isinstance(output.get(key), str) or not output[key].strip():
            issues.append(f"{key}: a non-empty string is required")
    o, r, d = (original.get(x) for x in ("ordered", "received", "delivery_note"))
    if not all(type(x) is int and x >= 0 for x in (o, r, d)):
        expected_difference, expected_status = None, "insufficient_data"
    elif o == r == d:
        expected_difference, expected_status = 0, "consistent"
    else:
        expected_difference, expected_status = o-r, "requires_review"
    if output.get("difference") != expected_difference:
        issues.append(f"difference: expected {expected_difference!r}")
    if output.get("status") != expected_status:
        issues.append(f"status: expected {expected_status}")
    return issues


def main():
    if len(sys.argv) != 3:
        print(__doc__)
        return 2
    fixture = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
    prediction = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))
    expected = {case["id"]: case for case in fixture["cases"]}
    results = prediction.get("results")
    if not isinstance(results, list):
        print("Error: predictions must contain a results array")
        return 2
    found = {}
    for entry in results:
        if not isinstance(entry, dict) or entry.get("id") not in expected:
            print("Error: unexpected or malformed case")
            return 2
        if entry["id"] in found:
            print("Error: duplicate id", entry["id"])
            return 2
        found[entry["id"]] = entry["output"]
    errors = 0
    for caseid, case in expected.items():
        if caseid not in found:
            print(f"FAIL {caseid}: missing prediction")
            errors += 1
            continue
        issues = check_contract(case["input"], found[caseid])
        if issues:
            errors += 1
            print("FAIL", caseid, "|", "; ".join(issues))
        else:
            print("PASS", caseid)
    print(f"Cases: {len(expected)}; passed: {len(expected)-errors}; failed: {errors}")
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main())
