from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
import models, schemas
from core.deps import get_current_admin_user
import httpx
import json
import time
from datetime import datetime
from typing import Optional
from builtin_tools import get_builtin_tools, get_tool_by_name, get_tools_by_category

router = APIRouter()

# 辅助函数：记录工具调用
def log_tool_call(
    db: Session,
    tool_id: int,
    employee_id: int,
    input_params: dict,
    output_result: str,
    status: str,
    execution_time: int,
    error_message: str = None,
    user_id: int = None,
    room_id: int = None
):
    """记录工具调用"""
    try:
        log = models.ToolCallLog(
            tool_id=tool_id,
            employee_id=employee_id,
            user_id=user_id,
            room_id=room_id,
            input_params=input_params,
            output_result=output_result,
            status=status,
            error_message=error_message,
            execution_time=execution_time,
            timestamp=datetime.utcnow()
        )
        db.add(log)
        db.commit()
        return log
    except Exception as e:
        print(f"记录工具调用失败: {e}")
        db.rollback()
        return None

# ---- AI Models ----
@router.get("/models", response_model=list[schemas.AIModelResponse])
def get_models(db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    return db.query(models.AIModel).all()

@router.post("/models", response_model=schemas.AIModelResponse)
def create_model(model: schemas.AIModelCreate, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    db_model = models.AIModel(**model.model_dump())
    db.add(db_model)
    db.commit()
    db.refresh(db_model)
    return db_model

@router.put("/models/{model_id}", response_model=schemas.AIModelResponse)
def update_model(model_id: int, model: schemas.AIModelCreate, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """更新模型配置"""
    db_model = db.query(models.AIModel).filter(models.AIModel.id == model_id).first()
    if not db_model:
        raise HTTPException(status_code=404, detail="模型不存在")
    
    db_model.name = model.name
    db_model.api_key = model.api_key
    db_model.base_url = model.base_url
    db.commit()
    db.refresh(db_model)
    return db_model

@router.delete("/models/{model_id}")
def delete_model(model_id: int, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    db_model = db.query(models.AIModel).filter(models.AIModel.id == model_id).first()
    if not db_model:
        raise HTTPException(status_code=404, detail="Model not found")
    db.delete(db_model)
    db.commit()
    return {"message": "Model deleted"}

@router.post("/models/{model_id}/set-default")
def set_default_model(model_id: int, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """设置默认模型"""
    db_model = db.query(models.AIModel).filter(models.AIModel.id == model_id).first()
    if not db_model:
        raise HTTPException(status_code=404, detail="模型不存在")
    
    # 取消所有模型的默认状态
    db.query(models.AIModel).update({"is_default": False})
    
    # 设置当前模型为默认
    db_model.is_default = True
    db.commit()
    db.refresh(db_model)
    
    return {
        "success": True,
        "message": f"已将 {db_model.name} 设置为默认模型"
    }

@router.get("/models/default/get")
def get_default_model(db: Session = Depends(get_db)):
    """获取默认模型（公开接口）"""
    default_model = db.query(models.AIModel).filter(models.AIModel.is_default == True).first()
    if not default_model:
        # 如果没有默认模型，返回第一个模型
        default_model = db.query(models.AIModel).first()
    
    if not default_model:
        raise HTTPException(status_code=404, detail="没有可用的模型")
    
    return default_model

@router.post("/models/{model_id}/test")
async def test_model(model_id: int, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """测试 AI 模型是否可以正常响应"""
    db_model = db.query(models.AIModel).filter(models.AIModel.id == model_id).first()
    if not db_model:
        raise HTTPException(status_code=404, detail="模型不存在")
    
    # 测试消息
    test_message = "你好，请回复'测试成功'来确认你可以正常工作。"
    
    try:
        # 构建请求
        headers = {
            "Authorization": f"Bearer {db_model.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": db_model.name,
            "messages": [
                {"role": "user", "content": test_message}
            ],
            "max_tokens": 100,
            "temperature": 0.7
        }
        
        # 发送请求到模型 API
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.post(
                f"{db_model.base_url}/chat/completions",
                headers=headers,
                json=payload
            )
            
            if response.status_code == 200:
                result = response.json()
                # 提取响应内容
                if "choices" in result and len(result["choices"]) > 0:
                    reply = result["choices"][0]["message"]["content"]
                    return {
                        "success": True,
                        "message": "模型测试成功",
                        "response": reply,
                        "model_name": db_model.name,
                        "latency_ms": response.elapsed.total_seconds() * 1000
                    }
                else:
                    return {
                        "success": False,
                        "message": "模型响应格式异常",
                        "error": "未找到有效的响应内容"
                    }
            else:
                error_detail = response.text
                try:
                    error_json = response.json()
                    error_detail = error_json.get("error", {}).get("message", error_detail)
                except:
                    pass
                
                return {
                    "success": False,
                    "message": f"模型响应错误 (HTTP {response.status_code})",
                    "error": error_detail
                }
                
    except httpx.TimeoutException:
        return {
            "success": False,
            "message": "请求超时",
            "error": "模型响应时间超过 30 秒"
        }
    except httpx.ConnectError:
        return {
            "success": False,
            "message": "连接失败",
            "error": f"无法连接到 {db_model.base_url}"
        }
    except Exception as e:
        return {
            "success": False,
            "message": "测试失败",
            "error": str(e)
        }


# ---- AI Tools ----
@router.get("/tools", response_model=list[schemas.AIToolResponse])
def get_tools(db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    return db.query(models.AITool).all()

@router.get("/tools/builtin")
def get_builtin_tools_list(admin_user: models.User = Depends(get_current_admin_user)):
    """获取内置工具列表"""
    return {
        "success": True,
        "tools": get_builtin_tools(),
        "count": len(get_builtin_tools())
    }

@router.get("/tools/categories")
def get_tool_categories(admin_user: models.User = Depends(get_current_admin_user)):
    """获取工具分类列表"""
    categories = set()
    for tool in get_builtin_tools():
        if "category" in tool:
            categories.add(tool["category"])
    return {
        "success": True,
        "categories": list(categories)
    }

@router.post("/tools", response_model=schemas.AIToolResponse)
def create_tool(tool: schemas.AIToolCreate, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    db_tool = models.AITool(**tool.model_dump())
    db.add(db_tool)
    db.commit()
    db.refresh(db_tool)
    return db_tool

@router.put("/tools/{tool_id}", response_model=schemas.AIToolResponse)
def update_tool(tool_id: int, tool: schemas.AIToolCreate, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """更新工具配置"""
    db_tool = db.query(models.AITool).filter(models.AITool.id == tool_id).first()
    if not db_tool:
        raise HTTPException(status_code=404, detail="工具不存在")
    
    db_tool.name = tool.name
    db_tool.description = tool.description
    db_tool.parameters_schema = tool.parameters_schema
    db.commit()
    db.refresh(db_tool)
    return db_tool

@router.delete("/tools/{tool_id}")
def delete_tool(tool_id: int, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    db_tool = db.query(models.AITool).filter(models.AITool.id == tool_id).first()
    if not db_tool:
        raise HTTPException(status_code=404, detail="Tool not found")
    db.delete(db_tool)
    db.commit()
    return {"message": "Tool deleted"}

@router.post("/tools/{tool_id}/execute")
async def execute_tool(
    tool_id: int, 
    parameters: dict, 
    employee_id: int = None,
    user_id: int = None,
    room_id: int = None,
    db: Session = Depends(get_db), 
    admin_user: models.User = Depends(get_current_admin_user)
):
    """执行工具函数"""
    start_time = time.time()
    
    db_tool = db.query(models.AITool).filter(models.AITool.id == tool_id).first()
    if not db_tool:
        raise HTTPException(status_code=404, detail="工具不存在")
    
    if not db_tool.is_code_tool or not db_tool.function_code:
        raise HTTPException(status_code=400, detail="该工具不支持代码执行")
    
    try:
        # 创建执行环境，使用完整的 builtins
        import builtins
        import urllib.request
        import urllib.error
        
        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(db_tool.function_code, safe_globals, local_vars)
        
        # 查找函数 - 查找所有 FunctionType，优先选择非导入函数
        import types
        func_name = None
        functions = []
        
        for name, obj in local_vars.items():
            if isinstance(obj, types.FunctionType) and not name.startswith('_'):
                functions.append(name)
        
        # 优先选择不在常见导入列表中的函数
        if functions:
            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 not func_name:
            execution_time = int((time.time() - start_time) * 1000)
            error_msg = "未找到可执行的函数"
            
            # 记录失败的调用
            if employee_id:
                log_tool_call(
                    db=db,
                    tool_id=tool_id,
                    employee_id=employee_id,
                    input_params=parameters,
                    output_result="",
                    status="error",
                    execution_time=execution_time,
                    error_message=error_msg,
                    user_id=user_id,
                    room_id=room_id
                )
            
            return {
                "success": False,
                "error": error_msg
            }
        
        # 执行函数
        result = local_vars[func_name](**parameters)
        execution_time = int((time.time() - start_time) * 1000)
        
        # 记录成功的调用
        if employee_id:
            log_tool_call(
                db=db,
                tool_id=tool_id,
                employee_id=employee_id,
                input_params=parameters,
                output_result=str(result),
                status="success",
                execution_time=execution_time,
                user_id=user_id,
                room_id=room_id
            )
        
        return {
            "success": True,
            "result": result,
            "function_name": func_name,
            "execution_time": execution_time
        }
        
    except SyntaxError as e:
        execution_time = int((time.time() - start_time) * 1000)
        error_msg = f"语法错误: {str(e)}"
        
        if employee_id:
            log_tool_call(
                db=db,
                tool_id=tool_id,
                employee_id=employee_id,
                input_params=parameters,
                output_result="",
                status="error",
                execution_time=execution_time,
                error_message=error_msg,
                user_id=user_id,
                room_id=room_id
            )
        
        return {
            "success": False,
            "error": error_msg
        }
    except NameError as e:
        execution_time = int((time.time() - start_time) * 1000)
        error_msg = f"名称错误: {str(e)}"
        
        if employee_id:
            log_tool_call(
                db=db,
                tool_id=tool_id,
                employee_id=employee_id,
                input_params=parameters,
                output_result="",
                status="error",
                execution_time=execution_time,
                error_message=error_msg,
                user_id=user_id,
                room_id=room_id
            )
        
        return {
            "success": False,
            "error": error_msg
        }
    except TypeError as e:
        execution_time = int((time.time() - start_time) * 1000)
        error_msg = f"参数错误: {str(e)}"
        
        if employee_id:
            log_tool_call(
                db=db,
                tool_id=tool_id,
                employee_id=employee_id,
                input_params=parameters,
                output_result="",
                status="error",
                execution_time=execution_time,
                error_message=error_msg,
                user_id=user_id,
                room_id=room_id
            )
        
        return {
            "success": False,
            "error": error_msg
        }
    except Exception as e:
        execution_time = int((time.time() - start_time) * 1000)
        error_msg = f"执行错误: {str(e)}"
        
        if employee_id:
            log_tool_call(
                db=db,
                tool_id=tool_id,
                employee_id=employee_id,
                input_params=parameters,
                output_result="",
                status="error",
                execution_time=execution_time,
                error_message=error_msg,
                user_id=user_id,
                room_id=room_id
            )
        
        return {
            "success": False,
            "error": error_msg
        }

@router.post("/tools/{tool_id}/test")
async def test_tool(tool_id: int, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """测试工具函数（使用示例参数）"""
    db_tool = db.query(models.AITool).filter(models.AITool.id == tool_id).first()
    if not db_tool:
        raise HTTPException(status_code=404, detail="工具不存在")
    
    if not db_tool.is_code_tool or not db_tool.function_code:
        return {
            "success": True,
            "message": "该工具不是代码工具，无需测试",
            "is_code_tool": False
        }
    
    # 从 parameters_schema 中提取示例参数
    test_params = {}
    if db_tool.parameters_schema and "properties" in db_tool.parameters_schema:
        for param_name, param_info in db_tool.parameters_schema["properties"].items():
            param_type = param_info.get("type", "string")
            
            # 生成测试值
            if param_type == "string":
                test_params[param_name] = param_info.get("example", "测试")
            elif param_type == "integer":
                test_params[param_name] = param_info.get("example", 42)
            elif param_type == "number":
                test_params[param_name] = param_info.get("example", 3.14)
            elif param_type == "boolean":
                test_params[param_name] = param_info.get("example", True)
            elif param_type == "array":
                test_params[param_name] = param_info.get("example", [1, 2, 3])
            elif param_type == "object":
                test_params[param_name] = param_info.get("example", {})
    
    # 执行测试（不记录调用日志，所以 employee_id=None）
    result = await execute_tool(
        tool_id=tool_id,
        parameters=test_params,
        employee_id=None,
        user_id=None,
        room_id=None,
        db=db,
        admin_user=admin_user
    )
    result["test_parameters"] = test_params
    result["is_code_tool"] = True
    
    return result

# ---- Digital Employees ----
@router.get("/employees", response_model=list[schemas.DigitalEmployeeResponse])
def get_employees(db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """获取所有数字员工列表"""
    employees = db.query(models.DigitalEmployee).all()
    
    # 为每个员工添加model_name
    result = []
    for emp in employees:
        model = db.query(models.AIModel).filter(models.AIModel.id == emp.model_id).first()
        result.append(schemas.DigitalEmployeeResponse(
            id=emp.id,
            name=emp.name,
            model_id=emp.model_id,
            model_name=model.name if model else "未知模型",
            system_prompt=emp.system_prompt,
            tool_ids=emp.tool_ids
        ))
    return result

@router.get("/employees/public", response_model=list[schemas.DigitalEmployeeResponse])
def get_public_employees(db: Session = Depends(get_db)):
    """获取所有数字员工列表（公开接口，普通用户可访问）"""
    employees = db.query(models.DigitalEmployee).all()
    
    # 为每个员工添加model_name
    result = []
    for emp in employees:
        model = db.query(models.AIModel).filter(models.AIModel.id == emp.model_id).first()
        result.append(schemas.DigitalEmployeeResponse(
            id=emp.id,
            name=emp.name,
            model_id=emp.model_id,
            model_name=model.name if model else "未知模型",
            system_prompt=emp.system_prompt,
            tool_ids=emp.tool_ids
        ))
    return result

@router.post("/employees", response_model=schemas.DigitalEmployeeResponse)
def create_employee(employee: schemas.DigitalEmployeeCreate, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """创建数字员工"""
    # 通过模型名称查找模型
    model = db.query(models.AIModel).filter(models.AIModel.name == employee.model_name).first()
    if not model:
        raise HTTPException(status_code=404, detail=f"模型 '{employee.model_name}' 不存在")
    
    # 创建数字员工,使用model_id
    db_emp = models.DigitalEmployee(
        name=employee.name,
        model_id=model.id,
        system_prompt=employee.system_prompt,
        tool_ids=employee.tool_ids
    )
    db.add(db_emp)
    db.commit()
    db.refresh(db_emp)
    
    # 返回时添加model_name
    response = schemas.DigitalEmployeeResponse(
        id=db_emp.id,
        name=db_emp.name,
        model_id=db_emp.model_id,
        model_name=model.name,
        system_prompt=db_emp.system_prompt,
        tool_ids=db_emp.tool_ids
    )
    return response

@router.put("/employees/{emp_id}", response_model=schemas.DigitalEmployeeResponse)
def update_employee(emp_id: int, employee: schemas.DigitalEmployeeCreate, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """更新数字员工配置"""
    db_emp = db.query(models.DigitalEmployee).filter(models.DigitalEmployee.id == emp_id).first()
    if not db_emp:
        raise HTTPException(status_code=404, detail="数字员工不存在")
    
    # 通过模型名称查找模型
    model = db.query(models.AIModel).filter(models.AIModel.name == employee.model_name).first()
    if not model:
        raise HTTPException(status_code=404, detail=f"模型 '{employee.model_name}' 不存在")
    
    # 更新数字员工
    db_emp.name = employee.name
    db_emp.model_id = model.id
    db_emp.system_prompt = employee.system_prompt
    db_emp.tool_ids = employee.tool_ids
    db.commit()
    db.refresh(db_emp)
    
    # 返回时添加model_name
    response = schemas.DigitalEmployeeResponse(
        id=db_emp.id,
        name=db_emp.name,
        model_id=db_emp.model_id,
        model_name=model.name,
        system_prompt=db_emp.system_prompt,
        tool_ids=db_emp.tool_ids
    )
    return response

@router.delete("/employees/{emp_id}")
def delete_employee(emp_id: int, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    db_emp = db.query(models.DigitalEmployee).filter(models.DigitalEmployee.id == emp_id).first()
    if not db_emp:
        raise HTTPException(status_code=404, detail="Employee not found")
    db.delete(db_emp)
    db.commit()
    return {"message": "Employee deleted"}

@router.post("/employees/generate-prompt")
async def generate_system_prompt(
    request: dict,
    db: Session = Depends(get_db),
    admin_user: models.User = Depends(get_current_admin_user)
):
    """根据员工名称生成系统提示词"""
    import httpx
    
    employee_name = request.get("employee_name")
    model_id = request.get("model_id")
    
    if not employee_name:
        raise HTTPException(status_code=400, detail="员工名称不能为空")
    
    # 获取模型信息
    if model_id:
        ai_model = db.query(models.AIModel).filter(models.AIModel.id == model_id).first()
    else:
        # 使用默认模型
        ai_model = db.query(models.AIModel).filter(models.AIModel.is_default == True).first()
        if not ai_model:
            ai_model = db.query(models.AIModel).first()
    
    if not ai_model:
        raise HTTPException(status_code=404, detail="没有可用的AI模型")
    
    try:
        headers = {
            "Authorization": f"Bearer {ai_model.api_key}",
            "Content-Type": "application/json"
        }
        
        # 构建生成提示词的prompt
        generation_prompt = f"""你是一个AI助手配置专家。请根据以下数字员工的名称，生成一个专业、详细的系统提示词（system prompt）。

员工名称：{employee_name}

要求：
1. 根据员工名称推断其职责和专业领域
2. 定义清晰的角色定位和工作范围
3. 说明其专业能力和服务特点
4. 设定合适的沟通风格和语气
5. 包含必要的行为准则和限制
6. 长度控制在200-400字之间
7. 使用中文回答

请直接输出系统提示词内容，不要包含任何解释或额外说明。"""

        payload = {
            "model": ai_model.name,
            "messages": [
                {"role": "user", "content": generation_prompt}
            ],
            "max_tokens": 800,
            "temperature": 0.7
        }
        
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.post(
                f"{ai_model.base_url}/chat/completions",
                headers=headers,
                json=payload
            )
            
            if response.status_code == 200:
                result = response.json()
                if "choices" in result and len(result["choices"]) > 0:
                    system_prompt = result["choices"][0]["message"]["content"].strip()
                    
                    return {
                        "success": True,
                        "system_prompt": system_prompt,
                        "model_name": ai_model.name
                    }
                else:
                    raise HTTPException(status_code=500, detail="AI响应格式异常")
            else:
                error_text = response.text
                raise HTTPException(status_code=500, detail=f"AI API错误: {response.status_code} - {error_text}")
                
    except httpx.TimeoutException:
        raise HTTPException(status_code=408, detail="请求超时")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成失败: {str(e)}")


# ---- Tool Call Logs ----
@router.get("/tool-call-logs")
def get_tool_call_logs(
    tool_id: int = None,
    employee_id: int = None,
    status: str = None,
    limit: int = 100,
    db: Session = Depends(get_db),
    admin_user: models.User = Depends(get_current_admin_user)
):
    """获取工具调用记录"""
    query = db.query(models.ToolCallLog)
    
    # 过滤条件
    if tool_id:
        query = query.filter(models.ToolCallLog.tool_id == tool_id)
    if employee_id:
        query = query.filter(models.ToolCallLog.employee_id == employee_id)
    if status:
        query = query.filter(models.ToolCallLog.status == status)
    
    # 按时间倒序，最新的在前
    logs = query.order_by(models.ToolCallLog.timestamp.desc()).limit(limit).all()
    
    # 构造返回数据，包含关联信息
    result = []
    for log in logs:
        tool = db.query(models.AITool).filter(models.AITool.id == log.tool_id).first()
        employee = db.query(models.DigitalEmployee).filter(models.DigitalEmployee.id == log.employee_id).first()
        user = db.query(models.User).filter(models.User.id == log.user_id).first() if log.user_id else None
        room = db.query(models.ChatRoom).filter(models.ChatRoom.id == log.room_id).first() if log.room_id else None
        
        result.append({
            "id": log.id,
            "tool_id": log.tool_id,
            "tool_name": tool.name if tool else "未知工具",
            "employee_id": log.employee_id,
            "employee_name": employee.name if employee else "未知员工",
            "user_id": log.user_id,
            "user_name": user.username if user else None,
            "room_id": log.room_id,
            "room_name": room.name if room else None,
            "input_params": log.input_params,
            "output_result": log.output_result,
            "status": log.status,
            "error_message": log.error_message,
            "execution_time": log.execution_time,
            "timestamp": log.timestamp
        })
    
    return result

@router.get("/tool-call-logs/stats")
def get_tool_call_stats(
    tool_id: int = None,
    employee_id: int = None,
    db: Session = Depends(get_db),
    admin_user: models.User = Depends(get_current_admin_user)
):
    """获取工具调用统计"""
    query = db.query(models.ToolCallLog)
    
    if tool_id:
        query = query.filter(models.ToolCallLog.tool_id == tool_id)
    if employee_id:
        query = query.filter(models.ToolCallLog.employee_id == employee_id)
    
    total_calls = query.count()
    success_calls = query.filter(models.ToolCallLog.status == "success").count()
    error_calls = query.filter(models.ToolCallLog.status == "error").count()
    
    # 计算平均执行时间
    avg_time_result = query.filter(models.ToolCallLog.status == "success").all()
    avg_execution_time = 0
    if avg_time_result:
        total_time = sum([log.execution_time for log in avg_time_result if log.execution_time])
        avg_execution_time = total_time / len(avg_time_result) if len(avg_time_result) > 0 else 0
    
    return {
        "total_calls": total_calls,
        "success_calls": success_calls,
        "error_calls": error_calls,
        "success_rate": round(success_calls / total_calls * 100, 2) if total_calls > 0 else 0,
        "avg_execution_time": round(avg_execution_time, 2)
    }

@router.delete("/tool-call-logs/{log_id}")
def delete_tool_call_log(
    log_id: int,
    db: Session = Depends(get_db),
    admin_user: models.User = Depends(get_current_admin_user)
):
    """删除工具调用记录"""
    log = db.query(models.ToolCallLog).filter(models.ToolCallLog.id == log_id).first()
    if not log:
        raise HTTPException(status_code=404, detail="Log not found")
    
    db.delete(log)
    db.commit()
    return {"message": "Log deleted"}

@router.delete("/tool-call-logs")
def clear_tool_call_logs(
    tool_id: int = None,
    employee_id: int = None,
    db: Session = Depends(get_db),
    admin_user: models.User = Depends(get_current_admin_user)
):
    """清空工具调用记录"""
    query = db.query(models.ToolCallLog)
    
    if tool_id:
        query = query.filter(models.ToolCallLog.tool_id == tool_id)
    if employee_id:
        query = query.filter(models.ToolCallLog.employee_id == employee_id)
    
    count = query.count()
    query.delete()
    db.commit()
    
    return {"message": f"Deleted {count} logs"}
