import pytest
from unittest.mock import MagicMock, patch, AsyncMock
from mcp.types import TextContent
from image_mcp_server.server import ImageMCPServer

@pytest.fixture
def mock_client():
    with patch('image_mcp_server.server.get_client') as mock:
        client = AsyncMock()
        mock.return_value = client
        yield client

@pytest.fixture
def mock_image_handler():
    with patch('image_mcp_server.server.image_handler') as mock:
        yield mock

@pytest.fixture
def server():
    return ImageMCPServer()

@pytest.mark.asyncio
async def test_edit_image_success(server, mock_client, mock_image_handler):
    # Setup mocks
    mock_image_handler.process_image_input.return_value = ("base64data", "image/jpeg")
    
    mock_client.edit_image.return_value = {
        "success": True,
        "url": "https://example.com/edited.png",
        "revised_prompt": "revised prompt"
    }

    # Call tool
    arguments = {
        "images": ["test.jpg"],
        "prompt": "make it better"
    }
    result = await server._handle_edit_image(arguments)

    # Verify
    assert len(result) == 1
    assert isinstance(result[0], TextContent)
    assert "https://example.com/edited.png" in result[0].text
    assert "revised prompt" in result[0].text
    
    # Verify client call
    mock_client.edit_image.assert_called_once()
    call_args = mock_client.edit_image.call_args[1]
    assert call_args["prompt"] == "make it better"
    assert len(call_args["images"]) == 1
    assert call_args["images"][0]["image"] == "data:image/jpeg;base64,base64data"

@pytest.mark.asyncio
async def test_edit_image_missing_args(server):
    # Missing images
    result = await server._handle_edit_image({"prompt": "test"})
    assert "错误: 缺少 images 参数" in result[0].text

    # Missing prompt
    result = await server._handle_edit_image({"images": ["test.jpg"]})
    assert "错误: 缺少 prompt 参数" in result[0].text

@pytest.mark.asyncio
async def test_edit_image_api_error(server, mock_client, mock_image_handler):
    # Setup mocks
    mock_image_handler.process_image_input.return_value = ("base64data", "image/jpeg")
    mock_client.edit_image.return_value = {
        "success": False,
        "error": "API Error"
    }

    # Call tool
    arguments = {
        "images": ["test.jpg"],
        "prompt": "test"
    }
    result = await server._handle_edit_image(arguments)

    # Verify
    assert "编辑失败: API Error" in result[0].text
