#!/bin/bash
# WSL Test Script for Outlook MCP Server
# This script tests the Outlook MCP server in WSL environment

set -e

echo "🔍 WSL Environment Test for Outlook MCP Server"
echo "=============================================="

# Check if we're running in WSL
check_wsl() {
    if grep -q microsoft /proc/version 2>/dev/null; then
        echo "✅ Running in WSL environment"
        return 0
    else
        echo "❌ Not running in WSL"
        return 1
    fi
}

# Check Python version
check_python() {
    echo "🐍 Checking Python version..."
    python3 --version
    if python3 -c "import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)"; then
        echo "✅ Python version is compatible"
    else
        echo "❌ Python 3.8+ required"
        exit 1
    fi
}

# Check if pywin32 is available
check_pywin32() {
    echo "🔧 Checking pywin32 availability..."
    if python3 -c "import win32com.client; print('✅ pywin32 is available')" 2>/dev/null; then
        return 0
    else
        echo "❌ pywin32 not available"
        echo "💡 Install with: pip install pywin32"
        echo "💡 Or install with WSL extras: pip install outlook-mcp-server-windows-com[wsl]"
        return 1
    fi
}

# Test Windows COM access
test_com_access() {
    echo "🖥️ Testing Windows COM access..."
    
    cat > /tmp/test_com.py << 'EOF'
import sys
import platform

def test_wsl_detection():
    """Test WSL detection"""
    try:
        with open('/proc/version', 'r') as f:
            version_info = f.read().lower()
            is_wsl = 'microsoft' in version_info or 'wsl' in version_info
        print(f"WSL detected: {is_wsl}")
        return is_wsl
    except Exception as e:
        print(f"Error detecting WSL: {e}")
        return False

def test_com_import():
    """Test COM import"""
    try:
        import win32com.client
        print("✅ win32com.client imported successfully")
        return True
    except ImportError as e:
        print(f"❌ Failed to import win32com.client: {e}")
        return False

def test_outlook_connection():
    """Test Outlook connection"""
    try:
        import win32com.client
        outlook = win32com.client.Dispatch("Outlook.Application")
        namespace = outlook.GetNamespace("MAPI")
        print("✅ Successfully connected to Outlook via COM")
        return True
    except Exception as e:
        print(f"❌ Failed to connect to Outlook: {e}")
        print("💡 Make sure Outlook is running on the Windows host")
        return False

if __name__ == "__main__":
    print("Platform:", platform.system())
    
    wsl_ok = test_wsl_detection()
    com_ok = test_com_import()
    
    if com_ok:
        outlook_ok = test_outlook_connection()
    else:
        outlook_ok = False
    
    if wsl_ok and com_ok and outlook_ok:
        print("\n🎉 WSL environment is ready for Outlook MCP Server!")
        sys.exit(0)
    else:
        print("\n⚠️ WSL environment needs configuration")
        sys.exit(1)
EOF

    python3 /tmp/test_com.py
    return $?
}

# Test MCP server import
test_mcp_server() {
    echo "📧 Testing MCP server import..."
    
    if python3 -c "
import sys
sys.path.insert(0, './src')
from outlook_mcp_server.server import OutlookClient
client = OutlookClient()
print('Server status:', 'Available' if client.is_available() else 'Not available')
print('✅ MCP server imported successfully')
" 2>/dev/null; then
        return 0
    else
        echo "❌ Failed to import MCP server"
        return 1
    fi
}

# Main test execution
main() {
    echo "Starting WSL compatibility tests..."
    echo
    
    # Check if in WSL
    if ! check_wsl; then
        echo "This script is designed for WSL environments"
        exit 1
    fi
    
    echo
    check_python
    echo
    
    pywin32_available=0
    if check_pywin32; then
        pywin32_available=1
    fi
    echo
    
    if [ $pywin32_available -eq 1 ]; then
        if test_com_access; then
            com_working=1
        else
            com_working=0
        fi
        echo
    else
        com_working=0
    fi
    
    if test_mcp_server; then
        mcp_working=1
    else
        mcp_working=0
    fi
    echo
    
    # Summary
    echo "📊 WSL Test Results"
    echo "=================="
    echo "WSL Environment: ✅"
    echo "Python 3.8+: ✅"
    echo "pywin32 Available: $([ $pywin32_available -eq 1 ] && echo "✅" || echo "❌")"
    echo "COM Access: $([ $com_working -eq 1 ] && echo "✅" || echo "❌")"
    echo "MCP Server: $([ $mcp_working -eq 1 ] && echo "✅" || echo "❌")"
    echo
    
    if [ $pywin32_available -eq 1 ] && [ $com_working -eq 1 ] && [ $mcp_working -eq 1 ]; then
        echo "🎉 All tests passed! Your WSL environment is ready."
        echo
        echo "💡 To use the MCP server:"
        echo "1. Make sure Outlook is running on Windows"
        echo "2. Run: python -m outlook_mcp_server"
        echo "3. Configure in Claude Desktop (see README.md)"
    else
        echo "⚠️ Some tests failed. See the guide below:"
        echo
        echo "🔧 Setup Instructions for WSL:"
        echo "1. Install Python dependencies:"
        echo "   pip install outlook-mcp-server-windows-com[wsl]"
        echo
        echo "2. Make sure Outlook is running on the Windows host"
        echo
        echo "3. If COM access fails, you may need to:"
        echo "   - Run Outlook as administrator on Windows"
        echo "   - Check Windows Defender/antivirus settings"
        echo "   - Ensure WSL has proper Windows integration"
    fi
}

# Run main function
main
