import os
import tempfile
import unittest
from pathlib import Path

from doc2md.converter import image_to_markdown, pdf_to_markdown


class OcrIntegrationTest(unittest.TestCase):
    def setUp(self) -> None:
        if os.environ.get("DOC2MD_RUN_OCR_TESTS") != "1":
            self.skipTest("Set DOC2MD_RUN_OCR_TESTS=1 to enable OCR integration tests")
        try:
            import paddleocr  # noqa: F401
        except Exception:
            self.skipTest("paddleocr is not installed")
        try:
            from PIL import Image, ImageDraw, ImageFont  # noqa: F401
        except Exception:
            self.skipTest("Pillow is not installed")

    def _make_image(self, path: Path) -> None:
        from PIL import Image, ImageDraw, ImageFont

        image = Image.new("RGB", (240, 80), "white")
        draw = ImageDraw.Draw(image)
        font = ImageFont.load_default()
        draw.text((10, 25), "HELLO", fill="black", font=font)
        image.save(path)

    def test_image_ocr_end_to_end(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            img_path = Path(tmpdir) / "hello.png"
            self._make_image(img_path)
            output = image_to_markdown(img_path, ocr_lang="en", ocr_device="cpu")
            self.assertTrue(output.strip())

    def test_pdf_ocr_end_to_end(self) -> None:
        try:
            import pypdfium2  # noqa: F401
        except Exception:
            self.skipTest("pypdfium2 is not installed")
        with tempfile.TemporaryDirectory() as tmpdir:
            img_path = Path(tmpdir) / "hello.png"
            pdf_path = Path(tmpdir) / "hello.pdf"
            self._make_image(img_path)
            from PIL import Image

            image = Image.open(img_path)
            image.save(pdf_path, "PDF")
            output = pdf_to_markdown(
                pdf_path,
                ocr_mode="always",
                ocr_lang="en",
                ocr_device="cpu",
            )
            self.assertTrue(output.strip())


if __name__ == "__main__":
    unittest.main()
