"""
分页工具函数

提供分页查询和响应创建的辅助功能
"""
from typing import List, Any, Optional, TypeVar, Generic
from fastapi import Query, Request
from src.models.response import PaginationParams, PaginationMetadata, ResponseModel, ErrorCode

T = TypeVar('T')


class Paginator(Generic[T]):
    """分页器

    用于处理分页查询和响应创建
    """

    def __init__(
        self,
        items: List[T],
        total: int,
        page: int,
        page_size: int
    ):
        """初始化分页器

        Args:
            items: 当前页的数据列表
            total: 总记录数
            page: 当前页码
            page_size: 每页数量
        """
        self.items = items
        self.total = total
        self.page = page
        self.page_size = page_size

    def get_metadata(self) -> PaginationMetadata:
        """获取分页元数据"""
        return PaginationMetadata.create(
            page=self.page,
            page_size=self.page_size,
            total=self.total
        )

    def to_response(self, request: Optional[Request] = None) -> ResponseModel:
        """转换为分页响应（使用 ResponseModel）"""
        total_pages = (self.total + self.page_size - 1) // self.page_size if self.page_size > 0 else 0

        # data 包含 items 和 pagination
        data = {
            "items": self.items,
            "pagination": {
                "page": self.page,
                "page_size": self.page_size,
                "total": self.total,
                "total_pages": total_pages
            }
        }

        from src.models.response import ResponseMeta

        return ResponseModel(
            code=ErrorCode.SUCCESS,
            message="success",
            data=data,
            meta=ResponseMeta(
                page=self.page,
                page_size=self.page_size,
                total=self.total,
                total_pages=total_pages
            )
        )


def create_pagination_params(
    page: int = Query(1, ge=1, description="页码,从1开始"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量,最大100"),
    sort: Optional[str] = Query(None, description="排序字段,格式: field:asc 或 field:desc"),
    filter: Optional[str] = Query(None, description="过滤条件,JSON格式")
) -> PaginationParams:
    """创建分页参数依赖
    
    用作 FastAPI 路由的依赖注入
    
    Example:
        @router.get("/items")
        async def list_items(pagination: PaginationParams = Depends(create_pagination_params)):
            ...
    """
    return PaginationParams(
        page=page,
        page_size=page_size,
        sort=sort,
        filter=filter
    )


def paginate_list(
    items: List[T],
    page: int = 1,
    page_size: int = 20
) -> Paginator[T]:
    """对内存中的列表进行分页
    
    Args:
        items: 完整的数据列表
        page: 页码
        page_size: 每页数量
    
    Returns:
        Paginator: 分页器对象
    """
    total = len(items)
    offset = (page - 1) * page_size
    paginated_items = items[offset:offset + page_size]
    
    return Paginator(
        items=paginated_items,
        total=total,
        page=page,
        page_size=page_size
    )


def parse_sort_param(sort: Optional[str]) -> tuple[Optional[str], Optional[str]]:
    """解析排序参数
    
    Args:
        sort: 排序字符串,格式: "field:asc" 或 "field:desc"
    
    Returns:
        tuple: (字段名, 排序方向) 或 (None, None)
    
    Example:
        >>> parse_sort_param("created_at:desc")
        ("created_at", "desc")
        >>> parse_sort_param("name:asc")
        ("name", "asc")
        >>> parse_sort_param(None)
        (None, None)
    """
    if not sort:
        return None, None
    
    parts = sort.split(":")
    if len(parts) != 2:
        return None, None
    
    field, direction = parts
    direction = direction.lower()
    
    if direction not in ["asc", "desc"]:
        return None, None
    
    return field, direction


def parse_filter_param(filter_str: Optional[str]) -> dict:
    """解析过滤参数
    
    Args:
        filter_str: JSON格式的过滤条件字符串
    
    Returns:
        dict: 过滤条件字典
    
    Example:
        >>> parse_filter_param('{"status": "active", "type": "video"}')
        {"status": "active", "type": "video"}
    """
    if not filter_str:
        return {}
    
    try:
        import json
        return json.loads(filter_str)
    except (json.JSONDecodeError, ValueError):
        return {}
