package com.ruoyi.web.core.config;

import com.ruoyi.cc.service.ICcParamsService;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import link.thingscloud.freeswitch.esl.EslConnectionUtil;
import link.thingscloud.freeswitch.esl.transport.message.EslMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自动更新/home/freeswitch/share/freeswitch/scripts/auth_user.lua 中的数据库连接
 */
@Component
@Slf4j
public class LuaDbCheckRunner implements ApplicationRunner {

    @Value("${spring.datasource.druid.master.url}")
    private String dbUrl;
    @Value("${spring.datasource.druid.master.username}")
    private String dbUsername;
    @Value("${spring.datasource.druid.master.password}")
    private String dbPassword;
    @Autowired
    private ICcParamsService ccParamsService;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        // 获取数据库连接参数
        String mysqlIp = "";
        String mysqlPort = "";
        String databaseName = "";

        // 使用正则表达式解析URL
        // 匹配：jdbc:mysql://IP:PORT/DBNAME?...
        String regex = "jdbc:mysql://([^:]+):(\\d+)/([^?]+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(dbUrl);

        if (matcher.find()) {
            mysqlIp = matcher.group(1);
            mysqlPort = matcher.group(2);
            databaseName = matcher.group(3);
        } else {
            log.warn("无法解析URL: {}", dbUrl);
        }
        log.info("mysqlIp：{}， mysqlPort：{}，databaseName：{}，dbUsername:{}，dbPassword:{}", mysqlIp, mysqlPort, databaseName, dbUsername, dbPassword);
        String dbh = String.format("mariadb://Server=%s;Port=%s;Database=%s;Uid=%s;Pwd=%s;", mysqlIp, mysqlPort, databaseName, dbUsername, dbPassword);
        // 获取
        String luaScriptPath = ccParamsService.getParamValueByCode("freeswitch_root", "/home/freeswitch") + "/share/freeswitch/scripts";
        String templateFile = luaScriptPath + "/auth_user_template.lua";
        String luaFile = luaScriptPath + "/auth_user.lua";
        try {
            // 3. 读取模板文件内容
            File template = new File(templateFile);
            if (!template.exists()) {
                log.error("模板文件不存在: " + templateFile);
                return;
            }

            String content = FileUtils.readFileToString(template, StandardCharsets.UTF_8);

            // 4. 替换占位符 ${_DB_URL} 为实际的 _dbUrl
            String replacedContent = content.replace("${_DB_URL}", dbh);

            // 5. 将替换后的内容写入目标文件（覆盖原有内容）
            File targetFile = new File(luaFile);
            FileUtils.writeStringToFile(targetFile, replacedContent, StandardCharsets.UTF_8, false);

            log.info("Lua脚本生成成功: " + luaFile);
            log.info("Lua脚本数据库URL已替换为: " + dbh);

        } catch (IOException e) {
            log.error("生成Lua脚本失败: " + e.getMessage());
            return;
        }



    }
}
