"""
ccMonet MCP SSE Server (Simplified Version)

This server uses the Model Context Protocol with Server-Sent Events (SSE) using FastMCP's built-in transport.
"""
from typing import Any, Dict, AsyncGenerator
import httpx
import logging
from mcp.server.fastmcp import FastMCP

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Import configuration
from mcp_ccmonet.ccmonet_server.config import (
    API_URL, 
    API_HEADERS, 
    SERVER_NAME, 
    REQUEST_TIMEOUT
)
from mcp_ccmonet import __version__

# Initialize FastMCP
mcp = FastMCP(SERVER_NAME)

# Set server version information
mcp._mcp_server.version = __version__

async def make_api_request(payload: Dict[str, Any]) -> AsyncGenerator[Dict[str, Any], None]:
    """Send a request to the API and stream the response

    Args:
        payload: The request body to send

    Yields:
        The API response content chunks
    """
    async with httpx.AsyncClient() as client:
        try:
            async with client.stream(
                'POST',
                API_URL,
                headers=API_HEADERS,
                json=payload,
                timeout=REQUEST_TIMEOUT
            ) as response:
                response.raise_for_status()
                async for chunk in response.aiter_json():
                    yield chunk
        except Exception as e:
            yield {"error": f"API request failed: {str(e)}"}

@mcp.tool()
async def fetch(id: str) -> str:
    """
    Fetch bill detail by id.
    """
    logger.info(f"fetch函数被调用，参数id: {id}")
    return "bill detail:" + id

@mcp.tool()
async def search(query: str) -> str:
    """Search for bill detail by query.
    """
    logger.info(f"search函数被调用，参数query: {query}")
    return "bill:" + query

    # message = query

    # payload = {
    #     "message": message,
    #     "thread_id": None,
    #     "response_message_id": None
    # }
    
    # async for chunk in make_api_request(payload):
    #     if "error" in chunk:
    #         yield f"Error: {chunk['error']}"
    #     elif "message" in chunk:
    #         yield chunk['message']
    #     else:
    #         yield str(chunk)

# 为uvicorn暴露SSE应用对象
app = mcp.sse_app

if __name__ == "__main__":
    # 使用 FastMCP 内置的 SSE 传输！
    mcp.run(transport='sse') 