import httpx
from fastapi import APIRouter, HTTPException
from app.core.config import openweathermap_api_key
from app.schemas.weather_schemas import WeatherRequest

router = APIRouter(
    prefix="/goal-skill-t/api/weather",
    tags=["Weather"]
)

@router.post("")
async def get_current_weather(request: WeatherRequest):
    API_KEY = openweathermap_api_key
    
    try:
        async with httpx.AsyncClient() as client:
            url = f"https://api.openweathermap.org/data/2.5/weather"
            params = {
                "lat": request.lat,
                "lon": request.lon,
                "appid": API_KEY,
                "units": "metric", # 섭씨 온도
                "lang": "ja"       # 일본어 응답
            }
            resp = await client.get(url, params=params)
            data = resp.json()
            
            if resp.status_code != 200:
                return {"weather_text": "Weather Error", "icon_url": ""}

            # 필요한 정보 추출
            weather_desc = data['weather'][0]['description'] # 예: 맑음, 흐림
            temp = round(data['main']['temp'], 1)            # 예: 23.5
            icon_code = data['weather'][0]['icon']           # 아이콘 코드
            icon_url = f"https://openweathermap.org/img/wn/{icon_code}@2x.png"
            
            # 예쁘게 포맷팅된 문자열 반환
            return {
                "weather_text": f"{temp}℃ {weather_desc}",
                "icon_url": icon_url
            }

    except Exception as e:
        print(f"Weather API Error: {e}")
        return {"weather_text": "", "icon_url": ""}