"""Weather awareness plugin — aktuelles Wetter über wttr.in (kein API-Key nötig)."""
from __future__ import annotations

import logging

import httpx

from hivemind.plugins.base import Plugin, capability

log = logging.getLogger(__name__)

# wttr.in JSON API — kein API-Key, keine Registrierung nötig
WTTR_URL = "https://wttr.in/{location}?format=j1&lang=de"

WEATHER_KEYWORDS = {
    # Deutsch
    "wetter", "temperatur", "grad", "regen", "schnee", "sonne", "sonnig",
    "wind", "sturm", "gewitter", "nebel", "bewölkt", "wolken", "wolkig",
    "kalt", "warm", "heiß", "kühl", "frostig", "eis", "hagel", "frost",
    "wettervorhersage", "vorhersage", "meteorologie", "Wetterbericht", 
    "wetterlage", "wetterbedingungen", "wetterinfo", "wetterinformationen",
    "regnen", "schneien", "sonnenschein", "windig", "stürmisch", "gewittert",
    "neblig", "bewölkung", "kälte", "wärme", "hitze", "kühle", "frostige", 
    "eisig", "hageln", "frostig", "kälter", "wärmer", "heißer", "kühler", 
    "frostiger", "eisiger", "hageliger",
    # Englisch
    "weather", "temperature", "rain", "snow", "sunny", "cloudy", "forecast",
    "humid", "humidity", "wind", "storm", "thunder", "fog", "hail",
    "cold", "hot", "warm", "cool", "freezing",
}


class WeatherPlugin(Plugin):
    """Plugin that fetches current weather from wttr.in."""

    name = "weather"
    version = "0.1.0"
    description = "Provides current weather information for any location via wttr.in"

    @capability("Get current weather for a location (city name or 'auto' for IP-based detection)")
    async def get_weather(self, location: str = "auto") -> str:
        """Fetch and format current weather conditions.

        Args:
            location: City name (e.g. 'Berlin'), or 'auto' for IP-based geolocation.
        """
        loc = location.strip() if location and location.strip() else "auto"
        url = WTTR_URL.format(location=loc)
        try:
            async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client:
                resp = await client.get(
                    url, headers={"User-Agent": "HiveMind/0.1 weather-plugin"}
                )
                resp.raise_for_status()
                data = resp.json()

            current = data["current_condition"][0]

            # Location display name
            area_info = data.get("nearest_area", [{}])[0]
            area_name = area_info.get("areaName", [{}])[0].get("value", loc)
            country = area_info.get("country", [{}])[0].get("value", "")
            location_str = f"{area_name}, {country}" if country else area_name

            # Weather values
            temp_c = current.get("temp_C", "?")
            feels_like = current.get("FeelsLikeC", "?")
            # Try German description first, fall back to English
            desc_list = current.get("lang_de") or current.get("weatherDesc", [{}])
            desc = desc_list[0].get("value", "unbekannt") if desc_list else "unbekannt"
            humidity = current.get("humidity", "?")
            wind_kmph = current.get("windspeedKmph", "?")
            wind_dir = current.get("winddir16Point", "?")
            visibility = current.get("visibility", "?")
            uv_index = current.get("uvIndex", "?")

            return (
                f"Wetter in {location_str}:\n"
                f"  Temperatur: {temp_c}°C (gefühlt {feels_like}°C)\n"
                f"  Beschreibung: {desc}\n"
                f"  Luftfeuchtigkeit: {humidity}%\n"
                f"  Wind: {wind_kmph} km/h aus {wind_dir}\n"
                f"  Sichtweite: {visibility} km  |  UV-Index: {uv_index}"
            )

        except Exception as e:
            log.warning("WeatherPlugin.get_weather(%s) error: %s", loc, e)
            return f"Wetterdaten konnten nicht abgerufen werden: {e}"

    @capability("Check if a query is asking about weather conditions")
    async def is_weather_query(self, query: str) -> bool:
        """Return True when the query is weather-related."""
        q = query.lower()
        return any(kw in q for kw in WEATHER_KEYWORDS)


PLUGIN_CLASS = WeatherPlugin
