"""
Worker 监控模块

提供 Worker 列表、汇总统计、趋势等查询功能。
数据来源：Redis 实时数据 + queue_snapshot 表历史数据。
"""
from fastapi import APIRouter, HTTPException, Query, Path
from typing import Optional, Dict, Any
from datetime import datetime
import logging

from jettask.core.namespace import NamespaceContext
from jettask.webui.deps import NsDep
from jettask.webui.services.queue_service import QueueService
from jettask.webui.services.worker_service import WorkerService

router = APIRouter(prefix="/workers", tags=["Worker监控"])
logger = logging.getLogger(__name__)


async def _get_worker_service(ns: NamespaceContext) -> WorkerService:
    redis_client = await ns.get_redis_client(decode=False)
    return WorkerService(redis_client=redis_client, redis_prefix=ns.redis_prefix)



@router.get("/trend", summary="全局 Worker 数量趋势")
async def get_worker_trend(
    ns: NsDep,
    time_range: Optional[str] = Query("1h", description="时间范围 (1h, 6h, 24h, 7d)"),
    start_time: Optional[datetime] = Query(None, description="开始时间（ISO格式）"),
    end_time: Optional[datetime] = Query(None, description="结束时间（ISO格式）")
) -> Dict[str, Any]:
    try:
        session = await ns.get_pg_session()
        async with session:
            return await QueueService.get_worker_trend(
                namespace=ns.name,
                pg_session=session,
                start_time=start_time,
                end_time=end_time,
                time_range=time_range
            )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取全局 Worker 趋势失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))



@router.get("/summary", summary="全局 Worker 汇总统计")
async def get_worker_summary(ns: NsDep) -> Dict[str, Any]:
    try:
        service = await _get_worker_service(ns)
        workers = await service.get_all_workers()
        summary = await service.get_summary(workers)
        return {"success": True, "data": summary}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取全局 Worker 汇总失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))



@router.get("/", summary="全局 Worker 列表")
async def get_worker_list(ns: NsDep) -> Dict[str, Any]:
    try:
        service = await _get_worker_service(ns)
        workers = await service.get_all_workers()
        return {"success": True, "data": workers, "total": len(workers)}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取全局 Worker 列表失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))



@router.get("/{queue}/trend", summary="队列级 Worker 数量趋势")
async def get_worker_trend_by_queue(
    ns: NsDep,
    queue: str = Path(..., description="队列名称"),
    time_range: Optional[str] = Query("1h", description="时间范围 (1h, 6h, 24h, 7d)"),
    start_time: Optional[datetime] = Query(None, description="开始时间（ISO格式）"),
    end_time: Optional[datetime] = Query(None, description="结束时间（ISO格式）")
) -> Dict[str, Any]:
    try:
        session = await ns.get_pg_session()
        async with session:
            return await QueueService.get_worker_trend_by_queue(
                namespace=ns.name,
                pg_session=session,
                queue=queue,
                start_time=start_time,
                end_time=end_time,
                time_range=time_range
            )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取队列级 Worker 趋势失败: queue={queue}, error={e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))



@router.get("/{queue}/summary", summary="队列级 Worker 汇总统计")
async def get_worker_summary_by_queue(
    ns: NsDep,
    queue: str = Path(..., description="队列名称")
) -> Dict[str, Any]:
    try:
        service = await _get_worker_service(ns)
        workers = await service.get_workers_by_queue(queue)
        summary = await service.get_summary(workers)
        return {"success": True, "data": summary}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取队列级 Worker 汇总失败: queue={queue}, error={e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))



@router.get("/{queue}", summary="队列级 Worker 列表")
async def get_worker_list_by_queue(
    ns: NsDep,
    queue: str = Path(..., description="队列名称")
) -> Dict[str, Any]:
    try:
        service = await _get_worker_service(ns)
        workers = await service.get_workers_by_queue(queue)
        return {"success": True, "data": workers, "total": len(workers)}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取队列级 Worker 列表失败: queue={queue}, error={e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))
