"""
在项目根目录执行(会加载根目录 .env):
  python scripts/verify_gate_funding.py

依次探测:[0] swap 余额(与 App「交易账户」同源);[1]–[3] 现货 / 统一账户资金路径.
打印 GATE_API_KEY 前 8 位便于与 Gate 控制台核对(不含 Secret).用于服务器自检.
"""
from __future__ import annotations

import importlib.util
import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
    sys.path.insert(0, ROOT)


def _load_app():
    path = os.path.join(ROOT, "app.py")
    spec = importlib.util.spec_from_file_location("crypto_app", path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def main():
    os.chdir(ROOT)
    mod = _load_app()
    print("LIVE_TRADING_ENABLED =", os.getenv("LIVE_TRADING_ENABLED"))
    ok, reason = mod.ensure_exchange_live_ready()
    print("ensure_exchange_live_ready =", ok, repr(reason))
    if not ok:
        print("跳过私有接口探测")
        return 1

    mod.ensure_markets_loaded()

    k = (os.getenv("GATE_API_KEY") or "").strip()
    s = (os.getenv("GATE_API_SECRET") or "").strip()
    if not k or "REPLACE" in k.upper():
        print("WARN: GATE_API_KEY 为空或仍像占位符,请核对 .env")
    if not s or "REPLACE" in s.upper():
        print("WARN: GATE_API_SECRET 为空或仍像占位符,请核对 .env")
    print("GATE_API_KEY prefix (8 chars):", (k[:8] + "…") if len(k) > 8 else "(short)")

    # 0) swap — 与 App「交易账户」余额同源(优先看此项是否与网页一致)
    try:
        bal = mod.exchange.fetch_balance({"type": "swap"})
        v0 = mod._extract_usdt_total(bal)
        print("[0] fetch_balance(swap) USDT total =", v0)
    except Exception as e:
        print("[0] fetch_balance(swap) FAILED:", type(e).__name__, e)

    # 1) fetch_balance spot + marginMode spot
    try:
        bal = mod.exchange.fetch_balance({"type": "spot", "marginMode": "spot"})
        v = mod._extract_usdt_total(bal)
        print("[1] fetch_balance(spot,marginMode=spot) USDT total =", v)
    except Exception as e:
        print("[1] fetch_balance(spot) FAILED:", type(e).__name__, e)

    # 2) raw spot accounts
    try:
        resp = mod.exchange.privateSpotGetAccounts({})
        v2 = mod._parse_gate_spot_accounts_response_usdt(resp)
        print("[2] privateSpotGetAccounts USDT =", v2)
    except Exception as e:
        print("[2] privateSpotGetAccounts FAILED:", type(e).__name__, e)

    # 3) unified accounts raw
    try:
        raw = mod.exchange.privateUnifiedGetAccounts({})
        body = raw
        if isinstance(body, dict) and isinstance(body.get("result"), dict):
            body = body["result"]
        if isinstance(body, dict):
            keys = sorted(body.keys())
            print("[3] unified top-level keys (sample):", keys[:25], "..." if len(keys) > 25 else "")
        v3 = mod._parse_usdt_from_gate_unified_accounts_body(body) if isinstance(body, dict) else None
        print("[3] parsed unified USDT =", v3)
    except Exception as e:
        print("[3] privateUnifiedGetAccounts FAILED:", type(e).__name__, e)

    fu = mod._fetch_gate_funding_usdt()
    print(">>> _fetch_gate_funding_usdt() =", fu)
    f, t = mod.get_exchange_capitals(force=True)
    print(">>> get_exchange_capitals(force=True) funding, trading =", f, t)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
