#!/usr/bin/env python3
"""
Example EPUB viewer using pyWebLayout.

This example demonstrates how to use pyWebLayout to load an EPUB file,
paginate it, and render pages as images.
"""

import os
import sys
import argparse
from pathlib import Path
from PIL import Image

# Add the parent directory to the path to import pyWebLayout
sys.path.append(str(Path(__file__).parent.parent.parent))

from pyWebLayout import (
    Document, Book, read_epub, 
    DocumentPaginator, Page
)


def main():
    # Parse command line arguments
    parser = argparse.ArgumentParser(description='EPUB viewer example')
    parser.add_argument('epub_file', help='Path to EPUB file')
    parser.add_argument('--output-dir', '-o', default='output', help='Output directory for rendered pages')
    parser.add_argument('--width', '-w', type=int, default=800, help='Page width')
    parser.add_argument('--height', '-y', type=int, default=1000, help='Page height')
    parser.add_argument('--margin', '-m', type=int, default=50, help='Page margin')
    parser.add_argument('--max-pages', '-p', type=int, default=10, help='Maximum number of pages to render')
    args = parser.parse_args()
    
    # Create output directory
    os.makedirs(args.output_dir, exist_ok=True)
    
    # Read EPUB file
    print(f"Reading EPUB file: {args.epub_file}")
    book = read_epub(args.epub_file)
    
    # Display book metadata
    print(f"Title: {book.get_title()}")
    print(f"Author: {book.get_metadata('AUTHOR')}")
    print(f"Chapters: {len(book.chapters)}")
    
    # Create a paginator
    page_size = (args.width, args.height)
    margins = (args.margin, args.margin, args.margin, args.margin)
    paginator = DocumentPaginator(
        document=book,
        page_size=page_size,
        margins=margins
    )
    
    # Paginate and render pages
    print("Paginating and rendering pages...")
    
    # Option 1: Render all pages at once
    pages = paginator.paginate(max_pages=args.max_pages)
    for i, page in enumerate(pages):
        # Render the page
        image = page.render()
        
        # Save the image
        output_path = os.path.join(args.output_dir, f"page_{i+1:03d}.png")
        image.save(output_path)
        print(f"Saved page {i+1} to {output_path}")
    
    # Option 2: Render pages one by one with state saving
    """
    # Clear paginator state
    paginator.state = DocumentPaginationState()
    
    for i in range(args.max_pages):
        # Get next page
        page = paginator.paginate_next()
        if page is None:
            print(f"No more pages after page {i}")
            break
        
        # Render the page
        image = page.render()
        
        # Save the image
        output_path = os.path.join(args.output_dir, f"page_{i+1:03d}.png")
        image.save(output_path)
        print(f"Saved page {i+1} to {output_path}")
        
        # Save pagination state (could be saved to a file for later resumption)
        state_dict = paginator.get_state()
        
        # Progress information
        progress = paginator.get_progress() * 100
        print(f"Progress: {progress:.1f}%")
    """


if __name__ == "__main__":
    main()
