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

from __future__ import annotations

import importlib.util
from pathlib import Path

import pytest


MODULE_PATH = Path(__file__).resolve().parents[1] / "scripts" / "export_preannotations.py"
SPEC = importlib.util.spec_from_file_location("export_preannotations", MODULE_PATH)
assert SPEC and SPEC.loader
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)


def test_build_preannotation_normalizes_boxes_and_exports_no_text() -> None:
    record = {
        "document_id": "document-0001",
        "status": "ok",
        "analysis": {
            "page_count": 1,
            "findings": [
                {
                    "page": 1,
                    "category": "person_name",
                    "box": {"x0": 10, "y0": 20, "x1": 110, "y1": 70},
                    "action": "redact",
                    "confidence": 88.0,
                    "source": "ocr",
                }
            ],
        },
    }

    result = MODULE.build_preannotation("document-0001", record, [(200.0, 100.0)])

    region = result["pages"][0]["regions"][0]
    assert region["box"] == {"x0": 0.05, "y0": 0.2, "x1": 0.55, "y1": 0.7}
    assert result["annotation_status"] == "MACHINE_PREANNOTATION_NOT_GROUND_TRUTH"
    assert result["provenance"]["ocr_text_exported"] is False
    assert "text" not in region
    assert region["human_reviewed"] is False


def test_build_preannotation_rejects_non_neutral_document_id() -> None:
    with pytest.raises(ValueError, match="neutral"):
        MODULE.build_preannotation(
            "patient-name",
            {"status": "ok", "analysis": {"page_count": 1, "findings": []}},
            [(100.0, 100.0)],
        )
