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

from __future__ import annotations

import importlib.util
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location(
    "mika_deid_analyze_corpus", ROOT / "scripts" / "analyze_corpus.py"
)
assert SPEC is not None and SPEC.loader is not None
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)


def test_corpus_name_gate_accepts_only_neutral_pdf_names() -> None:
    assert MODULE.NEUTRAL_PDF_NAME.fullmatch("document-0001.pdf")
    assert not MODULE.NEUTRAL_PDF_NAME.fullmatch("patient-name.pdf")
    assert not MODULE.NEUTRAL_PDF_NAME.fullmatch("document-0001.xlsx")


def test_corpus_aggregate_is_log_safe_and_does_not_claim_accuracy() -> None:
    record = {
        "document_id": "document-0001",
        "status": "ok",
        "duration_seconds": 2.0,
        "analysis": {
            "page_count": 2,
            "finding_count": 3,
            "category_counts": {"person_name": 2, "event_date": 1},
            "warnings": ["Страница 2: низкая уверенность OCR; требуется особенно внимательная проверка"],
            "pages_requiring_manual_review": [2],
        },
        "qa": {
            "pages_without_findings": 0,
            "finding_sources": {"ocr": 3},
            "action_counts": {"redact": 2, "review": 1},
            "severity_counts": {"critical": 2, "medium": 1},
            "ocr_pages_below_threshold": 1,
            "ocr_pages_without_confidence": 0,
            "ocr_mean_confidence_min": 51.0,
            "ocr_mean_confidence_median": 70.0,
            "ocr_mean_confidence_max": 89.0,
        },
    }

    summary = MODULE._aggregate([record], elapsed=4.0)

    assert summary["corpus_classification"] == "CONFIRMED_FULLY_SYNTHETIC"
    assert summary["document_count"] == 1
    assert summary["total_pages"] == 2
    assert summary["total_findings"] == 3
    assert summary["metric_boundary"]["recall_computed"] is False
    assert summary["metric_boundary"]["precision_computed"] is False
    assert summary["privacy"]["ocr_text_exported"] is False
    assert summary["privacy"]["original_filenames_exported"] is False
