import time
import json
import argparse

from vs_types import GroupConfig
from gco_wrapper import GCOWrapper
from logger_setup import setup_app_logger

from booker_builtin import BuiltinBookerGCO
from booker_order import OrderBookerGCO


def load_config(path):
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def main():
    # ===== 1️⃣ 命令行参数 =====
    parser = argparse.ArgumentParser(description="Booker Runner")

    parser.add_argument(
        "-c", "--config",
        type=str,
        required=False,
        default="config/config.json",
        help="Path to config.json"
    )

    args = parser.parse_args()

    # ===== 2️⃣ 日志 =====
    app_logger = setup_app_logger("Booker")
    app_logger.info("Booker Logger is ready!")

    # ===== 3️⃣ 加载配置 =====
    cfg_data = load_config(args.config)

    redis_conf = cfg_data.get('redis')
    groups_conf = cfg_data.get('group_list')

    wrappers = []

    # ===== 4️⃣ 启动逻辑 =====
    for item in groups_conf:
        cfg = GroupConfig.from_json(item)
        if not cfg.enable:
            continue

        if cfg.booker.account_source == "order":
            gco_class = OrderBookerGCO
            app_logger.info(f"[{cfg.identifier}] Mode: ORDER (Bound)")
        else:
            gco_class = BuiltinBookerGCO
            app_logger.info(f"[{cfg.identifier}] Mode: BUILT-IN (Unbound)")

        wrapper = GCOWrapper(
            gco_class=gco_class,
            gco_cfg=cfg,
            redis_conf=redis_conf
        )

        wrapper.load()
        wrapper.start()
        wrappers.append(wrapper)

    app_logger.info(f"Started {len(wrappers)} Booker groups.")

    # ===== 5️⃣ 保持运行 =====
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        app_logger.info("Shutting down...")
        for wrapper in wrappers:
            wrapper.stop()


if __name__ == "__main__":
    main()