"""
Admin API - Dashboard Routes

包含仪表板统计和系统资源相关的 API 路由。
"""

import logging
from fastapi import APIRouter, Depends, Query

from src.auth.dependencies import require_admin
from src.auth.models import UserAuth
from src.models.schemas import ResponseModel
from src.services.admin_service import admin_service
from src.utils.errors import ErrorCode, AppException

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/dashboard", tags=["admin-dashboard"])


@router.get("/stats", response_model=ResponseModel)
async def get_dashboard_stats(
    current_user: UserAuth = Depends(require_admin),
) -> ResponseModel:
    """
    Get dashboard statistics

    Returns counts of users, projects, and tasks by status.
    Requires admin privileges.
    """
    try:
        stats = await admin_service.get_dashboard_stats()
        return ResponseModel(data=stats.model_dump())
    except Exception as e:
        logger.error(f"Error getting dashboard stats: {e}")
        raise AppException(
            code=ErrorCode.INTERNAL_ERROR,
            message=str(e),
            status_code=500
        )


@router.get("/system", response_model=ResponseModel)
async def get_system_resources(
    current_user: UserAuth = Depends(require_admin),
) -> ResponseModel:
    """
    Get system resource information

    Returns CPU, memory, disk usage and uptime.
    Requires admin privileges.
    """
    try:
        resources = await admin_service.get_system_resources()
        return ResponseModel(data=resources.model_dump())
    except Exception as e:
        logger.error(f"Error getting system resources: {e}")
        raise AppException(
            code=ErrorCode.INTERNAL_ERROR,
            message=str(e),
            status_code=500
        )


@router.get("/activity", response_model=ResponseModel)
async def get_recent_activity(
    limit: int = Query(20, ge=1, le=100),
    current_user: UserAuth = Depends(require_admin),
) -> ResponseModel:
    """
    Get recent system activity

    Returns recent user, project, and task activities.
    Requires admin privileges.
    """
    try:
        activity = await admin_service.get_recent_activity(limit=limit)
        return ResponseModel(data=activity.model_dump())
    except Exception as e:
        logger.error(f"Error getting recent activity: {e}")
        raise AppException(
            code=ErrorCode.INTERNAL_ERROR,
            message=str(e),
            status_code=500
        )
