from database import SessionLocal
from models import ToolCallLog, AITool

db = SessionLocal()

# 获取工具信息
tool = db.query(AITool).filter(AITool.id == 7).first()
print(f"工具名称: {tool.name}")
print(f"工具描述: {tool.description}")
print(f"是否代码工具: {tool.is_code_tool}")
print(f"\n函数代码:")
print(tool.function_code)
print("\n" + "="*60)

# 获取最近的调用日志
logs = db.query(ToolCallLog).filter(ToolCallLog.tool_id == 7).order_by(ToolCallLog.timestamp.desc()).limit(5).all()

if logs:
    print(f"\n最近 {len(logs)} 次调用记录:")
    for i, log in enumerate(logs, 1):
        print(f"\n[{i}] 时间: {log.timestamp}")
        print(f"    状态: {log.status}")
        print(f"    输入参数: {log.input_params}")
        print(f"    输出结果: {log.output_result[:200] if log.output_result else 'None'}")
        if log.error_message:
            print(f"    错误信息: {log.error_message}")
        print(f"    执行时间: {log.execution_time}ms")
else:
    print("\n无调用记录")

db.close()

# 测试工具执行
print("\n" + "="*60)
print("测试工具执行:")
print("="*60)

try:
    import json
    from urllib.request import urlopen
    from urllib.error import URLError

    def get_baidu_hot_news():
        """获取百度热搜新闻排行榜"""
        url = "https://v2.xxapi.cn/api/baiduhot"
        try:
            with urlopen(url, timeout=10) as response:
                data = json.loads(response.read().decode('utf-8'))
                if data.get("code") == 200:
                    return data.get("data", [])
                else:
                    return []
        except (URLError, ValueError, KeyError) as e:
            return {"error": str(e)}
    
    result = get_baidu_hot_news()
    print(f"执行结果类型: {type(result)}")
    if isinstance(result, list):
        print(f"返回数据条数: {len(result)}")
        if result:
            print(f"第一条数据: {result[0]}")
    else:
        print(f"返回结果: {result}")
        
except Exception as e:
    print(f"执行失败: {type(e).__name__}: {e}")
    import traceback
    traceback.print_exc()
