"""策略交易记录页:已结束趋势 / 顺势加仓快照(三所统一)."""
from __future__ import annotations

import json
from typing import Any

from flask import flash, redirect, url_for

from lib.strategy.strategy_snapshot_lib import (
    STRATEGY_SNAPSHOTS_MAX_ROWS,
    dedupe_strategy_snapshots,
    list_strategy_snapshots_split,
)


def load_strategy_records_page(
    conn, *, limit: int = STRATEGY_SNAPSHOTS_MAX_ROWS
) -> dict[str, Any]:
    try:
        if dedupe_strategy_snapshots(conn):
            conn.commit()
    except Exception:
        pass
    trend, roll, symbols = list_strategy_snapshots_split(conn, limit=limit)
    return {
        "strategy_trend_records": trend,
        "strategy_roll_records": roll,
        "strategy_record_symbols": symbols,
        "strategy_records_limit": limit,
        "strategy_snapshots": trend + roll,
    }


def register_strategy_records(app, cfg: dict[str, Any]) -> None:
    login_required = cfg["login_required"]
    get_db = cfg["get_db"]

    def _lr(f):
        return login_required(f)

    @_lr
    @app.route("/strategy/records")
    def strategy_records_page():
        m = cfg.get("app_module")
        fn = getattr(m, "render_main_page", None)
        if not callable(fn):
            flash("render_main_page 未配置")
            return redirect(url_for("strategy_trading_page"))
        return fn("strategy_records")

    @_lr
    @app.route("/strategy/records/<int:snap_id>")
    def strategy_records_detail(snap_id: int):
        conn = get_db()
        row = conn.execute(
            "SELECT * FROM strategy_trade_snapshots WHERE id=?",
            (int(snap_id),),
        ).fetchone()
        conn.close()
        if not row:
            flash("未找到该策略快照")
            return redirect(url_for("strategy_records_page"))
        try:
            snap = json.loads(row["snapshot_json"] or "{}")
        except Exception:
            snap = {}
        dca = snap.get("dca_levels") or []
        flash(
            f"快照 #{snap_id} {row['strategy_type']} {row['symbol']} "
            f"{row['result_label']} · 补仓档 {len(dca)} 项(详情见列表页)"
        )
        return redirect(url_for("strategy_records_page"))
