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

Graceful-shutdown note
----------------------
The C++ library creates internal threads (``ApiServiceThread``) for
receiving multicast quotes and delivering them to the SWIG director
callback (``on_quote``).  When the Python interpreter starts
finalizing (e.g. Ctrl-C or normal exit), ``take_gil`` inside CPython
3.13 calls ``PyThread_exit_thread()`` which triggers
``_Unwind_ForcedUnwind`` through the C++ frames and ultimately
``abort()``.

To prevent this, ``demo.shutdown()`` stops the C++ threads first
(``unsubscribe_quote`` + ``logout``), then calls ``os._exit(0)`` to
skip Python's finalization entirely.

**Do NOT use ``atexit``** – atexit handlers execute during
``Py_FinalizeEx``, which is exactly the window where the crash
happens.
"""

from __future__ import annotations

import logging
import signal
import py_xlt_api as xlt

try:
    from quote_demo import QuoteAccount, XLTQuoteDemo, default_config
except ImportError:
    from .quote_demo import QuoteAccount, XLTQuoteDemo, default_config


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

    demo = XLTQuoteDemo(config=default_config())
    print("API version: %s" % demo.api_version())

    # Handle SIGTERM (e.g. ``kill <pid>``).
    # demo.shutdown() calls os._exit(0) internally, so we never return.
    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 = QuoteAccount(
        client_id=1,
        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_quote():
        return -1
    #
    # if not demo.query_static_quote_info():
    #     return -1

    # 【演示】查询上交所指定证券的level1行情
    # if not demo.query_level1_quote(xlt.ExchangeIndex_SH, "600000"):
    #     return -1
    # 【演示】查询深交所指定证券的level1行情
    # if not demo.query_level1_quote(xlt.ExchangeIndex_SZ, "000001"):
    #     return -1
    # 【演示】查询全量level1行情
    # if not demo.query_all_level1_quote():
    #     return -1

    # 【演示】请求回补上交所通道1的逐笔行情，序号范围 [1, 100]
    # import py_xlt_api as xlt
    # if not demo.request_rebuild_tick_quote(xlt.ExchangeIndex_SH, 1, 1, 100):
    #     return -1
    # 【演示】请求回补深交所通道2013的逐笔行情，序号范围 [1, 100]
    if not demo.request_rebuild_tick_quote(xlt.ExchangeIndex_SZ, 2019, 1, 100):
        return -1

    demo.run_forever()
    return 0


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

