"""
Example usage of Grasp Python SDK recording functionality.

This example demonstrates how to:
1. Create a container
2. Start a screen recording
3. Stop the recording
4. Get recording information
5. Download the recording file
"""

import os
import time

from grasp import Grasp

# Initialize the Grasp client
# API key can be provided via constructor or GRASP_API_KEY environment variable
client = Grasp(api_key=os.getenv("GRASP_API_KEY"))

# Create a new container
print("Creating container...")
container = client.create()
print(f"Container created: {container.id}")
print(f"WebSocket endpoint: {container.browser.ws_endpoint}")
print(f"Live view URL: {container.browser.live_url}")

try:
    # Start a recording
    print("\nStarting recording...")
    recording = container.browser.recording.start(
        format="mp4",
        framerate=30,
        quality="medium",
        audio=False,
        # Optional: specify max duration in milliseconds
        # max_duration=60000,  # 60 seconds
        # Optional: specify resolution
        # resolution="1920x1080",
    )
    print(f"Recording started: {recording.id}")
    print(f"Status: {recording.status}")
    print(f"Format: {recording.format}")
    print(f"Framerate: {recording.framerate}")
    print(f"Resolution: {recording.resolution}")

    # Simulate some browser activity (you would normally automate the browser here)
    print("\nRecording for 10 seconds...")
    time.sleep(10)

    # Stop the recording
    print("\nStopping recording...")
    recording = container.browser.recording.stop(recording.id)
    print(f"Recording stopped: {recording.id}")
    print(f"Status: {recording.status}")
    print(f"Duration: {recording.duration_seconds} seconds")
    print(f"File size: {recording.file_size_bytes} bytes")
    print(f"Local path: {recording.local_path}")
    if recording.cdn_url:
        print(f"CDN URL: {recording.cdn_url}")

    # Get recording information
    print("\nFetching recording info...")
    recording_info = container.browser.recording.get(recording.id)
    print(f"Recording info: {recording_info.id}")
    print(f"Status: {recording_info.status}")

    # List all recordings for this container
    print("\nListing all recordings...")
    recordings = container.browser.recording.get_all()
    print(f"Total recordings: {len(recordings)}")
    for rec in recordings:
        print(f"  - {rec.id}: {rec.status} ({rec.format})")

finally:
    # Clean up - shutdown the container
    print("\nShutting down container...")
    container.shutdown()
    print("Container shut down successfully")
