"""注册实例数据看板:快照 GET + SSE + 手动刷新(对齐中控)."""
from __future__ import annotations

from typing import Any, Callable, Optional

from flask import Flask, Response, jsonify, stream_with_context


def register_instance_dashboard_routes(
    app: Flask,
    *,
    login_required: Callable,
    get_db: Callable,
    fetch_options_positions: Optional[Callable[[], list[dict[str, Any]]]] = None,
    hedge_enabled: bool | Callable[[], bool] = False,
    enrich_orders: Optional[Callable[[list[dict[str, Any]]], list[dict[str, Any]]]] = None,
) -> None:
    from lib.instance.instance_dashboard_cache import instance_dashboard_store
    from lib.instance.instance_dashboard_lib import build_instance_dashboard_payload

    def _hedge_on() -> bool:
        if callable(hedge_enabled):
            try:
                return bool(hedge_enabled())
            except Exception:
                return False
        return bool(hedge_enabled)

    def _build() -> dict[str, Any]:
        conn = get_db()
        try:
            payload = build_instance_dashboard_payload(
                conn,
                fetch_options_positions=fetch_options_positions,
                hedge_enabled=_hedge_on(),
            )
            if callable(enrich_orders) and payload.get("ok") and isinstance(payload.get("orders"), dict):
                items = list(payload["orders"].get("items") or [])
                try:
                    enriched = enrich_orders(items) or items
                except Exception:
                    enriched = items
                payload["orders"]["items"] = enriched
                payload["orders"]["count"] = len(enriched)
            return payload
        finally:
            conn.close()

    instance_dashboard_store.start(_build)

    @app.route("/api/instance/dashboard")
    @login_required
    def api_instance_dashboard():
        return jsonify(instance_dashboard_store.snapshot_dict())

    @app.route("/api/instance/dashboard/stream")
    @login_required
    def api_instance_dashboard_stream():
        return Response(
            stream_with_context(instance_dashboard_store.iter_sse()),
            mimetype="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "X-Accel-Buffering": "no",
            },
        )

    @app.route("/api/instance/dashboard/refresh", methods=["POST"])
    @login_required
    def api_instance_dashboard_refresh():
        instance_dashboard_store.request_refresh()
        return jsonify(
            {
                "ok": True,
                "dashboard_version": instance_dashboard_store.version,
            }
        )
