"""Grade the three completed HandoffBench examples, using only Python's standard library.

Save this file and handoffbench-traces.json together, then run:
    python grade-handoffs.py

To explore a change, edit a copy of the JSON and pass its path as an argument.
The JSON also preserves the original five scores for comparison. This public
example recomputes the three checks that can be observed in the event summaries.
"""

import argparse
import json
from fractions import Fraction
from pathlib import Path


def grade(trace, required_roles, required_handoffs):
    if trace["status"] != "complete":
        raise ValueError("This example grades completed traces only.")

    results = [event["result"] for event in trace["events"] if "result" in event]
    handoffs = {(event["from"], event["to"]) for event in trace["events"] if "from" in event}
    missing_roles = required_roles.difference(results)
    missing_handoffs = required_handoffs.difference(handoffs)
    claimed_completion = trace["outcome"] == "responses_collected"
    return {
        "stage_coverage": int(not missing_roles),
        "handoff_coverage": Fraction(len(required_handoffs) - len(missing_handoffs), len(required_handoffs)),
        "outcome_truth": int(claimed_completion and len(results) == len(required_roles)),
    }


def main():
    parser = argparse.ArgumentParser(description="Score a four-role analysis trace.")
    parser.add_argument("traces", type=Path, nargs="?", default=Path(__file__).with_name("handoffbench-traces.json"))
    data = json.loads(parser.parse_args().traces.read_text(encoding="utf-8"))
    roles = set(data["roles"])
    handoffs = {tuple(pair) for pair in data["required_handoffs"]}
    print(f"{'Case':34} {'Role results':>12} {'Handoffs':>10} {'Completion':>12}")
    for trace in data["traces"]:
        scores = grade(trace, roles, handoffs)
        print(f"{trace['case']:34} {scores['stage_coverage']:>12} "
              f"{str(scores['handoff_coverage']):>10} {scores['outcome_truth']:>12}")


if __name__ == "__main__":
    main()
