"""Tally supplied example annotations of invented retrieval cases; not a semantic grader.
Usage: python evaluate_retrieval.py cases.json answer_annotations.csv
Python 3, standard library only. Reads files; prints JSON; makes no service calls.
"""
import csv
import json
import sys


def evaluate(cases_path, annotations_path):
    with open(cases_path, encoding="utf-8") as stream:
        data = json.load(stream)
    documents, cases = data["documents"], data["cases"]
    ids = [case["id"] for case in cases]
    if len(set(ids)) != len(ids) or not ids:
        raise ValueError("Cases need unique IDs and at least one case")
    annotations = {}
    with open(annotations_path, encoding="utf-8-sig", newline="") as stream:
        reader = csv.DictReader(stream)
        if reader.fieldnames != ["case_id", "supported", "complete", "abstained"]:
            raise ValueError("Unexpected annotation columns")
        for row in reader:
            key = row["case_id"]
            if key in annotations or any(row[field] not in ("0", "1") for field in ("supported", "complete", "abstained")):
                raise ValueError("Expected one binary annotation per case")
            annotations[key] = {field: row[field] == "1" for field in ("supported", "complete", "abstained")}
    if set(annotations) != set(ids):
        raise ValueError("Annotations must match case IDs exactly")
    results = []
    for case in cases:
        if type(case["answerable"]) is not bool:
            raise ValueError("answerable must be a boolean")
        if any(key not in documents for key in case["context_ids"] + case["reference_ids"]):
            raise ValueError("Unknown document ID")
        annotation = annotations[case["id"]]
        # This exercise uses one required reference document per answerable question.
        hit = bool(case["reference_ids"]) and set(case["reference_ids"]).issubset(case["context_ids"])
        citation_check = bool(case["citations"]) and set(case["citations"]).issubset(case["context_ids"])
        should_abstain = not case["answerable"] or not hit
        behavior_ok = annotation["abstained"] == should_abstain
        passed = citation_check and annotation["supported"] and annotation["complete"] and behavior_ok and (not case["answerable"] or hit)
        results.append({"id":case["id"], "answerable":case["answerable"],
                        "reference_in_context":hit, "citation_ids_available":citation_check,
                        **annotation, "abstention_behavior_ok":behavior_ok, "end_to_end_pass":passed})
    answerable = [row for row in results if row["answerable"]]
    unanswerable = [row for row in results if not row["answerable"]]
    def count(rows, field):
        return {"passed":sum(row[field] for row in rows), "total":len(rows)}
    return {"cases":results, "retrieval_on_answerable":count(answerable,"reference_in_context"),
            "citation_id_check":count(results,"citation_ids_available"),
            "supported_answer_key_cases":count(results,"supported"),
            "correct_abstention_on_unanswerable":count(unanswerable,"abstained"),
            "end_to_end":count(results,"end_to_end_pass"),
            "note":"Counts tally supplied answer-key labels. Changing an answer requires fresh review."}


if __name__ == "__main__":
    if len(sys.argv) != 3:
        raise SystemExit("Usage: python evaluate_retrieval.py cases.json answer_annotations.csv")
    print(json.dumps(evaluate(sys.argv[1], sys.argv[2]), indent=2))
