"""PDF quality fixes: table-cell merge guard, bold/italic fonts, unchanged
blocks left untouched (no redaction/rewrite), and stats propagation."""

import fitz
import pytest

from translators.pdf_translator import PDFTranslator


class TestTableCellMergeGuard:
    def test_table_cells_never_merge(self):
        t = PDFTranslator(provider=None)
        a = {
            "bbox": (72, 100, 200, 115),
            "font_size": 11,
            "_is_table_cell": True,
        }
        b = {
            "bbox": (72, 118, 200, 133),  # same column, next row
            "font_size": 11,
            "_is_table_cell": True,
        }
        assert t._should_merge_blocks(a, b) is False

    def test_table_cell_and_paragraph_do_not_merge(self):
        t = PDFTranslator(provider=None)
        a = {"bbox": (72, 100, 200, 115), "font_size": 11, "_is_table_cell": True}
        b = {"bbox": (72, 118, 200, 133), "font_size": 11}
        assert t._should_merge_blocks(a, b) is False

    def test_regular_paragraphs_still_merge(self):
        t = PDFTranslator(provider=None)
        a = {"bbox": (72, 100, 300, 115), "font_size": 11}
        b = {"bbox": (72, 118, 302, 133), "font_size": 11}
        assert t._should_merge_blocks(a, b) is True


class TestBoldItalicFontSelection:
    def _capturing_page(self):
        page = fitz.open().new_page()
        calls = []
        original = page.insert_textbox

        def capture(rect, text, fontname=None, fontfile=None, fontsize=None, **kw):
            calls.append({"fontname": fontname, "fontfile": fontfile})
            return 0

        page.insert_textbox = capture
        return page, calls

    def _block(self, **kwargs):
        block = {
            "bbox": (72, 100, 400, 130),
            "text": "Bold heading",
            "translated": "Titre en gras",
            "font_size": 20,
            "color": 0,
            "line_count": 1,
            "sub_bboxes": [(72, 100, 400, 130)],
        }
        block.update(kwargs)
        return block

    def test_bold_block_uses_hebo(self):
        page, calls = self._capturing_page()
        t = PDFTranslator(provider=None)
        t._font_path = None  # force base-14 selection
        t._write_translated_block(page, self._block(is_bold=True), None, False)
        assert calls and calls[0]["fontname"] == "hebo"

    def test_italic_block_uses_heit(self):
        page, calls = self._capturing_page()
        t = PDFTranslator(provider=None)
        t._font_path = None
        t._write_translated_block(page, self._block(is_italic=True), None, False)
        assert calls and calls[0]["fontname"] == "heit"

    def test_bold_italic_uses_hebi(self):
        page, calls = self._capturing_page()
        t = PDFTranslator(provider=None)
        t._font_path = None
        t._write_translated_block(
            page, self._block(is_bold=True, is_italic=True), None, False
        )
        assert calls and calls[0]["fontname"] == "hebi"

    def test_regular_block_keeps_helv(self):
        page, calls = self._capturing_page()
        t = PDFTranslator(provider=None)
        t._font_path = None
        t._write_translated_block(page, self._block(), None, False)
        assert calls and calls[0]["fontname"] == "helv"


class _IdentityProvider:
    """Returns the input text unchanged (new-style provider)."""

    def get_name(self):
        return "identity"

    def is_available(self):
        return True

    def translate_text(self, request):
        from services.providers.schemas import TranslationResponse

        return TranslationResponse(
            translated_text=request.text,
            provider_name="identity",
            from_cache=False,
        )


class TestUnchangedBlocksUntouched:
    def test_identity_translation_stats_and_no_rewrite(self, tmp_path):
        """Provider returning the source text: stats stay changed=0 (so the
        route gate detects it) and blocks are left un-redacted."""
        doc = fitz.open()
        page = doc.new_page()
        page.insert_text((72, 100), "Already in English, nothing to do.", fontsize=11)
        src = tmp_path / "en.pdf"
        doc.save(str(src))
        doc.close()

        t = PDFTranslator(provider=_IdentityProvider())
        out = tmp_path / "out.pdf"
        result = t.translate_file(src, out, "en", "auto")

        assert result.exists()
        stats = t.get_translation_stats()
        assert stats["attempted"] >= 1
        assert stats["changed"] == 0

        # The text is still there, byte-for-byte same rendering (block was
        # not redacted + rewritten in the substitute font).
        check = fitz.open(str(result))
        text = check[0].get_text("text")
        check.close()
        assert "Already in English" in text
