"""Entry point mirroring demo/xlt_trade_api_demo/main.cpp."""

from __future__ import annotations

import logging
import signal

try:
    # Running as a script from this folder
    from trade_demo import TradeAccount, XLTTradeDemo, default_config
except ImportError:
    # Running as a module/package
    from .trade_demo import TradeAccount, XLTTradeDemo, default_config


def main() -> int:
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")

    demo = XLTTradeDemo(config=default_config())

    print("API version: %s" % demo.api_version())

    def _on_sigterm(signo, frame):
        print("\nSIGTERM received, shutting down ...")
        demo.shutdown()          # calls os._exit(0)

    signal.signal(signal.SIGTERM, _on_sigterm)

    if not demo.initialize():
        return -1

    account = TradeAccount(
        client_id=99,
        account_name="88888888888801",
        password="12345678",
        pub_key_base64="XXXXXXXXXXXXXX",
    )

    if not demo.login(account):
        return -1

    print("Trading day: %d" % demo.trading_day())

    if not demo.subscribe_trade_message():
        return -1
    # if not demo.rebuild_trade_message(140, 0, demo.get_account_index()):
    #     return -1

    # 交易授权认证示例（PB/机构场景）
    # if not demo.auth_trade("88888888888801", "12345678"):
    #     return -1
    # if not demo.deauth_trade(demo._trade_token):
    #     return -1

    # 同步获取初始资产/持仓/账户索引（登录成功后可直接调用）
    demo.print_init_assets()
    demo.print_init_positions()
    print("Account index: %d" % demo.get_account_index())

    if not demo.query_assets(demo.get_account_index()):
        return -1
    if not demo.query_positions(demo.get_account_index()):
        return -1
    if not demo.query_orders():
        return -1
    if not demo.query_orders_by_page():
        return -1
    if not demo.query_trades():
        return -1
    # if not demo.query_init_assets(demo.get_account_index()):
    #     return -1
    # if not demo.query_init_positions(demo.get_account_index()):
    #     return -1
    # if not demo.query_trade_account_info():
    #     return -1
    # if not demo.submit_counter_fund_transfer_request(int(xlt.FundTransSide_IN), 3000000, 0):
    #     return -1
    # if not demo.submit_cluster_fund_transfer_request(2000000):
    #     return -1
    # if not demo.rebuild_trade_message(0, 100):
    #     return -1



    # 下单/撤单示例
    xid = demo.insert_order()
    if xid == 0:
        return -1
    # time.sleep(0.5)
    # cancel_xid = demo.cancel_order(xid)
    # if cancel_xid == 0:
    #     return -1

    # 重发订单请求（当委托超时时使用）
    # if not demo.resend_order_request(xid):
    #     return -1

    demo.run_forever()
    return 0


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