"""
Admin API - Projects Routes

包含项目管理相关的 API 路由。
"""

import logging
from typing import Optional

from fastapi import APIRouter, Depends, Query, Request

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.pagination import Paginator
from src.utils.errors import ErrorCode, AppException

logger = logging.getLogger(__name__)

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


@router.get("", response_model=ResponseModel)
async def list_projects(
    request: Request,
    page: int = Query(1, ge=1, description="Page number, starting from 1"),
    page_size: int = Query(20, ge=1, le=100, description="Items per page"),
    sort: Optional[str] = Query(None, description="Sort field, format: field:asc or field:desc"),
    filter: Optional[str] = Query(None, description="Filter conditions, JSON format"),
    current_user: UserAuth = Depends(require_admin),
) -> ResponseModel:
    """
    List all projects with pagination

    Supports filtering by status, type, and search by name.
    Requires admin privileges.
    """
    try:
        # Parse filters
        filters = {}
        if filter:
            import json
            try:
                filters = json.loads(filter)
            except json.JSONDecodeError:
                pass

        # Parse sort
        sort_by = "created_at"
        sort_order = "desc"
        if sort:
            parts = sort.split(":")
            if len(parts) == 2:
                sort_by = parts[0]
                sort_order = parts[1]

        items, total = await admin_service.list_projects(
            page=page,
            page_size=page_size,
            filters=filters if filters else None,
            sort_by=sort_by,
            sort_order=sort_order,
        )

        paginator = Paginator(
            items=[item.model_dump(by_alias=True) for item in items],
            total=total,
            page=page,
            page_size=page_size,
        )

        return paginator.to_response(request)
    except Exception as e:
        logger.error(f"Error listing projects: {e}")
        raise AppException(
            code=ErrorCode.INTERNAL_ERROR,
            message=str(e),
            status_code=500
        )


@router.get("/{project_id}", response_model=ResponseModel)
async def get_project(
    project_id: str,
    current_user: UserAuth = Depends(require_admin),
) -> ResponseModel:
    """
    Get project details by ID

    Requires admin privileges.
    """
    try:
        project = await admin_service.get_project(project_id)
        if not project:
            raise AppException(
                code=ErrorCode.NOT_FOUND,
                message="Project not found",
                status_code=404
            )
        return ResponseModel(data=project.model_dump())
    except AppException:
        raise
    except Exception as e:
        logger.error(f"Error getting project: {e}")
        raise AppException(
            code=ErrorCode.INTERNAL_ERROR,
            message=str(e),
            status_code=500
        )


@router.delete("/{project_id}", response_model=ResponseModel)
async def delete_project(
    project_id: str,
    current_user: UserAuth = Depends(require_admin),
) -> ResponseModel:
    """
    Delete a project

    Requires admin privileges.
    """
    try:
        success = await admin_service.delete_project(project_id)
        if not success:
            raise AppException(
                code=ErrorCode.NOT_FOUND,
                message="Project not found",
                status_code=404
            )

        return ResponseModel(
            data={
                "id": project_id,
                "deleted": True,
                "message": "Project deleted successfully",
            }
        )
    except AppException:
        raise
    except Exception as e:
        logger.error(f"Error deleting project: {e}")
        raise AppException(
            code=ErrorCode.INTERNAL_ERROR,
            message=str(e),
            status_code=500
        )
