"""
Debug script to test HTTP server startup and basic functionality.
"""

import time
import threading
from core.http_server import RateLoaderHTTPServer
from core.config import get_config
from core.logger import get_rateloader_logger

def test_server_startup():
    """Test server startup and basic functionality."""
    logger = get_rateloader_logger()
    config = get_config()
    port_str = config.get("server_port")
    port_int = config.get_int("server_port", 8000)
    
    print(f"Config server_port string value: {port_str}")
    print(f"get_int result: {port_int}")
    
    # Try manual conversion
    try:
        manual_port = int(port_str) if port_str else 8000
        print(f"Manual conversion result: {manual_port}")
        port = manual_port
    except:
        port = 8000
        print(f"Using fallback port: {port}")
    
    print(f"Testing server startup on port {port}...")
    
    # Create server instance
    server = RateLoaderHTTPServer(port=port)
    
    try:
        # Start server
        if not server.start():
            print("❌ FAIL: Failed to start server")
            return False
        
        print("✅ Server started successfully")
        print(f"Server running: {server.is_running}")
        
        # Wait a bit for server to fully start
        time.sleep(2)
        
        # Test Oracle connection
        print(f"Oracle connected: {server.oracle_connector.is_connected()}")
        
        # Stop server
        if not server.stop():
            print("❌ FAIL: Failed to stop server")
            return False
        
        print("✅ Server stopped successfully")
        print(f"Server running: {server.is_running}")
        
        # Cleanup
        server.cleanup()
        
        return True
        
    except Exception as e:
        logger.error(f"Error during server test: {str(e)}")
        print(f"❌ FAIL: Exception during test: {str(e)}")
        return False

if __name__ == "__main__":
    success = test_server_startup()
    if success:
        print("🎉 Server test passed!")
    else:
        print("❌ Server test failed!")