"""Integration tests for SDK version in actual telemetry payloads.

Validates Acceptance Criterion #2: SDK version is present in exported telemetry.
"""

import pytest
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor

from mca_sdk.version import __version__
from mca_sdk.core.providers import (
    setup_meter_provider,
    setup_logger_provider,
    setup_tracer_provider,
    create_resource_attributes,
)


class TestSDKVersionInTelemetryPayload:
    """Test that SDK version appears in actual exported telemetry payloads."""

    def test_sdk_version_in_metric_payload(self):
        """Verify SDK version is present in exported metric payloads."""
        resource = create_resource_attributes(
            service_name="test-service",
            model_id="mdl-001",
        )

        # Use InMemoryMetricReader to capture exported metrics
        reader = InMemoryMetricReader()
        from opentelemetry.sdk.metrics import MeterProvider

        provider = MeterProvider(resource=resource, metric_readers=[reader])

        # Create and record a metric
        meter = provider.get_meter("test-meter")
        counter = meter.create_counter("test_counter")
        counter.add(1, {"test": "value"})

        # Force export
        provider.force_flush()

        # Verify resource attributes in the exported metrics
        metrics = reader.get_metrics_data()
        resource_attrs = dict(metrics.resource_metrics[0].resource.attributes)

        assert resource_attrs.get("mca.sdk.version") == __version__
        assert resource_attrs.get("telemetry.sdk.version") == __version__

    def test_sdk_version_in_trace_payload(self):
        """Verify SDK version is present in exported trace payloads."""
        resource = create_resource_attributes(
            service_name="test-service",
            model_id="mdl-001",
        )

        # Use InMemorySpanExporter to capture exported spans
        exporter = InMemorySpanExporter()
        from opentelemetry.sdk.trace import TracerProvider

        provider = TracerProvider(resource=resource)
        provider.add_span_processor(SimpleSpanProcessor(exporter))

        # Create a span
        tracer = provider.get_tracer("test-tracer")
        with tracer.start_as_current_span("test-span") as span:
            span.set_attribute("test", "value")

        # Verify resource attributes in the exported spans
        spans = exporter.get_finished_spans()
        assert len(spans) == 1

        resource_attrs = dict(spans[0].resource.attributes)
        assert resource_attrs.get("mca.sdk.version") == __version__
        assert resource_attrs.get("telemetry.sdk.version") == __version__

    def test_sdk_version_in_log_payload(self):
        """Verify SDK version is present in exported log payloads."""
        resource = create_resource_attributes(
            service_name="test-service",
            model_id="mdl-001",
        )

        # Use InMemoryLogRecordExporter to capture exported logs
        exporter = InMemoryLogRecordExporter()
        from opentelemetry.sdk._logs import LoggerProvider

        provider = LoggerProvider(resource=resource)
        provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))

        # Emit a log
        logger = provider.get_logger("test-logger")
        from opentelemetry._logs import SeverityNumber

        logger.emit(
            body="Test log message",
            severity_number=SeverityNumber.INFO,
            attributes={"test": "value"},
        )

        # Verify resource attributes in the exported logs
        logs = exporter.get_finished_logs()
        assert len(logs) == 1

        resource_attrs = dict(logs[0].resource.attributes)
        assert resource_attrs.get("mca.sdk.version") == __version__
        assert resource_attrs.get("telemetry.sdk.version") == __version__

    def test_sdk_version_survives_user_override_in_payload(self):
        """Verify SDK version cannot be tampered with in actual exported payload."""
        malicious_extra = {
            "mca.sdk.version": "malicious-version",
            "telemetry.sdk.version": "fake-version",
        }
        resource = create_resource_attributes(
            service_name="test-service",
            model_id="mdl-001",
            extra_resource=malicious_extra,
        )

        # Use InMemoryMetricReader to verify actual exported data
        reader = InMemoryMetricReader()
        from opentelemetry.sdk.metrics import MeterProvider

        provider = MeterProvider(resource=resource, metric_readers=[reader])

        # Create and record a metric
        meter = provider.get_meter("test-meter")
        counter = meter.create_counter("test_counter")
        counter.add(1)

        # Force export
        provider.force_flush()

        # Verify the malicious override was blocked
        metrics = reader.get_metrics_data()
        resource_attrs = dict(metrics.resource_metrics[0].resource.attributes)

        assert resource_attrs.get("mca.sdk.version") == __version__
        assert resource_attrs.get("telemetry.sdk.version") == __version__
        assert resource_attrs.get("mca.sdk.version") != "malicious-version"
        assert resource_attrs.get("telemetry.sdk.version") != "fake-version"
