"""Example: Recording and Playing Back a Browser Session."""

import time
import os
from browser_hybrid import Browser

def main():
    # 1. Initialize browser
    browser = Browser()
    
    # Define recording file path
    path = "example_session.json"
    
    print(f"--- Recording Session to {path} ---")
    
    # 2. Start recording
    browser.start_recording(path)
    
    try:
        # 3. Perform some actions
        print("Navigating to example.com...")
        browser.goto("https://example.com")
        
        print("Wait for 'More information' link...")
        browser.wait_for(text="More information")
        
        # We can pause recording for diagnostic actions that we don't want replayed
        print("Pausing recording for snapshot...")
        browser.pause_recording()
        browser.snapshot()
        browser.resume_recording()
        
        print("Clicking 'More information'...")
        browser.click_by_text("More information")
        
        print("Wait for IANA page...")
        browser.wait_for_url("iana.org")
        
    finally:
        # 4. Stop and save recording
        saved_path = browser.stop_recording()
        print(f"Recording complete. File size: {os.path.getsize(saved_path)} bytes")
        
    print("\n--- Playing Back Session ---")
    
    # 5. Playback session at 2x speed with verification
    try:
        # Close current tab and open a fresh one for clean playback
        browser.close_tab()
        
        print(f"Replaying session from {saved_path} at 2.0x speed...")
        success = browser.playback(saved_path, speed=2.0, verify=True)
        
        if success:
            print("Playback successful!")
        else:
            print("Playback failed.")
            
    except Exception as e:
        print(f"Playback error: {e}")
        
    finally:
        # Cleanup
        if os.path.exists(saved_path):
            os.remove(saved_path)
            print(f"Cleaned up {saved_path}")

if __name__ == "__main__":
    main()
