import os
import sys
from pathlib import Path

from Module.DeviceInfo import Deviceinfo
from Module.FlaskSubprocessManager import FlaskSubprocessManager
from Utils.LogManager import LogManager

# 确定 exe 或 py 文件所在目录
BASE = Path(getattr(sys, 'frozen', False) and sys.executable or __file__).resolve().parent
LOG_DIR = BASE / "log"
LOG_DIR.mkdir(exist_ok=True)  # 确保 log 目录存在

print(f"日志目录: {LOG_DIR}")

def _run_flask_role():
    from Module import FlaskService
    port = int(os.getenv("FLASK_COMM_PORT", "34567"))  # 固定端口的兜底仍是 34567
    app_factory = getattr(FlaskService, "create_app", None)
    app = app_factory() if callable(app_factory) else FlaskService.app
    app.run(host="0.0.0.0", port=port + 1, debug=False, use_reloader=False)

if "--role=flask" in sys.argv:
    _run_flask_role()
    sys.exit(0)

# 项目入口
if __name__ == "__main__":
    # 清空日志等
    # LogManager.clearLogs()

    # 启动 Flask 子进程
    manager = FlaskSubprocessManager.get_instance()
    manager.start()

    # 设备监听（即使失败/很快返回，也不会导致主进程退出）
    try:
        info = Deviceinfo()
        info.startDeviceListener()
    except Exception as e:
        print("[WARN] Device listener not running:", e)

    # === 保活：阻塞主线程，直到收到 Ctrl+C/关闭 ===
    import threading, time, signal

    stop = threading.Event()

    def _handle(_sig, _frm):
        stop.set()
    
    # Windows 上 SIGINT/SIGTERM 都可以拦到
    try:
        signal.signal(signal.SIGINT, _handle)
        signal.signal(signal.SIGTERM, _handle)
    except Exception:
        pass  # 某些环境可能不支持，忽略

    try:
        while not stop.is_set():
            time.sleep(1)
    finally:
        # 进程退出前记得把子进程关掉
        manager.stop()
