
import subprocess
import signal
import time
import os
from typing import Dict

class ScriptManager:
    def __init__(self):
        self.processes: Dict[str, subprocess.Popen] = {}
        signal.signal(signal.SIGTERM, self._handle_signal)
        signal.signal(signal.SIGINT, self._handle_signal)

    def start_script(self, name: str, script_path: str) -> None:
        """启动指定脚本并记录进程"""
        if name in self.processes:
            print(f"脚本 {name} 已在运行")
            return
            
        proc = subprocess.Popen(
            ["python", script_path],
            start_new_session=True  # 防止僵尸进程
        )
        self.processes[name] = proc
        print(f"已启动脚本 {name} (PID: {proc.pid})")

    def stop_script(self, name: str, timeout=5) -> None:
        """优雅停止指定脚本"""
        if name not in self.processes:
            print(f"脚本 {name} 未运行")
            return

        proc = self.processes[name]
        try:
            proc.terminate()  # 先发送SIGTERM
            proc.wait(timeout=timeout)
        except subprocess.TimeoutExpired:
            proc.kill()  # 超时后强制终止
            print(f"强制终止脚本 {name}")
        finally:
            self.processes.pop(name)
            print(f"已停止脚本 {name}")

    def stop_all(self) -> None:
        """停止所有管理的脚本"""
        for name in list(self.processes.keys()):
            self.stop_script(name)

    def _handle_signal(self, signum, frame) -> None:
        """处理终止信号"""
        print(f"\n接收到终止信号 {signum}, 正在停止所有脚本...")
        self.stop_all()
        exit(0)

    def list_scripts(self) -> None:
        """列出所有运行中的脚本"""
        print("运行中的脚本:")
        for name, proc in self.processes.items():
            status = "运行中" if proc.poll() is None else "已停止"
            print(f"- {name} (PID: {proc.pid}, 状态: {status})")

if __name__ == "__main__":
    manager = ScriptManager()
    # 示例用法
    manager.start_script("worker1", "./filemonitorservice/filemonitorTM9.py")
    manager.start_script("worker2", "./filemonitorservice/filemonitorTM10.py")
    manager.start_script("worker3", "./filemonitorservice/filemonitorTM10A.py")
    manager.start_script("worker4", "./filemonitorservice/filemonitorTM10B.py")
    manager.start_script("worker5", "./filemonitorservice/filemonitorVC22.py")
    manager.start_script("worker6", "./filemonitorservice/filemonitorVC104.py")
    manager.start_script("worker7", "./reportservice/report_tilt.py")
    manager.start_script("worker8", "./reportservice/report_vibration.py")
    manager.start_script("worker9", "./reportservice/email_task.py")
    manager.list_scripts()
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        manager.stop_all()
