import httpx
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("Daily Utils Server")


@mcp.tool()
async def get_joke_of_the_day() -> str:
    """Get a random joke from the official joke API.

    Returns:
        A formatted joke with setup and punchline.
    """
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get("https://official-joke-api.appspot.com/random_joke")
            response.raise_for_status()
            joke_data = response.json()

            setup = joke_data.get("setup", "")
            punchline = joke_data.get("punchline", "")

            return f"😄 {setup}\n\n{punchline}"
        except Exception as e:
            return f"Error fetching joke: {str(e)}"


@mcp.tool()
async def get_weather(latitude: float, longitude: float) -> str:
    """Get current weather data for a location using latitude and longitude.

    Args:
        latitude: Latitude of the location (e.g., 52.52 for Berlin)
        longitude: Longitude of the location (e.g., 13.41 for Berlin)

    Returns:
        Formatted weather summary with temperature, wind speed, and humidity.
    """
    url = (
        f"https://api.open-meteo.com/v1/forecast"
        f"?latitude={latitude}&longitude={longitude}"
        f"&current=temperature_2m,wind_speed_10m,relative_humidity_2m,weather_code"
    )

    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url)
            response.raise_for_status()
            weather_data = response.json()

            current = weather_data.get("current", {})
            temp = current.get("temperature_2m")
            wind_speed = current.get("wind_speed_10m")
            humidity = current.get("relative_humidity_2m")
            weather_code = current.get("weather_code")

            return (
                f"🌤️ Weather Summary:\n"
                f"Temperature: {temp}°C\n"
                f"Wind Speed: {wind_speed} m/s\n"
                f"Humidity: {humidity}%\n"
                f"Weather Code: {weather_code}"
            )
        except Exception as e:
            return f"Error fetching weather: {str(e)}"


@mcp.tool()
async def predict_age_by_name(name: str) -> str:
    """Predict the age associated with a given name using the Agify API.

    Args:
        name: The first name to predict age for (e.g., "Michael", "Sarah")

    Returns:
        Predicted age and confidence count for the name.
    """
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(f"https://api.agify.io/?name={name}")
            response.raise_for_status()
            age_data = response.json()

            predicted_name = age_data.get("name", name)
            age = age_data.get("age")
            count = age_data.get("count", 0)

            if age is None:
                return f"No age prediction available for the name '{predicted_name}'"

            return (
                f"👤 Age Prediction for '{predicted_name}':\n"
                f"Predicted Age: {age} years\n"
                f"Based on {count:,} data samples"
            )
        except Exception as e:
            return f"Error predicting age: {str(e)}"
