"""Compare candidate boxes to independently drawn pilot boxes without adjudicating them."""

from __future__ import annotations

import json
from pathlib import Path
import statistics


def iou_xywh(a, b):
    ax1, ay1, aw, ah = a
    bx1, by1, bw, bh = b
    width = max(0, min(ax1 + aw, bx1 + bw) - max(ax1, bx1))
    height = max(0, min(ay1 + ah, by1 + bh) - max(ay1, by1))
    intersection = width * height
    union = aw * ah + bw * bh - intersection
    return intersection / union if union > 0 else 0.0


def audit(proposals_path, reviews_path, output):
    proposals = {row["frame_id"]: row for row in map(json.loads, Path(proposals_path).open())}
    reviews = json.loads(Path(reviews_path).read_text())
    rows = []
    for frame_id, reviewer_a, reviewer_b in zip(
            reviews["frame_ids"], reviews["reviewer_a_xywh"], reviews["reviewer_b_xywh"]):
        item = proposals[frame_id]
        if len(item["boxes"]) != 1:
            raise ValueError(f"audit expects one candidate instance: {frame_id}")
        candidate = [item["boxes"][0][key] for key in ("x", "y", "width", "height")]
        rows.append({"frame_id": frame_id, "domain": item["domain"],
                     "candidate": candidate, "reviewer_a": reviewer_a, "reviewer_b": reviewer_b,
                     "iou_a": iou_xywh(candidate, reviewer_a),
                     "iou_b": iou_xywh(candidate, reviewer_b),
                     "inter_reviewer_iou": iou_xywh(reviewer_a, reviewer_b)})
    by_domain = {}
    for domain in sorted({item["domain"] for item in rows}):
        subset = [item for item in rows if item["domain"] == domain]
        by_domain[domain] = {
            "frames": len(subset),
            "median_candidate_iou_a": statistics.median(item["iou_a"] for item in subset),
            "median_candidate_iou_b": statistics.median(item["iou_b"] for item in subset),
            "both_reviewers_iou_ge_0_5": sum(item["iou_a"] >= 0.5 and item["iou_b"] >= 0.5
                                          for item in subset),
        }
    report = {"reference": "blind machine reviewers; not human ground truth",
              "frames": rows, "by_domain": by_domain}
    Path(output).write_text(json.dumps(report, indent=2), encoding="utf-8")
    return report


if __name__ == "__main__":
    report = audit("outputs/annotations_fewshot.jsonl", "outputs/fewshot_audit_reviews.json",
                   "outputs/fewshot_candidate_audit.json")
    print(json.dumps(report["by_domain"], ensure_ascii=False))
