"""
Tests for integration fixes.

This test module verifies the two-mode pricing system (Performance/Standard)
and other integration fixes in the GateWay codebase.
"""

import os
from unittest.mock import MagicMock, patch

import pytest

# =============================================================================
# Test Issue #1: PricingTier enum values
# =============================================================================

class TestPricingTierValues:
    """Test that PricingTier enum has correct values."""

    def test_performance_enum_exists(self):
        """Verify PERFORMANCE is a valid PricingTier enum value."""
        from verlex_server.gateway.core.queue import PricingTier

        assert hasattr(PricingTier, "PERFORMANCE")
        assert PricingTier.PERFORMANCE.value == "performance"

    def test_standard_enum_exists(self):
        """Verify STANDARD is a valid PricingTier enum value."""
        from verlex_server.gateway.core.queue import PricingTier

        assert hasattr(PricingTier, "STANDARD")
        assert PricingTier.STANDARD.value == "standard"

    def test_all_pricing_tiers_exist(self):
        """Verify all expected pricing tiers are present."""
        from verlex_server.gateway.core.queue import PricingTier

        expected_tiers = ["PERFORMANCE", "STANDARD"]
        for tier in expected_tiers:
            assert hasattr(PricingTier, tier), f"Missing PricingTier.{tier}"

    def test_only_two_tiers(self):
        """Verify only two pricing tiers exist."""
        from verlex_server.gateway.core.queue import PricingTier

        tiers = list(PricingTier)
        assert len(tiers) == 2, f"Expected 2 tiers, got {len(tiers)}: {tiers}"


# =============================================================================
# Test Issue #2: Mode mapping
# =============================================================================

class TestModeTierMapping:
    """Test that modes map correctly to pricing tiers."""

    def test_mode_p_maps_to_performance(self):
        """Verify 'P' mode maps to PERFORMANCE."""
        from verlex_server.gateway.core.queue import PricingTier

        tier_map = {
            "P": PricingTier.PERFORMANCE,
            "S": PricingTier.STANDARD,
        }

        assert tier_map["P"] == PricingTier.PERFORMANCE

    def test_mode_s_maps_to_standard(self):
        """Verify 'S' mode maps to STANDARD."""
        from verlex_server.gateway.core.queue import PricingTier

        tier_map = {
            "P": PricingTier.PERFORMANCE,
            "S": PricingTier.STANDARD,
        }

        assert tier_map["S"] == PricingTier.STANDARD


# =============================================================================
# Test Issue #3: VS Code extension code submission endpoint
# =============================================================================

class TestCodeJobSubmission:
    """Test the /v1/jobs/submit/code endpoint for VS Code extension."""

    def test_code_job_submission_model_exists(self):
        """Verify CodeJobSubmission model exists."""
        from verlex_server.gateway.backend.api import CodeJobSubmission

        assert CodeJobSubmission is not None

    def test_code_job_submission_fields(self):
        """Verify CodeJobSubmission has correct fields."""
        from verlex_server.gateway.backend.api import CodeJobSubmission

        submission = CodeJobSubmission(
            code="print('hello')",
            file_path="/test/file.py",
            resources={"cpu": 2},
            mode="P",
            config={},
        )

        assert submission.code == "print('hello')"
        assert submission.file_path == "/test/file.py"
        assert submission.resources == {"cpu": 2}
        assert submission.mode == "P"

    def test_code_job_submission_defaults(self):
        """Verify CodeJobSubmission has sensible defaults."""
        from verlex_server.gateway.backend.api import CodeJobSubmission

        submission = CodeJobSubmission(code="x = 1")

        assert submission.code == "x = 1"
        assert submission.file_path is None
        assert submission.resources == {}
        assert submission.mode is None


# =============================================================================
# Test Issue #4: Pydantic .model_dump() usage
# =============================================================================

class TestPydanticModelDump:
    """Test that Pydantic models use .model_dump() instead of deprecated .dict()."""

    def test_webhook_uses_model_dump(self):
        """Verify webhooks_cron_api.py uses .model_dump()."""
        with open("verlex_server/gateway/backend/webhooks_cron_api.py") as f:
            content = f.read()

        assert ".model_dump()" in content

    def test_pydantic_v2_compatibility(self):
        """Verify we're using Pydantic V2 compatible code."""
        from pydantic import BaseModel

        class TestModel(BaseModel):
            name: str
            value: int

        model = TestModel(name="test", value=42)

        result = model.model_dump()
        assert result == {"name": "test", "value": 42}


# =============================================================================
# Test Issue #5: GitHub OIDC authentication endpoint
# =============================================================================

class TestGitHubOIDCEndpoint:
    """Test the /v1/auth/github-oidc endpoint."""

    def test_oidc_request_model_exists(self):
        """Verify GitHubOIDCRequest model exists."""
        from verlex_server.gateway.backend.api import GitHubOIDCRequest

        assert GitHubOIDCRequest is not None

    def test_oidc_response_model_exists(self):
        """Verify GitHubOIDCResponse model exists."""
        from verlex_server.gateway.backend.api import GitHubOIDCResponse

        assert GitHubOIDCResponse is not None

    def test_oidc_verifier_class_exists(self):
        """Verify GitHubOIDCVerifier class exists."""
        try:
            from verlex_server.gateway.backend.github_actions import GitHubOIDCVerifier
        except ImportError as e:
            pytest.fail(f"Failed to import GitHubOIDCVerifier: {e}")

        verifier = GitHubOIDCVerifier()
        assert verifier is not None


# =============================================================================
# Test Issue #6: Unified job submission
# =============================================================================

class TestUnifiedJobSubmission:
    """Test unified job submission function."""

    def test_submit_job_unified_exists(self):
        """Verify submit_job_unified function exists."""
        from verlex_server.gateway.backend.api import submit_job_unified

        assert submit_job_unified is not None
        assert callable(submit_job_unified)


# =============================================================================
# Test Issue #7: Clerk webhook security
# =============================================================================

class TestClerkWebhookSecurity:
    """Test Clerk webhook security in production mode."""

    def test_production_mode_requires_secret(self):
        """Verify production mode requires CLERK_WEBHOOK_SECRET."""
        import inspect

        import verlex_server.gateway.backend.webhooks as webhooks_module
        source = inspect.getsource(webhooks_module.clerk_webhook)

        assert "GATEWAY_ENV" in source or "production" in source.lower()
        assert "CLERK_WEBHOOK_SECRET" in source

    def test_get_webhook_secret_function(self):
        """Verify get_webhook_secret function works."""
        from verlex_server.gateway.backend.webhooks import get_webhook_secret

        original = os.environ.get("CLERK_WEBHOOK_SECRET")

        try:
            if "CLERK_WEBHOOK_SECRET" in os.environ:
                del os.environ["CLERK_WEBHOOK_SECRET"]
            assert get_webhook_secret() == ""

            os.environ["CLERK_WEBHOOK_SECRET"] = "whsec_test123"
            assert get_webhook_secret() == "whsec_test123"
        finally:
            if original:
                os.environ["CLERK_WEBHOOK_SECRET"] = original
            elif "CLERK_WEBHOOK_SECRET" in os.environ:
                del os.environ["CLERK_WEBHOOK_SECRET"]


# =============================================================================
# Integration test for all fixes together
# =============================================================================

class TestAllFixesIntegration:
    """Integration tests verifying all fixes work together."""

    def test_imports_work(self):
        """Verify all imports work without errors."""
        pass

    def test_pricing_tier_mode_consistency(self):
        """Verify pricing tier and mode mappings are consistent."""
        from verlex_server.gateway.core.queue import PricingTier

        modes_to_tiers = {
            "P": PricingTier.PERFORMANCE,
            "S": PricingTier.STANDARD,
        }

        for _mode, tier in modes_to_tiers.items():
            assert isinstance(tier, PricingTier)
            assert tier.value in ["performance", "standard"]


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