"""
Minimal reproduction test for backward navigation bug.

BUG: Backward navigation cannot reach block_index=0 from block_index=1.

This is a pyWebLayout issue, not a dreader-application issue.
"""

import unittest
import tempfile
import shutil
from pathlib import Path

from dreader.application import EbookReader


class TestBackwardNavigationBug(unittest.TestCase):
    """Minimal reproduction of backward navigation bug"""

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

        if not Path(self.epub_path).exists():
            self.skipTest(f"Test EPUB not found at {self.epub_path}")

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

    def test_minimal_backward_navigation_bug(self):
        """
        MINIMAL REPRODUCTION:

        1. Start at block_index=0
        2. Go forward once (to block_index=1)
        3. Go backward once
        4. BUG: Lands at block_index=1 instead of block_index=0

        This proves backward navigation cannot reach the first block.
        """
        reader = EbookReader(
            page_size=(800, 1000),
            bookmarks_dir=self.temp_dir,
            buffer_size=0
        )

        reader.load_epub(self.epub_path)

        # Starting position
        pos_start = reader.manager.current_position.copy()
        print(f"\n1. Starting at block_index={pos_start.block_index}")
        self.assertEqual(pos_start.block_index, 0, "Should start at block 0")

        # Go forward
        reader.next_page()
        pos_forward = reader.manager.current_position.copy()
        print(f"2. After next_page(): block_index={pos_forward.block_index}")
        self.assertEqual(pos_forward.block_index, 1, "Should be at block 1")

        # Go backward
        reader.previous_page()
        pos_final = reader.manager.current_position.copy()
        print(f"3. After previous_page(): block_index={pos_final.block_index}")

        # THE BUG: This assertion will fail
        print(f"\nEXPECTED: block_index=0")
        print(f"ACTUAL:   block_index={pos_final.block_index}")

        if pos_final.block_index != 0:
            print("\n❌ BUG CONFIRMED: Cannot navigate backward to block_index=0")
            print("   This is a pyWebLayout bug in the previous_page() method.")

        self.assertEqual(
            pos_final.block_index,
            0,
            "BUG: Backward navigation from block 1 should return to block 0"
        )

        reader.close()


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