#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：batch.py
模块描述：批量操作 API 路由

作者：czj
创建日期：2026-07-12
"""

import logging
from typing import List

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.services.batch_service import BatchService
from app.schemas.batch import (
    BatchDeleteRequest,
    BatchUpdateRequest,
    BatchCopyRequest,
    BatchAssignTagsRequest,
    BatchSetPriorityRequest,
    BatchOperationResponse,
)
from app.schemas.test_case import TestCaseResponse

logger = logging.getLogger(__name__)

router = APIRouter()


def get_batch_service(db: AsyncSession = Depends(get_db)) -> BatchService:
    """获取批量操作服务"""
    return BatchService(db)


@router.post("/delete", response_model=BatchOperationResponse)
async def batch_delete_cases(
    request: BatchDeleteRequest,
    service: BatchService = Depends(get_batch_service),
):
    """
    批量删除测试用例

    Args:
        request: 批量删除请求，包含用例ID列表

    Returns:
        BatchOperationResponse: 操作结果统计
    """
    try:
        result = await service.batch_delete(request.case_ids)
        return BatchOperationResponse(
            success=result["success"],
            failed=result["failed"],
            total=result["total"],
            message=f"成功删除 {result['success']} 个用例"
        )
    except Exception as e:
        logger.error(f"批量删除失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量删除失败: {str(e)}")


@router.post("/update", response_model=BatchOperationResponse)
async def batch_update_cases(
    request: BatchUpdateRequest,
    service: BatchService = Depends(get_batch_service),
):
    """
    批量更新测试用例

    Args:
        request: 批量更新请求，包含用例ID列表和更新字段

    Returns:
        BatchOperationResponse: 操作结果统计
    """
    try:
        result = await service.batch_update(request.case_ids, request.updates)
        return BatchOperationResponse(
            success=result["success"],
            failed=result["failed"],
            total=result["total"],
            message=f"成功更新 {result['success']} 个用例"
        )
    except ValueError as e:
        logger.warning(f"批量更新参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"批量更新失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量更新失败: {str(e)}")


@router.post("/copy", response_model=List[TestCaseResponse])
async def batch_copy_cases(
    request: BatchCopyRequest,
    service: BatchService = Depends(get_batch_service),
):
    """
    批量复制测试用例

    Args:
        request: 批量复制请求，包含用例ID列表和目标模块ID

    Returns:
        List[TestCaseResponse]: 新创建的用例列表
    """
    try:
        new_cases, stats = await service.batch_copy(
            request.case_ids,
            request.target_module_id
        )
        logger.info(f"批量复制完成: {stats}")
        return [TestCaseResponse.model_validate(c) for c in new_cases]
    except Exception as e:
        logger.error(f"批量复制失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量复制失败: {str(e)}")


@router.post("/assign-tags", response_model=BatchOperationResponse)
async def batch_assign_tags(
    request: BatchAssignTagsRequest,
    service: BatchService = Depends(get_batch_service),
):
    """
    批量分配标签

    Args:
        request: 批量分配标签请求

    Returns:
        BatchOperationResponse: 操作结果统计
    """
    try:
        result = await service.batch_assign_tags(
            request.case_ids,
            request.tag_names
        )
        return BatchOperationResponse(
            success=result["success"],
            failed=result["failed"],
            total=result["total"],
            message=f"成功分配标签到 {result['success']} 个用例"
        )
    except Exception as e:
        logger.error(f"批量分配标签失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量分配标签失败: {str(e)}")


@router.post("/set-priority", response_model=BatchOperationResponse)
async def batch_set_priority(
    request: BatchSetPriorityRequest,
    service: BatchService = Depends(get_batch_service),
):
    """
    批量设置优先级

    Args:
        request: 批量设置优先级请求

    Returns:
        BatchOperationResponse: 操作结果统计
    """
    try:
        result = await service.batch_set_priority(
            request.case_ids,
            request.priority
        )
        return BatchOperationResponse(
            success=result["success"],
            failed=result["failed"],
            total=result["total"],
            message=f"成功设置 {result['success']} 个用例的优先级"
        )
    except ValueError as e:
        logger.warning(f"批量设置优先级参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"批量设置优先级失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量设置优先级失败: {str(e)}")


@router.post("/enable", response_model=BatchOperationResponse)
async def batch_enable_cases(
    case_ids: List[str],
    service: BatchService = Depends(get_batch_service),
):
    """
    批量启用用例

    Args:
        case_ids: 用例ID列表

    Returns:
        BatchOperationResponse: 操作结果统计
    """
    try:
        result = await service.batch_enable(case_ids)
        return BatchOperationResponse(
            success=result["success"],
            failed=result["failed"],
            total=result["total"],
            message=f"成功启用 {result['success']} 个用例"
        )
    except Exception as e:
        logger.error(f"批量启用失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量启用失败: {str(e)}")


@router.post("/disable", response_model=BatchOperationResponse)
async def batch_disable_cases(
    case_ids: List[str],
    service: BatchService = Depends(get_batch_service),
):
    """
    批量禁用用例

    Args:
        case_ids: 用例ID列表

    Returns:
        BatchOperationResponse: 操作结果统计
    """
    try:
        result = await service.batch_disable(case_ids)
        return BatchOperationResponse(
            success=result["success"],
            failed=result["failed"],
            total=result["total"],
            message=f"成功禁用 {result['success']} 个用例"
        )
    except Exception as e:
        logger.error(f"批量禁用失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量禁用失败: {str(e)}")
