"""Tests for the E2 (untagged/scanned/hybrid) font-defect flagging fix in
scripts/remediate_pdf.py.

Root cause: the digital-tagged E3 path checked _has_font_defects(vera) and
set needs_manual on gate failure; the E2-insitu direct route (real case:
Calculas_derivation_LS_solutions.pdf, untagged, fails veraPDF 7.21.7) never
did, so callers couldn't distinguish "unfixable font defect" from "needs
more judgment". CI-light: mocks _run_e2 (no vendored ODL/java needed) and
verapdf_gate.run_verapdf.
"""

import os
import shutil
import sys

import fitz  # PyMuPDF
import pytest

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

import remediate_pdf as rp


def _tiny_pdf(path, text="Hello world"):
    doc = fitz.open()
    page = doc.new_page(width=200, height=200)
    page.insert_text((10, 20), text, fontsize=10)
    doc.save(str(path))
    doc.close()
    return path


def _fake_run_e2(work_input, input_path, output_path, judgment, title, lang, notes):
    shutil.copy(str(work_input), str(output_path))
    return {"promotions": [], "alts_set": {}, "tables_flagged": []}, title or "T"


class TestE2FontDefectFlagging:
    def test_font_defect_sets_needs_manual(self, tmp_path, monkeypatch):
        p = _tiny_pdf(tmp_path / "untagged.pdf")
        monkeypatch.setattr(rp, "_run_e2", _fake_run_e2)
        monkeypatch.setattr(
            rp.verapdf_gate, "run_verapdf",
            lambda *_a, **_k: {
                "compliant": False,
                "failed_summaries": [
                    {"clause": "7.21.7", "description": "missing ToUnicode CMap"},
                ],
            },
        )

        result = rp.remediate_pdf(p, judgment={}, cls="digital-untagged")

        assert result["engine"] == "E2-insitu"
        assert result["needs_manual"] is True
        assert "font" in result["manual_reason"]
        assert result["manual_reason"] == rp._FONT_DEFECT_REASON

    def test_non_font_structural_failure_does_not_set_needs_manual(self, tmp_path, monkeypatch):
        p = _tiny_pdf(tmp_path / "untagged.pdf")
        monkeypatch.setattr(rp, "_run_e2", _fake_run_e2)
        monkeypatch.setattr(
            rp.verapdf_gate, "run_verapdf",
            lambda *_a, **_k: {
                "compliant": False,
                "failed_summaries": [
                    {"clause": "7.1", "description": "unrelated structural failure"},
                ],
            },
        )

        result = rp.remediate_pdf(p, judgment={}, cls="digital-untagged")

        assert result["engine"] == "E2-insitu"
        assert result["needs_manual"] is False
        assert result["manual_reason"] is None

    def test_compliant_gate_never_sets_needs_manual(self, tmp_path, monkeypatch):
        p = _tiny_pdf(tmp_path / "untagged.pdf")
        monkeypatch.setattr(rp, "_run_e2", _fake_run_e2)
        monkeypatch.setattr(
            rp.verapdf_gate, "run_verapdf",
            lambda *_a, **_k: {"compliant": True, "failed_summaries": []},
        )

        result = rp.remediate_pdf(p, judgment={}, cls="digital-untagged")

        assert result["needs_manual"] is False
        assert result["manual_reason"] is None
