from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from database import get_db
import models, schemas
from core.deps import get_current_active_user
from typing import List
import uuid

router = APIRouter()

@router.post("/", response_model=schemas.ChatRoomResponse)
def create_chatroom(room: schemas.ChatRoomCreate, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    share_link = str(uuid.uuid4())
    db_room = models.ChatRoom(
        name=room.name,
        owner_id=current_user.id,
        share_link=share_link,
        is_private=False
    )
    db.add(db_room)
    db.commit()
    db.refresh(db_room)
    
    # 自动把创建者加入房间
    db_member = models.RoomMember(room_id=db_room.id, user_id=current_user.id)
    db.add(db_member)
    
    # 添加选中的成员
    for member_id in room.member_ids:
        if member_id != current_user.id:  # 避免重复添加创建者
            db_member = models.RoomMember(room_id=db_room.id, user_id=member_id)
            db.add(db_member)
    
    db.commit()
    
    return db_room

@router.post("/private/{friend_id}", response_model=schemas.ChatRoomResponse)
def create_or_get_private_chat(friend_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    """创建或获取与好友的私聊房间"""
    # 检查好友是否存在
    friend = db.query(models.User).filter(models.User.id == friend_id).first()
    if not friend:
        raise HTTPException(status_code=404, detail="Friend not found")
    
    # 查找是否已存在私聊房间
    # 私聊房间的特征：is_private=True，且只有两个成员
    user_rooms = db.query(models.RoomMember).filter(models.RoomMember.user_id == current_user.id).all()
    friend_rooms = db.query(models.RoomMember).filter(models.RoomMember.user_id == friend_id).all()
    
    user_room_ids = set([m.room_id for m in user_rooms])
    friend_room_ids = set([m.room_id for m in friend_rooms])
    
    # 找到共同的房间
    common_room_ids = user_room_ids & friend_room_ids
    
    for room_id in common_room_ids:
        room = db.query(models.ChatRoom).filter(models.ChatRoom.id == room_id).first()
        if room and room.is_private:
            # 检查是否只有两个成员
            member_count = db.query(models.RoomMember).filter(models.RoomMember.room_id == room_id).count()
            if member_count == 2:
                return room
    
    # 如果不存在，创建新的私聊房间
    room_name = f"{current_user.username} & {friend.username}"
    share_link = str(uuid.uuid4())
    
    db_room = models.ChatRoom(
        name=room_name,
        owner_id=current_user.id,
        share_link=share_link,
        is_private=True
    )
    db.add(db_room)
    db.commit()
    db.refresh(db_room)
    
    # 添加两个成员
    db_member1 = models.RoomMember(room_id=db_room.id, user_id=current_user.id)
    db_member2 = models.RoomMember(room_id=db_room.id, user_id=friend_id)
    db.add(db_member1)
    db.add(db_member2)
    db.commit()
    
    return db_room

@router.get("/", response_model=list[schemas.ChatRoomResponse])
def list_chatrooms(db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    # 查找自己所在的房间
    memberships = db.query(models.RoomMember).filter(models.RoomMember.user_id == current_user.id).all()
    room_ids = [m.room_id for m in memberships]
    rooms = db.query(models.ChatRoom).filter(models.ChatRoom.id.in_(room_ids)).all()
    return rooms

@router.post("/join/{share_link}", response_model=schemas.ChatRoomResponse)
def join_chatroom(share_link: str, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    room = db.query(models.ChatRoom).filter(models.ChatRoom.share_link == share_link).first()
    if not room:
        raise HTTPException(status_code=404, detail="Room not found")
        
    existing_member = db.query(models.RoomMember).filter(
        models.RoomMember.room_id == room.id,
        models.RoomMember.user_id == current_user.id
    ).first()
    
    if existing_member:
        raise HTTPException(status_code=400, detail="Already in the room")
        
    db_member = models.RoomMember(room_id=room.id, user_id=current_user.id)
    db.add(db_member)
    db.commit()
    
    return room

@router.post("/{room_id}/add_user/{user_id}")
def add_user_to_room(room_id: int, user_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    room = db.query(models.ChatRoom).filter(models.ChatRoom.id == room_id).first()
    if not room:
        raise HTTPException(status_code=404, detail="Room not found")
        
    if room.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="Only owner can add users directly")
        
    user_to_add = db.query(models.User).filter(models.User.id == user_id).first()
    if not user_to_add:
        raise HTTPException(status_code=404, detail="User not found")
        
    existing_member = db.query(models.RoomMember).filter(
        models.RoomMember.room_id == room.id,
        models.RoomMember.user_id == user_id
    ).first()
    
    if existing_member:
        raise HTTPException(status_code=400, detail="User already in the room")
        
    db_member = models.RoomMember(room_id=room.id, user_id=user_id)
    db.add(db_member)
    db.commit()
    
    return {"message": "User added successfully"}

@router.post("/{room_id}/add_employee/{employee_id}")
def add_employee_to_room(room_id: int, employee_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    """将数字员工添加到聊天室"""
    room = db.query(models.ChatRoom).filter(models.ChatRoom.id == room_id).first()
    if not room:
        raise HTTPException(status_code=404, detail="Room not found")
        
    if room.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="Only owner can add employees")
        
    employee = db.query(models.DigitalEmployee).filter(models.DigitalEmployee.id == employee_id).first()
    if not employee:
        raise HTTPException(status_code=404, detail="Employee not found")
        
    existing_employee = db.query(models.RoomEmployee).filter(
        models.RoomEmployee.room_id == room.id,
        models.RoomEmployee.employee_id == employee_id
    ).first()
    
    if existing_employee:
        raise HTTPException(status_code=400, detail="Employee already in the room")
        
    db_room_employee = models.RoomEmployee(room_id=room.id, employee_id=employee_id)
    db.add(db_room_employee)
    db.commit()
    
    return {"message": "Employee added successfully", "employee_name": employee.name}

@router.get("/{room_id}/messages")
def get_room_messages(room_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    # 检查是否有权限
    membership = db.query(models.RoomMember).filter(
        models.RoomMember.room_id == room_id,
        models.RoomMember.user_id == current_user.id
    ).first()
    
    if not membership:
        raise HTTPException(status_code=403, detail="Not a member of this room")
        
    messages = db.query(models.Message).filter(models.Message.room_id == room_id).order_by(models.Message.timestamp.asc()).all()
    
    # 构造返回数据，包含 sender_name
    result = []
    for msg in messages:
        # 检查是否是数字员工的消息（sender_id 为负数）
        if msg.sender_id < 0:
            # 数字员工消息
            employee_id = -msg.sender_id
            employee = db.query(models.DigitalEmployee).filter(models.DigitalEmployee.id == employee_id).first()
            sender_name = employee.name if employee else "AI助手"
        else:
            # 普通用户消息
            sender = db.query(models.User).filter(models.User.id == msg.sender_id).first()
            sender_name = sender.username if sender else "Unknown"
        
        result.append({
            "id": msg.id,
            "room_id": msg.room_id,
            "sender_id": msg.sender_id,
            "sender_name": sender_name,
            "content": msg.content,
            "message_type": msg.message_type if hasattr(msg, 'message_type') else "text",
            "timestamp": msg.timestamp,
            "is_sensitive": msg.is_sensitive,
            "is_employee": msg.sender_id < 0  # 标记是否是数字员工
        })
    
    return result

@router.get("/{room_id}/members", response_model=list[schemas.UserResponse])
def get_room_members(room_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    """获取房间成员列表"""
    # 检查是否有权限
    membership = db.query(models.RoomMember).filter(
        models.RoomMember.room_id == room_id,
        models.RoomMember.user_id == current_user.id
    ).first()
    
    if not membership:
        raise HTTPException(status_code=403, detail="Not a member of this room")
    
    members = db.query(models.RoomMember).filter(models.RoomMember.room_id == room_id).all()
    users = [db.query(models.User).filter(models.User.id == m.user_id).first() for m in members]
    return users

@router.get("/{room_id}/employees")
def get_room_employees(room_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    """获取房间中的数字员工列表"""
    # 检查是否有权限
    membership = db.query(models.RoomMember).filter(
        models.RoomMember.room_id == room_id,
        models.RoomMember.user_id == current_user.id
    ).first()
    
    if not membership:
        raise HTTPException(status_code=403, detail="Not a member of this room")
    
    room_employees = db.query(models.RoomEmployee).filter(models.RoomEmployee.room_id == room_id).all()
    employees = []
    for re in room_employees:
        employee = db.query(models.DigitalEmployee).filter(models.DigitalEmployee.id == re.employee_id).first()
        if employee:
            employees.append({
                "id": employee.id,
                "name": employee.name,
                "model_id": employee.model_id,
                "system_prompt": employee.system_prompt,
                "tool_ids": employee.tool_ids
            })
    return employees

@router.post("/{room_id}/employee_reply")
async def employee_reply(
    room_id: int, 
    request: dict,
    db: Session = Depends(get_db), 
    current_user: models.User = Depends(get_current_active_user)
):
    """数字员工回复消息（支持工具调用）"""
    import httpx
    import json
    from api.ai_agents import log_tool_call
    import time
    
    employee_id = request.get("employee_id")
    message = request.get("message")
    user_name = request.get("user_name")
    
    # 检查是否有权限
    membership = db.query(models.RoomMember).filter(
        models.RoomMember.room_id == room_id,
        models.RoomMember.user_id == current_user.id
    ).first()
    
    if not membership:
        raise HTTPException(status_code=403, detail="Not a member of this room")
    
    # 获取数字员工信息
    employee = db.query(models.DigitalEmployee).filter(models.DigitalEmployee.id == employee_id).first()
    if not employee:
        raise HTTPException(status_code=404, detail="Employee not found")
    
    # 检查数字员工是否在这个房间
    room_employee = db.query(models.RoomEmployee).filter(
        models.RoomEmployee.room_id == room_id,
        models.RoomEmployee.employee_id == employee_id
    ).first()
    
    if not room_employee:
        raise HTTPException(status_code=403, detail="Employee not in this room")
    
    # 获取 AI 模型信息
    ai_model = db.query(models.AIModel).filter(models.AIModel.id == employee.model_id).first()
    if not ai_model:
        raise HTTPException(status_code=404, detail="AI Model not found")
    
    # 获取数字员工的工具列表
    tools_schema = []
    tools_map = {}
    if employee.tool_ids:
        for tool_id in employee.tool_ids:
            tool = db.query(models.AITool).filter(models.AITool.id == tool_id).first()
            if tool:
                tools_map[tool.name] = tool
                tools_schema.append({
                    "type": "function",
                    "function": {
                        "name": tool.name,
                        "description": tool.description,
                        "parameters": tool.parameters_schema
                    }
                })
    
    try:
        # 调用 AI 模型生成回复
        headers = {
            "Authorization": f"Bearer {ai_model.api_key}",
            "Content-Type": "application/json"
        }
        
        messages = [
            {"role": "system", "content": employee.system_prompt},
            {"role": "user", "content": f"{user_name}: {message}"}
        ]
        
        payload = {
            "model": ai_model.name,
            "messages": messages,
            "max_tokens": 1000,
            "temperature": 0.7
        }
        
        # 如果有工具，添加到请求中
        if tools_schema:
            payload["tools"] = tools_schema
            payload["tool_choice"] = "auto"
        
        full_reply = ""
        tool_calls_info = []
        
        async with httpx.AsyncClient(timeout=60.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:
                    assistant_message = result["choices"][0]["message"]
                    
                    # 检查是否有工具调用
                    if "tool_calls" in assistant_message and assistant_message["tool_calls"]:
                        # 处理工具调用
                        for tool_call in assistant_message["tool_calls"]:
                            function_name = tool_call["function"]["name"]
                            function_args_str = tool_call["function"]["arguments"]
                            
                            try:
                                function_args = json.loads(function_args_str)
                            except json.JSONDecodeError:
                                function_args = {}
                            
                            # 执行工具
                            if function_name in tools_map:
                                tool = tools_map[function_name]
                                start_time = time.time()
                                
                                try:
                                    # 执行工具代码
                                    if tool.is_code_tool and tool.function_code:
                                        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(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 func_name:
                                            tool_result = local_vars[func_name](**function_args)
                                            execution_time = int((time.time() - start_time) * 1000)
                                            
                                            # 记录工具调用
                                            log_tool_call(
                                                db=db,
                                                tool_id=tool.id,
                                                employee_id=employee.id,
                                                input_params=function_args,
                                                output_result=str(tool_result),
                                                status="success",
                                                execution_time=execution_time,
                                                user_id=current_user.id,
                                                room_id=room_id
                                            )
                                            
                                            tool_calls_info.append({
                                                "tool_name": function_name,
                                                "args": function_args,
                                                "result": str(tool_result),
                                                "status": "success"
                                            })
                                            
                                            # 将工具结果添加到消息历史
                                            messages.append(assistant_message)
                                            messages.append({
                                                "role": "tool",
                                                "tool_call_id": tool_call["id"],
                                "name": function_name,
                                                "content": str(tool_result)
                                            })
                                        else:
                                            raise Exception("未找到可执行的函数")
                                    else:
                                        raise Exception("工具不支持代码执行")
                                        
                                except Exception as e:
                                    execution_time = int((time.time() - start_time) * 1000)
                                    error_msg = str(e)
                                    
                                    # 记录失败的工具调用
                                    log_tool_call(
                                        db=db,
                                        tool_id=tool.id,
                                        employee_id=employee.id,
                                        input_params=function_args,
                                        output_result="",
                                        status="error",
                                        execution_time=execution_time,
                                        error_message=error_msg,
                                        user_id=current_user.id,
                                        room_id=room_id
                                    )
                                    
                                    tool_calls_info.append({
                                        "tool_name": function_name,
                                        "args": function_args,
                                        "result": f"错误: {error_msg}",
                                        "status": "error"
                                    })
                                    
                                    # 将错误信息添加到消息历史
                                    messages.append(assistant_message)
                                    messages.append({
                                        "role": "tool",
                                        "tool_call_id": tool_call["id"],
                                        "name": function_name,
                                        "content": f"工具执行失败: {error_msg}"
                                    })
                        
                        # 如果有工具调用，需要再次调用模型获取最终回复
                        if messages[-1]["role"] == "tool":
                            payload["messages"] = messages
                            response2 = await client.post(
                                f"{ai_model.base_url}/chat/completions",
                                headers=headers,
                                json=payload
                            )
                            
                            if response2.status_code == 200:
                                result2 = response2.json()
                                if "choices" in result2 and len(result2["choices"]) > 0:
                                    full_reply = result2["choices"][0]["message"]["content"]
                            else:
                                full_reply = "抱歉，我在处理工具结果时遇到了问题。"
                    else:
                        # 没有工具调用，直接使用回复
                        full_reply = assistant_message.get("content", "")
                    
                    return {
                        "success": True,
                        "message": "Reply generated",
                        "reply": full_reply,
                        "employee_name": employee.name,
                        "employee_id": employee.id,
                        "tool_calls": tool_calls_info
                    }
                else:
                    raise HTTPException(status_code=500, detail="Invalid AI response")
            else:
                error_text = response.text
                raise HTTPException(status_code=500, detail=f"AI API error: {response.status_code} - {error_text}")
                
    except httpx.TimeoutException:
        raise HTTPException(status_code=408, detail="AI request timeout")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")

@router.post("/{room_id}/leave")
def leave_room(room_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    """退出群组"""
    room = db.query(models.ChatRoom).filter(models.ChatRoom.id == room_id).first()
    if not room:
        raise HTTPException(status_code=404, detail="聊天室不存在")
    
    # 群主不能退出，只能解散
    if room.owner_id == current_user.id:
        raise HTTPException(status_code=400, detail="群主不能退出群组，请先转让群主或解散群组")
    
    # 检查用户是否在群组中
    membership = db.query(models.RoomMember).filter(
        models.RoomMember.room_id == room_id,
        models.RoomMember.user_id == current_user.id
    ).first()
    
    if not membership:
        raise HTTPException(status_code=404, detail="您不在该群组中")
    
    # 删除成员关系
    db.delete(membership)
    db.commit()
    
    return {"message": "已退出群组"}

@router.delete("/{room_id}/members/{user_id}")
def remove_member(room_id: int, user_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    """移除群成员（仅群主）"""
    room = db.query(models.ChatRoom).filter(models.ChatRoom.id == room_id).first()
    if not room:
        raise HTTPException(status_code=404, detail="聊天室不存在")
    
    # 只有群主可以移除成员
    if room.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有群主可以移除成员")
    
    # 不能移除自己
    if user_id == current_user.id:
        raise HTTPException(status_code=400, detail="不能移除自己")
    
    # 查找成员
    membership = db.query(models.RoomMember).filter(
        models.RoomMember.room_id == room_id,
        models.RoomMember.user_id == user_id
    ).first()
    
    if not membership:
        raise HTTPException(status_code=404, detail="该用户不在群组中")
    
    # 删除成员
    db.delete(membership)
    db.commit()
    
    return {"message": "成员已移除"}

@router.delete("/{room_id}/employees/{employee_id}")
def remove_employee(room_id: int, employee_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    """移除数字员工（仅群主）"""
    room = db.query(models.ChatRoom).filter(models.ChatRoom.id == room_id).first()
    if not room:
        raise HTTPException(status_code=404, detail="聊天室不存在")
    
    # 只有群主可以移除数字员工
    if room.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有群主可以移除数字员工")
    
    # 查找数字员工关系
    room_employee = db.query(models.RoomEmployee).filter(
        models.RoomEmployee.room_id == room_id,
        models.RoomEmployee.employee_id == employee_id
    ).first()
    
    if not room_employee:
        raise HTTPException(status_code=404, detail="该数字员工不在群组中")
    
    # 删除关系
    db.delete(room_employee)
    db.commit()
    
    return {"message": "数字员工已移除"}


