"""
Tasks Controller - 任务管理
使用新的任务管理器 V2
"""
import logging
from typing import Optional
from fastapi import APIRouter, Query, Request, Depends

from src.models.schemas import ResponseModel, Task, PaginationParams
from src.services.task_manager import task_manager, TaskPriority
from src.auth.dependencies import get_current_user
from src.auth.models import UserAuth
from src.utils.errors import (
    TaskNotFoundException,
    InvalidParameterException,
    BusinessException,
    ErrorCode
)
from src.utils.pagination import Paginator

router = APIRouter(tags=["tasks"])
logger = logging.getLogger(__name__)


# 注意：更具体的路由（如 /tasks/stats）必须在参数化路由（如 /tasks/{task_id}）之前定义
# 否则 FastAPI 会将 "stats" 当作 task_id 处理


@router.get("/tasks/stats", response_model=ResponseModel)
async def get_task_stats():
    """获取任务统计信息
    
    Returns:
        任务统计数据
    """
    stats = task_manager.get_stats()
    return ResponseModel(data=stats)


@router.get("/tasks", response_model=ResponseModel)
async def list_tasks(
    request: Request,
    task_type: Optional[str] = Query(None, description="Filter by task type (image, video, script)"),
    status: Optional[str] = Query(None, description="Filter by status"),
    page: int = Query(1, ge=1, description="页码,从1开始"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量,最大100"),
    current_user: UserAuth = Depends(get_current_user)
):
    """列出任务（分页）

    只返回当前用户的任务

    Args:
        task_type: 任务类型过滤
        status: 状态过滤
        page: 页码
        page_size: 每页数量

    Returns:
        分页的任务列表
    """
    try:
        # 计算偏移量
        offset = (page - 1) * page_size

        # 获取当前用户的任务
        tasks = task_manager.list_tasks(
            type=task_type,
            limit=page_size,
            offset=offset,
            user_id=current_user.id
        )

        # 计算总数
        total = len(tasks)  # 简化处理，实际应该查询总数

        # 创建分页器
        paginator = Paginator(
            items=tasks,
            total=total,
            page=page,
            page_size=page_size
        )

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


@router.get("/tasks/{task_id}", response_model=ResponseModel)
async def get_task_status(
    task_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """获取任务状态

    只能访问当前用户的任务

    Args:
        task_id: 任务 ID

    Returns:
        任务详情

    Raises:
        TaskNotFoundException: 任务不存在或无权访问
    """
    task = await task_manager.get_task(task_id)

    if not task:
        raise TaskNotFoundException(task_id)

    # 检查任务是否属于当前用户
    if task.user_id and task.user_id != current_user.id:
        raise TaskNotFoundException(task_id)

    return ResponseModel(data=task)


@router.delete("/tasks/{task_id}", response_model=ResponseModel)
async def cancel_task(
    task_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """取消任务

    只能取消当前用户的任务

    Args:
        task_id: 任务 ID

    Returns:
        取消结果

    Raises:
        TaskNotFoundException: 任务不存在或无权访问
        BusinessException: 取消失败
    """
    try:
        # 先检查任务是否属于当前用户
        task = await task_manager.get_task(task_id)
        if not task:
            raise TaskNotFoundException(task_id)

        if task.user_id and task.user_id != current_user.id:
            raise TaskNotFoundException(task_id)

        success = await task_manager.cancel_task(task_id)

        if not success:
            raise BusinessException(
                ErrorCode.TASK_CANCELLED,
                "Task cannot be cancelled (already completed or failed)",
                {"task_id": task_id}
            )

        return ResponseModel(
            message="Task cancelled successfully",
            data={"task_id": task_id, "cancelled": True}
        )

    except TaskNotFoundException:
        raise
    except Exception as e:
        logger.error(f"Failed to cancel task {task_id}: {e}", exc_info=True)
        raise BusinessException(
            ErrorCode.UNKNOWN_ERROR,
            "Failed to cancel task",
            {"task_id": task_id, "reason": str(e)}
        )
