package com.fs.live.utils;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * &#064;Description:  专门使用 ff mpg 推流srs直播
 * &#064;Author:  yhq
 * &#064;Date:  20250723
 */
@Component
public class ProcessManager {
    private final Map<String, Process> processMap = new ConcurrentHashMap<>();

    /**
     * 启动进程（命令参数列表，避免字符串 split 导致路径含空格时异常或注入）
     */
    public Process startProcess(List<String> command) throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        Process process = processBuilder.start();

        String processId = getProcessId(process);
        processMap.put(processId, process);

        // 监听进程结束
        CompletableFuture.runAsync(() -> {
            try {
                process.waitFor();
                processMap.remove(processId);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        return process;
    }

    /**
     * 获取进程ID
     */
    private String getProcessId(Process process) {
        try {
            if (process.getClass().getName().equals("java.lang.UNIXProcess")) {
                Field pidField = process.getClass().getDeclaredField("pid");
                pidField.setAccessible(true);
                return String.valueOf(pidField.get(process));
            } else {
                // 对于Windows系统或其他Process实现
                return String.valueOf(process.hashCode());
            }
        } catch (Exception e) {
            // 如果获取失败，使用进程的hashCode作为备选方案
            return String.valueOf(process.hashCode());
        }
    }

    /**
     * 停止进程
     */
    public boolean stopProcess(String processId) {
        Process process = processMap.get(processId);
        if (process != null && process.isAlive()) {
            process.destroy();
            processMap.remove(processId);
            return true;
        }
        return false;
    }

    /**
     * 检查进程是否存活
     */
    public boolean isProcessAlive(String processId) {
        Process process = processMap.get(processId);
        return process != null && process.isAlive();
    }
}
