"""
Unit tests for DocumentManager.

Tests document loading in isolation without full EbookReader.
"""

import unittest
import tempfile
import os
from pathlib import Path

from dreader.managers.document import DocumentManager


class TestDocumentManager(unittest.TestCase):
    """Test DocumentManager in isolation"""

    def setUp(self):
        """Set up test environment"""
        self.temp_dir = tempfile.mkdtemp()
        self.epub_path = "tests/data/test.epub"
        self.manager = DocumentManager()

    def tearDown(self):
        """Clean up"""
        import shutil
        shutil.rmtree(self.temp_dir, ignore_errors=True)

    def test_initialization(self):
        """Test manager initializes correctly"""
        manager = DocumentManager()

        self.assertIsNone(manager.document_id)
        self.assertIsNone(manager.title)
        self.assertIsNone(manager.author)
        self.assertIsNone(manager.blocks)
        self.assertFalse(manager.is_loaded())

    def test_load_valid_epub(self):
        """Test loading a valid EPUB file"""
        if not Path(self.epub_path).exists():
            self.skipTest(f"Test EPUB not found at {self.epub_path}")

        success = self.manager.load_epub(self.epub_path)

        self.assertTrue(success)
        self.assertTrue(self.manager.is_loaded())
        self.assertIsNotNone(self.manager.document_id)
        self.assertIsNotNone(self.manager.title)
        self.assertIsNotNone(self.manager.author)
        self.assertIsNotNone(self.manager.blocks)
        self.assertGreater(len(self.manager.blocks), 0)

    def test_load_nonexistent_epub(self):
        """Test loading a non-existent EPUB file"""
        success = self.manager.load_epub("nonexistent.epub")

        self.assertFalse(success)
        self.assertFalse(self.manager.is_loaded())

    def test_load_invalid_epub(self):
        """Test loading an invalid file as EPUB"""
        # Create a temporary invalid file
        invalid_path = os.path.join(self.temp_dir, "invalid.epub")
        with open(invalid_path, 'w') as f:
            f.write("This is not a valid EPUB file")

        success = self.manager.load_epub(invalid_path)

        self.assertFalse(success)
        self.assertFalse(self.manager.is_loaded())

    def test_load_html_success(self):
        """Test loading HTML content"""
        html = """
        <html>
        <body>
            <h1>Test Document</h1>
            <p>This is a test paragraph.</p>
        </body>
        </html>
        """

        success = self.manager.load_html(
            html,
            title="Test HTML",
            author="Test Author",
            document_id="test_html"
        )

        self.assertTrue(success)
        self.assertTrue(self.manager.is_loaded())
        self.assertEqual(self.manager.title, "Test HTML")
        self.assertEqual(self.manager.author, "Test Author")
        self.assertEqual(self.manager.document_id, "test_html")
        self.assertGreater(len(self.manager.blocks), 0)

    def test_load_empty_html(self):
        """Test loading empty HTML"""
        success = self.manager.load_html("")

        self.assertFalse(success)
        self.assertFalse(self.manager.is_loaded())

    def test_get_metadata(self):
        """Test getting document metadata"""
        if not Path(self.epub_path).exists():
            self.skipTest(f"Test EPUB not found at {self.epub_path}")

        self.manager.load_epub(self.epub_path)
        metadata = self.manager.get_metadata()

        self.assertIsInstance(metadata, dict)
        self.assertIn('title', metadata)
        self.assertIn('author', metadata)
        self.assertIn('document_id', metadata)
        self.assertIn('total_blocks', metadata)
        self.assertGreater(metadata['total_blocks'], 0)

    def test_get_blocks(self):
        """Test getting content blocks"""
        if not Path(self.epub_path).exists():
            self.skipTest(f"Test EPUB not found at {self.epub_path}")

        self.manager.load_epub(self.epub_path)
        blocks = self.manager.get_blocks()

        self.assertIsInstance(blocks, list)
        self.assertGreater(len(blocks), 0)

    def test_clear(self):
        """Test clearing loaded document"""
        if not Path(self.epub_path).exists():
            self.skipTest(f"Test EPUB not found at {self.epub_path}")

        self.manager.load_epub(self.epub_path)
        self.assertTrue(self.manager.is_loaded())

        self.manager.clear()

        self.assertFalse(self.manager.is_loaded())
        self.assertIsNone(self.manager.document_id)
        self.assertIsNone(self.manager.title)
        self.assertIsNone(self.manager.author)
        self.assertIsNone(self.manager.blocks)

    def test_multiple_loads(self):
        """Test loading multiple documents sequentially"""
        html1 = "<html><body><h1>Document 1</h1></body></html>"
        html2 = "<html><body><h1>Document 2</h1></body></html>"

        # Load first document
        self.manager.load_html(html1, title="Doc 1", document_id="doc1")
        self.assertEqual(self.manager.title, "Doc 1")
        self.assertEqual(self.manager.document_id, "doc1")

        # Load second document (should replace first)
        self.manager.load_html(html2, title="Doc 2", document_id="doc2")
        self.assertEqual(self.manager.title, "Doc 2")
        self.assertEqual(self.manager.document_id, "doc2")


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