package cn.reghao.tnb.content.app.media;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2026-02-12 21:25:10
 */
//@Component
public class VideoProducer {
    private RabbitTemplate rabbitTemplate;

    public VideoProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public List<String> splitVideo(String inputPath, String outputFolder) throws Exception {
        // 命令：ffmpeg -i in.mp4 -f segment -segment_time 300 -c copy out/part_%03d.mp4
        List<String> commands = Arrays.asList(
                "ffmpeg", "-i", inputPath,
                "-f", "segment",
                "-segment_time", "300",
                "-c", "copy",
                outputFolder + "/part_%03d.mp4"
        );

        ProcessBuilder pb = new ProcessBuilder(commands);
        Process process = pb.start();
        int exitCode = process.waitFor();

        if (exitCode == 0) {
            // 返回生成的子文件路径列表
            return Files.list(Paths.get(outputFolder))
                    .map(Path::toString)
                    .collect(Collectors.toList());
        }
        throw new RuntimeException("切片失败");
    }

    public void dispatchParts(TranscodeTask task) {
        for (int i = 0; i < task.getPartPaths().size(); i++) {
            Map<String, Object> message = new HashMap<>();
            message.put("videoId", task.getVideoId());
            message.put("partPath", task.getPartPaths().get(i));
            message.put("index", i);

            // 发送到转码队列，由多个 Worker 节点消费
            rabbitTemplate.convertAndSend("transcoding_exchange", "part_routing_key", message);
        }
    }
}
