#!/usr/bin/env python3
"""
Open-Meteo Wetter-Abfrage (stdlib-only, kein API-Key nötig)
Usage: python3 weather_openmeteo.py [LAT] [LON] [TIMEZONE]

Beispiele:
  python3 weather_openmeteo.py                    # Wien (Default)
  python3 weather_openmeteo.py 52.52 13.405 Europe/Berlin  # Berlin
  python3 weather_openmeteo.py 40.7128 -74.0060 America/New_York  # NYC
"""

import urllib.request
import json
import sys
from datetime import datetime

# WMO Weather Code zu Text + Emoji
WEATHER_CODES = {
    0: ("Klarer Himmel", "☀️"),
    1: ("Überwiegend klar", "🌤️"),
    2: ("Teilweise bewölkt", "⛅"),
    3: ("Bewölkt", "☁️"),
    45: ("Nebel", "🌫️"),
    48: ("Ablagerender Reifnebel", "🌫️"),
    51: ("Leichter Nieselregen", "🌦️"),
    53: ("Mäßiger Nieselregen", "🌧️"),
    55: ("Starker Nieselregen", "🌧️"),
    61: ("Leichter Regen", "🌧️"),
    63: ("Mäßiger Regen", "🌧️"),
    65: ("Starker Regen", "🌧️"),
    71: ("Leichter Schneefall", "🌨️"),
    73: ("Mäßiger Schneefall", "🌨️"),
    75: ("Starker Schneefall", "❄️"),
    80: ("Leichte Regenschauer", "🌦️"),
    81: ("Mäßige Regenschauer", "🌧️"),
    82: ("Starke Regenschauer", "⛈️"),
    95: ("Gewitter", "⛈️"),
    96: ("Gewitter mit Hagel", "⛈️"),
    99: ("Schweres Gewitter mit Hagel", "⛈️"),
}


def get_weather(lat=48.2082, lon=16.3738, timezone="Europe/Vienna"):
    """Fetch current weather from Open-Meteo API."""
    url = (
        f"https://api.open-meteo.com/v1/forecast?"
        f"latitude={lat}&longitude={lon}"
        f"&current=temperature_2m,relative_humidity_2m"
        f",apparent_temperature,weather_code,wind_speed_10m,precipitation"
        f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
        f"&timezone={timezone}"
    )

    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=15) as resp:
        data = json.loads(resp.read().decode())

    current = data["current"]
    daily = data["daily"]

    code = current.get("weather_code", 0)
    weather_text, emoji = WEATHER_CODES.get(code, ("Unbekannt", "❓"))

    return {
        "location": f"{lat}, {lon}",
        "timezone": timezone,
        "timestamp": datetime.now().strftime("%d.%m.%Y %H:%M"),
        "weather_emoji": emoji,
        "weather_text": weather_text,
        "temperature": current["temperature_2m"],
        "feels_like": current["apparent_temperature"],
        "humidity": current["relative_humidity_2m"],
        "wind_speed": current["wind_speed_10m"],
        "precipitation": current["precipitation"],
        "today_max": daily["temperature_2m_max"][0],
        "today_min": daily["temperature_2m_min"][0],
        "today_rain": daily["precipitation_sum"][0],
    }


def format_output(w):
    """Format weather data for display."""
    lines = [
        f"🌍 Wetter — {w['timestamp']} ({w['timezone']})",
        f"",
        f"{w['weather_emoji']} {w['weather_text']}",
        f"🌡️ Temperatur: {w['temperature']}°C (gefühlt {w['feels_like']}°C)",
        f"📈 Max/Min heute: {w['today_max']}°C / {w['today_min']}°C",
        f"💧 Luftfeuchtigkeit: {w['humidity']}%",
        f"💨 Wind: {w['wind_speed']} km/h",
        f"🌧️ Niederschlag (heute): {w['today_rain']} mm",
    ]
    return "\n".join(lines)


def main():
    args = sys.argv[1:]
    
    if len(args) >= 2:
        lat = float(args[0])
        lon = float(args[1])
    else:
        lat, lon = 48.2082, 16.3738  # Wien default
    
    timezone = args[2] if len(args) >= 3 else "Europe/Vienna"
    
    try:
        weather = get_weather(lat, lon, timezone)
        print(format_output(weather))
    except Exception as e:
        print(f"❌ Fehler: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
