"""交易记录列表分页(三所 /records 共用)."""

from __future__ import annotations

from typing import Any, Callable


def list_trade_records_page(
    conn: Any,
    start_bj: str,
    end_bj: str,
    *,
    tr_ts: str,
    to_effective_fn: Callable[[Any], dict[str, Any]],
    filter_fn: Callable[[list[dict[str, Any]]], list[dict[str, Any]]],
    limit: int = 5,
    offset: int = 0,
    fetch_cap: int = 1000,
) -> dict[str, Any]:
    """按列表窗拉取、enrich、过滤「错过」后分页."""
    limit = max(1, min(100, int(limit or 5)))
    offset = max(0, int(offset or 0))
    raw_records = conn.execute(
        f"SELECT * FROM trade_records WHERE {tr_ts} >= ? AND {tr_ts} <= ? "
        f"ORDER BY id DESC LIMIT ?",
        (start_bj, end_bj, int(fetch_cap)),
    ).fetchall()
    records = filter_fn([to_effective_fn(r) for r in raw_records])
    total = len(records)
    pages = max(1, (total + limit - 1) // limit) if total else 1
    page = (offset // limit) + 1 if limit else 1
    if page > pages:
        page = pages
        offset = (page - 1) * limit
    items = records[offset : offset + limit]
    return {
        "ok": True,
        "items": items,
        "total": total,
        "limit": limit,
        "offset": offset,
        "page": page,
        "pages": pages,
    }
