
#tools.weather.py
import json
import requests


# Load JSON data from a file
# https://gist.github.com/stellasphere/9490c195ed2b53c707087c8c2db4ec0c
with open("src/weather_codes.json", "r", encoding="utf-8") as file:
    WEATHER_CODES = json.load(file)

def get_weather(city):
    """Fetches the current weather for a given city using Open-Meteo."""
    geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1&format=json"
    try:
        geo_response = requests.get(geocoding_url)
        geo_data = geo_response.json()
        if "results" in geo_data and geo_data["results"]:
            lat = geo_data["results"][0]["latitude"]
            lon = geo_data["results"][0]["longitude"]
            weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current_weather=true"
            weather_response = requests.get(weather_url)
            weather_data = weather_response.json()
            if "current_weather" in weather_data:
                temp = weather_data["current_weather"]["temperature"]
                condition_code = str(weather_data["current_weather"].get("weathercode", 0))  # Convert to string
                is_day = weather_data["current_weather"].get("is_day", 1)  # 1 = day, 0 = night
                
                # Retrieve weather description and image
                weather_info = WEATHER_CODES.get(condition_code, {"day": {"description": "Unknown", "image": ""}})
                time_of_day = "day" if is_day == 1 else "night"
                description = weather_info.get(time_of_day, {"description": "Unknown", "image": ""})

                return f"{description['description']} weather and {temp}°C"  # {description['image']}
        return "Weather data not available."
    except Exception as e:
        return f"Failed to retrieve weather data: {e}"