"""中控只读聚合:OKX 期权持仓 / 资金 / 本地统计."""

from __future__ import annotations

from typing import Any

from lib.options.options_history_lib import load_options_history
from lib.options.options_stats_lib import compute_options_stats_from_history


def _compute_options_stats(ex, cfg) -> dict[str, Any]:
    history = load_options_history(ex, cfg)
    return compute_options_stats_from_history(history)


def build_options_hub_snapshot(cfg: dict[str, Any]) -> dict[str, Any]:
    if not cfg.get("enabled"):
        return {"ok": True, "enabled": False}
    ex = cfg.get("exchange_options")
    ready_fn = cfg.get("options_api_ready")
    if not callable(ready_fn):
        return {"ok": False, "enabled": True, "msg": "期权模块未就绪"}
    ok, reason = ready_fn(ex)
    if not ok:
        return {"ok": False, "enabled": True, "msg": reason or "期权 API 未配置"}
    try:
        from lib.options.options_positions_lib import build_display_option_positions

        raw = cfg["fetch_option_positions"](ex)
        if raw is None:
            return {"ok": False, "enabled": True, "msg": "获取期权持仓失败"}
        positions = build_display_option_positions(cfg, ex, raw)
        target_monitors: list[dict[str, Any]] = []
        try:
            conn = cfg["get_db"]()
            try:
                from lib.hedge_plan.hedge_plan_db import active_options_targets_by_inst
                from lib.options.options_target_lib import list_active_targets, list_closing_targets, targets_by_inst

                target_monitors = list_active_targets(conn) + list_closing_targets(conn)
                tgt_map = targets_by_inst(conn)
                hedge_target_map = active_options_targets_by_inst(conn)
                target_monitors.extend(hedge_target_map.values())
                for p in positions:
                    mon = tgt_map.get(str(p.get("inst_id") or ""))
                    if mon:
                        p["target_index"] = mon.get("target_index")
                        p["target_monitor_id"] = mon.get("id")
                        p["target_monitor"] = mon
                    hedge_target = hedge_target_map.get(str(p.get("inst_id") or ""))
                    if hedge_target:
                        p["hedge_plan_target"] = hedge_target
                        if not mon:
                            # 中控卡片共用 target_index 只读展示；实际平仓仍由对冲计划监控处理。
                            p["target_index"] = hedge_target.get("target_index")
            finally:
                conn.close()
        except Exception:
            target_monitors = []
        from lib.options.options_positions_lib import net_pnl_from_display_row

        upl_total = 0.0
        has_upl = False
        for p in positions:
            # 与持仓卡「净盈亏」一致(买一回收−权利金);不用交易所标记价 upl
            net = net_pnl_from_display_row(p)
            if net is None:
                continue
            has_upl = True
            upl_total += float(net)
        bal = cfg["fetch_options_balances"](ex)
        stats = _compute_options_stats(ex, cfg)
        return {
            "ok": True,
            "enabled": True,
            "positions": positions,
            "position_count": len(positions),
            "target_monitors": target_monitors,
            "upl_total_usdc": round(upl_total, 4) if has_upl else None,
            "balances": bal,
            "funding_usdc": bal.get("funding_usdc"),
            "funding_usdt": bal.get("funding_usdt"),
            "trading_usdc": bal.get("trading_usdc"),
            "trading_usdt": bal.get("trading_usdt"),
            "stats": stats,
            "trade_budget": cfg.get("trade_budget"),
            "account_label": cfg.get("account_label") or "OKX期权",
        }
    except Exception as e:
        return {"ok": False, "enabled": True, "msg": str(e)}
