"""Evaluate invented classifier scores, without training or external requests.
Usage: python evaluate_threshold.py scores.csv 0.50
"""
import csv
import json
import math
import sys


def evaluate(filename, threshold):
    if not math.isfinite(threshold) or not 0 <= threshold <= 1:
        raise ValueError("Threshold must be between 0 and 1")
    counts = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
    seen = set()
    with open(filename, encoding="utf-8-sig", newline="") as stream:
        reader = csv.DictReader(stream)
        if reader.fieldnames != ["case_id", "actual_positive", "score"]:
            raise ValueError("Unexpected CSV header")
        for row in reader:
            case_id = row["case_id"]
            if not case_id or case_id in seen or row["actual_positive"] not in ("0", "1"):
                raise ValueError("Expected unique case IDs and binary labels")
            seen.add(case_id)
            actual, score = int(row["actual_positive"]), float(row["score"])
            if not math.isfinite(score) or not 0 <= score <= 1:
                raise ValueError("Scores must be finite numbers between 0 and 1")
            predicted = score >= threshold
            key = ("tp" if actual else "fp") if predicted else ("fn" if actual else "tn")
            counts[key] += 1
    tp, fp, fn, tn = (counts[key] for key in ("tp", "fp", "fn", "tn"))
    ratio = lambda numerator, denominator: numerator / denominator if denominator else None
    return {"threshold": threshold, **counts, "flagged": tp + fp,
            "precision": ratio(tp, tp + fp), "recall": ratio(tp, tp + fn),
            "accuracy": ratio(tp + tn, tp + fp + fn + tn)}


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