package cn.reghao.bnt.web.devops.util;

import cn.reghao.bnt.web.admin.service.UserMessageService;
import cn.reghao.bnt.web.config.AppProperties;
import cn.reghao.bnt.web.devops.build.db.repository.CompilerConfigRepository;
import cn.reghao.bnt.web.devops.build.model.po.CompilerConfig;
import cn.reghao.bnt.web.devops.build.service.BuildDirService;
import cn.reghao.bnt.web.devops.builder.model.constant.CompileType;
import cn.reghao.jutil.jdk.shell.ShellExecutor;
import cn.reghao.jutil.jdk.shell.ShellResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author reghao
 * @date 2025-10-07 23:52:25
 */
@Slf4j
@Service
public class BuilderInit {
    private final AppProperties appProperties;
    private final ShellExecutor shellExecutor;
    private final BuildDirService buildDirService;
    private final CompilerConfigRepository compilerConfigRepository;
    private final UserMessageService userMessageService;

    public BuilderInit(AppProperties appProperties, ShellExecutor shellExecutor, BuildDirService buildDirService,
                       CompilerConfigRepository compilerConfigRepository,UserMessageService userMessageService) {
        this.appProperties = appProperties;
        this.shellExecutor = shellExecutor;
        this.buildDirService = buildDirService;
        this.compilerConfigRepository = compilerConfigRepository;
        this.userMessageService = userMessageService;
    }

    public void init() {
        initBuildDir();
        checkCompilerConfig();
    }

    private void initBuildDir() {
        String userDir = System.getProperty("user.dir");
        String baseDir = appProperties.getDevopsDir();
        File dir = new File(baseDir);
        if (!dir.exists() && !dir.mkdirs()) {
            log.error("创建本地构建目录 {} 失败，devops-mgr 结束运行", baseDir);
            System.exit(1);
        } else {
            try {
                buildDirService.init(baseDir);
            } catch (Exception e) {
                log.error("初始化本地构建目录失败，devops-mgr 结束运行");
                e.printStackTrace();
                System.exit(1);
            }
        }
    }

    private void checkCompilerConfig() {
        List<CompilerConfig> list = compilerConfigRepository.findAll();
        for (CompilerConfig compilerConfig : list) {
            if (compilerConfig.getType().equals(CompileType.none.getName())) {
                continue;
            }

            if (compilerConfig.getType().equals(CompileType.shell.getName())) {
                String versionCmd = compilerConfig.getVersionCmd();
                ShellResult shellResult = shellExecutor.exec(versionCmd.split("\\s+"));
                if (shellResult.getExitCode() != 0) {
                    String title = "编译配置异常";
                    String content = shellResult.getResult();
                    userMessageService.sendUserMessage(title, content);
                }
            }
        }
    }
}
