"""Integration tests for credential sanitization across entire pipeline.

Phase 3.8: System-level verification per adversarial review.
Tests that credentials are masked end-to-end. PHI masking removed - application responsibility.
"""

import pytest
from mca_sdk import MCAClient


class TestCredentialSanitizationIntegration:
    """System-level tests proving credentials are masked by SDK."""

    def test_aws_key_in_input_data_is_masked(self):
        """Verify AWS keys in input_data are masked before telemetry export."""
        client = MCAClient(
            service_name="test-service", model_id="test-model", team_name="test-team"
        )

        # Input contains AWS key (security issue)
        input_data = {
            "user_query": "Deploy to prod",
            "aws_access_key": "AKIA1234567890123456",  # Should be masked
            "config_value": "some-value",
        }

        # Record prediction with credential in input
        client.record_prediction(input_data=input_data, output={"result": "deployed"}, latency=0.1)

        # The input_data should have been sanitized internally
        # We cannot directly inspect telemetry export here, but we can verify
        # the sanitization function works correctly
        from mca_sdk.core.client import _sanitize_data_recursive

        sanitized = _sanitize_data_recursive(input_data)
        assert sanitized["aws_access_key"] == "[REDACTED]"
        assert sanitized["user_query"] == "Deploy to prod"
        assert sanitized["config_value"] == "some-value"

        client.shutdown()

    def test_gcp_key_in_output_is_masked(self):
        """Verify GCP keys in output are masked before telemetry export."""
        client = MCAClient(
            service_name="test-service", model_id="test-model", team_name="test-team"
        )

        # Output contains GCP key (security issue)
        gcp_key = "AIzaSy" + "A" * 33  # 39 chars total
        output_data = {
            "response": "API call successful",
            "api_key": gcp_key,  # Should be masked
            "status_code": 200,
        }

        # Record prediction with credential in output
        client.record_prediction(input_data={"query": "test"}, output=output_data, latency=0.05)

        # Verify sanitization
        from mca_sdk.core.client import _sanitize_data_recursive

        sanitized = _sanitize_data_recursive(output_data)
        assert sanitized["api_key"] == "[REDACTED]"
        assert sanitized["response"] == "API call successful"
        assert sanitized["status_code"] == 200

        client.shutdown()

    def test_jwt_token_in_nested_structure_is_masked(self):
        """Verify JWT tokens in nested dicts are masked."""
        client = MCAClient(
            service_name="test-service", model_id="test-model", team_name="test-team"
        )

        # Nested structure with JWT
        input_data = {
            "request": {
                "headers": {
                    "authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
                    "content-type": "application/json",
                },
                "body": {"user_id": 123},
            }
        }

        client.record_prediction(input_data=input_data, output={"result": "success"}, latency=0.08)

        # Verify sanitization works on nested structures
        from mca_sdk.core.client import _sanitize_data_recursive

        sanitized = _sanitize_data_recursive(input_data)
        assert "[JWT-REDACTED]" in str(sanitized["request"]["headers"]["authorization"])
        assert sanitized["request"]["headers"]["content-type"] == "application/json"
        assert sanitized["request"]["body"]["user_id"] == 123

        client.shutdown()

    def test_phi_data_not_masked_by_sdk(self):
        """Verify PHI data is NOT masked by SDK - application responsibility."""
        client = MCAClient(
            service_name="test-service", model_id="test-model", team_name="test-team"
        )

        # Input contains PHI patterns (SDK does NOT mask these)
        input_data = {
            "patient_name": "John Smith",  # PHI - NOT masked by SDK
            "ssn": "123-45-6789",  # PHI - NOT masked by SDK
            "email": "patient@example.com",  # PHI - NOT masked by SDK
            "diagnosis": "Type 2 Diabetes",  # PHI - NOT masked by SDK
        }

        client.record_prediction(input_data=input_data, output={"risk_score": 0.75}, latency=0.12)

        # Verify PHI is NOT masked by SDK
        from mca_sdk.core.client import _sanitize_data_recursive

        sanitized = _sanitize_data_recursive(input_data)
        # SDK no longer masks PHI - only credentials
        assert sanitized["ssn"] == "123-45-6789"  # NOT masked
        assert sanitized["email"] == "patient@example.com"  # NOT masked
        assert sanitized["patient_name"] == "John Smith"  # NOT masked

        client.shutdown()

    def test_data_sanitizer_hook_integration(self):
        """Verify application hook is called before SDK sanitization."""

        # Define application PHI sanitization hook
        def sanitize_patient_data(data: dict) -> dict:
            """Application-specific PHI remover."""
            sanitized = data.copy()
            sanitized.pop("patient_name", None)
            sanitized.pop("patient_id", None)
            sanitized.pop("medical_record_number", None)
            return sanitized

        client = MCAClient(
            service_name="test-service",
            model_id="test-model",
            team_name="test-team",
            data_sanitizer_hook=sanitize_patient_data,
        )

        # Input with PHI and credentials
        input_data = {
            "patient_name": "Jane Doe",
            "patient_id": "MRN-123456",
            "aws_key": "AKIA9876543210987654",
            "diagnosis": "Hypertension",
        }

        client.record_prediction(
            input_data=input_data, output={"treatment": "Medication A"}, latency=0.09
        )

        # Verify hook removed PHI fields
        result = sanitize_patient_data(input_data)
        assert "patient_name" not in result
        assert "patient_id" not in result
        assert "aws_key" in result  # Hook doesn't remove this (SDK will)

        # Verify SDK would then mask credentials
        from mca_sdk.core.client import _sanitize_data_recursive

        sanitized = _sanitize_data_recursive(result)
        assert "[AWS-KEY-REDACTED]" in str(sanitized["aws_key"])

        client.shutdown()

    def test_bearer_token_in_string_is_masked(self):
        """Verify Bearer tokens in string values are masked."""
        client = MCAClient(
            service_name="test-service", model_id="test-model", team_name="test-team"
        )

        # String containing Bearer token
        input_data = {
            "log_message": "Auth failed: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
            "request_id": "req-123",
        }

        client.record_prediction(
            input_data=input_data, output={"error": "unauthorized"}, latency=0.05
        )

        # Verify Bearer token masked in string
        from mca_sdk.core.client import _sanitize_data_recursive

        sanitized = _sanitize_data_recursive(input_data)
        assert "Bearer [TOKEN-REDACTED]" in sanitized["log_message"]
        assert "eyJhbG" not in sanitized["log_message"]  # Token removed
        assert sanitized["request_id"] == "req-123"

        client.shutdown()


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