#!/usr/bin/env python3
"""Frankfurter MCP server (ILLUSTRATIVE SAMPLE — agent-ready package demo).

Exposes the public, no-auth Frankfurter exchange-rates API (https://frankfurter.dev) as agent tools
so an AI agent (Claude, Cursor, ...) can look up and convert currencies. Not affiliated with Frankfurter.

Run:  pip install "mcp[cli]" httpx  &&  python frankfurter_mcp.py
This is a sample deliverable demonstrating format/quality — read-only tools only (no writes to worry about).
"""
from typing import Optional
import httpx
from mcp.server.fastmcp import FastMCP

API = "https://api.frankfurter.dev/v1"
mcp = FastMCP("frankfurter")


def _get(path: str, params: dict) -> dict:
    params = {k: v for k, v in params.items() if v}
    r = httpx.get(f"{API}{path}", params=params, timeout=15)
    r.raise_for_status()
    return r.json()


@mcp.tool()
def get_latest_rates(base: str = "EUR", symbols: str = "") -> dict:
    """Get the most recent exchange rates.

    Args:
        base: base currency (ISO 4217, e.g. "USD"). Defaults to EUR.
        symbols: optional comma-separated target currencies (e.g. "USD,GBP"). Empty = all.
    """
    return _get("/latest", {"base": base, "symbols": symbols})


@mcp.tool()
def convert(amount: float, from_currency: str, to_currency: str) -> dict:
    """Convert an amount from one currency to another at the latest rate.

    Args:
        amount: how much to convert.
        from_currency: source currency (ISO 4217).
        to_currency: target currency (ISO 4217).
    """
    data = _get("/latest", {"base": from_currency, "symbols": to_currency})
    rate = data.get("rates", {}).get(to_currency.upper())
    if rate is None:
        return {"error": f"no rate for {from_currency}->{to_currency}"}
    return {"amount": amount, "from": from_currency.upper(), "to": to_currency.upper(),
            "rate": rate, "result": round(amount * rate, 4), "date": data.get("date")}


@mcp.tool()
def get_historical_rates(date: str, base: str = "EUR", symbols: str = "") -> dict:
    """Get exchange rates for a specific date (YYYY-MM-DD).

    Weekends/holidays resolve to the most recent prior working day.
    """
    return _get(f"/{date}", {"base": base, "symbols": symbols})


@mcp.tool()
def list_currencies() -> dict:
    """List supported currency codes and their names."""
    return _get("/currencies", {})


if __name__ == "__main__":
    mcp.run()
