#!/usr/bin/env python3
"""
启动脚本 - 同时启动视频服务器和主API服务器
解决视频流阻塞主线程的问题
"""

import subprocess
import sys
import os
import time
import signal
import logging
import argparse

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def start_servers():
    """启动视频服务器和主API服务器"""
    parser = argparse.ArgumentParser(description='启动控制面板服务器')
    parser.add_argument('--localtest', action='store_true', help='前端本地测试模式，强制 API_BASE_URL 指向 http://localhost:5010/api')
    args = parser.parse_args()

    script_dir = os.path.dirname(os.path.abspath(__file__))

    # 启动视频流服务器
    logger.info("启动独立视频流服务器...")
    video_server_process = subprocess.Popen([
        sys.executable, 'video_stream_server.py'
    ], cwd=script_dir)

    # 等待视频服务器启动
    time.sleep(3)

    # 启动主API服务器（按需传递 localtest 标志）
    logger.info("启动主API服务器{}...".format(" (localtest)" if args.localtest else ""))
    env = os.environ.copy()
    if args.localtest:
        env['SDK_LOCALTEST'] = '1'
    api_cmd = [sys.executable, 'demo_api_server.py']
    if args.localtest:
        api_cmd.append('--localtest')
    api_server_process = subprocess.Popen(api_cmd, cwd=script_dir, env=env)

    logger.info("所有服务器已启动！")
    logger.info("主API服务器: http://localhost:5010")
    logger.info("视频流服务器: http://localhost:5011")
    if args.localtest:
        logger.info("已启用 --localtest：前端将使用 http://localhost:5010/api 作为 API_BASE_URL")
    logger.info("按 Ctrl+C 停止所有服务器")
    
    def signal_handler(sig, frame):
        logger.info("正在停止所有服务器...")
        try:
            video_server_process.terminate()
            api_server_process.terminate()
            
            # 等待进程结束
            video_server_process.wait(timeout=5)
            api_server_process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            logger.warning("强制终止服务器进程...")
            video_server_process.kill()
            api_server_process.kill()
        
        logger.info("所有服务器已停止")
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)
    
    try:
        # 等待任一进程结束
        while video_server_process.poll() is None and api_server_process.poll() is None:
            time.sleep(1)
    except KeyboardInterrupt:
        signal_handler(signal.SIGINT, None)

if __name__ == '__main__':
    try:
        start_servers()
    except Exception as e:
        logger.error(f"启动服务器失败: {e}")
        sys.exit(1)
