import time
import json
import argparse

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


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


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

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

    args = parser.parse_args()

    # ===== 2️⃣ logger =====
    app_logger = setup_app_logger("Sentinel")
    app_logger.info("Sentinel Logger is ready! All VSC macros are hooked.")

    # ===== 3️⃣ 读取配置 =====
    cfg_data = load_config(args.config)

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

    wrappers = []

    # ===== 4️⃣ 启动 groups =====
    for item in groups_conf:
        cfg = GroupConfig.from_json(item)

        if not cfg.enable:
            app_logger.info(f"Group [{cfg.identifier}] is disabled. Skipping.")
            continue

        app_logger.info(f"Starting wrapper for group [{cfg.identifier}]...")

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

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

    app_logger.info(
        f"Successfully started {len(wrappers)} Sentinel groups. Press Ctrl+C to stop."
    )

    # ===== 5️⃣ keep alive =====
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        app_logger.info("Shutting down Sentinels...")
        for wrapper in wrappers:
            wrapper.stop()


if __name__ == "__main__":
    main()