from datetime import datetime

import requests


_HEEMSTEDE_LAT = 52.3499
_HEEMSTEDE_LON = 4.6203

_WEATHER_CODES = {
    0: ("Zonnig", "☀️"),
    1: ("Grotendeels zonnig", "🌤️"),
    2: ("Gedeeltelijk bewolkt", "⛅"),
    3: ("Bewolkt", "☁️"),
    45: ("Mist", "🌫️"),
    48: ("Mist met rijp", "🌫️"),
    51: ("Lichte motregen", "🌧️"),
    53: ("Matige motregen", "🌧️"),
    55: ("Dichte motregen", "🌧️"),
    61: ("Lichte regen", "🌧️"),
    63: ("Matige regen", "🌧️"),
    65: ("Hevige regen", "🌧️"),
    71: ("Lichte sneeuw", "🌨️"),
    73: ("Matige sneeuw", "🌨️"),
    75: ("Hevige sneeuw", "🌨️"),
    95: ("Onweer", "⛈️"),
    96: ("Onweer met hagel", "⛈️"),
    99: ("Zwaar onweer met hagel", "⛈️"),
}

_WEEKDAYS = ["Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"]
_MONTHS = [
    "januari",
    "februari",
    "maart",
    "april",
    "mei",
    "juni",
    "juli",
    "augustus",
    "september",
    "oktober",
    "november",
    "december",
]


def resolve_forecast_date(raw_value: str | None):
    value = str(raw_value or "").strip().lower()
    if not value or value in {"today", "vandaag"}:
        return datetime.now().date()
    return datetime.strptime(value, "%Y-%m-%d").date()


def dutch_long_date(target_date) -> str:
    return f"{_WEEKDAYS[target_date.weekday()]} {target_date.day} {_MONTHS[target_date.month - 1]}"


def fetch_heemstede_forecast(raw_value: str | None) -> dict:
    target_date = resolve_forecast_date(raw_value)
    url = (
        "https://api.open-meteo.com/v1/forecast"
        f"?latitude={_HEEMSTEDE_LAT}&longitude={_HEEMSTEDE_LON}"
        "&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max,weather_code,sunrise,sunset,wind_speed_10m_max"
        "&timezone=Europe/Amsterdam"
        f"&start_date={target_date}&end_date={target_date}"
    )
    response = requests.get(url, timeout=15)
    response.raise_for_status()
    data = response.json()
    daily = data["daily"]
    weather_code = int(daily["weather_code"][0])
    condition, emoji = _WEATHER_CODES.get(weather_code, ("Onbekend weertype", "🌤️"))
    temp_min = round(float(daily["temperature_2m_min"][0]))
    temp_max = round(float(daily["temperature_2m_max"][0]))
    wind_kmph = round(float(daily.get("wind_speed_10m_max", [0])[0]))
    sunrise = str(daily["sunrise"][0]).split("T")[1][:5] if daily.get("sunrise") else "07:00"
    sunset = str(daily["sunset"][0]).split("T")[1][:5] if daily.get("sunset") else "19:00"
    return {
        "date": target_date,
        "date_iso": str(target_date),
        "date_label": dutch_long_date(target_date),
        "temp_min": temp_min,
        "temp_max": temp_max,
        "temp_avg": round((temp_min + temp_max) / 2),
        "rain_chance": int(daily["precipitation_probability_max"][0]),
        "wind_kmph": wind_kmph,
        "weather_code": weather_code,
        "condition": condition,
        "condition_display": f"{condition} {emoji}".strip(),
        "sunrise": sunrise,
        "sunset": sunset,
    }