#!/usr/bin/env python3
"""
Local Screenshot Capture Test

Tests the screenshot capture module independently without LiveKit room connection.
Captures frames from a Slidev deck and saves them to disk for verification.
"""

import asyncio
import os
import sys
from pathlib import Path
from datetime import datetime

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

# Try to load environment variables from .env.local (optional)
try:
    from dotenv import load_dotenv
    env_file = Path(__file__).parent / '.env.local'
    if env_file.exists():
        load_dotenv(env_file)
        print(f"[LocalTest] ✅ Loaded environment variables from {env_file}")
    else:
        print(f"[LocalTest] ℹ️  No .env.local file found (this is OK for screenshot-only tests)")
        print(f"[LocalTest] ℹ️  Create .env.local for LiveKit room tests (see .env.local.example)")
except ImportError:
    print("[LocalTest] ℹ️  python-dotenv not installed (optional for screenshot-only tests)")
    print("[LocalTest] ℹ️  Install with: .venv/bin/pip install python-dotenv")

from bot import ScreenshotCapture


class TeeLogger:
    """
    Dual output logger that writes to both console and file (like Railway).

    Railway's bot-spawn-livekit.step.ts logs to both stdout/stderr and a log file.
    This class mimics that behavior for local testing.
    """
    def __init__(self, file_path: Path, stream_type: str = "STDOUT"):
        self.terminal = sys.stdout if stream_type == "STDOUT" else sys.stderr
        self.log = open(file_path, 'a', encoding='utf-8')
        self.stream_type = stream_type

    def write(self, message: str):
        self.terminal.write(message)
        # Prefix with stream type like Railway does
        if message.strip():  # Only prefix non-empty lines
            self.log.write(f"[{self.stream_type}] {message}")
        else:
            self.log.write(message)

    def flush(self):
        self.terminal.flush()
        self.log.flush()

    def close(self):
        self.log.close()


async def main():
    """Run local screenshot capture test"""

    # Configuration
    deck_url = "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/"
    output_dir = Path("./test_screenshots")
    num_frames = 30  # Capture 30 frames (3 seconds at 10 FPS)

    # Create output directory
    output_dir.mkdir(exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    session_dir = output_dir / f"session_{timestamp}"
    session_dir.mkdir(exist_ok=True)

    # Set up logging (like Railway)
    log_dir = Path("./test_logs")
    log_dir.mkdir(exist_ok=True)
    log_file = log_dir / f"bot-test-{timestamp}.log"

    # Redirect stdout and stderr to both console and file
    stdout_logger = TeeLogger(log_file, "STDOUT")
    stderr_logger = TeeLogger(log_file, "STDERR")
    original_stdout = sys.stdout
    original_stderr = sys.stderr
    sys.stdout = stdout_logger
    sys.stderr = stderr_logger

    print(f"[LocalTest] Starting screenshot capture test")
    print(f"[LocalTest] Log file: {log_file}")
    print(f"[LocalTest] Deck URL: {deck_url}")
    print(f"[LocalTest] Output directory: {output_dir}")
    print(f"[LocalTest] Frames to capture: {num_frames}")
    print()

    print(f"[LocalTest] Created session directory: {session_dir}")

    # Initialize screenshot capture
    print(f"[LocalTest] Initializing screenshot capture module...")
    capture = ScreenshotCapture(deck_url)

    try:
        # Start the capture module (launches browser)
        print(f"[LocalTest] Starting browser...")
        await capture.start()
        print(f"[LocalTest] ✅ Browser started and deck loaded")
        print()

        # Capture frames
        print(f"[LocalTest] Capturing {num_frames} frames...")
        for i in range(num_frames):
            frame_data = await capture.capture_frame()

            if frame_data:
                # Save frame to disk
                frame_path = session_dir / f"frame_{i:03d}.png"
                with open(frame_path, 'wb') as f:
                    f.write(frame_data)

                frame_size_kb = len(frame_data) / 1024
                print(f"[LocalTest] Frame {i+1}/{num_frames}: {frame_size_kb:.1f} KB -> {frame_path.name}")
            else:
                print(f"[LocalTest] ⚠️  Frame {i+1}/{num_frames}: Capture failed")

            # Simulate 10 FPS (100ms between frames)
            await asyncio.sleep(0.1)

        print()
        print(f"[LocalTest] ✅ Capture complete!")

        # Get and display statistics
        stats = capture.metrics
        print(f"[LocalTest] 📊 Capture Statistics:")
        print(f"[LocalTest]   - Total captures: {stats['capture_count']}")
        print(f"[LocalTest]   - Average time: {stats['avg_capture_time_ms']:.2f} ms")
        print(f"[LocalTest]   - Failed captures: {stats['failed_captures']}")
        print(f"[LocalTest]   - Success rate: {stats['success_rate']:.1f}%")
        print()
        print(f"[LocalTest] 📁 Frames saved to: {session_dir}")

    except Exception as e:
        print(f"[LocalTest] ❌ Error: {e}", file=sys.stderr)
        import traceback
        traceback.print_exc()
    finally:
        # Cleanup
        print(f"[LocalTest] Cleaning up...")
        await capture.stop()
        print(f"[LocalTest] ✅ Browser closed")

        # Restore original stdout/stderr and close log files
        sys.stdout = original_stdout
        sys.stderr = original_stderr
        stdout_logger.close()
        stderr_logger.close()

        print(f"[LocalTest] ✅ Log file saved: {log_file}")


if __name__ == "__main__":
    asyncio.run(main())
