#!/usr/bin/env python3
"""
Test script for Screen Cast integration in MbetterClient
Tests the integration without actually starting FFmpeg or Chromecast
"""

import sys
import logging
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from mbetterclient.config.settings import AppSettings
from mbetterclient.core.application import MbetterClientApplication
from mbetterclient.core.message_bus import MessageBus
from mbetterclient.core.screen_cast import ScreenCastComponent

def setup_logging():
    """Setup basic logging for testing"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    return logging.getLogger(__name__)

def test_screen_cast_config():
    """Test screen cast configuration"""
    logger = logging.getLogger("test_config")
    logger.info("Testing ScreenCast configuration...")
    
    # Test default settings
    settings = AppSettings()
    assert hasattr(settings, 'screen_cast'), "ScreenCast config not found in AppSettings"
    assert hasattr(settings, 'enable_screen_cast'), "enable_screen_cast not found in AppSettings"
    
    # Test configuration values
    sc_config = settings.screen_cast
    assert sc_config.stream_port == 8000, f"Expected port 8000, got {sc_config.stream_port}"
    assert sc_config.resolution == "1280x720", f"Expected 1280x720, got {sc_config.resolution}"
    assert sc_config.framerate == 15, f"Expected 15fps, got {sc_config.framerate}"
    
    logger.info("✓ ScreenCast configuration test passed")
    return True

def test_screen_cast_component():
    """Test screen cast component initialization"""
    logger = logging.getLogger("test_component")
    logger.info("Testing ScreenCast component initialization...")
    
    # Create message bus
    message_bus = MessageBus()
    message_bus.register_component("test")
    
    # Create screen cast component
    try:
        screen_cast = ScreenCastComponent(
            message_bus=message_bus,
            stream_port=8001,  # Use different port for testing
            chromecast_name="Test Device",
            output_dir="/tmp/test_screen_cast"
        )
        
        # Test component attributes
        assert screen_cast.stream_port == 8001
        assert screen_cast.chromecast_name == "Test Device"
        assert screen_cast.name == "screen_cast"
        assert not screen_cast.capture_active
        assert not screen_cast.streaming_active
        
        logger.info("✓ ScreenCast component initialization test passed")
        return True
        
    except Exception as e:
        logger.error(f"✗ ScreenCast component test failed: {e}")
        return False

def test_application_integration():
    """Test application integration"""
    logger = logging.getLogger("test_integration")
    logger.info("Testing MbetterClient application integration...")
    
    try:
        # Test direct component integration with thread manager
        from mbetterclient.core.thread_manager import ThreadManager
        from mbetterclient.core.message_bus import MessageBus
        from mbetterclient.config.settings import AppSettings
        from mbetterclient.core.screen_cast import ScreenCastComponent
        
        # Create components
        settings = AppSettings()
        message_bus = MessageBus()
        message_bus.register_component("core")
        thread_manager = ThreadManager(message_bus, settings)
        
        # Create and register screen cast component
        screen_cast = ScreenCastComponent(
            message_bus=message_bus,
            stream_port=8001,
            chromecast_name="Test Device",
            output_dir="/tmp/test_screen_cast"
        )
        
        thread_manager.register_component("screen_cast", screen_cast)
        
        # Test that component is registered
        if "screen_cast" in thread_manager.get_component_names():
            logger.info("✓ ScreenCast component registered with thread manager")
            
            # Test component status
            status = thread_manager.get_component_status("screen_cast")
            if status and status["name"] == "screen_cast":
                logger.info("✓ ScreenCast component status available")
                return True
            else:
                logger.error("✗ ScreenCast component status not available")
                return False
        else:
            logger.error("✗ ScreenCast component not registered")
            return False
            
    except Exception as e:
        logger.error(f"✗ Application integration test failed: {e}")
        return False

def test_web_routes():
    """Test web dashboard routes"""
    logger = logging.getLogger("test_web")
    logger.info("Testing web dashboard routes...")
    
    try:
        from mbetterclient.web_dashboard.screen_cast_routes import screen_cast_bp
        
        # Check that blueprint was imported successfully
        assert screen_cast_bp is not None, "screen_cast_bp is None"
        assert screen_cast_bp.name == "screen_cast", f"Expected 'screen_cast', got {screen_cast_bp.name}"
        
        # Test that the blueprint can be registered (basic functionality test)
        from flask import Flask
        test_app = Flask(__name__)
        
        # This will raise an exception if the blueprint is malformed
        test_app.register_blueprint(screen_cast_bp, url_prefix='/screen_cast')
        
        # Check that routes were registered
        routes = [rule.rule for rule in test_app.url_map.iter_rules()]
        
        # Check for at least one of our routes
        screen_cast_routes = [r for r in routes if '/screen_cast' in r]
        if screen_cast_routes:
            logger.info(f"✓ Found screen cast routes: {len(screen_cast_routes)} routes")
        else:
            logger.warning("No screen cast routes found, but blueprint registered successfully")
        
        logger.info("✓ Web dashboard routes test passed")
        return True
        
    except Exception as e:
        logger.error(f"✗ Web routes test failed: {e}")
        return False

def test_dependencies():
    """Test that optional dependencies can be imported or fail gracefully"""
    logger = logging.getLogger("test_deps")
    logger.info("Testing optional dependencies...")
    
    # Test ffmpeg-python import
    try:
        import ffmpeg
        logger.info("✓ ffmpeg-python is available")
        ffmpeg_available = True
    except ImportError:
        logger.warning("⚠ ffmpeg-python not available (this is expected if not installed)")
        ffmpeg_available = False
    
    # Test pychromecast import
    try:
        import pychromecast
        logger.info("✓ pychromecast is available")
        chromecast_available = True
    except ImportError:
        logger.warning("⚠ pychromecast not available (this is expected if not installed)")
        chromecast_available = False
    
    # The component should handle missing dependencies gracefully
    logger.info("✓ Dependencies test passed (graceful handling)")
    return True

def main():
    """Main test function"""
    logger = setup_logging()
    logger.info("=" * 60)
    logger.info("Starting MbetterClient ScreenCast Integration Tests")
    logger.info("=" * 60)
    
    tests = [
        ("Configuration", test_screen_cast_config),
        ("Component", test_screen_cast_component),
        ("Application Integration", test_application_integration),
        ("Web Routes", test_web_routes),
        ("Dependencies", test_dependencies),
    ]
    
    passed = 0
    failed = 0
    
    for test_name, test_func in tests:
        logger.info(f"\nRunning {test_name} test...")
        try:
            if test_func():
                passed += 1
                logger.info(f"✓ {test_name} test PASSED")
            else:
                failed += 1
                logger.error(f"✗ {test_name} test FAILED")
        except Exception as e:
            failed += 1
            logger.error(f"✗ {test_name} test FAILED with exception: {e}")
    
    logger.info("\n" + "=" * 60)
    logger.info(f"Test Results: {passed} passed, {failed} failed")
    logger.info("=" * 60)
    
    if failed == 0:
        logger.info("🎉 All tests passed! ScreenCast integration is working correctly.")
        return 0
    else:
        logger.error(f"❌ {failed} test(s) failed. Please check the integration.")
        return 1

if __name__ == "__main__":
    sys.exit(main())