import asyncio
import logging
import os
import sys

import httpx
from fastmcp import FastMCP

logger = logging.getLogger(__name__)
logging.basicConfig(format="[%(levelname)s]: %(message)s", level=logging.INFO)

mcp = FastMCP("Currency MCP Server 💵")


@mcp.tool()
def get_exchange_rate(
    currency_from: str = "USD",
    currency_to: str = "EUR",
    currency_date: str = "latest",
):
    """Use this to get current exchange rate.

    Args:
        currency_from: The currency to convert from (e.g., "USD").
        currency_to: The currency to convert to (e.g., "EUR").
        currency_date: The date for the exchange rate or "latest". Defaults to "latest".

    Returns:
        A dictionary containing the exchange rate data, or an error message if the request fails.
    """
    logger.info(
        f"--- 🛠️ Tool: get_exchange_rate called for converting {currency_from} to {currency_to} ---"
    )
    try:
        response = httpx.get(
            f"https://api.frankfurter.app/{currency_date}",
            params={"from": currency_from, "to": currency_to},
        )
        response.raise_for_status()

        data = response.json()
        if "rates" not in data:
            logger.error(f"❌ rates not found in response: {data}")
            return {"error": "Invalid API response format."}
        logger.info(f"✅ API response: {data}")
        return data
    except httpx.HTTPError as e:
        logger.error(f"❌ API request failed: {e}")
        return {"error": f"API request failed: {e}"}
    except ValueError:
        logger.error("❌ Invalid JSON response from API")
        return {"error": "Invalid JSON response from API."}


def main():
    """Main entry point for the MCP server."""
    # 支持stdio协议作为主要启动方式
    # 可以通过环境变量TRANSPORT选择传输协议
    transport = os.getenv("TRANSPORT", "stdio")

    if transport == "stdio":
        # stdio模式 - 适用于MCP客户端
        logger.info("🚀 MCP server starting in stdio mode")
        mcp.run(transport="stdio")
    elif transport == "http":
        # HTTP模式 - 适用于Web服务
        port = int(os.getenv("PORT", 8080))
        logger.info(f"🚀 MCP server starting in HTTP mode on port {port}")
        asyncio.run(
            mcp.run_async(
                transport="http",
                host="0.0.0.0",
                port=port,
            )
        )
    else:
        logger.error(f"❌ Unsupported transport: {transport}")
        sys.exit(1)


if __name__ == "__main__":
    main()