import pytest
import os
import base64
from unittest.mock import MagicMock
from azure_maps_mcp import get_static_map, GetStaticMapInput

# Read API Key
try:
    with open(".apikey", "r") as f:
        API_KEY = f.read().strip()
except FileNotFoundError:
    API_KEY = "dummy_key" # Fallback if file not found, though tests will likely fail on API call

@pytest.fixture
def mock_context():
    return MagicMock()

@pytest.fixture(autouse=True)
def setup_env():
    os.environ["AZURE_MAPS_SUBSCRIPTION_KEY"] = API_KEY
    yield
    if "AZURE_MAPS_SUBSCRIPTION_KEY" in os.environ:
        del os.environ["AZURE_MAPS_SUBSCRIPTION_KEY"]

@pytest.mark.asyncio
async def test_get_static_map_basic(mock_context):
    """Test retrieving a basic map with center point and zoom."""
    params = GetStaticMapInput(
        centerPoint="47.610,-122.107",
        zoomLevel=12,
        mapSize="400,400"
    )
    
    result = await get_static_map(params, mock_context)
    
    if "error" in result:
        pytest.fail(f"Tool returned error: {result['error']}")
    
    assert result["width"] == "400"
    assert result["height"] == "400"
    assert result["image_data_base64"] is not None
    
    # Verify it's valid base64
    img_data = base64.b64decode(result["image_data_base64"])
    assert len(img_data) > 0
    assert result["format"] == "png"

@pytest.mark.asyncio
async def test_get_static_map_with_pins(mock_context):
    """Test retrieving a map with pushpins."""
    # Using the example format from the code: style;location;title
    # Location must be 'lat,lon'
    params = GetStaticMapInput(
        centerPoint="47.610,-122.107",
        zoomLevel=12,
        pushpins=["default;47.615,-122.110;Pin1", "default;47.605,-122.100;Pin2"]
    )
    
    result = await get_static_map(params, mock_context)
    
    if "error" in result:
        pytest.fail(f"Tool returned error: {result['error']}")

    assert result["image_data_base64"] is not None
    img_data = base64.b64decode(result["image_data_base64"])
    assert len(img_data) > 0

@pytest.mark.asyncio
async def test_get_static_map_invalid_center(mock_context):
    """Test error handling for invalid center point."""
    params = GetStaticMapInput(
        centerPoint="invalid_lat_lon",
        zoomLevel=10
    )
    
    result = await get_static_map(params, mock_context)
    
    # The tool returns an error dict, not raises an exception (based on code analysis)
    assert "error" in result
    assert "centerPoint must be" in result["error"]
