"""LIVE 下单用的运行时合约解析（禁止只用 env 默认 perp_inst_id）。"""

from __future__ import annotations

from ..config import Settings
from ..exchange.runtime import load_runtime_settings


def live_settings() -> Settings:
    return load_runtime_settings()


def resolve_perp_inst_id(db, *, group_id: str | None = None) -> str:
    """优先组内落库合约，否则 DB/交易所默认（load_runtime_settings）。"""
    s = live_settings()
    if group_id:
        try:
            row = db.fetchone(
                "SELECT perp_inst_id FROM groups WHERE group_id=?",
                (group_id,),
            )
            if row and row["perp_inst_id"]:
                return str(row["perp_inst_id"])
        except Exception:
            pass
    return str(s.perp_inst_id)
