"""
标签分类视图路由
处理标签分类的 API 接口
"""
from fastapi import APIRouter, Query, Path, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.ext.asyncio import AsyncSession

from app.base.async_mysql_connection import get_db
from app.services.tag_category_service import TagCategoryService
from app.services.auth_service import AuthService
from app.sample.models.tag_category import TagCategory
from app.sample.schemas.tag_category import (
    TagCategoryCreate,
    TagCategoryUpdate,
    TagCategoryBatchDeleteRequest,
    TagCategoryMoveRequest,
    TagCategoryTreeResponse
)
from app.schemas.base import ResponseSchema, PaginatedResponseSchema

router = APIRouter(prefix="/sample/tag", tags=["样本中心-标签分类"])
security = HTTPBearer()


async def get_current_user_id(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    session: AsyncSession = Depends(get_db)
) -> str:
    """获取当前登录用户UUID"""
    auth_service = AuthService(session)
    user = await auth_service.get_current_user(credentials.credentials)
    return user.id


@router.post("/create", response_model=ResponseSchema)
async def create_tag_category(
    tag_data: TagCategoryCreate,
    session: AsyncSession = Depends(get_db),
    current_user_id: str = Depends(get_current_user_id)
):
    """创建标签分类"""
    service = TagCategoryService(session)
    result = await service.create_tag_category(tag_data, created_by=current_user_id)
    await session.commit()
    
    return ResponseSchema(
        code=200,
        message="创建标签分类成功",
        data=result.model_dump()
    )


@router.get("/detail/{category_id}", response_model=ResponseSchema)
async def get_tag_category(
    category_id: int = Path(..., description="分类ID"),
    session: AsyncSession = Depends(get_db)
):
    """获取标签分类详情"""
    service = TagCategoryService(session)
    result = await service.get_tag_category_by_id(category_id)
    
    return ResponseSchema(
        code=200,
        message="获取成功",
        data=result.model_dump() if result else None
    )


@router.get("/list", response_model=PaginatedResponseSchema)
async def list_tag_categories(
    parent_id: int = Query(None, description="父级分类ID"),
    status: int = Query(None, description="状态筛选"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    session: AsyncSession = Depends(get_db)
):
    """列表查询标签分类"""
    skip = (page - 1) * page_size
    
    service = TagCategoryService(session)
    categories = await service.list_tag_categories(
        parent_id=parent_id,
        status=status,
        skip=skip,
        limit=page_size
    )
    
    return PaginatedResponseSchema(
        code=200,
        message="获取标签分类列表成功",
        data=[cat.model_dump() for cat in categories],
        meta={
            "page": page,
            "page_size": page_size,
            "total": len(categories)
        }
    )


@router.post("/update/{category_id}", response_model=ResponseSchema)
async def update_tag_category(
    category_id: int = Path(..., description="分类ID"),
    tag_data: TagCategoryUpdate = None,
    session: AsyncSession = Depends(get_db)
):
    """更新标签分类"""
    service = TagCategoryService(session)
    result = await service.update_tag_category(category_id, tag_data)
    await session.commit()
    
    return ResponseSchema(
        code=200,
        message="更新标签分类成功",
        data=result.model_dump()
    )


@router.post("/delete/{category_id}", response_model=ResponseSchema)
async def delete_tag_category(
    category_id: int = Path(..., description="分类ID"),
    soft_delete: bool = Query(True, description="是否软删除"),
    session: AsyncSession = Depends(get_db)
):
    """删除标签分类"""
    service = TagCategoryService(session)
    await service.delete_tag_category(category_id, soft_delete=soft_delete)
    await session.commit()
    
    return ResponseSchema(
        code=200,
        message="删除标签分类成功"
    )


@router.get("/tree", response_model=ResponseSchema)
async def get_category_tree(
    include_disabled: bool = Query(False, description="是否包含禁用分类"),
    session: AsyncSession = Depends(get_db)
):
    """获取标签分类树（层级结构）"""
    service = TagCategoryService(session)
    tree = await service.get_category_tree(root_id=0, include_disabled=include_disabled)
    
    return ResponseSchema(
        code=200,
        message="获取分类树成功",
        data=[_build_tree_response(node) for node in tree]
    )


def _build_tree_response(category: TagCategory) -> dict:
    """将 TagCategory 转换为完整的树响应结构"""
    return {
        'id': category.id,
        'parent_id': category.parent_id,
        'parent_name': getattr(category, 'parent_name', None),
        'name': category.name,
        'path': category.path,
        'level': category.level,
        'type': category.type,
        'sort_no': category.sort_no,
        'status': category.status,
        'is_deleted': category.is_deleted,
        'created_by': category.created_by,
        'created_by_name': getattr(category, 'created_by_name', None),
        'created_at': category.created_at,
        'updated_by': category.updated_by,
        'updated_by_name': getattr(category, 'updated_by_name', None),
        'updated_at': category.updated_at,
        'children': [_build_tree_response(child) for child in (getattr(category, 'children', None) or [])] if hasattr(category, 'children') and category.children else None
    }


@router.get("/breadcrumb/{category_id}", response_model=ResponseSchema)
async def get_category_breadcrumb(
    category_id: int = Path(..., description="分类ID"),
    session: AsyncSession = Depends(get_db)
):
    """获取分类的面包屑路径"""
    service = TagCategoryService(session)
    breadcrumb = await service.get_breadcrumb(category_id)
    
    return ResponseSchema(
        code=200,
        message="获取面包屑路径成功",
        data=breadcrumb
    )


@router.post("/batch/delete", response_model=ResponseSchema)
async def batch_delete_categories(
    request: TagCategoryBatchDeleteRequest,
    soft_delete: bool = Query(True, description="是否软删除"),
    session: AsyncSession = Depends(get_db)
):
    """批量删除标签分类"""
    service = TagCategoryService(session)
    success_count, message = await service.batch_delete_tag_categories(
        request.ids, soft_delete=soft_delete
    )
    await session.commit()
    
    return ResponseSchema(
        code=200,
        message=message,
        data={"success_count": success_count, "total": len(request.ids)}
    )


@router.post("/move/{category_id}", response_model=ResponseSchema)
async def move_tag_category(
    category_id: int = Path(..., description="分类ID"),
    request: TagCategoryMoveRequest = None,
    session: AsyncSession = Depends(get_db)
):
    """移动分类到新的父分类"""
    service = TagCategoryService(session)
    result = await service.move_tag_category(category_id, request.parent_id)
    await session.commit()
    
    return ResponseSchema(
        code=200,
        message="移动分类成功",
        data=result.model_dump()
    )


@router.post("/reorder/{category_id}", response_model=ResponseSchema)
async def reorder_tag_category(
    category_id: int = Path(..., description="分类ID"),
    sort_no: int = Query(..., description="新的排序号"),
    session: AsyncSession = Depends(get_db)
):
    """重新排序分类"""
    service = TagCategoryService(session)
    result = await service.reorder_siblings(category_id, sort_no)
    await session.commit()
    
    return ResponseSchema(
        code=200,
        message="排序成功",
        data=result.model_dump()
    )


@router.get("/children-count/{category_id}", response_model=ResponseSchema)
async def get_children_count(
    category_id: int = Path(..., description="分类ID"),
    recursive: bool = Query(False, description="是否递归计算所有后代"),
    session: AsyncSession = Depends(get_db)
):
    """获取分类的子分类数量"""
    service = TagCategoryService(session)
    count = await service.get_children_count(category_id, recursive=recursive)
    
    return ResponseSchema(
        code=200,
        message="获取子分类数量成功",
        data={"count": count}
    )
