"""Integration test fixtures for Docker tests."""

import pytest
from pathlib import Path


@pytest.fixture(scope="session")
def project_root():
    """Get project root directory (mca-prototype/)."""
    # Get the directory containing this conftest.py file
    tests_dir = Path(__file__).parent  # tests/integration/
    return tests_dir.parent.parent  # mca-prototype/


@pytest.fixture(autouse=True, scope="function")
def reset_otel_providers():
    """Reset global OTel providers before and after each test to prevent state pollution.

    This fixture runs automatically for every test (autouse=True) and ensures
    that global OpenTelemetry provider state doesn't leak between tests.

    Addresses: Global State Pollution (Issue #8 from adversarial review)
    """
    import time
    from opentelemetry import metrics, trace, _logs
    from opentelemetry.util._once import Once

    # Reset providers BEFORE test starts
    try:
        # Give background workers a moment to finish current operations
        time.sleep(0.1)

        # Shutdown meter provider if it exists and isn't already shutdown
        try:
            provider = metrics.get_meter_provider()
            if provider and hasattr(provider, "shutdown") and hasattr(provider, "_shutdown"):
                if not provider._shutdown:
                    provider.shutdown(timeout_millis=2000)
        except Exception:
            pass

        # Shutdown tracer provider if it exists
        try:
            provider = trace.get_tracer_provider()
            if provider and hasattr(provider, "shutdown"):
                provider.shutdown()
        except Exception:
            pass

        # Shutdown logger provider if it exists
        try:
            from opentelemetry._logs import get_logger_provider

            provider = get_logger_provider()
            if provider and hasattr(provider, "shutdown"):
                provider.shutdown()
        except Exception:
            pass

        # Reset all providers
        metrics._METER_PROVIDER = None
        metrics._METER_PROVIDER_SET_ONCE = Once()
        trace._TRACER_PROVIDER = None
        trace._TRACER_PROVIDER_SET_ONCE = Once()
        _logs._LOGGER_PROVIDER = None
        _logs._LOGGER_PROVIDER_SET_ONCE = Once()
    except Exception:
        pass

    yield  # Run test

    # Reset providers AFTER test completes
    try:
        time.sleep(0.1)

        # Shutdown meter provider
        try:
            provider = metrics.get_meter_provider()
            if provider and hasattr(provider, "shutdown") and hasattr(provider, "_shutdown"):
                if not provider._shutdown:
                    provider.shutdown(timeout_millis=2000)
        except Exception:
            pass

        # Shutdown tracer provider
        try:
            provider = trace.get_tracer_provider()
            if provider and hasattr(provider, "shutdown"):
                provider.shutdown()
        except Exception:
            pass

        # Shutdown logger provider
        try:
            from opentelemetry._logs import get_logger_provider

            provider = get_logger_provider()
            if provider and hasattr(provider, "shutdown"):
                provider.shutdown()
        except Exception:
            pass

        # Reset all providers
        metrics._METER_PROVIDER = None
        metrics._METER_PROVIDER_SET_ONCE = Once()
        trace._TRACER_PROVIDER = None
        trace._TRACER_PROVIDER_SET_ONCE = Once()
        _logs._LOGGER_PROVIDER = None
        _logs._LOGGER_PROVIDER_SET_ONCE = Once()
    except Exception as e:
        import warnings

        warnings.warn(f"Failed to reset OTel providers: {e}", UserWarning)
