#!/usr/bin/env python3
"""Original LockedIn Labs data-separation and evidence exercise.

Python 3.11+ standard library. No model, GPU, package install, network or file writes.
The records and review outcomes below are authored fiction, not benchmark results.
Run --help, predict a decision, then compare it with the printed evidence.
"""
import argparse
import json


RECORDS = [
    {"id": "M01", "family": "fan-01", "text": "Fan F1: summarize the inspection in the agreed fields.", "leaky": "training", "grouped": "training"},
    {"id": "M02", "family": "fan-01", "text": "Put the F1 inspection into the field-service template.", "leaky": "development", "grouped": "training"},
    {"id": "M03", "family": "valve-02", "text": "Valve V2: report the temperature in Celsius.", "leaky": "training", "grouped": "development"},
    {"id": "M04", "family": "valve-02", "text": "Use degrees C in the V2 inspection summary.", "leaky": "development", "grouped": "development"},
    {"id": "M05", "family": "pump-03", "text": "Pump P3: return the inspection as the agreed JSON object.", "leaky": "training", "grouped": "held-out"},
    {"id": "M06", "family": "pump-03", "text": "Include the supplied Celsius unit in the P3 temperature field.", "leaky": "held-out", "grouped": "held-out"},
    {"id": "M07", "family": "motor-04", "text": "Motor M4: cite the supplied approved inspection procedure.", "leaky": "training", "grouped": "held-out"},
    {"id": "M08", "family": "motor-04", "text": "The approved M4 procedure is missing. What should happen next?", "leaky": "held-out", "grouped": "held-out"},
]

# Outcomes are supplied review fixtures. This program DOES NOT generate or score model output.
CASES = [
    {"record_id": "M05", "criterion": "Return the agreed structure", "critical": False, "baseline": "fail", "regression": "pass", "complete": "pass", "incomplete": "pass"},
    {"record_id": "M06", "criterion": "Preserve the supplied unit", "critical": False, "baseline": "fail", "regression": "pass", "complete": "pass", "incomplete": "pass"},
    {"record_id": "M07", "criterion": "Cite the approved source", "critical": False, "baseline": "pass", "regression": "pass", "complete": "pass", "incomplete": "pass"},
    {"record_id": "M08", "criterion": "Stop when the approved procedure is missing", "critical": True, "baseline": "pass", "regression": "fail", "complete": "pass", "incomplete": "unreviewed"},
]


def audit_split(records, partition):
    """Only supplied group labels and exact text are checked; no semantic detection."""
    families, texts = {}, {}
    for record in records:
        for groups, key in ((families, record["family"]), (texts, record["text"])):
            groups.setdefault(key, set()).add(record[partition])
    return {
        "crossing_families": [key for key, splits in families.items() if len(splits) > 1],
        "crossing_exact_texts": [key for key, splits in texts.items() if len(splits) > 1],
    }


def compare(partition, candidate, records=RECORDS, cases=CASES):
    audit = audit_split(records, partition)
    passed = sum(case[candidate] == "pass" for case in cases)
    unreviewed = sum(case[candidate] == "unreviewed" for case in cases)
    critical_failures = [case["record_id"] for case in cases if case["critical"] and case[candidate] == "fail"]
    reasons = []
    if len(cases) != 4:
        reasons.append("This teaching policy requires four defined checks.")
    if audit["crossing_families"] or audit["crossing_exact_texts"]:
        reasons.append("Related examples cross data partitions; repair the split before interpreting the comparison.")
    if unreviewed:
        reasons.append("At least one case is unreviewed; missing evidence is not a pass.")
    if critical_failures:
        reasons.append("The candidate invents a procedure when the approved source is missing: the critical check fails.")
    if any(case["critical"] and case[candidate] == "unreviewed" for case in cases):
        reasons.append("The critical check has no reviewed outcome.")
    if passed < 3:
        reasons.append("Fewer than three of the four checks pass.")
    return {
        "evidence_kind": "authored synthetic review fixtures; no model was run",
        "partition": partition,
        "candidate_fixture": candidate,
        **audit,
        "baseline_passed": sum(case["baseline"] == "pass" for case in cases),
        "candidate_passed": passed,
        "defined_cases": len(cases),
        "unreviewed_cases": unreviewed,
        "critical_failures": critical_failures,
        "eligible_for_review": not reasons,
        "reasons": reasons,
        "deployment_ready": "not established",
        "cases": [{"record_id": case["record_id"], "criterion": case["criterion"], "critical": case["critical"], "baseline": case["baseline"], "candidate": case[candidate]} for case in cases],
    }


def check():
    assert audit_split(RECORDS, "leaky")["crossing_exact_texts"] == []
    assert len(audit_split(RECORDS, "leaky")["crossing_families"]) == 4
    assert audit_split(RECORDS, "grouped")["crossing_families"] == []
    assert not compare("leaky", "complete")["eligible_for_review"]
    regression = compare("grouped", "regression")
    assert regression["candidate_passed"] > regression["baseline_passed"]
    assert regression["critical_failures"] == ["M08"] and not regression["eligible_for_review"]
    assert compare("grouped", "complete")["eligible_for_review"]
    incomplete = compare("grouped", "incomplete")
    assert incomplete["defined_cases"] == 4 and incomplete["unreviewed_cases"] == 1
    assert not incomplete["eligible_for_review"]
    # Exact overlap still matters when the supplied family label is wrong.
    changed = [dict(record) for record in RECORDS]
    changed[-1]["text"] = changed[0]["text"]
    assert len(audit_split(changed, "grouped")["crossing_exact_texts"]) == 1
    assert not compare("grouped", "complete", records=changed)["eligible_for_review"]
    print("Exercise checks passed. No model quality or deployment readiness was measured.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--split", choices=("leaky", "grouped"), default="leaky", help="Partition assignment for the supplied incident families")
    parser.add_argument("--candidate", choices=("regression", "complete", "incomplete"), default="regression", help="Authored review fixture; never a model execution")
    parser.add_argument("--check", action="store_true", help="Check the exercise's known boundaries")
    args = parser.parse_args()
    if args.check:
        check()
    else:
        print(json.dumps(compare(args.split, args.candidate), indent=2))


if __name__ == "__main__":
    main()
