#!/usr/bin/env python3
"""Comprehensive test suite for openclaw-installer."""

import tempfile
import os
import sys
from pathlib import Path

def test_imports():
    """Test that all imports work correctly."""
    print("Testing imports...")
    try:
        from openclaw_installer import Config, OpenClawInstaller
        from openclaw_installer.config import AIConfig, ChannelsConfig, GatewayConfig
        from openclaw_installer.installer import get_platform, get_node_download_url
        print("✓ All imports successful")
        return True
    except Exception as e:
        print(f"✗ Import failed: {e}")
        return False

def test_config_validation():
    """Test configuration validation."""
    print("\nTesting config validation...")
    from openclaw_installer.config import Config
    
    # Test valid configs
    valid_configs = [
        {"ai": {"provider": "kimi", "key": "test"}},
        {"ai": {"provider": "anthropic", "key": "test"}},
        {"ai": {"provider": "openai", "key": "test"}},
        {"ai": {"provider": "ollama", "key": ""}},
    ]
    
    for config_data in valid_configs:
        try:
            config = Config.model_validate(config_data)
            print(f"✓ Valid config accepted: {config.ai.provider}")
        except Exception as e:
            print(f"✗ Valid config rejected: {e}")
            return False
    
    # Test invalid config
    try:
        Config.model_validate({"ai": {"provider": "invalid", "key": "test"}})
        print("✗ Invalid config was accepted (should have failed)")
        return False
    except Exception:
        print("✓ Invalid config properly rejected")
    
    return True

def test_yaml_loading():
    """Test YAML config loading."""
    print("\nTesting YAML loading...")
    from openclaw_installer.config import Config
    
    with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
        f.write("""
ai:
  provider: kimi
  key: "sk-test123"
  model: "kimi-k2.5"

channels:
  web: true
  telegram: false

gateway:
  port: 18789
  autostart: true
""")
        f.flush()
        temp_path = f.name
    
    try:
        config = Config.from_yaml(Path(temp_path))
        assert config.ai.provider == "kimi"
        assert config.ai.key == "sk-test123"
        assert config.channels.web is True
        assert config.gateway.port == 18789
        print("✓ YAML loading works correctly")
        return True
    except Exception as e:
        print(f"✗ YAML loading failed: {e}")
        return False
    finally:
        os.unlink(temp_path)

def test_config_to_env():
    """Test config to environment variable conversion."""
    print("\nTesting config to env conversion...")
    from openclaw_installer.config import Config
    
    config = Config.model_validate({
        "ai": {
            "provider": "kimi",
            "key": "sk-test123",
            "model": "kimi-k2.5"
        },
        "gateway": {
            "port": 18789
        }
    })
    
    env = config.to_env()
    
    expected = {
        "OPENCLAW_PROVIDER": "kimi",
        "OPENCLAW_MODEL": "kimi-k2.5",
        "OPENCLAW_API_KEY": "sk-test123",
        "OPENCLAW_BASE_URL": "https://api.moonshot.cn/v1",
        "OPENCLAW_PORT": "18789"
    }
    
    for key, value in expected.items():
        if env.get(key) != value:
            print(f"✗ Env var mismatch: {key} = {env.get(key)}, expected {value}")
            return False
    
    print("✓ Config to env conversion works correctly")
    return True

def test_all_example_configs():
    """Test all example configuration files."""
    print("\nTesting example config files...")
    from openclaw_installer.config import Config
    
    example_dir = Path("examples")
    if not example_dir.exists():
        print("⚠ Examples directory not found, skipping")
        return True
    
    config_files = list(example_dir.glob("*.yaml"))
    if not config_files:
        print("⚠ No example config files found, skipping")
        return True
    
    for config_file in config_files:
        try:
            config = Config.from_yaml(config_file)
            print(f"✓ {config_file.name}: {config.ai.provider}")
        except Exception as e:
            print(f"✗ {config_file.name}: {e}")
            return False
    
    return True

def main():
    """Run all tests."""
    print("=" * 60)
    print("OpenClaw Installer Comprehensive Test Suite")
    print("=" * 60)
    
    tests = [
        test_imports,
        test_config_validation,
        test_yaml_loading,
        test_config_to_env,
        test_all_example_configs,
    ]
    
    results = []
    for test in tests:
        try:
            results.append(test())
        except Exception as e:
            print(f"✗ Test crashed: {e}")
            import traceback
            traceback.print_exc()
            results.append(False)
    
    print("\n" + "=" * 60)
    print(f"Test Results: {sum(results)}/{len(results)} passed")
    print("=" * 60)
    
    if all(results):
        print("✓ All tests passed!")
        sys.exit(0)
    else:
        print("✗ Some tests failed")
        sys.exit(1)

if __name__ == "__main__":
    main()
