#!/usr/bin/env python3
"""
Simple example showing the most common EbookReader usage.

This script loads an EPUB and allows you to navigate through it,
saving each page as an image.

Usage:
    python simple_ereader_example.py book.epub
"""

import sys
from pathlib import Path

# Add parent directory to path to import pyWebLayout
sys.path.insert(0, str(Path(__file__).parent.parent))

from dreader.application import EbookReader


def main():
    if len(sys.argv) < 2:
        print("Usage: python simple_ereader_example.py book.epub")
        sys.exit(1)
    
    epub_path = sys.argv[1]
    
    # Create reader and load EPUB
    print(f"Loading: {epub_path}")
    reader = EbookReader(page_size=(800, 1000))
    
    if not reader.load_epub(epub_path):
        print("Failed to load EPUB")
        sys.exit(1)
    
    # Get book information
    info = reader.get_book_info()
    print(f"\nBook: {info['title']}")
    print(f"Author: {info['author']}")
    print(f"Total blocks: {info['total_blocks']}")
    
    # Get chapters
    chapters = reader.get_chapters()
    print(f"Chapters: {len(chapters)}")
    if chapters:
        print("\nChapter list:")
        for title, idx in chapters[:10]:  # Show first 10
            print(f"  {idx}: {title}")
        if len(chapters) > 10:
            print(f"  ... and {len(chapters) - 10} more")
    
    # Navigate through first 10 pages
    print("\nRendering first 10 pages...")
    for i in range(10):
        page = reader.get_current_page()
        if page:
            filename = f"page_{i+1:03d}.png"
            reader.render_to_file(filename)
            
            # Show progress
            progress = reader.get_reading_progress()
            chapter_info = reader.get_current_chapter_info()
            chapter_name = chapter_info['title'] if chapter_info else "N/A"
            
            print(f"  Page {i+1}: {filename} (Progress: {progress*100:.1f}%, Chapter: {chapter_name})")
        
        # Move to next page
        if not reader.next_page():
            print("  Reached end of book")
            break
    
    # Save current position
    reader.save_position("stopped_at_page_10")
    print("\nSaved position as 'stopped_at_page_10'")
    
    # Example: Jump to a chapter (if available)
    if len(chapters) >= 2:
        print(f"\nJumping to chapter: {chapters[1][0]}")
        reader.jump_to_chapter(1)
        reader.render_to_file("chapter_2_start.png")
        print("  Saved to: chapter_2_start.png")
    
    # Example: Increase font size
    print("\nIncreasing font size...")
    reader.increase_font_size()
    reader.render_to_file("larger_font.png")
    print(f"  Font size now: {reader.get_font_size():.1f}x")
    print("  Saved to: larger_font.png")
    
    # Close reader (saves current position automatically)
    reader.close()
    print("\nDone! Current position saved automatically.")


if __name__ == "__main__":
    main()
