#!/usr/bin/env python
"""
Run all example scripts in the FMUS-VID library.
This script executes each example and reports the results.
"""

import os
import sys
import subprocess
import time
from pathlib import Path
import traceback
import shutil

def ensure_directories():
    """Create necessary directories for example outputs."""
    # Create directories for example outputs
    dirs_to_create = [
        "test_media",
        "transition_output",
        "output",
        "analysis_output"
    ]

    for directory in dirs_to_create:
        os.makedirs(directory, exist_ok=True)
        print(f"Ensured directory exists: {directory}")

    # Create parent test_media directory as well
    parent_dir = Path(__file__).parent.parent / "test_media"
    os.makedirs(parent_dir, exist_ok=True)
    print(f"Ensured parent directory exists: {parent_dir}")

def run_example(example_name, script_path):
    """Run an example script and return its success status.

    Args:
        example_name: Display name of the example
        script_path: Path to the script file

    Returns:
        tuple: (success, execution_time, output)
    """
    print(f"\n{'='*80}")
    print(f"Running {example_name}...")
    print(f"{'='*80}")

    start_time = time.time()
    success = False
    output = ""

    try:
        # Run the example script as a subprocess to capture output
        # Use longer timeout for video operations (10 minutes)
        timeout = 600 if "Video Transitions" in example_name else 300
        result = subprocess.run(
            [sys.executable, script_path],
            capture_output=True,
            text=True,
            timeout=timeout
        )

        # Print stdout and stderr
        output = result.stdout
        print(output)

        if result.stderr:
            print("\nErrors/Warnings:")
            print(result.stderr)
            output += "\n" + result.stderr

        # Check if the script executed successfully
        success = result.returncode == 0

        if success:
            print(f"\n[PASS] {example_name} completed successfully")
        else:
            print(f"\n[FAIL] {example_name} failed with exit code {result.returncode}")

    except subprocess.TimeoutExpired:
        print(f"\n[TIMEOUT] {example_name} timed out after 5 minutes")
        output = "Execution timed out after 5 minutes"
    except Exception as e:
        print(f"\n[FAIL] {example_name} failed with error: {e}")
        traceback.print_exc()
        output = f"Exception: {str(e)}\n{traceback.format_exc()}"

    execution_time = time.time() - start_time
    print(f"Execution time: {execution_time:.2f} seconds")

    return success, execution_time, output

def clean_output_directories():
    """Clean output directories before running examples."""
    dirs_to_clean = [
        "transition_output",
        "output",
        "analysis_output"
    ]

    for directory in dirs_to_clean:
        if os.path.exists(directory):
            try:
                shutil.rmtree(directory)
                print(f"Cleaned directory: {directory}")
            except Exception as e:
                print(f"Warning: Could not clean directory {directory}: {e}")

    # Recreate directories
    for directory in dirs_to_clean:
        os.makedirs(directory, exist_ok=True)

def main():
    # Ensure we're in the examples directory
    script_dir = Path(__file__).parent.absolute()
    os.chdir(script_dir)

    # Add parent directory to path for imports
    parent_dir = script_dir.parent
    if str(parent_dir) not in sys.path:
        sys.path.insert(0, str(parent_dir))

    # Create required directories
    ensure_directories()

    # Clean output directories
    clean_output_directories()

    # Define examples to run
    examples = [
        ("Video Transitions", "transitions_example.py"),
        ("Audio Analysis", "audio_analysis.py"),
        ("Scene Detection and Video Analysis", "video_analysis.py"),
        ("Asynchronous Video Processing", "async_processing.py"),
        ("AI-Enhanced Features", "ai_features.py")
    ]

    # Run examples and collect results
    results = []

    for name, script in examples:
        script_path = script_dir / script
        if not script_path.exists():
            print(f"\n[WARN] {name} script not found at {script_path}")
            results.append((name, False, 0, "Script not found"))
            continue

        success, execution_time, output = run_example(name, script_path)
        results.append((name, success, execution_time, output))

        # Give the system a moment to clean up resources
        time.sleep(2)

    # Print summary
    print("\n\n" + "="*80)
    print("EXAMPLES EXECUTION SUMMARY")
    print("="*80)

    successful = 0
    total_time = 0

    for name, success, time_taken, _ in results:
        status = "[PASS]" if success else "[FAIL]"
        print(f"{status} - {name} ({time_taken:.2f}s)")
        if success:
            successful += 1
        total_time += time_taken

    print("-"*80)
    print(f"Results: {successful}/{len(examples)} examples completed successfully")
    print(f"Total execution time: {total_time:.2f} seconds")
    print("="*80)

    # Return non-zero exit code if any examples failed
    if successful < len(examples):
        sys.exit(1)

if __name__ == "__main__":
    main()
