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

from __future__ import annotations

from typing import Any, Callable, Optional


def enrich_trade_price_displays(
    item: dict[str, Any],
    format_price_fn: Optional[Callable[[Any, Any], str]] = None,
) -> dict[str, Any]:
    """为成交/止损/止盈补交易所精度展示字段(供交易记录表直接渲染)."""
    if not format_price_fn or not isinstance(item, dict):
        return item
    sym = item.get("symbol")
    stop_show = item.get("display_open_stop_loss")
    if stop_show in (None, ""):
        stop_show = item.get("initial_stop_loss")
    if stop_show in (None, ""):
        stop_show = item.get("stop_loss")
    tp_show = item.get("effective_take_profit")
    if tp_show in (None, ""):
        tp_show = item.get("take_profit")
    try:
        item["trigger_price_display"] = format_price_fn(sym, item.get("trigger_price"))
        item["stop_loss_display"] = format_price_fn(sym, stop_show)
        item["take_profit_display"] = format_price_fn(sym, tp_show)
    except Exception:
        pass
    return item


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,
    format_price_fn: Optional[Callable[[Any, Any], str]] = None,
) -> 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]
    if format_price_fn is not None:
        items = [enrich_trade_price_displays(dict(it), format_price_fn) for it in items]
    return {
        "ok": True,
        "items": items,
        "total": total,
        "limit": limit,
        "offset": offset,
        "page": page,
        "pages": pages,
    }
