#!/usr/bin/env python3
import requests
import json
import sys
import os

# CONFIGURATION
import requests
import json
import sys
import os

# CONFIGURATION
API_KEY = "ebb6d6ea53be021675e3276f7fe8cd77"  # Remplacez par votre clé OpenWeatherMap
CITY = "Paris"                 # Ville par défaut si non précisée
UNITS = "metric"               # "metric" pour °C, "imperial" pour °F
LANG = "fr"                    # "fr" pour français, "en" pour anglais

def get_weather():
    if not API_KEY or API_KEY == "VOTRE_CLE_API_ICI":
        return {"text": "❌ Clé API manquante", "class": "weather-error", "tooltip": "Configurez la clé API dans le script."}

    try:
        url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}&units={UNITS}&lang={LANG}"
        response = requests.get(url, timeout=5)
        
        if response.status_code == 401:
            return {"text": "❌ Clé API invalide", "class": "weather-error", "tooltip": "Erreur 401: Vérifiez votre clé OpenWeatherMap."}
        
        if response.status_code == 404:
            return {"text": "❌ Ville introuvable", "class": "weather-error", "tooltip": f"La ville '{CITY}' n'a pas été trouvée."}
        
        if response.status_code != 200:
            return {"text": "⚠️ Erreur API", "class": "weather-error", "tooltip": f"Code {response.status_code}: {response.text}"}

        data = response.json()
        
        # Extraction des données
        temp = data["main"]["temp"]
        description = data["weather"][0]["description"].capitalize()
        icon_code = data["weather"][0]["icon"]
        wind_speed = data["wind"]["speed"]
        
        # Mapping des icônes OpenWeather vers les icônes Waybar standard (ou Unicode)
        # OpenWeather utilise des codes comme "10d", "01n". Waybar utilise souvent des noms ou des emojis.
        # Ici, nous utilisons des emojis pour une compatibilité universelle.
        icon = "☁️"
        if "01" in icon_code:
            icon = "☀️" if "d" in icon_code else "🌙"
        elif "02" in icon_code:
            icon = "⛅" if "d" in icon_code else "🌥️"
        elif "03" in icon_code or "04" in icon_code:
            icon = "☁️"
        elif "09" in icon_code or "10" in icon_code:
            icon = "🌧️"
        elif "11" in icon_code:
            icon = "⛈️"
        elif "13" in icon_code:
            icon = "❄️"
        elif "50" in icon_code:
            icon = "🌫️"

        # Formatage du texte
        text = f"{icon} {int(temp)}°C"
        tooltip = f"{description}\nVent: {wind_speed} m/s\nVille: {data['name']}, {data['sys']['country']}"

        return {
            "text": text,
            "tooltip": tooltip,
            "class": "weather-good" if temp > 10 else "weather-cold" if temp < 0 else "weather-warm"
        }

    except requests.exceptions.Timeout:
        return {"text": "⏱️ Timeout", "class": "weather-error", "tooltip": "La requête a expiré."}
    except requests.exceptions.ConnectionError:
        return {"text": "🚫 Pas de réseau", "class": "weather-error", "tooltip": "Impossible de se connecter à OpenWeatherMap."}
    except Exception as e:
        return {"text": "❌ Erreur", "class": "weather-error", "tooltip": str(e)}

if __name__ == "__main__":
    result = get_weather()
    print(json.dumps(result))
    sys.stdout.flush()
