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
from core.security import get_password_hash
from datetime import datetime, timedelta

router = APIRouter()

@router.get("/users", response_model=list[schemas.UserResponse])
def get_all_users(
    search: str = None,
    db: Session = Depends(get_db), 
    admin_user: models.User = Depends(get_current_admin_user)
):
    """获取用户列表，支持根据用户名和邮箱模糊搜索"""
    query = db.query(models.User)
    
    # 如果提供了搜索关键词，进行模糊搜索
    if search:
        search_pattern = f"%{search}%"
        query = query.filter(
            (models.User.username.ilike(search_pattern)) | 
            (models.User.email.ilike(search_pattern))
        )
    
    return query.all()

@router.post("/users", response_model=schemas.UserResponse)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """管理员创建新用户"""
    # 检查用户名是否已存在
    existing_user = db.query(models.User).filter(models.User.username == user.username).first()
    if existing_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 检查邮箱是否已存在
    existing_email = db.query(models.User).filter(models.User.email == user.email).first()
    if existing_email:
        raise HTTPException(status_code=400, detail="邮箱已被使用")
    
    hashed_password = get_password_hash(user.password)
    db_user = models.User(
        username=user.username,
        email=user.email,
        hashed_password=hashed_password,
        is_active=True,
        is_admin=False
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

@router.get("/users/{user_id}", response_model=schemas.UserResponse)
def get_user_detail(user_id: int, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """获取用户详情"""
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

@router.put("/users/{user_id}", response_model=schemas.UserResponse)
def update_user(
    user_id: int, 
    user_update: schemas.UserUpdate, 
    db: Session = Depends(get_db), 
    admin_user: models.User = Depends(get_current_admin_user)
):
    """更新用户信息（邮箱和密码）"""
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 更新邮箱
    if user_update.email is not None:
        # 检查邮箱是否已被其他用户使用
        existing_email = db.query(models.User).filter(
            models.User.email == user_update.email,
            models.User.id != user_id
        ).first()
        if existing_email:
            raise HTTPException(status_code=400, detail="邮箱已被其他用户使用")
        user.email = user_update.email
    
    # 更新密码
    if user_update.password is not None:
        user.hashed_password = get_password_hash(user_update.password)
    
    db.commit()
    db.refresh(user)
    return user

@router.put("/users/{user_id}/status", response_model=schemas.UserResponse)
def update_user_status(user_id: int, is_active: bool, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """更新用户状态（启用/禁用）"""
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    if user.id == admin_user.id:
        raise HTTPException(status_code=400, detail="不能禁用自己的账号")
        
    user.is_active = is_active
    db.commit()
    db.refresh(user)
    return user

@router.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """删除用户"""
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    if user.id == admin_user.id:
        raise HTTPException(status_code=400, detail="不能删除自己的账号")
    
    db.delete(user)
    db.commit()
    return {"message": "用户已删除"}

@router.get("/chat-logs")
def get_chat_logs(
    skip: int = 0, 
    limit: int = 50, 
    search: str = None,
    sender_name: str = None,
    is_sensitive: bool = None,
    db: Session = Depends(get_db), 
    admin_user: models.User = Depends(get_current_admin_user)
):
    """获取聊天记录，支持搜索"""
    from datetime import timedelta
    
    query = db.query(models.Message).order_by(models.Message.timestamp.desc())
    
    # 根据内容搜索
    if search:
        search_pattern = f"%{search}%"
        query = query.filter(models.Message.content.ilike(search_pattern))
    
    # 根据发送者搜索
    if sender_name:
        sender_pattern = f"%{sender_name}%"
        query = query.join(models.User).filter(models.User.username.ilike(sender_pattern))
    
    # 根据敏感状态筛选
    if is_sensitive is not None:
        query = query.filter(models.Message.is_sensitive == is_sensitive)
    
    messages = query.offset(skip).limit(limit).all()
    
    # 填充发送者和房间信息，并转换时区
    result = []
    for msg in messages:
        sender = db.query(models.User).filter(models.User.id == msg.sender_id).first()
        room = db.query(models.ChatRoom).filter(models.ChatRoom.id == msg.room_id).first()
        
        # 将UTC时间转换为东八区时间
        local_timestamp = msg.timestamp + timedelta(hours=8) if msg.timestamp else None
        
        result.append({
            "id": msg.id,
            "room_id": msg.room_id,
            "room_name": room.name if room else "未知房间",
            "sender_id": msg.sender_id,
            "sender_name": sender.username if sender else "未知用户",
            "content": msg.content,
            "timestamp": local_timestamp.isoformat() if local_timestamp else None,
            "is_sensitive": msg.is_sensitive
        })
    
    return result

@router.get("/analyze-sensitive")
async def analyze_sensitive_messages(
    start_date: str = None,
    end_date: str = None,
    model_id: int = None,
    db: Session = Depends(get_db), 
    admin_user: models.User = Depends(get_current_admin_user)
):
    """使用AI模型分析敏感消息 - 支持流式返回进度"""
    from datetime import datetime, timezone, timedelta
    from fastapi.responses import StreamingResponse
    import httpx
    import json
    import asyncio
    
    async def generate_progress():
        # 东八区时区
        tz_cn = timezone(timedelta(hours=8))
        
        # 获取指定时间段的消息
        query = db.query(models.Message)
        
        if start_date:
            try:
                local_dt = datetime.fromisoformat(start_date.replace('Z', ''))
                utc_dt = local_dt - timedelta(hours=8)
                query = query.filter(models.Message.timestamp >= utc_dt)
            except Exception as e:
                yield f"data: {json.dumps({'error': f'开始时间格式错误: {str(e)}'}, ensure_ascii=False)}\n\n"
                return
        
        if end_date:
            try:
                local_dt = datetime.fromisoformat(end_date.replace('Z', ''))
                utc_dt = local_dt - timedelta(hours=8)
                query = query.filter(models.Message.timestamp <= utc_dt)
            except Exception as e:
                yield f"data: {json.dumps({'error': f'结束时间格式错误: {str(e)}'}, ensure_ascii=False)}\n\n"
                return
        
        messages = query.all()
        total = len(messages)
        
        if total == 0:
            yield f"data: {json.dumps({'type': 'complete', 'message': '指定时间段内没有消息', 'total': 0, 'analyzed': 0, 'sensitive_found': 0}, ensure_ascii=False)}\n\n"
            return
        
        # 获取AI模型配置
        if model_id:
            ai_model = db.query(models.AIModel).filter(models.AIModel.id == model_id).first()
            if not ai_model:
                yield f"data: {json.dumps({'error': '模型不存在'}, ensure_ascii=False)}\n\n"
                return
        else:
            ai_model = db.query(models.AIModel).first()
            if not ai_model:
                yield f"data: {json.dumps({'error': '没有可用的AI模型，请先配置模型'}, ensure_ascii=False)}\n\n"
                return
        
        # 发送开始信息
        yield f"data: {json.dumps({'type': 'start', 'total': total, 'model': ai_model.name}, ensure_ascii=False)}\n\n"
        
        analyzed_count = 0
        sensitive_count = 0
        
        for idx, msg in enumerate(messages):
            try:
                # 发送分析中的消息
                yield f"data: {json.dumps({'type': 'analyzing', 'index': idx + 1, 'total': total, 'content': msg.content[:50] + '...' if len(msg.content) > 50 else msg.content}, ensure_ascii=False)}\n\n"
                
                # 调用AI模型API
                headers = {
                    "Authorization": f"Bearer {ai_model.api_key}",
                    "Content-Type": "application/json"
                }
                
                payload = {
                    "model": ai_model.name,
                    "messages": [
                        {
                            "role": "system",
                            "content": "你是一个内容审核助手。请判断用户发送的消息是否包含敏感内容。敏感内容包括：暴力、色情、政治敏感、违法信息、人身攻击等。请只回答'敏感'或'正常'。"
                        },
                        {
                            "role": "user",
                            "content": f"请判断以下消息是否敏感：\n{msg.content}"
                        }
                    ],
                    "temperature": 0.3,
                    "max_tokens": 10
                }
                
                async with httpx.AsyncClient(timeout=10.0) as client:
                    response = await client.post(
                        f"{ai_model.base_url}/chat/completions",
                        headers=headers,
                        json=payload
                    )
                
                is_sensitive = False
                if response.status_code == 200:
                    result = response.json()
                    ai_response = result.get("choices", [{}])[0].get("message", {}).get("content", "").strip()
                    
                    if "敏感" in ai_response:
                        is_sensitive = True
                        msg.is_sensitive = True
                        sensitive_count += 1
                    else:
                        msg.is_sensitive = False
                    
                    analyzed_count += 1
                else:
                    # API调用失败，使用关键词匹配
                    sensitive_keywords = ["违规", "涉黄", "涉政", "暴力", "敏感", "fuck", "shit"]
                    for kw in sensitive_keywords:
                        if kw in msg.content.lower():
                            is_sensitive = True
                            msg.is_sensitive = True
                            sensitive_count += 1
                            break
                    analyzed_count += 1
                
                # 发送分析结果
                yield f"data: {json.dumps({'type': 'result', 'index': idx + 1, 'total': total, 'content': msg.content[:50] + '...' if len(msg.content) > 50 else msg.content, 'is_sensitive': is_sensitive, 'analyzed': analyzed_count, 'sensitive_found': sensitive_count}, ensure_ascii=False)}\n\n"
                
                # 小延迟，让前端有时间渲染
                await asyncio.sleep(0.1)
                    
            except Exception as e:
                # 如果AI调用失败，使用关键词匹配
                sensitive_keywords = ["违规", "涉黄", "涉政", "暴力", "敏感", "fuck", "shit"]
                is_sensitive = False
                for kw in sensitive_keywords:
                    if kw in msg.content.lower():
                        is_sensitive = True
                        msg.is_sensitive = True
                        sensitive_count += 1
                        break
                analyzed_count += 1
                
                yield f"data: {json.dumps({'type': 'result', 'index': idx + 1, 'total': total, 'content': msg.content[:50] + '...' if len(msg.content) > 50 else msg.content, 'is_sensitive': is_sensitive, 'analyzed': analyzed_count, 'sensitive_found': sensitive_count, 'error': str(e)}, ensure_ascii=False)}\n\n"
        
        db.commit()
        
        # 发送完成信息
        yield f"data: {json.dumps({'type': 'complete', 'message': f'分析完成！共分析 {analyzed_count} 条消息，发现 {sensitive_count} 条敏感消息', 'total': total, 'analyzed': analyzed_count, 'sensitive_found': sensitive_count, 'model_used': ai_model.name}, ensure_ascii=False)}\n\n"
    
    return StreamingResponse(generate_progress(), media_type="text/event-stream")

@router.get("/dashboard-stats")
def get_dashboard_stats(db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """获取仪表板统计数据"""
    from datetime import timedelta
    
    user_count = db.query(models.User).count()
    active_user_count = db.query(models.User).filter(models.User.is_active == True).count()
    room_count = db.query(models.ChatRoom).count()
    message_count = db.query(models.Message).count()
    sensitive_count = db.query(models.Message).filter(models.Message.is_sensitive == True).count()
    
    # 今日消息数 - 使用东八区时间计算
    today = datetime.utcnow().date()
    # 东八区的今天开始时间（UTC时间需要减8小时）
    today_start_utc = datetime.combine(today, datetime.min.time()) - timedelta(hours=8)
    today_message_count = db.query(models.Message).filter(
        models.Message.timestamp >= today_start_utc
    ).count()
    
    # 模型和工具统计
    model_count = db.query(models.AIModel).count()
    tool_count = db.query(models.AITool).count()
    employee_count = db.query(models.DigitalEmployee).count()
    
    return {
        "user_count": user_count,
        "active_user_count": active_user_count,
        "room_count": room_count,
        "message_count": message_count,
        "today_message_count": today_message_count,
        "sensitive_count": sensitive_count,
        "model_count": model_count,
        "tool_count": tool_count,
        "employee_count": employee_count
    }

@router.get("/analytics/hourly")
def get_hourly_analytics(db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """获取每小时消息统计"""
    from datetime import timedelta
    
    # 获取最近24小时的消息（基于东八区时间）
    now_utc = datetime.utcnow()
    hours_data = []
    
    for i in range(24):
        # 计算东八区的小时范围
        hour_start_utc = now_utc - timedelta(hours=23-i)
        hour_end_utc = hour_start_utc + timedelta(hours=1)
        
        count = db.query(models.Message).filter(
            models.Message.timestamp >= hour_start_utc,
            models.Message.timestamp < hour_end_utc
        ).count()
        
        # 转换为东八区时间显示
        hour_start_local = hour_start_utc + timedelta(hours=8)
        hours_data.append({
            "time": hour_start_local.strftime("%H:00"),
            "value": count
        })
    
    return hours_data

@router.get("/analytics/risk-distribution")
def get_risk_distribution(db: Session = Depends(get_db), admin_user: models.User = Depends(get_current_admin_user)):
    """获取风险消息分布"""
    total = db.query(models.Message).count()
    sensitive = db.query(models.Message).filter(models.Message.is_sensitive == True).count()
    normal = total - sensitive
    
    if total == 0:
        return [
            {"name": "正常", "value": 100},
            {"name": "中等", "value": 0},
            {"name": "高风险", "value": 0}
        ]
    
    # 简化处理：敏感消息中，假设70%是中等风险，30%是高风险
    medium = int(sensitive * 0.7)
    high = sensitive - medium
    
    return [{
        "name": "正常",
        "value": round(normal / total * 100, 1)
    }, {
        "name": "中等",
        "value": round(medium / total * 100, 1)
    }, {
        "name": "高风险",
        "value": round(high / total * 100, 1)
    }]

@router.get("/generate-tool")
async def generate_tool_by_ai(
    description: str,
    model_id: int,
    db: Session = Depends(get_db),
    admin_user: models.User = Depends(get_current_admin_user)
):
    """使用AI模型生成工具配置 - 支持流式返回"""
    from fastapi.responses import StreamingResponse
    import httpx
    import json
    import asyncio
    import re
    
    async def generate_stream():
        # 获取AI模型
        ai_model = db.query(models.AIModel).filter(models.AIModel.id == model_id).first()
        if not ai_model:
            yield f"data: {json.dumps({'error': '模型不存在'}, ensure_ascii=False)}\n\n"
            return
        
        # 发送开始信息
        yield f"data: {json.dumps({'type': 'start', 'message': '开始生成工具配置...'}, ensure_ascii=False)}\n\n"
        await asyncio.sleep(0.5)
        
        # 构建提示词
        system_prompt = """你是一个专业的工具开发助手。用户会描述他们需要的工具功能，你需要生成完整的工具配置。

请严格按照以下JSON格式返回，不要添加任何其他文字：

{
  "name": "工具名称（英文，使用下划线分隔）",
  "description": "工具的详细描述（中文）",
  "is_code_tool": true,
  "parameters_schema": {
    "type": "object",
    "properties": {
      "参数名": {
        "type": "string/number/boolean",
        "description": "参数描述",
        "example": "示例值"
      }
    },
    "required": ["必需参数列表"]
  },
  "function_code": "def function_name(参数列表):\\n    \\"\\"\\"函数文档字符串\\"\\"\\"\\n    # 实现代码\\n    return result"
}

注意事项：
1. name必须是有效的Python函数名（小写字母和下划线）
2. function_code必须是完整可执行的Python函数
3. 函数参数名必须与parameters_schema中的属性名一致
4. 可以使用的模块：json, datetime, math, random, re
5. 函数必须有返回值
6. 代码要简洁、健壮，包含错误处理"""

        user_prompt = f"请为以下需求生成工具配置：\n\n{description}"
        
        yield f"data: {json.dumps({'type': 'thinking', 'message': '正在分析需求...'}, ensure_ascii=False)}\n\n"
        await asyncio.sleep(0.5)
        
        try:
            # 调用AI模型
            headers = {
                "Authorization": f"Bearer {ai_model.api_key}",
                "Content-Type": "application/json"
            }
            
            payload = {
                "model": ai_model.name,
                "messages": [
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                "temperature": 0.7,
                "max_tokens": 2000
            }
            
            yield f"data: {json.dumps({'type': 'generating', 'message': '正在生成工具配置...'}, ensure_ascii=False)}\n\n"
            
            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:
                yield f"data: {json.dumps({'error': f'AI模型调用失败: {response.status_code}'}, ensure_ascii=False)}\n\n"
                return
            
            result = response.json()
            ai_response = result.get("choices", [{}])[0].get("message", {}).get("content", "").strip()
            
            yield f"data: {json.dumps({'type': 'parsing', 'message': '正在解析生成结果...'}, ensure_ascii=False)}\n\n"
            await asyncio.sleep(0.5)
            
            # 提取JSON（可能被markdown代码块包裹）
            json_match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', ai_response, re.DOTALL)
            if json_match:
                json_str = json_match.group(1)
            else:
                # 尝试直接解析
                json_str = ai_response
            
            # 解析JSON
            tool_config = json.loads(json_str)
            
            # 验证必需字段
            required_fields = ['name', 'description', 'parameters_schema']
            for field in required_fields:
                if field not in tool_config:
                    yield f"data: {json.dumps({'error': f'生成的配置缺少必需字段: {field}'}, ensure_ascii=False)}\n\n"
                    return
            
            yield f"data: {json.dumps({'type': 'validating', 'message': '正在验证配置...'}, ensure_ascii=False)}\n\n"
            await asyncio.sleep(0.5)
            
            # 验证函数代码（如果是代码工具）
            if tool_config.get('is_code_tool') and tool_config.get('function_code'):
                try:
                    # 简单的语法检查
                    compile(tool_config['function_code'], '<string>', 'exec')
                    yield f"data: {json.dumps({'type': 'validated', 'message': '代码语法验证通过'}, ensure_ascii=False)}\n\n"
                except SyntaxError as e:
                    yield f"data: {json.dumps({'error': f'生成的代码有语法错误: {str(e)}'}, ensure_ascii=False)}\n\n"
                    return
            
            # 发送完成信息
            yield f"data: {json.dumps({'type': 'complete', 'message': '工具配置生成完成！', 'data': tool_config}, ensure_ascii=False)}\n\n"
            
        except json.JSONDecodeError as e:
            error_msg = f'解析AI返回的JSON失败: {str(e)}\n\n原始响应: {ai_response[:200]}'
            yield f"data: {json.dumps({'error': error_msg}, ensure_ascii=False)}\n\n"
        except Exception as e:
            yield f"data: {json.dumps({'error': f'生成工具配置时出错: {str(e)}'}, ensure_ascii=False)}\n\n"
    
    return StreamingResponse(generate_stream(), media_type="text/event-stream")

