# Copyright (C) 2026 NPO NT
# SPDX-License-Identifier: AGPL-3.0-only

from __future__ import annotations

import argparse
import json
from pathlib import Path

from mika_deid.analyzer import analyze_document
from mika_deid.loader import load_document
from mika_deid.models import Box
from mika_deid.ocr import TesseractOcr


def main() -> int:
    parser = argparse.ArgumentParser(description="Evaluate detected regions against a synthetic MIKA annotation file")
    parser.add_argument("document", type=Path)
    parser.add_argument("annotation", type=Path)
    parser.add_argument("--minimum-overlap", type=float, default=0.5)
    args = parser.parse_args()

    analysis = analyze_document(load_document(args.document), ocr=TesseractOcr())
    truth = json.loads(args.annotation.read_text(encoding="utf-8"))
    misses: list[dict[str, object]] = []
    matched = 0
    total = 0
    for page in truth.get("pages", []):
        page_index = int(page["page"]) - 1
        page_data = analysis.document.pages[page_index]
        for region in page.get("regions", []):
            total += 1
            raw = region["box"]
            expected = Box(
                raw["x0"] * page_data.width,
                raw["y0"] * page_data.height,
                raw["x1"] * page_data.width,
                raw["y1"] * page_data.height,
            )
            candidates = [
                finding
                for finding in analysis.findings
                if finding.page_index == page_index and finding.category == region["category"]
            ]
            overlap = max((finding.box.overlap_ratio(expected) for finding in candidates), default=0.0)
            if overlap >= args.minimum_overlap:
                matched += 1
            else:
                misses.append(
                    {
                        "region_id": region.get("region_id"),
                        "category": region.get("category"),
                        "page": page_index + 1,
                        "best_overlap": round(overlap, 3),
                    }
                )
    payload = {
        "schema": "mika-deid-evaluation-v1",
        "passed": not misses and analysis.capabilities.complete,
        "truth_regions": total,
        "matched_regions": matched,
        "recall": round(matched / total, 4) if total else 0.0,
        "detected_regions": len(analysis.findings),
        "misses": misses,
        "capabilities": analysis.capabilities.as_dict(),
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return 0 if payload["passed"] else 2


if __name__ == "__main__":
    raise SystemExit(main())
