# Import the module.
import python_weather
import asyncio
from datetime import date, datetime, timedelta



async def get_weather_for_location(location: str):


    now = datetime.now().time()
    today = date.today()    

  
    # Declare the client. The measuring unit used defaults to the metric system (celcius, km/h, etc.)
    async with python_weather.Client(unit=python_weather.METRIC) as client:
        
        # Fetch a weather forecast from a city.
        weather = await client.get(location) ##e. g. Brackenheim

        # weather ist dein Forecast-Objekt von python_weather
        today_forecast = next(
            (daily for daily in weather if daily.date == today),
            None
        )

        def closest_hourly(hourlies, now_time):
            closest = None
            min_diff = None
            for hourly in hourlies:
                # Differenz zwischen aktueller Uhrzeit und Forecast-Stunde
                diff = abs(
                    datetime.combine(date.today(), hourly.time) -
                    datetime.combine(date.today(), now_time)
                )
                if min_diff is None or diff < min_diff:
                    min_diff = diff
                    closest = hourly
            return closest

        current_hourly = closest_hourly(today_forecast.hourly_forecasts, now)

        KIND_TO_DE = {
        "SUNNY": "sonnig",
        "PARTLY_CLOUDY": "teilweise bewölkt",
        "CLOUDY": "bewölkt",
        "VERY_CLOUDY": "stark bewölkt",
        "FOG": "nebelig",
        "LIGHT_SHOWERS": "nach leichtem Regen",
        "LIGHT_SLEET_SHOWERS": "nach leichtem Schneeregen",
        "LIGHT_SLEET": "nach leichtem Schneeregen",
        "THUNDERY_SHOWERS": "nach Gewitterregen",
        "LIGHT_SNOW": "nach leichtem Schneefall",
        "HEAVY_SNOW": "nach starkem Schneefall",
        "LIGHT_RAIN": "nach leichtem Regen",
        "HEAVY_SHOWERS": "nach starken Schauer",
        "HEAVY_RAIN": "nach starkem Regen",
        "LIGHT_SNOW_SHOWERS": "nach leichten Schneeschauern",
        "HEAVY_SNOW_SHOWERS": "nach starken Schneeschauern",
        "THUNDERY_HEAVY_RAIN": "nach starken Gewitterregen",
        "THUNDERY_SNOW_SHOWERS": "nach starken Gewitterschnee",
        }

        wetterlage = KIND_TO_DE.get(current_hourly.kind.name, "unbegständig")
        temperatur = current_hourly.temperature
        

        return {
            "location": weather.location,
            "temperatur": temperatur,
            "wetterlage": wetterlage
        }
    

#print(f"Aktuell sind es in {ort} {temperatur} Grad und die Wetterlage sieht {wetterlage} aus.")


#if __name__ == '__main__':
#  asyncio.run(main())