import requests

def weather_tool(location: str):
  """指定された地域の天気情報を取得"""
  # 地名から緯度・経度を取得（ジオコーディング）
  geocoding = requests.get(
    f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1")
  geocoding_data = geocoding.json()
  if not geocoding_data.get("results"):
    return {"error": f"地名 '{location}' が見つかりません"}

  # 最初の検索結果から座標情報を取得）
  data = geocoding_data["results"][0]
  lat, lon = data["latitude"], data["longitude"]

  # 取得した座標で現在の天気情報を取得
  url = ("https://api.open-meteo.com/v1/forecast?latitude="
         f"{lat}&longitude={lon}&current=temperature_2m,"
         "relative_humidity_2m,wind_speed_10m")
  weather = requests.get(url)
  current = weather.json()["current"]

  # 天気情報を返す
  return {
    "temperature": current["temperature_2m"],      # 気温（℃）
    "humidity": current["relative_humidity_2m"],   # 湿度（%）
    "wind_speed": current["wind_speed_10m"],       # 風速（m/s）
    "location": data["name"]                       # 地名
  }

# OpenAIのFunction Callingの形式でツールを定義
WEATHER_TOOL = {
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "指定された地域の現在の天気情報を取得",
    "parameters": {
      "type": "object",
      "properties": {
        "location": {"type": "string", 
                     "description": "地名（ローマ字表記）"}
      },
      "required": ["location"]
    }
  }
}
