#!/usr/bin/env python3
import argparse
import threading

from app.client import QingjianClient
from app.config import HTTP_HOST, HTTP_PORT
from app.http_api import run_http_server
from app.logger import setup_logger
from app.task_manager import TaskManager


logger = setup_logger()


def start_http(host: str, port: int, tm: TaskManager):
    run_http_server(host=host, port=port, task_manager=tm)


def main():
    parser = argparse.ArgumentParser(description='Qingjian CS launcher')
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument('--api-only', action='store_true', help='only run HTTP API')
    mode.add_argument('--tianwang', action='store_true', help='run HTTP API + websocket client')
    parser.add_argument('--host', default=HTTP_HOST)
    parser.add_argument('--port', type=int, default=HTTP_PORT)
    args = parser.parse_args()

    tm = TaskManager()

    if args.api_only:
        logger.info('启动模式: API Only %s:%s', args.host, args.port)
        start_http(args.host, args.port, tm)
        return

    if args.tianwang:
        logger.info('启动模式: Tianwang (API + WebSocket)')
        th = threading.Thread(target=start_http, args=(args.host, args.port, tm), daemon=True)
        th.start()

    logger.info('启动模式: WebSocket')
    QingjianClient().run()


if __name__ == '__main__':
    main()
