"""
天气查询 API
"""
from fastapi import APIRouter, HTTPException
import httpx

router = APIRouter()

WEATHER_API_KEY = "2d5c904b712686d2"
WEATHER_API_URL = "https://v2.xxapi.cn/api/weatherDetails"

@router.get("/weather")
async def get_weather(city: str):
    """
    查询城市天气信息
    
    参数:
        city: 城市名称，例如：北京、上海、广州
    
    返回:
        天气信息
    """
    try:
        headers = {"key": WEATHER_API_KEY}
        params = {"city": city}
        
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.get(WEATHER_API_URL, headers=headers, params=params)
            
            if response.status_code == 200:
                data = response.json()
                
                if data.get("code") == 200:
                    weather_data = data.get("data", {})
                    city_name = weather_data.get("city", city)
                    
                    # 获取今天的天气
                    today_data = weather_data.get("data", [])[0] if weather_data.get("data") else {}
                    
                    # 获取当前实时天气（第一个时间点）
                    real_time = today_data.get("real_time_weather", [])[0] if today_data.get("real_time_weather") else {}
                    
                    result = {
                        "city": city_name,
                        "date": today_data.get("date", ""),
                        "day": today_data.get("day", ""),
                        "high_temp": today_data.get("high_temp", 0),
                        "low_temp": today_data.get("low_temp", 0),
                        "current_temp": real_time.get("temperature", ""),
                        "weather": real_time.get("weather", ""),
                        "description": real_time.get("description", ""),
                        "humidity": real_time.get("humidity", ""),
                        "wind_dir": real_time.get("wind_dir", ""),
                        "wind_speed": real_time.get("wind_speed", ""),
                        "pressure": real_time.get("pressure", ""),
                        "precipitation": real_time.get("precipitation", ""),
                        "cloud_cover": real_time.get("cloud_cover", ""),
                        "summary": f"{city_name}天气：{real_time.get('weather', '')}，当前温度{real_time.get('temperature', '')}°C，最高{today_data.get('high_temp', 0)}°C，最低{today_data.get('low_temp', 0)}°C，湿度{real_time.get('humidity', '')}，{real_time.get('wind_dir', '')}，风速{real_time.get('wind_speed', '')}"
                    }
                    
                    return {
                        "success": True,
                        "data": result
                    }
                else:
                    raise HTTPException(status_code=400, detail=data.get("msg", "查询失败"))
            else:
                raise HTTPException(status_code=response.status_code, detail="天气 API 请求失败")
                
    except httpx.TimeoutException:
        raise HTTPException(status_code=408, detail="请求超时")
    except httpx.ConnectError:
        raise HTTPException(status_code=503, detail="无法连接到天气服务")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询天气时发生错误: {str(e)}")
