"""
创建天气查询工具
"""
import requests
import json

BASE_URL = "http://localhost:8000/api"
WEATHER_API_KEY = "2d5c904b712686d2"

def login():
    """登录获取 token"""
    response = requests.post(f"{BASE_URL}/users/login", data={
        "username": "admin",
        "password": "admin123"
    })
    if response.status_code == 200:
        token = response.json()["access_token"]
        print("✓ 登录成功")
        return token
    else:
        print("✗ 登录失败:", response.text)
        return None

def create_weather_tool(token):
    """创建天气查询工具"""
    headers = {"Authorization": f"Bearer {token}"}
    
    # 天气查询工具配置
    weather_tool = {
        "name": "天气查询",
        "description": "查询全国各城市的详细天气信息，包括实时天气、温度、湿度、风力等",
        "is_code_tool": True,
        "function_code": f'''import json
try:
    import httpx
except:
    # 如果 httpx 不可用，使用 urllib
    import urllib.request
    import urllib.parse

def get_weather(city):
    """
    查询指定城市的天气信息
    
    参数:
        city: 城市名称，例如：北京、上海、广州
    
    返回:
        天气信息的字典，包含城市、温度、天气状况等
    """
    api_key = "{WEATHER_API_KEY}"
    base_url = "https://v2.xxapi.cn/api/weatherDetails"
    
    try:
        # 尝试使用 httpx
        try:
            import httpx
            headers = {{"key": api_key}}
            params = {{"city": city}}
            
            with httpx.Client(timeout=10.0) as client:
                response = client.get(base_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_name,
                            "日期": today_data.get("date", ""),
                            "星期": today_data.get("day", ""),
                            "最高温度": f"{{today_data.get('high_temp', 0)}}°C",
                            "最低温度": f"{{today_data.get('low_temp', 0)}}°C",
                            "当前温度": f"{{real_time.get('temperature', 0)}}°C",
                            "天气": real_time.get("weather", ""),
                            "天气描述": real_time.get("description", ""),
                            "湿度": real_time.get("humidity", ""),
                            "风向": real_time.get("wind_dir", ""),
                            "风速": real_time.get("wind_speed", ""),
                            "气压": real_time.get("pressure", ""),
                            "降水量": real_time.get("precipitation", ""),
                            "云量": real_time.get("cloud_cover", "")
                        }}
                        
                        return result
                    else:
                        return {{"错误": data.get("msg", "查询失败")}}
                else:
                    return {{"错误": f"API 请求失败，状态码: {{response.status_code}}"}}
        except ImportError:
            # 如果 httpx 不可用，使用 urllib
            import urllib.request
            import urllib.parse
            
            params = urllib.parse.urlencode({{"city": city}})
            url = f"{{base_url}}?{{params}}"
            
            req = urllib.request.Request(url)
            req.add_header("key", api_key)
            
            with urllib.request.urlopen(req, timeout=10) as response:
                data = json.loads(response.read().decode())
                
                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_name,
                        "日期": today_data.get("date", ""),
                        "星期": today_data.get("day", ""),
                        "最高温度": f"{{today_data.get('high_temp', 0)}}°C",
                        "最低温度": f"{{today_data.get('low_temp', 0)}}°C",
                        "当前温度": f"{{real_time.get('temperature', 0)}}°C",
                        "天气": real_time.get("weather", ""),
                        "天气描述": real_time.get("description", ""),
                        "湿度": real_time.get("humidity", ""),
                        "风向": real_time.get("wind_dir", ""),
                        "风速": real_time.get("wind_speed", ""),
                        "气压": real_time.get("pressure", ""),
                        "降水量": real_time.get("precipitation", ""),
                        "云量": real_time.get("cloud_cover", "")
                    }}
                    
                    return result
                else:
                    return {{"错误": data.get("msg", "查询失败")}}
                    
    except Exception as e:
        return {{"错误": f"查询天气时发生错误: {{str(e)}}"}}
''',
        "parameters_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "要查询天气的城市名称，例如：北京、上海、广州、深圳、杭州等",
                    "example": "北京"
                }
            },
            "required": ["city"]
        }
    }
    
    # 检查工具是否已存在
    response = requests.get(f"{BASE_URL}/ai-agents/tools", headers=headers)
    if response.status_code == 200:
        tools = response.json()
        for tool in tools:
            if tool["name"] == "天气查询":
                print(f"✓ 天气查询工具已存在 (ID={tool['id']})")
                return tool["id"]
    
    # 创建新工具
    response = requests.post(f"{BASE_URL}/ai-agents/tools", json=weather_tool, headers=headers)
    if response.status_code == 200:
        tool_id = response.json()["id"]
        print(f"✓ 天气查询工具创建成功 (ID={tool_id})")
        return tool_id
    else:
        print("✗ 创建工具失败:", response.text)
        return None

def test_weather_tool(token, tool_id):
    """测试天气查询工具"""
    headers = {"Authorization": f"Bearer {token}"}
    
    print(f"\n正在测试天气查询工具...")
    print("="*60)
    
    # 测试多个城市
    test_cities = ["北京", "上海", "广州", "深圳", "杭州"]
    
    for city in test_cities:
        print(f"\n查询城市: {city}")
        print("-"*60)
        
        response = requests.post(
            f"{BASE_URL}/ai-agents/tools/{tool_id}/execute",
            json={"city": city},
            headers=headers
        )
        
        if response.status_code == 200:
            result = response.json()
            
            if result["success"]:
                weather_info = result["result"]
                print(f"✓ 查询成功")
                print(f"  城市: {weather_info.get('城市', 'N/A')}")
                print(f"  日期: {weather_info.get('日期', 'N/A')} {weather_info.get('星期', 'N/A')}")
                print(f"  温度: {weather_info.get('当前温度', 'N/A')} (最高: {weather_info.get('最高温度', 'N/A')}, 最低: {weather_info.get('最低温度', 'N/A')})")
                print(f"  天气: {weather_info.get('天气', 'N/A')}")
                print(f"  描述: {weather_info.get('天气描述', 'N/A')}")
                print(f"  湿度: {weather_info.get('湿度', 'N/A')}")
                print(f"  风向: {weather_info.get('风向', 'N/A')}")
                print(f"  风速: {weather_info.get('风速', 'N/A')}")
            else:
                print(f"✗ 查询失败: {result.get('error', 'N/A')}")
        else:
            print(f"✗ 请求失败: {response.text}")
    
    print("\n" + "="*60)

def main():
    print("="*60)
    print("创建天气查询工具")
    print("="*60)
    
    # 登录
    token = login()
    if not token:
        print("无法继续，请先创建管理员账号")
        return
    
    # 创建天气查询工具
    print("\n--- 创建天气查询工具 ---")
    tool_id = create_weather_tool(token)
    
    if tool_id:
        # 测试工具
        print("\n--- 测试天气查询工具 ---")
        test_weather_tool(token, tool_id)
    
    print("\n" + "="*60)
    print("完成！")
    print("="*60)
    print("\n使用说明：")
    print("1. 天气查询工具已创建并可以使用")
    print("2. 在管理后台的'工具管理'中可以看到该工具")
    print("3. 可以在'数字员工管理'中将此工具分配给 AI 员工")
    print("4. AI 员工就可以调用此工具查询天气信息")
    print("\n支持的城市：全国所有城市，例如：")
    print("  - 直辖市: 北京、上海、天津、重庆")
    print("  - 省会城市: 广州、杭州、成都、武汉、西安等")
    print("  - 其他城市: 深圳、苏州、青岛、大连、厦门等")

if __name__ == "__main__":
    main()
