#!/usr/bin/env python3
"""
  python scripts/verify_binance_funding.py

打印 BINANCE_API_KEY 前 8 位便于与 Binance 控制台核对(不含 Secret).用于服务器自检.
对比 App:资产 → 资金账户(Funding) / 现货账户(Spot) / U本位合约.
"""
import os
import sys

BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE)


def load_env(path):
    if not os.path.exists(path):
        return
    for line in open(path, "r", encoding="utf-8", errors="ignore"):
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, v = line.split("=", 1)
        k = k.strip().lstrip("\ufeff")
        if k.replace("_", "").isalnum():
            os.environ[k] = v.strip().strip('"').strip("'")


def main():
    load_env(os.path.join(BASE, ".env"))
    k = (os.getenv("BINANCE_API_KEY") or "").strip()
    s = (os.getenv("BINANCE_API_SECRET") or "").strip()
    if not k or "REPLACE" in k.upper():
        print("WARN: BINANCE_API_KEY 为空或仍像占位符,请核对 .env")
    if not s or "REPLACE" in s.upper():
        print("WARN: BINANCE_API_SECRET 为空或仍像占位符,请核对 .env")
    print("BINANCE_API_KEY prefix (8 chars):", (k[:8] + "…") if len(k) > 8 else "(short)")
    print("BINANCE_FUNDING_INCLUDE_SPOT:", os.getenv("BINANCE_FUNDING_INCLUDE_SPOT", "false"))

    import app as mod  # noqa: E402

    mod.ensure_markets_loaded()
    ccy = getattr(mod, "TRANSFER_CCY", "USDT")

    try:
        raw = mod.exchange.sapiGetAssetWalletBalance({"quoteAsset": ccy})
        print(f"\n>>> sapi/v1/asset/wallet/balance (quoteAsset={ccy}):")
        if isinstance(raw, list):
            for row in raw:
                if isinstance(row, dict):
                    print(
                        "   ",
                        row.get("walletName"),
                        "activate=",
                        row.get("activate"),
                        "balance=",
                        row.get("balance"),
                    )
        else:
            print("   ", raw)
    except Exception as e:
        print(">>> wallet/balance error:", e)

    try:
        raw = mod.exchange.sapiPostAssetGetFundingAsset({"asset": ccy})
        print(f"\n>>> get-funding-asset (asset={ccy}):", raw)
    except Exception as e:
        print(">>> get-funding-asset error:", e)

    fu = mod._fetch_binance_funding_usdt()
    print("\n>>> _fetch_binance_funding_usdt() (页顶资金账户) =", fu)
    try:
        fw = mod._fetch_binance_funding_usdt_from_wallet_overview()
        print(">>> _fetch_binance_funding_usdt_from_wallet_overview() =", fw)
        sp = mod._fetch_binance_spot_usdt_total()
        print(">>> _fetch_binance_spot_usdt_total() =", sp)
        sw = mod._fetch_binance_swap_usdt_total()
        print(">>> _fetch_binance_swap_usdt_total() (合约账户) =", sw)
        sf = mod._fetch_binance_swap_usdt_free()
        print(">>> _fetch_binance_swap_usdt_free() (合约可用) =", sf)
    except Exception as e:
        print(">>> balance fetch error:", e)


if __name__ == "__main__":
    main()
