"""Integration tests for Prometheus exporter with HTTP scraping."""

import time
import pytest
import requests
from mca_sdk import MCAClient


class TestPrometheusHTTPEndpoint:
    """Test Prometheus HTTP endpoint scraping."""

    def test_metrics_endpoint_accessible(self):
        """Prometheus /metrics endpoint should be accessible."""
        client = MCAClient(
            service_name="test-service",
            model_id="test-model",
            team_name="test-team",
            prometheus_enabled=True,
            prometheus_port=9467,
        )

        # Give server time to start
        time.sleep(0.5)

        try:
            response = requests.get("http://127.0.0.1:9467/metrics", timeout=2)
            assert response.status_code == 200
            assert "text/plain" in response.headers.get("Content-Type", "")
        finally:
            client.shutdown()

    def test_metrics_in_prometheus_format(self):
        """Metrics should be in Prometheus text format."""
        client = MCAClient(
            service_name="test-service",
            model_id="test-model",
            team_name="test-team",
            prometheus_enabled=True,
            prometheus_port=9468,
        )

        # Record some metrics
        client.record_prediction(latency=0.15)

        time.sleep(0.5)

        try:
            response = requests.get("http://127.0.0.1:9468/metrics", timeout=2)
            body = response.text

            # Check for standard Prometheus metric format
            # Should contain TYPE and HELP comments
            assert "# TYPE" in body or "# HELP" in body

            # Should contain our metric names
            assert "model_predictions_total" in body or "model_latency_seconds" in body

        finally:
            client.shutdown()

    def test_resource_attributes_as_labels(self):
        """Resource attributes should appear as Prometheus labels."""
        client = MCAClient(
            service_name="prom-test-service",
            model_id="prom-test-model",
            team_name="prom-test-team",
            prometheus_enabled=True,
            prometheus_port=9469,
        )

        client.record_prediction(latency=0.15)

        time.sleep(0.5)

        try:
            response = requests.get("http://127.0.0.1:9469/metrics", timeout=2)
            body = response.text

            # Resource attributes become labels in Prometheus
            # Check for service.name label
            assert "service_name" in body or "service.name" in body

        finally:
            client.shutdown()

    def test_port_conflict_graceful_degradation(self):
        """Should handle port conflicts gracefully (AC #5)."""
        # Start first client
        client1 = MCAClient(
            service_name="test-1",
            model_id="model-1",
            team_name="team-1",
            prometheus_enabled=True,
            prometheus_port=9470,
        )

        # Try to start second client on same port - should log warning but not crash
        client2 = MCAClient(
            service_name="test-2",
            model_id="model-2",
            team_name="team-2",
            prometheus_enabled=True,
            prometheus_port=9470,  # Same port - conflict!
        )

        # Second client should still work (just without Prometheus)
        assert client2 is not None
        client2.record_prediction(latency=0.1)  # Should not crash

        client1.shutdown()
        client2.shutdown()

    def test_multiple_metrics_exported(self):
        """Multiple metric types should be exported correctly."""
        client = MCAClient(
            service_name="multi-metric-service",
            model_id="multi-metric-model",
            team_name="test-team",
            prometheus_enabled=True,
            prometheus_port=9471,
        )

        # Record different types of metrics
        client.record_prediction(latency=0.15)
        client.record_prediction(latency=0.22)
        client.record_counter("model.custom_events_total", 5)

        time.sleep(0.5)

        try:
            response = requests.get("http://127.0.0.1:9471/metrics", timeout=2)
            body = response.text

            # Should contain multiple metrics
            assert "model_predictions_total" in body
            assert "model_latency_seconds" in body

        finally:
            client.shutdown()
