package top.baogutang.admin.services.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import top.baogutang.admin.services.IScriptService;
import top.baogutang.common.constants.ErrorCodeEnum;
import top.baogutang.common.exceptions.BusinessException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @description:
 * @author: nikooh
 * @date: 2023/10/12 : 13:47
 */
@Slf4j
@Service
public class ScriptServiceImpl implements IScriptService {


    @Override
    @Async("commonExecutor")
    public void execPython(String scriptPath) {
        try {
            ProcessBuilder pb = new ProcessBuilder("/usr/bin/python3", scriptPath);
            //启动进程
            Process process = pb.start();
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                //处理Python脚本的输出
                log.info(">>>>>>>>>>script exec:{}<<<<<<<<<<", line);
            }
            // 等待 Python 脚本执行完成
            int exitCode = process.waitFor();
            in.close();
            log.info("Python script execution completed with exit code: {}", exitCode);
        } catch (IOException | InterruptedException e) {
            log.error(">>>>>>>>>>exec python :{} error:{}<<<<<<<<<<", scriptPath, e.getMessage(), e);
            throw new BusinessException(ErrorCodeEnum.E_EXEC_SCRIPT_ERROR);
        }
    }
}
