"""api_integration_tools_demo.py — get_weather @tool + Open-Meteo GET"""

from dotenv import load_dotenv
import requests
from langchain.agents import create_agent
from langchain.tools import tool

load_dotenv()

GEOCODE_URL = "https://geocoding-api.open-meteo.com/v1/search"
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"


def fetch_weather(city: str) -> str:
    city = city.strip()
    if not city:
        return "City name required"

    try:
        geo_resp = requests.get(
            GEOCODE_URL, params={"name": city, "count": 1}, timeout=10
        )
        geo_resp.raise_for_status()
        results = geo_resp.json().get("results") or []
        if not results:
            return f"No coordinates for '{city}'."

        lat = results[0]["latitude"]
        lon = results[0]["longitude"]
        name = results[0].get("name", city)

        forecast_resp = requests.get(
            FORECAST_URL,
            params={
                "latitude": lat,
                "longitude": lon,
                "current": "temperature_2m,relative_humidity_2m",
            },
            timeout=10,
        )
        forecast_resp.raise_for_status()
        current = forecast_resp.json()["current"]
        temp = current["temperature_2m"]
        humidity = current["relative_humidity_2m"]
        return f"{name}: {temp}°C, humidity {humidity}%"
    except requests.RequestException as exc:
        return f"API request failed: {exc}"


@tool("get_weather")
def get_weather(city: str) -> str:
    """Get current temperature and humidity for a city."""
    return fetch_weather(city)


agent = create_agent(model="openai:gpt-4o-mini", tools=[get_weather])

questions = [
    "What's the weather in Kolkata today? Use get_weather.",
    "What's the weather in Berlin? Use get_weather.",
]

for question in questions:
    print(f"\nQuestion: {question}")
    result = agent.invoke({"messages": [{"role": "user", "content": question}]})
    for msg in result["messages"]:
        if getattr(msg, "type", None) == "tool":
            print(f"get_weather returned: {msg.content}")
    print(f"Answer: {result['messages'][-1].content}")