"""
Tests for GateWay core functionality.
"""


import pytest


# Test profiling
class TestProfiling:
    """Tests for resource estimation."""

    def test_estimate_simple_function(self):
        """Test resource estimation for simple function."""
        from verlex_server.gateway.core.profiling import estimate_resources

        def simple():
            return [x * 2 for x in range(1000)]

        estimate = estimate_resources(simple)

        assert estimate.cpu_cores >= 1
        assert estimate.memory_mb > 0

    def test_code_analyzer_exists(self):
        """Test CodeAnalyzer class exists."""
        from verlex_server.gateway.core.profiling import CodeAnalyzer

        assert CodeAnalyzer is not None

    def test_code_analyzer_basic(self):
        """Test CodeAnalyzer basic operations."""
        import ast

        from verlex_server.gateway.core.profiling import CodeAnalyzer

        code = """
x = [i * 2 for i in range(10000)]
result = sum(x)
"""
        tree = ast.parse(code)
        analyzer = CodeAnalyzer()
        analyzer.visit(tree)

        # Analyzer should process without error
        assert analyzer is not None


# Test pricing
class TestPricing:
    """Tests for cloud pricing."""

    def test_compare_prices(self):
        """Test price comparison."""
        from verlex_server.gateway.core.pricing import compare_prices

        comparison = compare_prices(
            cpu=2,
            memory_gb=4,
        )

        assert len(comparison.options) > 0
        assert comparison.cheapest is not None

    def test_compare_gpu_prices(self):
        """Test GPU price comparison."""
        from verlex_server.gateway.core.pricing import compare_prices

        comparison = compare_prices(
            cpu=4,
            memory_gb=16,
            gpu_type="A100",
        )

        assert len(comparison.options) > 0
        for option in comparison.options:
            assert option.gpu_type == "A100"

    def test_estimate_cost(self):
        """Test cost estimation."""
        from verlex_server.gateway.core.pricing import compare_prices, estimate_cost

        # First get a price info
        comparison = compare_prices(cpu=2, memory_gb=4)
        price_info = comparison.cheapest

        cost = estimate_cost(
            price_info=price_info,
            duration_seconds=7200,  # 2 hours
        )

        assert cost["total_cost"] > 0
        assert cost["hourly_rate"] > 0

    def test_exclude_providers(self):
        """Test excluding providers from comparison."""
        from verlex_server.gateway.core.pricing import compare_prices

        comparison = compare_prices(
            cpu=2,
            memory_gb=4,
            excluded_providers=["aws", "gcp"],
        )

        for option in comparison.options:
            assert option.provider.value not in ["aws", "gcp"]


# Test selection strategies
class TestSelection:
    """Tests for provider selection strategies."""

    def test_priority_selector(self):
        """Test Priority mode selection."""
        from verlex_server.gateway.core.selection import select_provider

        selection = select_provider(
            mode="P",
            cpu=2,
            memory_gb=4,
        )

        assert selection is not None
        assert selection.provider is not None

    def test_patient_selector(self):
        """Test Patient mode selection."""
        from verlex_server.gateway.core.selection import select_provider

        selection = select_provider(
            mode="N",
            cpu=2,
            memory_gb=4,
        )

        assert selection is not None

    def test_flexible_selector(self):
        """Test Flexible mode selection."""
        from verlex_server.gateway.core.selection import select_provider

        selection = select_provider(
            mode="F",
            cpu=2,
            memory_gb=4,
        )

        assert selection is not None


# Test decorators
class TestDecorators:
    """Tests for decorators."""

    def test_resource_decorator(self):
        """Test @resource decorator."""
        from verlex_server.gateway.client.decorators import resource

        @resource(cpu=4, memory="8GB", gpu="T4")
        def my_func():
            return 42

        assert hasattr(my_func, "_gateway_resource_config")
        config = my_func._gateway_resource_config
        assert config.cpu == 4
        assert config.memory == "8GB"
        assert config.gpu == "T4"

    def test_checkpoint_decorator(self):
        """Test @checkpoint decorator."""
        from verlex_server.gateway.client.decorators import checkpoint

        @checkpoint(interval=60, framework="pytorch")
        def my_func():
            return 42

        assert hasattr(my_func, "_gateway_checkpoint_config")
        config = my_func._gateway_checkpoint_config
        assert config.interval == 60
        assert config.framework == "pytorch"

    def test_gpu_shorthand(self):
        """Test GPU shorthand decorator."""
        from verlex_server.gateway.client.decorators import gpu

        @gpu("A100")
        def my_func():
            return 42

        assert hasattr(my_func, "_gateway_resource_config")
        config = my_func._gateway_resource_config
        assert config.gpu == "A100"

    def test_resource_config_to_dict(self):
        """Test ResourceConfig conversion to dict."""
        from verlex_server.gateway.client.decorators import resource

        @resource(cpu=8, memory="32GB", gpu="H100", timeout=7200)
        def my_func():
            return 42

        config = my_func._gateway_resource_config
        d = config.to_dict()

        assert d["cpu"] == 8
        assert d["memory"] == "32GB"
        assert d["gpu"] == "H100"
        assert d["timeout"] == 7200


# Test configuration
class TestConfig:
    """Tests for configuration."""

    def test_default_config(self):
        """Test default configuration."""
        from verlex_server.gateway.client.config import GateWayConfig, get_config

        config = get_config()

        assert isinstance(config, GateWayConfig)
        assert config.default_mode in ("P", "N", "S", "F")

    def test_config_override(self):
        """Test configuration override."""
        from verlex_server.gateway.client.config import config as set_config
        from verlex_server.gateway.client.config import get_config

        set_config(
            default_mode="N",
            default_timeout=7200,
        )

        config = get_config()

        assert config.default_mode == "N"
        assert config.default_timeout == 7200

    def test_config_to_dict(self):
        """Test configuration to dict conversion."""
        from verlex_server.gateway.client.config import get_config

        config = get_config()
        d = config.to_dict()

        assert "default_mode" in d
        assert "preferred_providers" in d


# Test serialization module exists
class TestSerializationModule:
    """Tests for serialization module structure."""

    def test_serialize_function_exists(self):
        """Test serialize_function exists."""
        from verlex_server.gateway.core.serialization import serialize_function
        assert callable(serialize_function)

    def test_deserialize_function_exists(self):
        """Test deserialize_function exists."""
        from verlex_server.gateway.core.serialization import deserialize_function
        assert callable(deserialize_function)

    def test_serialized_function_dataclass(self):
        """Test SerializedFunction dataclass exists."""
        from verlex_server.gateway.core.serialization import SerializedFunction
        assert SerializedFunction is not None


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
