#!/usr/bin/env python3
"""
Test page navigation (forward and backward).
"""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))

from dreader.application import EbookReader

def test_navigation():
    """Test forward and backward page navigation."""

    # Find a test book
    epub_path = Path("tests/data/library-epub/pg11-images-3.epub")

    if not epub_path.exists():
        print(f"Error: Test EPUB not found at {epub_path}")
        return False

    print("=" * 70)
    print("Page Navigation Test")
    print("=" * 70)

    # Create reader
    reader = EbookReader(page_size=(800, 1200))

    # Load book
    print(f"\nLoading: {epub_path}")
    if not reader.load_epub(str(epub_path)):
        print("Failed to load EPUB")
        return False

    print(f"✓ Loaded: {reader.book_title}")

    # Get starting position
    start_pos = reader.get_position_info()
    print(f"\nStarting position: {start_pos}")

    # Test forward navigation
    print("\n" + "-" * 70)
    print("Test 1: Forward navigation (next_page)")
    print("-" * 70)

    for i in range(3):
        page = reader.next_page()
        if page:
            pos = reader.get_position_info()
            print(f"  Page {i+1}: position={pos['position']}, progress={reader.get_reading_progress()*100:.1f}%")
        else:
            print(f"  Page {i+1}: Failed to advance")
            return False

    forward_pos = reader.get_position_info()
    print(f"\nPosition after 3 forward: {forward_pos}")

    # Test backward navigation
    print("\n" + "-" * 70)
    print("Test 2: Backward navigation (previous_page)")
    print("-" * 70)

    for i in range(3):
        page = reader.previous_page()
        if page:
            pos = reader.get_position_info()
            print(f"  Back {i+1}: position={pos['position']}, progress={reader.get_reading_progress()*100:.1f}%")
        else:
            print(f"  Back {i+1}: Failed to go back (might be at start)")

    final_pos = reader.get_position_info()
    print(f"\nPosition after 3 backward: {final_pos}")

    # Verify we're back at start
    print("\n" + "-" * 70)
    print("Test 3: Verify position")
    print("-" * 70)

    if final_pos['position'] == start_pos['position']:
        print("✓ Successfully returned to starting position")
        print("✓ Backward navigation working correctly")
        result = True
    else:
        print(f"✗ Position mismatch!")
        print(f"  Expected: {start_pos['position']}")
        print(f"  Got: {final_pos['position']}")
        result = False

    # Test going back from start (should return None or current page)
    print("\n" + "-" * 70)
    print("Test 4: Try going back from first page")
    print("-" * 70)

    page = reader.previous_page()
    if page:
        pos = reader.get_position_info()
        print(f"  Still at position: {pos['position']}")
        if pos['position'] == 0:
            print("✓ Correctly stayed at first page")
        else:
            print("⚠ Position changed but shouldn't have")
    else:
        print("  previous_page() returned None (at start)")
        print("✓ Correctly indicated at start of book")

    # Cleanup
    reader.close()

    print("\n" + "=" * 70)
    if result:
        print("✓ ALL TESTS PASSED - Page navigation working correctly")
    else:
        print("✗ TESTS FAILED")
    print("=" * 70)

    return result

if __name__ == "__main__":
    success = test_navigation()
    sys.exit(0 if success else 1)
