#!/usr/bin/env python3
"""Real functionality test for openclaw-installer."""

import sys
import tempfile
from pathlib import Path

def test_ollama_config():
    """Test the ollama-config.yaml file specifically."""
    print("\n=== Testing ollama-config.yaml ===")
    from openclaw_installer.config import Config
    
    ollama_config = Path("ollama-config.yaml")
    if not ollama_config.exists():
        print("✗ ollama-config.yaml not found")
        return False
    
    try:
        config = Config.from_yaml(ollama_config)
        print(f"[OK] Config loaded successfully")
        print(f"  Provider: {config.ai.provider}")
        print(f"  Model: {config.ai.model}")
        print(f"  Base URL: {config.ai.base_url}")
        print(f"  Web UI: {config.channels.web}")
        print(f"  Port: {config.gateway.port}")
        
        # Verify values
        assert config.ai.provider == "ollama"
        assert config.ai.model == "llama3.1:8b"
        assert config.ai.base_url == "http://localhost:11434"
        assert config.channels.web is True
        assert config.gateway.port == 18789
        assert config.gateway.autostart is True
        
        print("[OK] All values verified correctly")
        return True
    except Exception as e:
        print(f"[FAIL] Failed to load config: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_all_example_configs():
    """Test all example configuration files."""
    print("\n=== Testing All Example Configs ===")
    from openclaw_installer.config import Config
    
    configs = [
        ("examples/kimi-config.yaml", "kimi", "kimi-k2.5"),
        ("examples/claude-config.yaml", "anthropic", "claude-3-5-sonnet"),
        ("examples/ollama-config.yaml", "ollama", "llama3.2"),
    ]
    
    all_passed = True
    for config_path, expected_provider, expected_model in configs:
        config_file = Path(config_path)
        if not config_file.exists():
            print(f"⚠ {config_path} not found, skipping")
            continue
        
        try:
            config = Config.from_yaml(config_file)
            assert config.ai.provider == expected_provider
            assert config.ai.model == expected_model
            print(f"✓ {config_path}: {expected_provider} ({expected_model})")
        except Exception as e:
            print(f"✗ {config_path}: {e}")
            all_passed = False
    
    return all_passed

def test_environment_generation():
    """Test environment variable generation for each provider."""
    print("\n=== Testing Environment Generation ===")
    from openclaw_installer.config import Config
    
    test_cases = [
        {
            "name": "Kimi",
            "config": {"ai": {"provider": "kimi", "key": "sk-test", "model": "kimi-k2.5"}},
            "expected_url": "https://api.moonshot.cn/v1",
        },
        {
            "name": "Anthropic",
            "config": {"ai": {"provider": "anthropic", "key": "sk-test", "model": "claude-3-5-sonnet"}},
            "expected_url": "https://api.anthropic.com",
        },
        {
            "name": "OpenAI",
            "config": {"ai": {"provider": "openai", "key": "sk-test", "model": "gpt-4o"}},
            "expected_url": "https://api.openai.com",
        },
        {
            "name": "Ollama",
            "config": {"ai": {"provider": "ollama", "key": "", "model": "llama3.2", "base_url": "http://localhost:11434"}},
            "expected_url": "http://localhost:11434",
        },
    ]
    
    all_passed = True
    for case in test_cases:
        try:
            config = Config.model_validate(case["config"])
            env = config.to_env()
            
            assert env["OPENCLAW_PROVIDER"] == case["config"]["ai"]["provider"]
            assert env["OPENCLAW_API_KEY"] == case["config"]["ai"]["key"]
            assert env["OPENCLAW_MODEL"] == case["config"]["ai"]["model"]
            assert env["OPENCLAW_BASE_URL"] == case["expected_url"]
            
            print(f"[OK] {case['name']}: environment vars correct")
        except Exception as e:
            print(f"[FAIL] {case['name']}: {e}")
            all_passed = False
    
    return all_passed

def test_installer_logic():
    """Test installer logic without actually installing."""
    print("\n=== Testing Installer Logic ===")
    from openclaw_installer.installer import check_system_node, get_platform, get_node_download_url
    from openclaw_installer.config import Config
    
    all_passed = True
    
    # Test platform detection
    try:
        platform = get_platform()
        print(f"✓ Platform detected: {platform}")
    except Exception as e:
        print(f"✗ Platform detection failed: {e}")
        all_passed = False
    
    # Test Node.js detection
    try:
        has_system, version, node_path, npm_path = check_system_node()
        if has_system:
            print(f"✓ Node.js found: {version}")
        else:
            print(f"⚠ No system Node.js detected (will download bundled)")
    except Exception as e:
        print(f"✗ Node.js detection failed: {e}")
        all_passed = False
    
    # Test Node.js download URL generation
    try:
        urls = []
        for platform in ["win", "darwin", "linux"]:
            # Mock platform for testing
            import openclaw_installer.installer as installer_module
            original_platform = installer_module.sys.platform
            
            if platform == "win":
                installer_module.sys.platform = "win32"
            elif platform == "darwin":
                installer_module.sys.platform = "darwin"
            else:
                installer_module.sys.platform = "linux"
            
            url = get_node_download_url("22.14.0")
            urls.append(f"{platform}: {url}")
            
            # Restore
            installer_module.sys.platform = original_platform
        
        print(f"✓ Node.js URLs generated for all platforms")
    except Exception as e:
        print(f"✗ Node.js URL generation failed: {e}")
        all_passed = False
    
    # Test installer instantiation
    try:
        config = Config.model_validate({
            "ai": {"provider": "kimi", "key": "sk-test"},
            "channels": {"web": True}
        })
        
        from openclaw_installer.installer import OpenClawInstaller
        installer = OpenClawInstaller(config, dry_run=True)
        print(f"✓ Installer instantiated successfully (dry-run mode)")
    except Exception as e:
        print(f"✗ Installer instantiation failed: {e}")
        all_passed = False
    
    return all_passed

def test_real_world_scenarios():
    """Test real-world usage scenarios."""
    print("\n=== Testing Real-World Scenarios ===")
    from openclaw_installer.config import Config
    
    scenarios = [
        {
            "name": "Minimal Kimi Config",
            "yaml": """
ai:
  provider: kimi
  key: "sk-actual-key-from-moonshot"
""",
        },
        {
            "name": "Full Claude Config with All Channels",
            "yaml": """
ai:
  provider: anthropic
  key: "sk-ant-api03-actual-key"
  model: "claude-3-5-sonnet-20241022"

channels:
  web: true
  telegram: true
  telegram_token: "${TELEGRAM_BOT_TOKEN}"

gateway:
  port: 18789
  autostart: true
  verbose: false
""",
        },
        {
            "name": "Ollama Local Config",
            "yaml": """
ai:
  provider: ollama
  key: ""
  model: "llama3.1:8b"
  base_url: "http://localhost:11434"

channels:
  web: true

gateway:
  port: 18789
  autostart: true
""",
        },
    ]
    
    all_passed = True
    for scenario in scenarios:
        try:
            with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
                f.write(scenario["yaml"])
                temp_path = f.name
            
            config = Config.from_yaml(Path(temp_path))
            env = config.to_env()
            
            print(f"[OK] {scenario['name']}: validated")
            
            os.unlink(temp_path)
        except Exception as e:
            print(f"[FAIL] {scenario['name']}: {e}")
            all_passed = False
    
    return all_passed

def main():
    """Run all real tests."""
    print("=" * 70)
    print("OpenClaw Installer - REAL FUNCTIONALITY TEST")
    print("=" * 70)
    
    tests = [
        test_ollama_config,
        test_all_example_configs,
        test_environment_generation,
        test_installer_logic,
        test_real_world_scenarios,
    ]
    
    results = []
    for test in tests:
        try:
            results.append(test())
        except Exception as e:
            print(f"\n[FAIL] TEST CRASHED: {e}")
            import traceback
            traceback.print_exc()
            results.append(False)
    
    print("\n" + "=" * 70)
    passed = sum(results)
    total = len(results)
    print(f"Test Results: {passed}/{total} test suites passed")
    print("=" * 70)
    
    if all(results):
        print("\n[SUCCESS] ALL REAL TESTS PASSED!")
        print("\nThe installer is ready for production use.")
        return 0
    else:
        print("\n[ERROR] SOME TESTS FAILED")
        return 1

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