import requests

from src.multi_agent.config import gaode_key


def search_weather(area_str):
    district_code_url = 'https://restapi.amap.com/v3/config/district?parameters'
    weather_url = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'

    # area_str = '上海市'

    response = requests.get(district_code_url, params={'key': gaode_key, 'keywords': area_str})
    district_code_list = response.json().get('districts')

    if not district_code_list:
        raise Exception('查询失败')

    district_code = district_code_list[0].get('adcode')

    response = requests.get(weather_url, params={'key': gaode_key, 'city': district_code})
    weather_list = response.json().get('lives')
    if not weather_list:
        raise Exception('查询失败')

    weather = weather_list[0]

    result = f'{area_str}现在{weather["weather"]}，{weather["temperature"]}摄氏度，湿度{weather["humidity"]}%，{weather["winddirection"]}风{weather["windpower"]}级'
    return result
