"""
Tests for GateWay Secrets Management
"""

import asyncio
from datetime import datetime, timedelta


class TestSecretsManagement:
    """Test suite for secrets management."""

    def test_secret_dataclass(self):
        """Test Secret dataclass."""
        from verlex_server.gateway.backend.secrets import Secret

        secret = Secret(
            name="test_secret",
            value="secret_value",
            user_id="user123",
        )

        assert secret.name == "test_secret"
        assert secret.value == "secret_value"
        assert secret.user_id == "user123"
        assert not secret.is_expired

        # Test expiration
        expired_secret = Secret(
            name="expired",
            value="old",
            user_id="user123",
            expires_at=datetime.utcnow() - timedelta(hours=1),
        )
        assert expired_secret.is_expired

        print("✓ Secret dataclass works")

    def test_environment_storage(self):
        """Test environment variable storage backend."""
        from verlex_server.gateway.backend.secrets import EnvironmentSecretStorage

        async def run_test():
            storage = EnvironmentSecretStorage()

            # Set a secret
            secret = await storage.set(
                name="test_key",
                value="test_value",
                user_id="user123",
            )

            assert secret.name == "test_key"
            assert secret.value == "test_value"

            # Get the secret
            retrieved = await storage.get("test_key", "user123")
            assert retrieved is not None
            assert retrieved.value == "test_value"

            # Check exists
            exists = await storage.exists("test_key", "user123")
            assert exists

            # List secrets
            secrets = await storage.list("user123")
            assert "test_key" in secrets

            # Delete
            deleted = await storage.delete("test_key", "user123")
            assert deleted

            # Verify deleted
            exists = await storage.exists("test_key", "user123")
            assert not exists

            print("✓ Environment storage works")

        asyncio.run(run_test())

    def test_secrets_manager(self):
        """Test SecretsManager high-level interface."""
        from verlex_server.gateway.backend.secrets import SecretBackend, SecretsManager

        async def run_test():
            # Use environment backend for testing
            manager = SecretsManager(backend=SecretBackend.ENVIRONMENT)

            # Set secrets
            await manager.set("api_key", "sk-test123", user_id="user1")
            await manager.set("db_password", "secret123", user_id="user1")

            # Get for job
            secrets = await manager.get_for_job(
                ["api_key", "db_password"],
                user_id="user1",
            )

            assert len(secrets) == 2
            assert "api_key" in secrets
            assert secrets["api_key"].value == "sk-test123"

            # Convert to env dict
            env_dict = manager.to_env_dict(secrets)
            assert "API_KEY" in env_dict
            assert "DB_PASSWORD" in env_dict

            # Test standard mappings
            await manager.set("openai_key", "sk-openai", user_id="user1")
            secrets = await manager.get_for_job(["openai_key"], user_id="user1")
            env_dict = manager.to_env_dict(secrets, use_standard_names=True)
            assert "OPENAI_API_KEY" in env_dict

            # Cleanup
            await manager.delete("api_key", "user1")
            await manager.delete("db_password", "user1")
            await manager.delete("openai_key", "user1")

            print("✓ SecretsManager works")

        asyncio.run(run_test())

    def test_global_instance(self):
        """Test global secrets manager instance."""
        from verlex_server.gateway.backend.secrets import (
            SecretBackend,
            configure_secrets,
            get_secrets_manager,
        )

        # Get default instance
        manager1 = get_secrets_manager()
        assert manager1 is not None

        # Configure with specific backend
        manager2 = configure_secrets(backend=SecretBackend.ENVIRONMENT)
        assert manager2 is not None

        # Get should return configured instance
        manager3 = get_secrets_manager()
        assert manager3 is manager2

        print("✓ Global instance works")


def run_all_tests():
    """Run all tests."""
    tests = TestSecretsManagement()

    print("Testing Secrets Management...")
    print("-" * 40)

    tests.test_secret_dataclass()
    tests.test_environment_storage()
    tests.test_secrets_manager()
    tests.test_global_instance()

    print("-" * 40)
    print("All secrets tests passed! ✓")


if __name__ == "__main__":
    run_all_tests()
