#!/usr/bin/env python3
"""
Debug script to test WebDashboard SSL setup
"""

import sys
import logging
from pathlib import Path

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

from mbetterclient.config.settings import AppSettings
from mbetterclient.web_dashboard.app import WebDashboard
from mbetterclient.core.message_bus import MessageBus
from mbetterclient.database.manager import DatabaseManager
from mbetterclient.config.manager import ConfigManager

def test_webapp_ssl():
    """Test WebDashboard SSL configuration"""
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    
    print("=== Testing WebDashboard SSL Setup ===")
    
    # Create settings with SSL enabled
    settings = AppSettings()
    settings.web.enable_ssl = True
    settings.web.host = "127.0.0.1"
    settings.web.port = 5001
    
    print(f"SSL enabled in settings: {settings.web.enable_ssl}")
    print(f"SSL auto-generate: {settings.web.ssl_auto_generate}")
    print(f"Host: {settings.web.host}, Port: {settings.web.port}")
    
    # Initialize components needed by WebDashboard
    try:
        # Create required components
        message_bus = MessageBus()
        db_manager = DatabaseManager(db_path="test.db")
        config_manager = ConfigManager(db_manager)
        
        # Create WebDashboard instance
        web_dashboard = WebDashboard(
            message_bus=message_bus,
            db_manager=db_manager,
            config_manager=config_manager,
            settings=settings.web
        )
        
        print("WebDashboard instance created successfully")
        
        # Initialize (this should trigger SSL setup)
        success = web_dashboard.initialize()
        print(f"WebDashboard initialization: {'SUCCESS' if success else 'FAILED'}")
        
        # Check if SSL context was created
        if hasattr(web_dashboard, 'ssl_context') and web_dashboard.ssl_context:
            print(f"SSL context created: {web_dashboard.ssl_context}")
            print(f"SSL context type: {type(web_dashboard.ssl_context)}")
        else:
            print("ERROR: No SSL context created")
        
        # Check server configuration
        if hasattr(web_dashboard, 'server') and web_dashboard.server:
            print(f"Server created: {web_dashboard.server}")
            print(f"Server type: {type(web_dashboard.server)}")
            
            # Check if server has SSL context
            if hasattr(web_dashboard.server, 'ssl_context'):
                print(f"Server SSL context: {web_dashboard.server.ssl_context}")
            else:
                print("Server has no ssl_context attribute")
        else:
            print("ERROR: No server created")
            
        # Check settings after initialization
        print(f"Settings SSL enabled after init: {web_dashboard.settings.enable_ssl}")
        
    except Exception as e:
        logger.error(f"Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    return True

if __name__ == "__main__":
    success = test_webapp_ssl()
    if success:
        print("\n✅ WebDashboard SSL test completed")
    else:
        print("\n❌ WebDashboard SSL test failed")
        sys.exit(1)