"""
创建天气查询工具（简化版，仅使用 Python 标准库）
"""
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}"}
    
    # 由于沙箱限制，我们创建一个模拟的天气工具
    # 实际使用时，应该在后端创建一个专门的 API 端点来调用天气 API
    weather_tool = {
        "name": "天气查询助手",
        "description": "查询全国各城市的天气信息，返回温度、天气状况、湿度、风力等详细信息",
        "is_code_tool": True,
        "function_code": '''def get_weather(city):
    """
    查询指定城市的天气信息
    
    参数:
        city: 城市名称，例如：北京、上海、广州
    
    返回:
        天气信息字符串
    """
    # 注意：由于沙箱环境限制，这里返回模拟数据
    # 实际部署时，应该通过后端 API 调用真实的天气接口
    
    weather_data = {
        "北京": {
            "温度": "15°C",
            "天气": "晴",
            "湿度": "45%",
            "风向": "北风",
            "风力": "3级"
        },
        "上海": {
            "温度": "18°C",
            "天气": "多云",
            "湿度": "65%",
            "风向": "东南风",
            "风力": "2级"
        },
        "广州": {
            "温度": "25°C",
            "天气": "晴",
            "湿度": "70%",
            "风向": "南风",
            "风力": "2级"
        },
        "深圳": {
            "温度": "26°C",
            "天气": "多云",
            "湿度": "75%",
            "风向": "东南风",
            "风力": "3级"
        },
        "杭州": {
            "温度": "20°C",
            "天气": "阴",
            "湿度": "60%",
            "风向": "东风",
            "风力": "2级"
        }
    }
    
    if city in weather_data:
        info = weather_data[city]
        result = f"{city}天气：{info['天气']}，温度{info['温度']}，湿度{info['湿度']}，{info['风向']}{info['风力']}"
        return result
    else:
        # 返回通用信息
        return f"{city}的天气信息暂时无法获取。支持的城市：北京、上海、广州、深圳、杭州"
''',
        "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"]:
                print(f"✓ 查询成功")
                print(f"  结果: {result['result']}")
            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. 要使用真实天气数据，需要在后端创建专门的 API 端点")
    print("\n下一步：创建真实的天气 API 端点")
    print("  运行: python create_weather_api.py")

if __name__ == "__main__":
    main()
