"""
PyPI Package Verification Tests

These tests verify that the mca-sdk package is properly installed from PyPI
and can be used without local path manipulation.

Installation:
    pip install mca-sdk

Usage:
    pytest tests/test_pypi_package.py -v
"""

import subprocess
import sys
import pytest


def test_package_installed():
    """Verify mca-sdk is installed from PyPI"""
    result = subprocess.run(
        [sys.executable, "-m", "pip", "show", "mca-sdk"], capture_output=True, text=True
    )
    assert result.returncode == 0, "mca-sdk package is not installed"
    assert (
        "mca-sdk" in result.stdout or "mca_sdk" in result.stdout
    ), "Package name not found in pip show output"
    assert "Version:" in result.stdout, "Version info not found"


def test_package_version():
    """Verify package version matches expected"""
    result = subprocess.run(
        [sys.executable, "-m", "pip", "show", "mca-sdk"], capture_output=True, text=True
    )
    assert result.returncode == 0
    # Extract version from output
    for line in result.stdout.split("\n"):
        if line.startswith("Version:"):
            version = line.split(":", 1)[1].strip()
            # Version should be 0.3.0 or higher (SDK is pre-1.0)
            major, minor, patch = version.split(".")
            assert int(major) >= 0, f"Expected major version >= 0, got {version}"
            break
    else:
        pytest.fail("Version not found in pip show output")


def test_import_works():
    """Verify imports work without local path manipulation"""
    # This should work if package is installed
    from mca_sdk import MCAClient

    assert MCAClient is not None, "MCAClient import failed"


def test_import_integrations():
    """Verify integration modules can be imported"""
    from mca_sdk.integrations import create_genai_client, VendorBridge

    assert create_genai_client is not None
    assert VendorBridge is not None


def test_create_client():
    """Verify client can be instantiated"""
    from mca_sdk import MCAClient

    client = MCAClient(
        service_name="test-service",
        model_id="test-001",
        team_name="test-team",
        collector_endpoint="http://localhost:4318",
    )
    assert client is not None, "Client instantiation failed"
    assert hasattr(client, "meter"), "Client missing meter attribute"
    assert hasattr(client, "logger"), "Client missing logger attribute"
    assert hasattr(client, "tracer"), "Client missing tracer attribute"

    # Clean up
    client.shutdown()


def test_create_metrics():
    """Verify metrics can be created"""
    from mca_sdk import MCAClient

    client = MCAClient(
        service_name="test-metrics",
        model_id="test-002",
        team_name="test-team",
        collector_endpoint="http://localhost:4318",
    )

    # Create counter
    counter = client.meter.create_counter("test.counter", description="Test counter")
    assert counter is not None, "Counter creation failed"

    # Create histogram
    histogram = client.meter.create_histogram(
        "test.histogram", description="Test histogram", unit="ms"
    )
    assert histogram is not None, "Histogram creation failed"

    # Record values
    counter.add(1, {"test": "true"})
    histogram.record(42.5)

    # Clean up
    client.shutdown()


def test_dependencies_installed():
    """Verify core dependencies are installed with mca-sdk"""
    required_packages = [
        "opentelemetry-api",
        "opentelemetry-sdk",
        "opentelemetry-exporter-otlp-proto-http",
        "pyyaml",
    ]

    for package in required_packages:
        result = subprocess.run(
            [sys.executable, "-m", "pip", "show", package],
            capture_output=True,
            text=True,
        )
        assert result.returncode == 0, f"Required dependency '{package}' is not installed"


def test_optional_genai_dependencies():
    """Check if genai optional dependencies are available"""
    try:
        import litellm

        genai_installed = True
    except ImportError:
        genai_installed = False

    if genai_installed:
        # If litellm is installed, genai integration should work
        from mca_sdk.integrations import create_genai_client

        assert create_genai_client is not None


def test_optional_vendor_dependencies():
    """Check if vendor optional dependencies are available"""
    try:
        import requests

        vendor_installed = True
    except ImportError:
        vendor_installed = False

    if vendor_installed:
        # If requests is installed, vendor integration should work
        from mca_sdk.integrations import VendorBridge

        assert VendorBridge is not None


def test_no_local_imports():
    """Verify that imports don't rely on local repository structure"""
    import mca_sdk
    import inspect

    # Get the location of the installed package
    mca_location = inspect.getfile(mca_sdk)

    # Skip in development environment (when running from source tree)
    if "mca-prototype" in mca_location:
        pytest.skip("Running in development mode with local source")

    # In CI/production, verify package is from site-packages
    assert (
        "site-packages" in mca_location or "dist-packages" in mca_location
    ), f"mca_sdk is being imported from local repository, not from installed package: {mca_location}"


if __name__ == "__main__":
    # Run tests if executed directly
    pytest.main([__file__, "-v"])
