#!/usr/bin/env python3
"""
Example demonstrating persistent rendering settings.

This shows how to:
1. Initialize StateManager to load saved settings
2. Apply saved settings to EbookReader
3. Modify settings during reading
4. Save settings automatically for next session

The settings (font size, line spacing, etc.) will persist between
application sessions, so the user doesn't have to reconfigure each time.
"""

import sys
from pathlib import Path

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

from dreader import EbookReader
from dreader.state import StateManager, Settings


def demonstrate_persistent_settings():
    """Show how settings persist across sessions"""

    print("=" * 70)
    print("Persistent Settings Example")
    print("=" * 70)

    # 1. Initialize state manager (loads saved state from disk)
    state_file = Path.home() / ".config" / "dreader" / "state.json"
    state_file.parent.mkdir(parents=True, exist_ok=True)

    state_manager = StateManager(state_file=state_file)
    state = state_manager.load_state()

    print(f"\nLoaded settings from: {state_file}")
    print(f"  Font scale: {state.settings.font_scale}")
    print(f"  Line spacing: {state.settings.line_spacing}px")
    print(f"  Inter-block spacing: {state.settings.inter_block_spacing}px")
    print(f"  Word spacing: {state.settings.word_spacing}px")

    # 2. Create reader with saved settings
    reader = EbookReader(
        page_size=(800, 1000),
        line_spacing=state.settings.line_spacing,
        inter_block_spacing=state.settings.inter_block_spacing
    )

    # Load a book
    epub_dir = Path(__file__).parent.parent / 'tests' / 'data' / 'library-epub'
    epubs = list(epub_dir.glob('*.epub'))

    if not epubs:
        print("\nError: No test EPUB files found!")
        print(f"Looked in: {epub_dir}")
        return

    epub_path = epubs[0]
    print(f"\nLoading book: {epub_path.name}")

    if not reader.load_epub(str(epub_path)):
        print("Failed to load book!")
        return

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

    # 3. Apply saved settings to the book
    print("\nApplying saved settings to book...")
    settings_dict = state.settings.to_dict()
    reader.apply_settings(settings_dict)

    # Render initial page
    print("\nRendering page with saved settings...")
    page = reader.get_current_page()
    reader.render_to_file("persistent_settings_before.png")
    print("✓ Saved: persistent_settings_before.png")

    # 4. Simulate user changing settings
    print("\n" + "=" * 70)
    print("User adjusts settings...")
    print("=" * 70)

    # Increase font size
    print("\n1. Increasing font size...")
    reader.increase_font_size()
    reader.increase_font_size()
    print(f"   New font scale: {reader.base_font_scale}")

    # Increase line spacing
    print("2. Increasing line spacing...")
    new_line_spacing = state.settings.line_spacing + 4
    reader.set_line_spacing(new_line_spacing)
    print(f"   New line spacing: {new_line_spacing}px")

    # Increase word spacing
    print("3. Increasing word spacing...")
    new_word_spacing = state.settings.word_spacing + 3
    reader.set_word_spacing(new_word_spacing)
    print(f"   New word spacing: {new_word_spacing}px")

    # Render page with new settings
    print("\nRendering page with new settings...")
    page = reader.get_current_page()
    reader.render_to_file("persistent_settings_after.png")
    print("✓ Saved: persistent_settings_after.png")

    # 5. Save new settings to state
    print("\n" + "=" * 70)
    print("Saving settings for next session...")
    print("=" * 70)

    current_settings = reader.get_current_settings()
    state_manager.update_settings(current_settings)

    print(f"\nSettings to be saved:")
    print(f"  Font scale: {current_settings['font_scale']}")
    print(f"  Line spacing: {current_settings['line_spacing']}px")
    print(f"  Inter-block spacing: {current_settings['inter_block_spacing']}px")
    print(f"  Word spacing: {current_settings['word_spacing']}px")

    # Save state to disk
    if state_manager.save_state():
        print(f"\n✓ Settings saved to: {state_file}")
        print("  These settings will be used the next time you open a book!")
    else:
        print("\n✗ Failed to save settings")

    # 6. Demonstrate that settings are saved
    print("\n" + "=" * 70)
    print("Verification: Reloading state from disk...")
    print("=" * 70)

    # Create new state manager to verify persistence
    verification_manager = StateManager(state_file=state_file)
    verification_state = verification_manager.load_state()

    print(f"\nVerified saved settings:")
    print(f"  Font scale: {verification_state.settings.font_scale}")
    print(f"  Line spacing: {verification_state.settings.line_spacing}px")
    print(f"  Inter-block spacing: {verification_state.settings.inter_block_spacing}px")
    print(f"  Word spacing: {verification_state.settings.word_spacing}px")

    if (verification_state.settings.font_scale == current_settings['font_scale'] and
        verification_state.settings.line_spacing == current_settings['line_spacing'] and
        verification_state.settings.word_spacing == current_settings['word_spacing']):
        print("\n✓ Settings successfully persisted!")
    else:
        print("\n✗ Settings mismatch!")

    # Cleanup
    reader.close()

    print("\n" + "=" * 70)
    print("Demo Complete!")
    print("=" * 70)
    print("\nKey Points:")
    print("  • Settings are automatically loaded from ~/.config/dreader/state.json")
    print("  • Use reader.apply_settings() to apply saved settings after loading a book")
    print("  • Use reader.get_current_settings() to get current settings")
    print("  • Use state_manager.update_settings() to save new settings")
    print("  • Settings persist across application restarts")
    print("\nGenerated files:")
    print("  • persistent_settings_before.png - Page with original settings")
    print("  • persistent_settings_after.png - Page with modified settings")


if __name__ == '__main__':
    demonstrate_persistent_settings()
