"""Tests for scripts/ocr_text_layer.py.

The lazy-import error path is CI-light (no Vision needed to prove the
RuntimeError). Actual OCR needs the remediation_tools marker (macOS Vision)."""

import builtins
import os
import sys

import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "fixtures"))

import ocr_text_layer as otl

try:
    import Vision  # noqa: F401
    VISION_READY = True
except ImportError:
    VISION_READY = False


class TestLazyImportErrorPath:
    def test_import_vision_raises_clear_runtime_error_when_absent(self, monkeypatch):
        real_import = builtins.__import__

        def _blocked_import(name, *args, **kwargs):
            if name == "Vision":
                raise ImportError("simulated: pyobjc-framework-Vision not installed")
            return real_import(name, *args, **kwargs)

        monkeypatch.setattr(builtins, "__import__", _blocked_import)
        with pytest.raises(RuntimeError, match="Vision framework unavailable"):
            otl._import_vision()

    def test_module_imports_cleanly_without_vision(self):
        # Importing ocr_text_layer at module load time (see sys.path.insert above)
        # never touches Vision — only add_text_layer -> _import_vision does.
        assert hasattr(otl, "add_text_layer")


@pytest.mark.remediation_tools
@pytest.mark.skipif(not VISION_READY, reason="macOS Vision (pyobjc-framework-Vision) not installed")
class TestAddTextLayerLive:
    def test_scanned_page_gets_invisible_text_layer(self, tmp_path):
        import gen_a11y_fixtures as gf
        import fitz

        src = gf.build_scanned_fixture(tmp_path / "scanned.pdf", lines=["A single scanned line of words."])
        out = tmp_path / "scanned.ocr.pdf"

        result = otl.add_text_layer(src, out, dpi=150)

        assert result["pages_ocred"] == [1]
        assert result["lines_added"] > 0

        doc = fitz.open(str(out))
        extracted = doc[0].get_text() or ""
        assert "scanned" in extracted.lower() or "line" in extracted.lower()
        doc.close()

    def test_page_with_ample_text_is_skipped(self, tmp_path):
        import fitz
        doc = fitz.open()
        page = doc.new_page(width=612, height=792)
        page.insert_text((72, 72), "x" * 150, fontsize=11)
        src = tmp_path / "has_text.pdf"
        doc.save(str(src))
        doc.close()

        out = tmp_path / "has_text.ocr.pdf"
        result = otl.add_text_layer(src, out)
        assert result["pages_ocred"] == []
