#!/usr/bin/env python3
"""
Test script for OpenClaw Auto-Login Automation.

This script verifies that the automation module works correctly
across all platforms (Windows, macOS, Linux).
"""

import sys
import platform
from pathlib import Path

def test_imports():
    """Test that all automation modules can be imported."""
    print("Testing imports...")
    try:
        from openclaw_installer.automation.auto_login import (
            auto_login,
            get_wrapper_path,
            check_gateway_status,
            get_platform_name,
            open_browser,
        )
        print("  [OK] All imports successful")
        return True
    except ImportError as e:
        print(f"  [FAIL] Import failed: {e}")
        return False


def test_platform_detection():
    """Test platform detection."""
    print("\nTesting platform detection...")
    from openclaw_installer.automation.auto_login import get_platform_name
    
    detected = get_platform_name()
    actual = platform.system()
    
    mapping = {
        "Windows": "Windows",
        "Darwin": "macOS",
        "Linux": "Linux"
    }
    
    expected = mapping.get(actual, actual)
    
    if detected == expected:
        print(f"  [OK] Detected platform: {detected}")
        return True
    else:
        print(f"  [FAIL] Platform mismatch: detected={detected}, expected={expected}")
        return False


def test_wrapper_path():
    """Test wrapper path detection."""
    print("\nTesting wrapper path detection...")
    from openclaw_installer.automation.auto_login import get_wrapper_path
    
    wrapper = get_wrapper_path()
    system = platform.system()
    
    if wrapper is None:
        print(f"  [WARN] Wrapper not found (expected if not installed)")
        # This is OK - wrapper may not be installed yet
        return True
    
    if system == "Windows":
        expected_suffix = "bin\\openclaw.cmd"
    else:
        expected_suffix = ".local/bin/openclaw"
    
    if str(wrapper).endswith(expected_suffix):
        print(f"  [OK] Wrapper path correct: {wrapper}")
        return True
    else:
        print(f"  [FAIL] Unexpected wrapper path: {wrapper}")
        return False


def test_config_validation():
    """Test that automation config is valid."""
    print("\nTesting config validation...")
    try:
        from openclaw_installer.config import AutomationConfig, Config
        
        # Test default config
        cfg = AutomationConfig()
        assert cfg.auto_open_dashboard == True
        assert cfg.auto_login == True
        assert cfg.startup_timeout == 30
        
        print("  [OK] Config validation passed")
        return True
    except Exception as e:
        print(f"  [FAIL] Config validation failed: {e}")
        return False


def test_cli_commands():
    """Test CLI commands are registered."""
    print("\nTesting CLI commands...")
    try:
        from openclaw_installer.cli import app
        
        # Check commands exist - filter out None values
        commands = [cmd.name for cmd in app.registered_commands if cmd and hasattr(cmd, 'name')]
        
        if "auto-login" in commands:
            print(f"  [OK] CLI commands registered: {commands}")
            return True
        else:
            print(f"  [FAIL] Missing 'auto-login' command. Found: {commands}")
            return False
    except Exception as e:
        print(f"  [FAIL] CLI test failed: {e}")
        return False


def test_port_conflict_functions():
    """Test port conflict resolution functions exist."""
    print("\nTesting port conflict resolution...")
    try:
        from openclaw_installer.automation.auto_login import (
            find_process_using_port,
            kill_process,
            resolve_port_conflict,
        )
        
        # Test that functions exist and are callable
        assert callable(find_process_using_port)
        assert callable(kill_process)
        assert callable(resolve_port_conflict)
        
        # Test port check (port 18789 should be free or show openclaw)
        result = find_process_using_port(18789)
        if result:
            pid, name = result
            print(f"  [INFO] Port 18789 in use by {name} (PID: {pid})")
        else:
            print(f"  [OK] Port 18789 is available")
        
        return True
    except Exception as e:
        print(f"  [FAIL] Port conflict test failed: {e}")
        return False


def test_shell_scripts_exist():
    """Test that shell scripts exist."""
    print("\nTesting shell scripts...")
    
    automation_dir = Path(__file__).parent / "openclaw_installer" / "automation"
    
    ps_script = automation_dir / "auto-login.ps1"
    sh_script = automation_dir / "auto-login.sh"
    readme = automation_dir / "README.md"
    
    results = []
    
    if ps_script.exists():
        print(f"  [OK] PowerShell script found")
        results.append(True)
    else:
        print(f"  [FAIL] PowerShell script missing")
        results.append(False)
    
    if sh_script.exists():
        print(f"  [OK] Bash script found")
        results.append(True)
    else:
        print(f"  [FAIL] Bash script missing")
        results.append(False)
    
    if readme.exists():
        print(f"  [OK] README found")
        results.append(True)
    else:
        print(f"  [FAIL] README missing")
        results.append(False)
    
    return all(results)


def main():
    """Run all tests."""
    print("=" * 60)
    print("OpenClaw Automation Test Suite")
    print("=" * 60)
    print(f"Platform: {platform.system()} {platform.release()}")
    print(f"Python: {sys.version}")
    print("")
    
    tests = [
        ("Imports", test_imports),
        ("Platform Detection", test_platform_detection),
        ("Wrapper Path", test_wrapper_path),
        ("Config Validation", test_config_validation),
        ("CLI Commands", test_cli_commands),
        ("Port Conflict Resolution", test_port_conflict_functions),
        ("Shell Scripts", test_shell_scripts_exist),
    ]
    
    results = []
    for name, test_func in tests:
        try:
            result = test_func()
            results.append((name, result))
        except Exception as e:
            print(f"  [FAIL] Test crashed: {e}")
            results.append((name, False))
    
    # Summary
    print("\n" + "=" * 60)
    print("Test Summary")
    print("=" * 60)
    
    passed = sum(1 for _, r in results if r)
    total = len(results)
    
    for name, result in results:
        status = "[OK] PASS" if result else "[FAIL]"
        print(f"  {status}: {name}")
    
    print("")
    print(f"Result: {passed}/{total} tests passed")
    
    if passed == total:
        print("\n[SUCCESS] All tests passed!")
        return 0
    else:
        print("\n[WARNING] Some tests failed")
        return 1


if __name__ == "__main__":
    sys.exit(main())
