"""
完整测试 get_baidu_hot_news 工具修复
模拟实际的工具调用流程
"""
import json
import time
from database import SessionLocal
from models import AITool

db = SessionLocal()

# 获取工具
tool = db.query(AITool).filter(AITool.id == 7).first()

print("="*60)
print("测试 get_baidu_hot_news 工具")
print("="*60)
print(f"工具名称: {tool.name}")
print(f"工具描述: {tool.description}")
print(f"是否代码工具: {tool.is_code_tool}")
print()

# 模拟工具执行
start_time = time.time()

try:
    # 执行工具代码 - 使用修复后的沙箱环境
    import builtins
    import urllib.request
    import urllib.error
    import types
    
    safe_globals = {
        '__builtins__': builtins,
        'json': json,
        'datetime': __import__('datetime'),
        'math': __import__('math'),
        'random': __import__('random'),
        'urllib': __import__('urllib'),
        'urlopen': urllib.request.urlopen,
        'URLError': urllib.error.URLError,
    }
    
    local_vars = {}
    exec(tool.function_code, safe_globals, local_vars)
    
    # 查找函数
    functions = []
    for name, obj in local_vars.items():
        if isinstance(obj, types.FunctionType) and not name.startswith('_'):
            functions.append(name)
    
    # 优先选择非导入函数
    common_imports = ['urlopen', 'loads', 'dumps', 'randint', 'choice', 'strftime', 'strptime']
    user_functions = [f for f in functions if f not in common_imports]
    
    if user_functions:
        func_name = user_functions[0]
    else:
        func_name = functions[-1] if functions else None
    
    if func_name:
        print(f"找到函数: {func_name}")
        print(f"所有函数: {functions}")
        print()
        
        # 执行函数（无参数）
        result = local_vars[func_name]()
        execution_time = int((time.time() - start_time) * 1000)
        
        print(f"✓ 执行成功!")
        print(f"执行时间: {execution_time}ms")
        print(f"返回数据类型: {type(result)}")
        
        if isinstance(result, list):
            print(f"返回数据条数: {len(result)}")
            print()
            print("前5条热搜:")
            print("-" * 60)
            for i, item in enumerate(result[:5], 1):
                title = item.get('title', 'N/A')
                hot = item.get('hot', 'N/A')
                print(f"{i}. {title}")
                print(f"   热度: {hot}")
        else:
            print(f"返回结果: {result}")
        
        print()
        print("="*60)
        print("✓ 工具测试通过!")
        print("="*60)
        
    else:
        print("✗ 错误: 未找到可执行的函数")
        
except Exception as e:
    execution_time = int((time.time() - start_time) * 1000)
    print(f"✗ 执行失败!")
    print(f"执行时间: {execution_time}ms")
    print(f"错误类型: {type(e).__name__}")
    print(f"错误信息: {e}")
    import traceback
    traceback.print_exc()

db.close()
