"""
Tests for the document parser service.
"""

import os
import tempfile

from django.test import TestCase

from library.services.parsers import (
    IMAGE_EXTENSIONS,
    PLAINTEXT_EXTENSIONS,
    PYMUPDF_EXTENSIONS,
    DocumentParser,
    ParseResult,
)


class DocumentParserPlaintextTests(TestCase):
    """Tests for plain text parsing."""

    def setUp(self):
        self.parser = DocumentParser()

    def test_parse_txt_file(self):
        with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
            f.write("Hello World\n\nThis is a test document.")
            f.flush()
            path = f.name

        try:
            result = self.parser.parse(path, "txt")
            self.assertIsInstance(result, ParseResult)
            self.assertEqual(result.file_type, "txt")
            self.assertEqual(len(result.text_blocks), 1)
            self.assertIn("Hello World", result.text_blocks[0].text)
            self.assertEqual(len(result.images), 0)
        finally:
            os.unlink(path)

    def test_parse_md_file(self):
        with tempfile.NamedTemporaryFile(mode="w", suffix=".md", delete=False) as f:
            f.write("# Heading\n\nSome markdown content.")
            f.flush()
            path = f.name

        try:
            result = self.parser.parse(path, "md")
            self.assertEqual(result.file_type, "md")
            self.assertIn("Heading", result.text_blocks[0].text)
        finally:
            os.unlink(path)

    def test_parse_empty_file(self):
        with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
            f.write("")
            f.flush()
            path = f.name

        try:
            result = self.parser.parse(path, "txt")
            self.assertEqual(len(result.text_blocks), 0)
        finally:
            os.unlink(path)

    def test_parse_bytes(self):
        data = b"Hello from bytes"
        result = self.parser.parse_bytes(data, "txt", filename="test.txt")
        self.assertEqual(len(result.text_blocks), 1)
        self.assertIn("Hello from bytes", result.text_blocks[0].text)


class DocumentParserValidationTests(TestCase):
    """Tests for parser input validation."""

    def setUp(self):
        self.parser = DocumentParser()

    def test_unsupported_format_raises(self):
        with tempfile.NamedTemporaryFile(suffix=".xyz", delete=False) as f:
            f.write(b"data")
            path = f.name

        try:
            with self.assertRaises(ValueError) as ctx:
                self.parser.parse(path, "xyz")
            self.assertIn("Unsupported file type", str(ctx.exception))
        finally:
            os.unlink(path)

    def test_file_type_normalization(self):
        """File type should be normalized (lowercase, no dot)."""
        with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
            f.write("test")
            path = f.name

        try:
            result = self.parser.parse(path, ".TXT")
            self.assertEqual(result.file_type, "txt")
        finally:
            os.unlink(path)


class SupportedExtensionsTests(TestCase):
    """Tests for supported extension sets."""

    def test_pymupdf_includes_pdf(self):
        self.assertIn("pdf", PYMUPDF_EXTENSIONS)

    def test_pymupdf_includes_epub(self):
        self.assertIn("epub", PYMUPDF_EXTENSIONS)

    def test_pymupdf_includes_docx(self):
        self.assertIn("docx", PYMUPDF_EXTENSIONS)

    def test_pymupdf_includes_pptx(self):
        self.assertIn("pptx", PYMUPDF_EXTENSIONS)

    def test_plaintext_includes_txt(self):
        self.assertIn("txt", PLAINTEXT_EXTENSIONS)

    def test_plaintext_includes_md(self):
        self.assertIn("md", PLAINTEXT_EXTENSIONS)

    def test_image_includes_png(self):
        self.assertIn("png", IMAGE_EXTENSIONS)

    def test_image_includes_jpg(self):
        self.assertIn("jpg", IMAGE_EXTENSIONS)
