#!/usr/bin/env python3
"""
Test script for audio and video recording functionality from video_utils.py

This script tests the recording capabilities of the AVR-Eval-Agent system,
including both video and audio recording from virtual displays.

Before running this test, ensure you have:
1. FFmpeg installed (for recording)
2. Xvfb installed (for virtual display)
3. Chrome/Chromium installed (for web content)
4. PulseAudio configured (for audio recording)

Usage:
    python test_video_recording.py [--duration SECONDS] [--with-audio] [--chromium-path PATH]

Example:
    python test_video_recording.py --duration 5 --with-audio --chromium-path /path/to/chromium
"""

import argparse
import os
import sys
import tempfile
import time
from pathlib import Path

# Import the recording functions from video_utils
from video_utils import record_content, start_xvfb, cleanup_xvfb, record_video_only, record_audio_only

def create_test_html():
    """Create a simple test HTML file with audio and visual content."""
    html_content = """
<!DOCTYPE html>
<html>
<head>
    <title>Audio/Video Recording Test</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
            margin: 0;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            color: white;
        }
        .container {
            text-align: center;
            background: rgba(255, 255, 255, 0.1);
            padding: 40px;
            border-radius: 20px;
            backdrop-filter: blur(10px);
        }
        h1 {
            margin-bottom: 20px;
            font-size: 2.5em;
        }
        .audio-controls {
            margin: 20px 0;
        }
        button {
            background: #ff6b6b;
            color: white;
            border: none;
            padding: 15px 30px;
            font-size: 16px;
            border-radius: 25px;
            cursor: pointer;
            margin: 10px;
            transition: transform 0.3s;
        }
        button:hover {
            transform: scale(1.1);
        }
        .visual-element {
            width: 200px;
            height: 200px;
            background: radial-gradient(circle, #fff, #4ecdc4);
            border-radius: 50%;
            margin: 20px auto;
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2); opacity: 0.7; }
            100% { transform: scale(1); opacity: 1; }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Audio/Video Recording Test</h1>
        <p>This is a test page for recording audio and video</p>
        
        <div class="visual-element"></div>
        
        <div class="audio-controls">
            <button id="start-button" onclick="startAudio()">Start Audio</button>
            <button onclick="playTone()">Play Tone</button>
        </div>
        
        <p id="status">Click "Start Audio" to begin</p>
    </div>

    <script>
        let audioContext;
        let oscillator;
        
        function startAudio() {
            if (!audioContext) {
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
            }
            document.getElementById('status').textContent = 'Audio started!';
            console.log('Audio context initialized');
        }
        
        function playTone() {
            if (!audioContext) {
                startAudio();
            }
            
            if (oscillator) {
                oscillator.stop();
            }
            
            oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.setValueAtTime(440, audioContext.currentTime);
            oscillator.type = 'sine';
            
            gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 2);
            
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 2);
            
            console.log('Playing 440Hz tone for 2 seconds');
        }
        
        // Auto-start the audio context
        setTimeout(() => {
            startAudio();
        }, 1000);
    </script>
</body>
</html>
"""
    return html_content

def test_video_recording(duration=5, enable_audio=False, chromium_path=None, monitor_source=None, display_num=100, server_root=None):
    """Test video recording functionality."""
    print("=" * 60)
    print("Testing Video Recording Functionality")
    print("=" * 60)
    
    # Create temporary directory for test files
    temp_path = Path(server_root)
    
    # Create test HTML file
    html_file = temp_path / "test.html"
    html_file.write_text(create_test_html())
    print(f"Created test HTML file: {html_file}")
    
    # Create output video path
    output_video = temp_path / "test_recording.mp4"
    
    print(f"\nTest Configuration:")
    print(f"Duration: {duration} seconds")
    print(f"Audio: {'Enabled' if enable_audio else 'Disabled'}")
    print(f"Output: {output_video}")
    print(f"Chromium Path: {chromium_path}")
    
    # Test recording
    try:
        print("\nStarting recording test...")
        start_time = time.time()
        
        video_path, logs_path, no_errors = record_content(
            html_path=str(html_file),
            output_video_path=str(output_video),
            duration=duration,
            fps=30,
            enable_audio=enable_audio,
            display_num=display_num,
            chromium_path=chromium_path,
            monitor_source=monitor_source,
            server_root=server_root
        )
        
        end_time = time.time()
        elapsed = end_time - start_time
        
        print(f"\nRecording completed in {elapsed:.2f} seconds")
        print(f"Video file: {video_path}")
        print(f"Console logs: {logs_path}")
        print(f"No console errors: {no_errors}")
        
        # Check if files were created
        if os.path.exists(video_path):
            size = os.path.getsize(video_path)
            print(f"Video file size: {size / 1024 / 1024:.2f} MB")
            
            if size > 0:
                print("✅ Video recording test PASSED")
                return True
            else:
                print("❌ Video recording test FAILED - empty file")
                return False
        else:
            print("❌ Video recording test FAILED - file not created")
            return False
            
    except Exception as e:
        print(f"❌ Video recording test FAILED with exception: {e}")
        import traceback
        traceback.print_exc()
        return False

def check_dependencies():
    """Check if all required dependencies are available."""
    print("\n" + "=" * 60)
    print("Checking Dependencies")
    print("=" * 60)
    
    dependencies = {
        "ffmpeg": ["ffmpeg", "-version"],
        "Xvfb": ["Xvfb", "-help"],
        "PulseAudio": ["pulseaudio", "--version"],
    }
    
    all_available = True
    
    for name, cmd in dependencies.items():
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
            if result.returncode == 0:
                print(f"✅ {name}: Available")
            else:
                print(f"❌ {name}: Not available")
                all_available = False
        except (subprocess.TimeoutExpired, FileNotFoundError):
            print(f"❌ {name}: Not available")
            all_available = False
    
    return all_available

def main():
    parser = argparse.ArgumentParser(description="Test audio/video recording functionality")
    parser.add_argument("--duration", type=int, default=5, help="Recording duration in seconds")
    parser.add_argument("--with_audio", action="store_true", help="Enable audio recording")
    parser.add_argument("--chromium_path", type=str, help="Path to Chromium installation")
    parser.add_argument("--display_num", type=int, default=None, help="Allow model to exit early if satisfied with the current content")    
    parser.add_argument("--skip_deps", action="store_true", help="Skip dependency check")
    parser.add_argument("--monitor_source", type=str, default="default", help="FOR AUDIO, YOU MUST SET UP AUDIOPULSE IN ADVANCE AND PROVIDE THE SOURCE")
    parser.add_argument("--server_root", type=str, default='', help="Root of server host, should be above the assets and the html (if left as '' its not used)")

    args = parser.parse_args()
    
    print("Audio/Video Recording Test Suite")
    print("================================")
    
    # Check dependencies
    if not args.skip_deps:
        if not check_dependencies():
            print("\n❌ Some dependencies are missing. Please install them before running tests.")
            sys.exit(1)
    
    # Test full recording
    print("\n" + "=" * 60)
    print("Testing Full Recording Pipeline")
    print("=" * 60)
    
    success = test_video_recording(
        duration=args.duration,
        enable_audio=args.with_audio,
        chromium_path=args.chromium_path,
        monitor_source=args.monitor_source,
        display_num=args.display_num,
        server_root=args.server_root,
    )
    
    if success:
        print("\n🎉 All tests PASSED! Your audio/video recording setup is working correctly.")
    else:
        print("\n💥 Some tests FAILED. Please check the output above for details.")
        sys.exit(1)

if __name__ == "__main__":
    import subprocess
    main()
