"""
物业人员管理工具 - 查询物业人员信息、分配任务
"""
import json
from typing import Optional, List
from langchain.tools import tool
from storage.database.supabase_client import get_supabase_client
import logging

logger = logging.getLogger(__name__)


@tool
def get_available_staff(
    department: Optional[str] = None,
    service_type: Optional[str] = None,
    building: Optional[str] = None
) -> str:
    """
    查询可用的物业人员。
    
    参数:
        department: 部门筛选，如"安保部"、"维修部"、"保洁部"
        service_type: 服务类型筛选，如"安保巡逻"、"设施维修"、"清洁服务"
        building: 楼栋筛选，如"1号楼"
    
    返回:
        可用人员列表JSON字符串
    """
    try:
        client = get_supabase_client()
        
        # 构建查询
        query = client.table('staff').select('*').eq('is_active', True).eq('status', 'online')
        
        if department:
            query = query.eq('department', department)
        
        # 执行查询
        result = query.order('current_tasks', desc=False).limit(5).execute()
        
        if result.data:
            return json.dumps({
                "success": True,
                "count": len(result.data),
                "staff": result.data
            }, ensure_ascii=False)
        else:
            return json.dumps({
                "success": True,
                "count": 0,
                "staff": [],
                "message": "暂无可用人员"
            }, ensure_ascii=False)
            
    except Exception as e:
        error_msg = f"查询物业人员时发生错误: {str(e)}"
        logger.error(error_msg, exc_info=True)
        return json.dumps({
            "success": False,
            "error": error_msg
        }, ensure_ascii=False)


@tool
def assign_task_to_staff(
    task_id: int,
    staff_id: int
) -> str:
    """
    将任务分配给指定的物业人员。
    
    参数:
        task_id: 任务ID
        staff_id: 物业人员ID
    
    返回:
        分配结果JSON字符串
    """
    try:
        client = get_supabase_client()
        
        # 更新任务状态和负责人
        task_result = client.table('tasks').update({
            'assigned_to': staff_id,
            'status': 'in_progress'
        }).eq('id', task_id).execute()
        
        if not task_result.data:
            return json.dumps({
                "success": False,
                "error": f"任务 {task_id} 不存在"
            }, ensure_ascii=False)
        
        # 更新人员的当前任务数
        staff_result = client.table('staff').select('current_tasks').eq('id', staff_id).execute()
        if staff_result.data:
            current_tasks = int(staff_result.data[0].get('current_tasks', 0) or 0)  # type: ignore
            client.table('staff').update({
                'current_tasks': current_tasks + 1
            }).eq('id', staff_id).execute()
        
        # 获取人员信息
        staff_info = client.table('staff').select('*').eq('id', staff_id).execute()
        staff_name = staff_info.data[0].get('name', '工作人员') if staff_info.data else '工作人员'  # type: ignore
        
        logger.info(f"任务 {task_id} 已分配给 {staff_name}")
        
        return json.dumps({
            "success": True,
            "task_id": task_id,
            "staff_id": staff_id,
            "staff_name": staff_name,
            "message": f"任务已分配给 {staff_name}"
        }, ensure_ascii=False)
            
    except Exception as e:
        error_msg = f"分配任务时发生错误: {str(e)}"
        logger.error(error_msg, exc_info=True)
        return json.dumps({
            "success": False,
            "error": error_msg
        }, ensure_ascii=False)


@tool
def update_task_status(
    task_id: int,
    status: str,
    note: Optional[str] = None
) -> str:
    """
    更新任务状态。
    
    参数:
        task_id: 任务ID
        status: 新状态 - pending(待处理)/in_progress(处理中)/completed(已完成)/cancelled(已取消)
        note: 备注说明（可选）
    
    返回:
        更新结果JSON字符串
    """
    try:
        client = get_supabase_client()
        
        update_data = {'status': status}
        if note:
            update_data['completion_note'] = note
        
        result = client.table('tasks').update(update_data).eq('id', task_id).execute()
        
        if result.data:
            return json.dumps({
                "success": True,
                "task_id": task_id,
                "new_status": status,
                "message": f"任务状态已更新为: {status}"
            }, ensure_ascii=False)
        else:
            return json.dumps({
                "success": False,
                "error": f"任务 {task_id} 不存在"
            }, ensure_ascii=False)
            
    except Exception as e:
        error_msg = f"更新任务状态时发生错误: {str(e)}"
        logger.error(error_msg, exc_info=True)
        return json.dumps({
            "success": False,
            "error": error_msg
        }, ensure_ascii=False)
