"""
系统监控API
提供系统状态、执行统计、性能指标等监控数据
"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Optional
from app.core.database import get_db
from app.api.auth import get_current_user
from app.models.user import User
from app.services.monitoring_service import MonitoringService
from app.core.exceptions import UnauthorizedError

router = APIRouter(
    prefix="/api/v1/monitoring",
    tags=["monitoring"],
    responses={
        401: {"description": "未授权"},
        403: {"description": "无权访问"}
    }
)


@router.get("/overview")
async def get_system_overview(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取系统概览统计
    
    返回工作流、Agent、执行记录等数量统计
    """
    # 普通用户只能查看自己的数据，管理员可以查看全部
    user_id = None if current_user.role == "admin" else current_user.id
    
    overview = MonitoringService.get_system_overview(db, user_id)
    return overview


@router.get("/executions")
async def get_execution_statistics(
    days: int = Query(7, ge=1, le=30, description="统计天数"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取执行统计信息
    
    返回执行数量、成功率、平均执行时间、执行趋势等
    """
    # 普通用户只能查看自己的数据，管理员可以查看全部
    user_id = None if current_user.role == "admin" else current_user.id
    
    statistics = MonitoringService.get_execution_statistics(db, user_id, days)
    return statistics


@router.get("/node-types")
async def get_node_type_statistics(
    days: int = Query(7, ge=1, le=30, description="统计天数"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取节点类型统计
    
    返回各节点类型的执行次数、平均耗时、错误率等
    """
    # 普通用户只能查看自己的数据，管理员可以查看全部
    user_id = None if current_user.role == "admin" else current_user.id
    
    statistics = MonitoringService.get_node_type_statistics(db, user_id, days)
    return statistics


@router.get("/activities")
async def get_recent_activities(
    limit: int = Query(10, ge=1, le=50, description="返回数量限制"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取最近的活动记录
    
    返回最近的执行记录等
    """
    # 普通用户只能查看自己的数据，管理员可以查看全部
    user_id = None if current_user.role == "admin" else current_user.id
    
    activities = MonitoringService.get_recent_activities(db, user_id, limit)
    return activities
