"""Tests for production environment detection in TelemetryQueue.

Tests the _is_production_environment() method to ensure accurate detection
of production vs development environments.
"""

import os
import pytest
from mca_sdk.buffering.queue import TelemetryQueue
from mca_sdk.utils.exceptions import BufferingError


class TestProductionDetection:
    """Test production environment detection logic."""

    def test_env_production_detected(self, tmp_path, monkeypatch):
        """Test ENV=production triggers production detection."""
        monkeypatch.setenv("ENV", "production")
        monkeypatch.setenv(
            "MCA_QUEUE_ENCRYPTION_KEY", "BpT1hufvpYqkZMrQVS6Rag4mN2nH450ViRSopZR-OY0="
        )

        with pytest.raises(BufferingError, match="PRODUCTION SECURITY VIOLATION"):
            TelemetryQueue(
                max_size=10,
                persist=True,
                persist_path=str(tmp_path / "queue.json"),
                encryption_enabled=True,
            )

    def test_environment_production_detected(self, tmp_path, monkeypatch):
        """Test ENVIRONMENT=production triggers production detection."""
        monkeypatch.setenv("ENVIRONMENT", "production")
        monkeypatch.setenv(
            "MCA_QUEUE_ENCRYPTION_KEY", "BpT1hufvpYqkZMrQVS6Rag4mN2nH450ViRSopZR-OY0="
        )

        with pytest.raises(BufferingError, match="PRODUCTION SECURITY VIOLATION"):
            TelemetryQueue(
                max_size=10,
                persist=True,
                persist_path=str(tmp_path / "queue.json"),
                encryption_enabled=True,
            )

    def test_kubernetes_service_host_detected(self, tmp_path, monkeypatch):
        """Test KUBERNETES_SERVICE_HOST presence triggers production detection."""
        monkeypatch.setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")
        monkeypatch.setenv("KUBERNETES_NAMESPACE", "production-cluster")
        monkeypatch.setenv(
            "MCA_QUEUE_ENCRYPTION_KEY", "BpT1hufvpYqkZMrQVS6Rag4mN2nH450ViRSopZR-OY0="
        )

        with pytest.raises(BufferingError, match="PRODUCTION SECURITY VIOLATION"):
            TelemetryQueue(
                max_size=10,
                persist=True,
                persist_path=str(tmp_path / "queue.json"),
                encryption_enabled=True,
            )

    def test_gcp_project_prod_detected(self, tmp_path, monkeypatch):
        """Test GCP_PROJECT with 'prod' triggers production detection."""
        monkeypatch.setenv("GCP_PROJECT", "my-company-prod")
        monkeypatch.setenv(
            "MCA_QUEUE_ENCRYPTION_KEY", "BpT1hufvpYqkZMrQVS6Rag4mN2nH450ViRSopZR-OY0="
        )

        with pytest.raises(BufferingError, match="PRODUCTION SECURITY VIOLATION"):
            TelemetryQueue(
                max_size=10,
                persist=True,
                persist_path=str(tmp_path / "queue.json"),
                encryption_enabled=True,
            )

    def test_override_allows_production_env_keys(self, tmp_path, monkeypatch):
        """Test MCA_ALLOW_ENV_KEYS_IN_PROD=true allows env keys in production."""
        from cryptography.fernet import Fernet

        key = Fernet.generate_key()

        monkeypatch.setenv("ENV", "production")
        monkeypatch.setenv("MCA_QUEUE_ENCRYPTION_KEY", key.decode("ascii"))
        monkeypatch.setenv("MCA_ALLOW_ENV_KEYS_IN_PROD", "true")

        # Should NOT raise exception
        queue = TelemetryQueue(
            max_size=10,
            persist=True,
            persist_path=str(tmp_path / "queue.json"),
            encryption_enabled=True,
        )
        queue.shutdown()

    def test_development_environment_allows_env_keys(self, tmp_path, monkeypatch):
        """Test development environment allows env variable keys."""
        from cryptography.fernet import Fernet

        key = Fernet.generate_key()

        monkeypatch.setenv("ENV", "development")
        monkeypatch.setenv("MCA_QUEUE_ENCRYPTION_KEY", key.decode("ascii"))

        # Should NOT raise exception
        queue = TelemetryQueue(
            max_size=10,
            persist=True,
            persist_path=str(tmp_path / "queue.json"),
            encryption_enabled=True,
        )
        queue.shutdown()

    def test_no_environment_markers_allows_env_keys(self, tmp_path, monkeypatch):
        """Test absence of production markers allows env keys (dev default)."""
        from cryptography.fernet import Fernet

        key = Fernet.generate_key()

        # Clear all production markers
        for var in ["ENV", "ENVIRONMENT", "KUBERNETES_SERVICE_HOST", "GCP_PROJECT"]:
            monkeypatch.delenv(var, raising=False)

        monkeypatch.setenv("MCA_QUEUE_ENCRYPTION_KEY", key.decode("ascii"))

        # Should NOT raise exception (defaults to development)
        queue = TelemetryQueue(
            max_size=10,
            persist=True,
            persist_path=str(tmp_path / "queue.json"),
            encryption_enabled=True,
        )
        queue.shutdown()

    def test_false_positive_dev_for_product_team(self, tmp_path, monkeypatch):
        """Test false positive: 'product' in dev environment name."""
        from cryptography.fernet import Fernet

        key = Fernet.generate_key()

        # Dev environment with "product" substring
        monkeypatch.setenv("ENV", "dev-for-product-team")
        monkeypatch.setenv("MCA_QUEUE_ENCRYPTION_KEY", key.decode("ascii"))

        # Should NOT raise exception (not actually production)
        queue = TelemetryQueue(
            max_size=10,
            persist=True,
            persist_path=str(tmp_path / "queue.json"),
            encryption_enabled=True,
        )
        queue.shutdown()

    def test_staging_environment_not_detected_as_production(self, tmp_path, monkeypatch):
        """Test staging environment is not detected as production."""
        from cryptography.fernet import Fernet

        key = Fernet.generate_key()

        monkeypatch.setenv("ENV", "staging")
        monkeypatch.setenv("MCA_QUEUE_ENCRYPTION_KEY", key.decode("ascii"))

        # Should NOT raise exception
        queue = TelemetryQueue(
            max_size=10,
            persist=True,
            persist_path=str(tmp_path / "queue.json"),
            encryption_enabled=True,
        )
        queue.shutdown()

    def test_kubernetes_dev_namespace_not_detected(self, tmp_path, monkeypatch):
        """Test Kubernetes dev namespace is not detected as production."""
        from cryptography.fernet import Fernet

        key = Fernet.generate_key()

        monkeypatch.setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")
        monkeypatch.setenv("KUBERNETES_NAMESPACE", "development")
        monkeypatch.setenv("MCA_QUEUE_ENCRYPTION_KEY", key.decode("ascii"))

        # Should NOT raise exception
        queue = TelemetryQueue(
            max_size=10,
            persist=True,
            persist_path=str(tmp_path / "queue.json"),
            encryption_enabled=True,
        )
        queue.shutdown()

    def test_underscore_prod_detected(self, tmp_path, monkeypatch):
        """Test GCP_PROJECT with underscores: acme_prod_main detected as production."""
        monkeypatch.setenv("GCP_PROJECT", "acme_prod_main")
        monkeypatch.setenv(
            "MCA_QUEUE_ENCRYPTION_KEY", "BpT1hufvpYqkZMrQVS6Rag4mN2nH450ViRSopZR-OY0="
        )

        with pytest.raises(BufferingError, match="PRODUCTION SECURITY VIOLATION"):
            TelemetryQueue(
                max_size=10,
                persist=True,
                persist_path=str(tmp_path / "queue.json"),
                encryption_enabled=True,
            )

    def test_dot_prod_detected(self, tmp_path, monkeypatch):
        """Test KUBERNETES_NAMESPACE with dots: cluster.prod.us detected as production."""
        monkeypatch.setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")
        monkeypatch.setenv("KUBERNETES_NAMESPACE", "cluster.prod.us")
        monkeypatch.setenv(
            "MCA_QUEUE_ENCRYPTION_KEY", "BpT1hufvpYqkZMrQVS6Rag4mN2nH450ViRSopZR-OY0="
        )

        with pytest.raises(BufferingError, match="PRODUCTION SECURITY VIOLATION"):
            TelemetryQueue(
                max_size=10,
                persist=True,
                persist_path=str(tmp_path / "queue.json"),
                encryption_enabled=True,
            )

    def test_mixed_delimiters_prod_detected(self, tmp_path, monkeypatch):
        """Test mixed delimiters: my-company_prod.cluster detected as production."""
        monkeypatch.setenv("GCP_PROJECT", "my-company_prod.cluster")
        monkeypatch.setenv(
            "MCA_QUEUE_ENCRYPTION_KEY", "BpT1hufvpYqkZMrQVS6Rag4mN2nH450ViRSopZR-OY0="
        )

        with pytest.raises(BufferingError, match="PRODUCTION SECURITY VIOLATION"):
            TelemetryQueue(
                max_size=10,
                persist=True,
                persist_path=str(tmp_path / "queue.json"),
                encryption_enabled=True,
            )
