#!/usr/bin/env python3
"""
Test script for Outlook MCP Server

This script tests the basic functionality of the Outlook MCP server
and provides information about the current environment.
"""

import sys
import platform
import os

# Add the src directory to Python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

def test_imports():
    """Test that all required modules can be imported."""
    print("🔍 Testing imports...")
    
    try:
        import outlook_mcp_server.server
        print("✅ MCP server module imported successfully")
    except ImportError as e:
        print(f"❌ Failed to import MCP server module: {e}")
        return False
    
    return True

def test_platform_detection():
    """Test platform detection and Windows COM availability."""
    print("\n🖥️  Testing platform detection...")
    
    current_platform = platform.system()
    print(f"Current platform: {current_platform}")
    
    # Check if running in WSL
    is_wsl = False
    if current_platform == "Linux":
        try:
            with open('/proc/version', 'r') as f:
                version_info = f.read().lower()
                is_wsl = 'microsoft' in version_info or 'wsl' in version_info
            if is_wsl:
                print("🐧 Running in WSL (Windows Subsystem for Linux)")
        except (FileNotFoundError, IOError):
            pass
    
    if current_platform == "Windows":
        try:
            import win32com.client
            print("✅ Windows COM interface available")
            return True
        except ImportError:
            print("❌ Windows COM interface not available (pywin32 not installed)")
            return False
    elif is_wsl:
        try:
            import win32com.client
            print("✅ Windows COM interface available in WSL")
            print("💡 Make sure Outlook is running on the Windows host")
            return True
        except ImportError:
            print("❌ Windows COM interface not available in WSL (pywin32 not installed)")
            print("💡 Install with: pip install pywin32")
            return False
    else:
        print(f"⚠️  Running on {current_platform} - Outlook functionality will be limited")
        return True

def test_outlook_client():
    """Test Outlook client initialization."""
    print("\n📧 Testing Outlook client...")
    
    try:
        from outlook_mcp_server.server import OutlookClient
        client = OutlookClient()
        
        if client.is_available():
            print("✅ Outlook client connected successfully")
            return True
        else:
            print("⚠️  Outlook client initialized but not connected to Outlook")
            print("   This is expected if:")
            print("   - Running on non-Windows platform")
            print("   - Outlook is not running")
            print("   - pywin32 is not installed")
            return True
            
    except Exception as e:
        print(f"❌ Failed to initialize Outlook client: {e}")
        return False

def test_mcp_server():
    """Test MCP server initialization."""
    print("\n🔧 Testing MCP server components...")
    
    try:
        from outlook_mcp_server.server import server
        print("✅ MCP server initialized successfully")
        
        # Test that handlers are registered
        handlers = [
            "list_resources",
            "read_resource", 
            "list_prompts",
            "get_prompt",
            "list_tools",
            "call_tool"
        ]
        
        for handler in handlers:
            if hasattr(server, f"_{handler}_handler"):
                print(f"✅ {handler} handler registered")
            else:
                print(f"⚠️  {handler} handler not found")
        
        return True
        
    except Exception as e:
        print(f"❌ Failed to initialize MCP server: {e}")
        return False

def main():
    """Run all tests."""
    print("🚀 Outlook MCP Server Test Suite")
    print("=" * 50)
    
    tests = [
        test_imports,
        test_platform_detection,
        test_outlook_client,
        test_mcp_server
    ]
    
    results = []
    for test in tests:
        try:
            results.append(test())
        except Exception as e:
            print(f"❌ Test {test.__name__} failed with exception: {e}")
            results.append(False)
    
    print("\n📊 Test Results")
    print("=" * 50)
    
    passed = sum(results)
    total = len(results)
    
    print(f"Tests passed: {passed}/{total}")
    
    if passed == total:
        print("🎉 All tests passed!")
        current_platform = platform.system()
        
        # Check if WSL
        is_wsl = False
        if current_platform == "Linux":
            try:
                with open('/proc/version', 'r') as f:
                    version_info = f.read().lower()
                    is_wsl = 'microsoft' in version_info or 'wsl' in version_info
            except (FileNotFoundError, IOError):
                pass
        
        if current_platform == "Windows":
            print("\n💡 To use the server:")
            print("1. Make sure Outlook is running")
            print("2. Run: outlook-mcp-server-windows-com")
            print("3. Configure in Claude Desktop (see README.md)")
        elif is_wsl:
            print("\n💡 To use the server in WSL:")
            print("1. Make sure Outlook is running on Windows host")
            print("2. Run: outlook-mcp-server-windows-com")
            print("3. Configure Claude Desktop with WSL-compatible settings")
            print("4. Use ./test_wsl.sh for comprehensive WSL testing")
        else:
            print(f"\n💡 Running on {current_platform}:")
            print("- Server will start but Outlook functionality is limited")
            print("- Full functionality requires Windows or WSL with Outlook installed")
    else:
        print("⚠️  Some tests failed. Check the output above for details.")
        sys.exit(1)

if __name__ == "__main__":
    main()
