package top.r3944realms.ltdmanager.utils

import top.r3944realms.ltdmanager.core.config.YamlConfigLoader
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import kotlin.system.exitProcess

object ConfigInitializer {

    private val SQL_TEMPLATES = listOf(
        "sql/invitation/query_qualification.sql",
        "sql/invitation/query_token_info.sql",
        "sql/invitation/query_code_ids.sql",
        "sql/invitation/upsert_ascription.sql",
        "sql/whitelist/query_whitelist_record.sql",
    )

    fun initConfig(fileName: String = "application.yml", configDir: String = "config", shouldExit: Boolean = true) {
        val dirPath = Paths.get(configDir)
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath)
            LoggerUtil.logger.info("已创建配置目录: $configDir")
        }

        val filePath = dirPath.resolve(fileName)

        if (!Files.exists(filePath)) {
            val resourceStream = YamlConfigLoader::class.java.classLoader.getResourceAsStream(fileName)
            if (resourceStream != null) {
                Files.copy(resourceStream, filePath, StandardCopyOption.REPLACE_EXISTING)
                LoggerUtil.logger.info("已生成默认配置文件: $filePath")
                if (shouldExit) {
                    LoggerUtil.logger.info("第一次启动，请修改配置后再启动")
                    exitProcess(-1);
                }
            } else throw Error("Jar内部资源文件缺失")
        } else {
            LoggerUtil.logger.info("配置文件已存在: $filePath")
        }
    }

    /** 首次启动时将 SQL 模板从 classpath 复制到 config/sql/ */
    fun initSqlTemplates() {
        var copied = 0
        for (resourcePath in SQL_TEMPLATES) {
            val target = Paths.get("config", resourcePath)
            if (Files.exists(target)) continue

            val resourceStream = YamlConfigLoader::class.java.classLoader
                .getResourceAsStream(resourcePath)
            if (resourceStream != null) {
                Files.createDirectories(target.parent)
                Files.copy(resourceStream, target)
                resourceStream.close()
                copied++
            } else {
                LoggerUtil.logger.warn("SQL 模板资源缺失: $resourcePath")
            }
        }
        if (copied > 0) {
            LoggerUtil.logger.info("已从 JAR 复制 $copied 个 SQL 模板到 config/sql/")
        }
    }
}