"""实例顶栏 / 系统设置区块显示开关(存 SQLite,即时生效)."""
from __future__ import annotations

from typing import Any, Callable, Optional

from lib.instance.runtime_settings_lib import runtime_get_prefix, runtime_set_many, with_db

DISPLAY_RUNTIME_PREFIX = "display."

DEFAULT_INSTANCE_DISPLAY: dict[str, bool] = {
    "show_nav_dashboard": False,
    "show_nav_strategy": True,
    "show_nav_strategy_records": True,
    "show_nav_records": True,
    "show_nav_stats": True,
    "show_nav_risk_policy": True,
    "show_nav_env_config": True,
    "show_nav_options": True,
    "show_nav_options_review": True,
    "show_nav_hedge_plan": True,
    "show_settings_transfer": True,
    "show_settings_export": True,
    "show_settings_password": True,
    "show_settings_exchange_api": True,
    "show_settings_options_swap": True,
    "show_settings_options_transfer": True,
}

DISPLAY_LABELS: dict[str, str] = {
    "show_nav_dashboard": "数据看板",
    "show_nav_strategy": "策略交易",
    "show_nav_strategy_records": "策略交易记录",
    "show_nav_records": "交易记录与复盘",
    "show_nav_stats": "统计分析",
    "show_nav_risk_policy": "风控说明",
    "show_nav_env_config": "env配置",
    "show_nav_options": "期权",
    "show_nav_options_review": "期权复盘",
    "show_nav_hedge_plan": "对冲计划",
    "show_settings_transfer": "资金划转",
    "show_settings_export": "数据导出",
    "show_settings_password": "账户密码修改",
    "show_settings_exchange_api": "交易所 API",
    "show_settings_options_swap": "期权币种兑换",
    "show_settings_options_transfer": "期权资金划转",
}

NAV_TAB_ALLOWED: dict[str, str] = {
    "dashboard": "show_nav_dashboard",
    "strategy": "show_nav_strategy",
    "strategy_records": "show_nav_strategy_records",
    "records": "show_nav_records",
    "stats": "show_nav_stats",
    "risk_policy": "show_nav_risk_policy",
    "env_config": "show_nav_env_config",
    "options": "show_nav_options",
    "options_review": "show_nav_options_review",
    "hedge_plan": "show_nav_hedge_plan",
}


def normalize_display_prefs(raw: dict | None) -> dict[str, bool]:
    out = dict(DEFAULT_INSTANCE_DISPLAY)
    if isinstance(raw, dict):
        for key in DEFAULT_INSTANCE_DISPLAY:
            if key in raw:
                out[key] = bool(raw[key])
    return out


def _load_from_conn(conn) -> dict[str, bool]:
    stored = runtime_get_prefix(conn, DISPLAY_RUNTIME_PREFIX)
    merged: dict[str, Any] = {}
    for key in DEFAULT_INSTANCE_DISPLAY:
        sk = key
        if sk in stored:
            merged[key] = stored[sk].strip().lower() in ("1", "true", "yes", "on")
    return normalize_display_prefs(merged)


def get_display_prefs(get_db: Callable) -> dict[str, bool]:
    return with_db(get_db, _load_from_conn)


def save_display_prefs(get_db: Callable, prefs: dict) -> dict[str, bool]:
    normalized = normalize_display_prefs(prefs)

    def _save(conn):
        mapping = {DISPLAY_RUNTIME_PREFIX + k: ("1" if v else "0") for k, v in normalized.items()}
        runtime_set_many(conn, mapping)
        return normalized

    return with_db(get_db, _save)


def display_prefs_template_context(get_db: Callable) -> dict[str, Any]:
    prefs = get_display_prefs(get_db)
    return {"display": prefs, "display_meta": display_meta_for_ui()}


def tab_allowed(tab: str, display: Optional[dict[str, bool]] = None) -> bool:
    prefs = normalize_display_prefs(display or {})
    key = NAV_TAB_ALLOWED.get((tab or "").strip())
    if not key:
        return True
    return bool(prefs.get(key, True))


def display_meta_for_ui() -> list[dict[str, Any]]:
    nav_keys = [
        "show_nav_dashboard",
        "show_nav_strategy",
        "show_nav_strategy_records",
        "show_nav_records",
        "show_nav_stats",
        "show_nav_risk_policy",
        "show_nav_env_config",
        "show_nav_options",
        "show_nav_options_review",
        "show_nav_hedge_plan",
    ]
    settings_keys = [
        "show_settings_exchange_api",
        "show_settings_transfer",
        "show_settings_export",
        "show_settings_password",
        "show_settings_options_swap",
        "show_settings_options_transfer",
    ]
    return [
        {"group": "顶栏导航", "entries": [{"key": k, "label": DISPLAY_LABELS[k]} for k in nav_keys]},
        {"group": "系统设置区块", "entries": [{"key": k, "label": DISPLAY_LABELS[k]} for k in settings_keys]},
    ]
