import httpx
import json

name = "weather"
description = (
    "Fetches current weather or a 3-day forecast for a specified city using wttr.in. "
    "Supports 'now' (default) for current conditions and 'forecast' for a 3-day outlook."
)
parameters = {
    "type": "object",
    "properties": {
        "city": {"type": "string", "description": "The name of the city."},
        "action": {
            "type": "string",
            "enum": ["now", "forecast"],
            "description": "The type of weather data to retrieve.",
        },
    },
    "required": ["city"],
}

async def execute(params: dict) -> str:
    city = params.get("city")
    action = params.get("action", "now")
    
    # wttr.in JSON format: 
    # For 'now', we use format=j1
    # For 'forecast', we use format=j1 (it includes current + forecast in the JSON)
    
    url = f"https://wttr.in/{city}?format=j1"
    
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url)
            response.raise_for_status()
            data = response.json()
        except Exception as e:
            return f"Error fetching weather data: {str(e)}"

    if action == "now":
        current = data.get("current_condition", [{}])[0]
        temp = current.get("temp_C", "N/A")
        desc = current.get("weatherDesc", [{}])[0].get("value", "N/A")
        humidity = current.get("humidity", "N/A")
        wind = current.get("windspeedKmph", "N/A")
        
        return (f"Current weather in {city}:\n"
                f"- Temperature: {temp}°C\n"
                f"- Condition: {desc}\n"
                f"- Humidity: {humidity}%\n"
                f"- Wind Speed: {wind} km/h")

    elif action == "forecast":
        forecast_list = data.get("weather", [])
        if not forecast_list:
            return f"No forecast available for {city}."
        
        # We take the next 3 days from the forecast list (skipping the first if it's just 'today's' continuation)
        # wttr.in j1 format: 'weather' array contains daily objects.
        
        output = [f"3-Day Forecast for {city}:"]
        # The 'weather' array in j1 contains daily forecasts.
        for day in forecast_list[:3]:
            date = day.get("date", "Unknown")
            # Each day has 'maxtempC' and 'mintempC'
            max_t = day.get("maxtempC", "N/					A")
            min_t = day.get("mintempC", "N/A")
            output.append(f"- {date}: High {max_t}°C, Low {min_t}°C")
            
        return "\n".join(output)
    
    else:
        return "Invalid action. Use 'now' or 'forecast'."
