package cn.iocoder.byzs.module.infra.framework.file.core.client.local;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.iocoder.byzs.module.infra.framework.file.core.client.AbstractFileClient;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

/**
 * 本地文件客户端
 *
 * @author 博雅智算源码
 */
public class LocalFileClient extends AbstractFileClient<LocalFileClientConfig> {

    public LocalFileClient(Long id, LocalFileClientConfig config) {
        super(id, config);
    }

    @Override
    protected void doInit() {
    }

    @Override
    public String ffmpegHts(String pathMp4) {
        pathMp4= getFilePath(pathMp4);
        String filePathName = pathMp4.substring(0, pathMp4.lastIndexOf("."));
        String pathM3u8 = filePathName + ".m3u8";
        try {
            System.out.println("PATH环境变量: " + System.getenv("PATH"));
            // 构建FFmpeg命令进行HLS切片
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "ffmpeg", "-i", pathMp4,
                    "-c:v", "h264", "-c:a", "aac",
                    "-hls_time", "10", "-hls_list_size", "0",
                    "-hls_segment_filename",  filePathName + "_%03d.ts",
                    pathM3u8
            );

            // 重定向错误流到输入流（便于捕获FFmpeg输出信息）
            processBuilder.redirectErrorStream(true);

            // 启动进程
            Process process = processBuilder.start();

            // 读取FFmpeg输出日志
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("FFmpeg输出: " + line);
                }
            }

            // 等待进程执行完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                pathM3u8 = pathM3u8.substring(pathM3u8.lastIndexOf(File.separator)+1);
                System.out.println("视频切片成功，m3u8路径: " + pathM3u8);
                return super.formatFileUrl(config.getDomain(), pathM3u8);
            } else {
                System.err.println("FFmpeg执行失败，退出码: " + exitCode);
                return null;
            }

        }catch (Exception e) {
            throw new RuntimeException("视频处理失败，请检查视频格式是否支持：", e);
        }
    }

    @Override
    public String upload(byte[] content, String path, String type) {
        // 执行写入
        String filePath = getFilePath(path);
        FileUtil.writeBytes(content, filePath);

        // 拼接返回路径
        return super.formatFileUrl(config.getDomain(), path);
    }

    @Override
    public void delete(String path) {
        String filePath = getFilePath(path);
        FileUtil.del(filePath);
    }

    @Override
    public byte[] getContent(String path) {
        String filePath = getFilePath(path);
        return FileUtil.readBytes(filePath);
    }

    private String getFilePath(String path) {
        return config.getBasePath() + File.separator + path;
    }

}
