#!/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}")
    
    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
    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!")
        if platform.system() == "Windows":
            print("\n💡 To use the server:")
            print("1. Make sure Outlook is running")
            print("2. Run: uv run python -m outlook_mcp_server")
            print("3. Configure in Claude Desktop (see README.md)")
        else:
            print(f"\n💡 Running on {platform.system()}:")
            print("- Server will start but Outlook functionality is limited")
            print("- Full functionality requires Windows with Outlook installed")
    else:
        print("⚠️  Some tests failed. Check the output above for details.")
        sys.exit(1)

if __name__ == "__main__":
    main()
