#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
库位队列管理API
提供队列状态监控和管理接口
"""

from fastapi import APIRouter, HTTPException, Query
from typing import Dict, Any, Optional
from services.execution.handlers.storage_queue_manager import storage_queue_manager
from utils.api_response import success_response, error_response
from utils.logger import get_logger

logger = get_logger("routes.storage_queue_api")

router = APIRouter(prefix="/api/storage-queue", tags=["库位队列管理"])

@router.get("/stats", summary="获取队列统计信息")
async def get_queue_stats() -> Dict[str, Any]:
    """获取队列统计信息"""
    try:
        stats = storage_queue_manager.get_queue_stats()
        return success_response(data=stats, message="获取队列统计信息成功")
    except Exception as e:
        logger.error(f"获取队列统计信息失败: {str(e)}")
        return error_response(f"获取队列统计信息失败: {str(e)}")

@router.get("/status/{request_id}", summary="获取请求状态")
async def get_request_status(request_id: str) -> Dict[str, Any]:
    """获取特定请求的状态"""
    try:
        status = await storage_queue_manager.get_request_status(request_id)
        if status:
            return success_response(data=status, message="获取请求状态成功")
        else:
            return error_response("请求不存在")
    except Exception as e:
        logger.error(f"获取请求状态失败: {str(e)}")
        return error_response(f"获取请求状态失败: {str(e)}")

@router.post("/cancel/{request_id}", summary="取消请求")
async def cancel_request(request_id: str) -> Dict[str, Any]:
    """取消指定的请求"""
    try:
        success = await storage_queue_manager.cancel_request(request_id)
        if success:
            return success_response(message=f"取消请求成功: {request_id}")
        else:
            return error_response("请求不存在或无法取消")
    except Exception as e:
        logger.error(f"取消请求失败: {str(e)}")
        return error_response(f"取消请求失败: {str(e)}")

@router.get("/health", summary="队列健康检查")
async def queue_health_check() -> Dict[str, Any]:
    """检查队列管理器的健康状态"""
    try:
        stats = storage_queue_manager.get_queue_stats()
        
        # 判断健康状态
        health_status = "healthy"
        issues = []
        
        # 检查队列大小
        if stats.get('queue_size', 0) > 800:  # 队列接近满载
            health_status = "warning"
            issues.append("队列接近满载")
        
        # 检查活跃工作者数量
        if stats.get('active_workers', 0) == 0:
            health_status = "critical"
            issues.append("没有活跃的工作者")
        
        # 检查失败率
        total_requests = stats.get('requests_total', 0)
        if total_requests > 0:
            failure_rate = stats.get('requests_failed', 0) / total_requests
            if failure_rate > 0.1:  # 失败率超过10%
                health_status = "warning"
                issues.append(f"失败率过高: {failure_rate:.2%}")
        
        return success_response(data={
            "status": health_status,
            "issues": issues,
            "stats": stats
        }, message="队列健康检查完成")
        
    except Exception as e:
        logger.error(f"队列健康检查失败: {str(e)}")
        return error_response(f"队列健康检查失败: {str(e)}")

@router.post("/start", summary="启动队列管理器")
async def start_queue_manager() -> Dict[str, Any]:
    """启动队列管理器"""
    try:
        await storage_queue_manager.start()
        return success_response(message="队列管理器启动成功")
    except Exception as e:
        logger.error(f"启动队列管理器失败: {str(e)}")
        return error_response(f"启动队列管理器失败: {str(e)}")

@router.post("/stop", summary="停止队列管理器")
async def stop_queue_manager() -> Dict[str, Any]:
    """停止队列管理器"""
    try:
        await storage_queue_manager.stop()
        return success_response(message="队列管理器停止成功")
    except Exception as e:
        logger.error(f"停止队列管理器失败: {str(e)}")
        return error_response(f"停止队列管理器失败: {str(e)}")

@router.get("/config", summary="获取队列配置")
async def get_queue_config() -> Dict[str, Any]:
    """获取队列管理器配置"""
    try:
        config = {
            "max_workers": storage_queue_manager.max_workers,
            "max_queue_size": storage_queue_manager.max_queue_size,
            "handlers_registered": list(storage_queue_manager.handlers.keys())
        }
        return success_response(data=config, message="获取队列配置成功")
    except Exception as e:
        logger.error(f"获取队列配置失败: {str(e)}")
        return error_response(f"获取队列配置失败: {str(e)}")