import httpx
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Currency Server")

BASE_URL = "https://open.er-api.com/v6/latest"

@mcp.tool()
async def get_exchange_rate(base: str, target: str) -> str:
    """
    Get exchange rate between two currencies.
    Args:
        base: base currency code e.g. USD, EUR, GBP, INR
        target: target currency code e.g. USD, EUR, GBP, INR
    """
    async with httpx.AsyncClient() as client:
        response = await client.get(f"{BASE_URL}/{base.upper()}")
        data = response.json()

    if data.get("result") != "success":
        return f"Error: Could not fetch rates for {base}"

    rate = data["rates"].get(target.upper())
    if not rate:
        return f"Error: Currency '{target}' not found"

    return f"1 {base.upper()} = {rate} {target.upper()}"


@mcp.tool()
async def convert_currency(amount: float, base: str, target: str) -> str:
    """
    Convert amount from one currency to another.
    Args:
        amount: amount to convert
        base: source currency code
        target: target currency code
    """
    async with httpx.AsyncClient() as client:
        response = await client.get(f"{BASE_URL}/{base.upper()}")
        data = response.json()

    if data.get("result") != "success":
        return f"Error: Could not fetch rates for {base}"

    rate = data["rates"].get(target.upper())
    if not rate:
        return f"Error: Currency '{target}' not found"

    converted = round(amount * rate, 2)
    return f"{amount} {base.upper()} = {converted} {target.upper()}"


def main():
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()