#!/usr/bin/env python3
"""
Debug previous_page issue.
"""

import sys
from pathlib import Path

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

from dreader.application import EbookReader

def debug_previous():
    """Debug previous_page functionality."""

    epub_path = Path("tests/data/library-epub/pg11-images-3.epub")

    print("=" * 70)
    print("Debug Previous Page")
    print("=" * 70)

    reader = EbookReader(page_size=(800, 1200))
    reader.load_epub(str(epub_path))

    print(f"\nLoaded: {reader.book_title}")
    print(f"Manager type: {type(reader.manager)}")
    print(f"Manager has previous_page: {hasattr(reader.manager, 'previous_page')}")

    # Check manager's state
    if reader.manager:
        print(f"\nManager state:")
        print(f"  current_position: {reader.manager.current_position}")
        if hasattr(reader.manager, 'page_buffer'):
            print(f"  page_buffer length: {len(reader.manager.page_buffer)}")
        if hasattr(reader.manager, 'buffer'):
            print(f"  buffer: {reader.manager.buffer}")

    # Try going forward first
    print("\n" + "-" * 70)
    print("Going forward 3 pages...")
    print("-" * 70)

    for i in range(3):
        page = reader.next_page()
        if page:
            print(f"  Forward {i+1}: position = {reader.manager.current_position}")
        else:
            print(f"  Forward {i+1}: FAILED")

    if reader.manager:
        print(f"\nAfter forward navigation:")
        print(f"  current_position: {reader.manager.current_position}")
        if hasattr(reader.manager, 'page_buffer'):
            print(f"  page_buffer length: {len(reader.manager.page_buffer)}")
            if len(reader.manager.page_buffer) > 0:
                print(f"  page_buffer[0]: {reader.manager.page_buffer[0].position if hasattr(reader.manager.page_buffer[0], 'position') else 'N/A'}")

    # Now try going backward
    print("\n" + "-" * 70)
    print("Trying to go backward...")
    print("-" * 70)

    # Try calling previous_page directly on manager
    if reader.manager:
        print("\nCalling manager.previous_page() directly...")
        result = reader.manager.previous_page()
        print(f"  Result: {type(result) if result else None}")
        if result:
            print(f"  Result has render(): {hasattr(result, 'render')}")
            print(f"  Position after: {reader.manager.current_position}")
        else:
            print(f"  Result is None")
            print(f"  Position still: {reader.manager.current_position}")

    # Try via reader.previous_page()
    print("\nCalling reader.previous_page()...")
    page = reader.previous_page()
    if page:
        print(f"  SUCCESS: Got page {page.size}")
        print(f"  Position: {reader.manager.current_position}")
    else:
        print(f"  FAILED: Got None")
        print(f"  Position: {reader.manager.current_position}")

    reader.close()

if __name__ == "__main__":
    debug_previous()
