"""
测试管理后台所有功能的脚本
"""
import requests
import json

BASE_URL = "http://localhost:8000/api"

# 1. 登录获取 token
def login():
    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

# 2. 测试用户管理
def test_user_management(token):
    headers = {"Authorization": f"Bearer {token}"}
    
    # 获取用户列表
    response = requests.get(f"{BASE_URL}/admin/users", headers=headers)
    if response.status_code == 200:
        print(f"✓ 获取用户列表成功: {len(response.json())} 个用户")
    else:
        print("✗ 获取用户列表失败:", response.text)
    
    # 创建新用户
    new_user = {
        "username": "testuser",
        "email": "test@example.com",
        "password": "test123"
    }
    response = requests.post(f"{BASE_URL}/admin/users", json=new_user, headers=headers)
    if response.status_code == 200:
        user_id = response.json()["id"]
        print(f"✓ 创建用户成功: ID={user_id}")
        return user_id
    else:
        print("✗ 创建用户失败:", response.text)
        return None

# 3. 测试聊天记录管理
def test_chat_logs(token):
    headers = {"Authorization": f"Bearer {token}"}
    
    # 获取聊天记录
    response = requests.get(f"{BASE_URL}/admin/chat-logs", headers=headers)
    if response.status_code == 200:
        print(f"✓ 获取聊天记录成功: {len(response.json())} 条消息")
    else:
        print("✗ 获取聊天记录失败:", response.text)
    
    # AI 分析敏感消息
    response = requests.post(f"{BASE_URL}/admin/analyze-sensitive", headers=headers)
    if response.status_code == 200:
        print(f"✓ AI 分析完成: {response.json()['message']}")
    else:
        print("✗ AI 分析失败:", response.text)

# 4. 测试大模型管理
def test_model_management(token):
    headers = {"Authorization": f"Bearer {token}"}
    
    # 创建模型
    new_model = {
        "name": "gpt-4",
        "api_key": "sk-test-key",
        "base_url": "https://api.openai.com/v1"
    }
    response = requests.post(f"{BASE_URL}/ai-agents/models", json=new_model, headers=headers)
    if response.status_code == 200:
        model_id = response.json()["id"]
        print(f"✓ 创建模型成功: ID={model_id}")
        
        # 获取模型列表
        response = requests.get(f"{BASE_URL}/ai-agents/models", headers=headers)
        if response.status_code == 200:
            print(f"✓ 获取模型列表成功: {len(response.json())} 个模型")
        
        return model_id
    else:
        print("✗ 创建模型失败:", response.text)
        return None

# 5. 测试工具管理
def test_tool_management(token):
    headers = {"Authorization": f"Bearer {token}"}
    
    # 创建工具
    new_tool = {
        "name": "天气查询",
        "description": "查询指定城市的天气信息",
        "parameters_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名称"}
            },
            "required": ["city"]
        }
    }
    response = requests.post(f"{BASE_URL}/ai-agents/tools", json=new_tool, headers=headers)
    if response.status_code == 200:
        tool_id = response.json()["id"]
        print(f"✓ 创建工具成功: ID={tool_id}")
        
        # 获取工具列表
        response = requests.get(f"{BASE_URL}/ai-agents/tools", headers=headers)
        if response.status_code == 200:
            print(f"✓ 获取工具列表成功: {len(response.json())} 个工具")
        
        return tool_id
    else:
        print("✗ 创建工具失败:", response.text)
        return None

# 6. 测试数字员工管理
def test_employee_management(token, model_id, tool_id):
    headers = {"Authorization": f"Bearer {token}"}
    
    # 创建数字员工
    new_employee = {
        "name": "客服助手",
        "model_id": model_id,
        "system_prompt": "你是一个专业的客服助手，负责回答用户问题。",
        "tool_ids": [tool_id] if tool_id else []
    }
    response = requests.post(f"{BASE_URL}/ai-agents/employees", json=new_employee, headers=headers)
    if response.status_code == 200:
        emp_id = response.json()["id"]
        print(f"✓ 创建数字员工成功: ID={emp_id}")
        
        # 获取数字员工列表
        response = requests.get(f"{BASE_URL}/ai-agents/employees", headers=headers)
        if response.status_code == 200:
            print(f"✓ 获取数字员工列表成功: {len(response.json())} 个员工")
        
        return emp_id
    else:
        print("✗ 创建数字员工失败:", response.text)
        return None

# 7. 测试数据分析
def test_analytics(token):
    headers = {"Authorization": f"Bearer {token}"}
    
    # 获取仪表板统计
    response = requests.get(f"{BASE_URL}/admin/dashboard-stats", headers=headers)
    if response.status_code == 200:
        stats = response.json()
        print(f"✓ 获取统计数据成功:")
        print(f"  - 用户数: {stats.get('user_count', 0)}")
        print(f"  - 消息数: {stats.get('message_count', 0)}")
        print(f"  - 模型数: {stats.get('model_count', 0)}")
    else:
        print("✗ 获取统计数据失败:", response.text)
    
    # 获取每小时分析
    response = requests.get(f"{BASE_URL}/admin/analytics/hourly", headers=headers)
    if response.status_code == 200:
        print(f"✓ 获取每小时分析成功: {len(response.json())} 个数据点")
    else:
        print("✗ 获取每小时分析失败:", response.text)
    
    # 获取风险分布
    response = requests.get(f"{BASE_URL}/admin/analytics/risk-distribution", headers=headers)
    if response.status_code == 200:
        print(f"✓ 获取风险分布成功: {len(response.json())} 个类别")
    else:
        print("✗ 获取风险分布失败:", response.text)

def main():
    print("=" * 50)
    print("开始测试管理后台功能")
    print("=" * 50)
    
    # 登录
    token = login()
    if not token:
        print("无法继续测试，请先创建管理员账号")
        return
    
    print("\n--- 测试用户管理 ---")
    user_id = test_user_management(token)
    
    print("\n--- 测试聊天记录管理 ---")
    test_chat_logs(token)
    
    print("\n--- 测试大模型管理 ---")
    model_id = test_model_management(token)
    
    print("\n--- 测试工具管理 ---")
    tool_id = test_tool_management(token)
    
    print("\n--- 测试数字员工管理 ---")
    if model_id:
        test_employee_management(token, model_id, tool_id)
    
    print("\n--- 测试数据分析 ---")
    test_analytics(token)
    
    print("\n" + "=" * 50)
    print("测试完成！")
    print("=" * 50)

if __name__ == "__main__":
    main()
