"""Unit tests for queue persistence configuration (Story 3-4).

Tests that persist_queue configuration issues warnings (not errors) and
validates HIPAA compliance guidance.
"""

import os
import warnings

import pytest

from mca_sdk.config import MCAConfig
from mca_sdk.config.settings import SecurityWarning


class TestPersistQueueConfiguration:
    """Test persist_queue configuration validation."""

    def test_persist_queue_issues_warning(self):
        """Test: persist_queue=True issues warning, not error."""
        # Should NOT raise ConfigurationError anymore (Story 3-4 change)
        with warnings.catch_warnings(record=True) as warning_list:
            warnings.simplefilter("always", SecurityWarning)

            config = MCAConfig(service_name="test-persist", persist_queue=True)

            # Should create config successfully
            assert config.persist_queue is True

            # Should have issued warning (SecurityWarning or UserWarning)
            relevant_warnings = [
                w for w in warning_list if issubclass(w.category, (SecurityWarning, UserWarning))
            ]
            assert (
                len(relevant_warnings) > 0
            ), f"Should issue SecurityWarning, got {[w.category for w in warning_list]}"

    def test_warning_contains_hipaa_guidance(self):
        """Test: Warning message contains HIPAA compliance guidance."""
        with warnings.catch_warnings(record=True) as warning_list:
            warnings.simplefilter("always", SecurityWarning)

            config = MCAConfig(service_name="test-hipaa", persist_queue=True)

            # Find SecurityWarning or UserWarning
            relevant_warnings = [
                w for w in warning_list if issubclass(w.category, (SecurityWarning, UserWarning))
            ]
            assert len(relevant_warnings) > 0, "Should have security warnings"

            warning_msg = str(relevant_warnings[0].message)

            # Verify warning contains key HIPAA compliance terms
            assert "encryption at rest" in warning_msg.lower(), "Should mention encryption at rest"
            assert "unencrypted" in warning_msg.lower(), "Should warn about unencrypted storage"
            assert "phi" in warning_msg.lower(), "Should mention PHI"
            assert "production" in warning_msg.lower(), "Should mention production usage"

    def test_persist_path_default(self):
        """Test: persist_path defaults to ~/.mca_sdk/queue.pkl."""
        import os as _os

        config = MCAConfig(service_name="test-default-path")

        # Should be under ~/.mca_sdk/ using user-specific home directory
        expected = _os.path.expanduser(_os.path.join("~", ".mca_sdk", "queue.pkl"))
        assert (
            config.persist_path == expected
        ), f"persist_path should be ~/.mca_sdk/queue.pkl, got: {config.persist_path}"

        # Should be under .mca_sdk (not bare /tmp/queue.pkl or similar)
        assert ".mca_sdk" in config.persist_path
        assert "queue.pkl" in config.persist_path

    def test_persist_disabled_by_default(self):
        """Test: persist_queue defaults to False (backward compatibility)."""
        config = MCAConfig(service_name="test-default-persist")

        # Should be disabled by default
        assert config.persist_queue is False

        # Should not issue warnings when disabled
        with warnings.catch_warnings(record=True) as warning_list:
            warnings.simplefilter("always")

            config2 = MCAConfig(service_name="test-no-persist", persist_queue=False)

            # Should not have SecurityWarnings about persistence
            security_warnings = [w for w in warning_list if issubclass(w.category, SecurityWarning)]
            persistence_warnings = [
                w for w in security_warnings if "persist" in str(w.message).lower()
            ]
            assert len(persistence_warnings) == 0, "Should not warn when persist_queue=False"

    def test_custom_persist_path(self):
        """Test: Custom persist_path is respected (Story 3.15: must be in allowed dirs)."""
        # Use whitelisted directory
        custom_path = "/var/lib/mca/queue.json"

        with warnings.catch_warnings(record=True):
            warnings.simplefilter("always", SecurityWarning)

            config = MCAConfig(
                service_name="test-custom-path",
                persist_queue=True,
                persist_path=custom_path,
            )

            assert config.persist_path == custom_path

    def test_persist_path_expanded(self):
        """Test: persist_path with ~ is expanded to user home (Story 3.15: whitelisted dir)."""
        with warnings.catch_warnings(record=True):
            warnings.simplefilter("always", SecurityWarning)

            config = MCAConfig(
                service_name="test-expand",
                persist_queue=True,
                persist_path="~/.mca_sdk/queue.pkl",  # Use whitelisted directory
            )

            # Path should be stored with ~ (expansion happens at use time)
            assert ".mca_sdk" in config.persist_path
            assert "queue.pkl" in config.persist_path

    def test_logging_warning_for_persistence(self):
        """Test: Logging warning is also issued for disk persistence."""
        import logging

        # Capture logging output
        with warnings.catch_warnings(record=True):
            warnings.simplefilter("always", SecurityWarning)

            # Create logger to capture warnings
            logger = logging.getLogger("mca_sdk.config.settings")
            logger.setLevel(logging.WARNING)

            config = MCAConfig(service_name="test-logging", persist_queue=True)

            # Config should be created successfully
            assert config.persist_queue is True
            # Note: Hard to test logging output without capturing it,
            # but we verify config is created without errors
