package com.huimv.employment.integration.kb;

import com.huimv.employment.common.exception.BizException;
import com.huimv.employment.common.exception.ErrorCode;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;

/**
 * 基于模板占位符生成 Markdown 文件（输出至 {@code fe.kb.upload-path/template} 目录）。
 */
@Component
public class KbMarkdownGenerator {

    /** 相对 upload-path 的模板目录名 */
    public static final String TEMPLATE_DIR = "template";

    /** classpath 内置模板目录，部署时可复制到上传目录 */
    public static final String CLASSPATH_TEMPLATE_PREFIX = "kb-template/";

    private final KbApiProperties properties;

    public KbMarkdownGenerator(KbApiProperties properties) {
        this.properties = properties;
    }

    /**
     * 从模板生成 Markdown 文件。
     *
     * @param templateFileName 模板文件名
     * @param outputFileName   输出文件名
     * @param placeholders     占位符键名不含花括号，如 {@code drugName} → {@code {drugName}}
     * @return 生成文件的绝对路径
     */
    public Path generateFromTemplate(String templateFileName, String outputFileName, Map<String, String> placeholders) {
        if (!StringUtils.hasText(templateFileName)) {
            throw new BizException(ErrorCode.BAD_REQUEST, "Markdown 模板文件名为空");
        }
        if (!StringUtils.hasText(outputFileName)) {
            throw new BizException(ErrorCode.BAD_REQUEST, "Markdown 输出文件名为空");
        }
        Path templatePath;
        try {
            templatePath = resolveTemplatePath(templateFileName);
        } catch (IOException e) {
            throw new BizException(ErrorCode.KB_SERVICE_FAILED, "准备 Markdown 模板失败：" + e.getMessage());
        }
        String content;
        try {
            content = new String(Files.readAllBytes(templatePath), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new BizException(ErrorCode.KB_SERVICE_FAILED,
                    "读取 Markdown 模板失败：" + templatePath + "，" + e.getMessage());
        }
        content = applyPlaceholders(content, placeholders);
        Path outputDir = templateDirectory();
        try {
            Files.createDirectories(outputDir);
            Path output = outputDir.resolve(outputFileName);
            Files.write(output, content.getBytes(StandardCharsets.UTF_8));
            return output;
        } catch (IOException e) {
            throw new BizException(ErrorCode.KB_SERVICE_FAILED, "写入 Markdown 文件失败：" + e.getMessage());
        }
    }

    public Path templateDirectory() {
        String profile = properties.getUploadPath();
        if (!StringUtils.hasText(profile)) {
            throw new BizException(ErrorCode.BAD_REQUEST, "未配置 fe.kb.upload-path，无法生成知识库 Markdown 文件");
        }
        return Paths.get(profile, TEMPLATE_DIR);
    }

    /** 删除临时 Markdown（忽略不存在）。 */
    public void deleteQuietly(Path path) {
        if (path == null) {
            return;
        }
        try {
            Files.deleteIfExists(path);
        } catch (IOException ignored) {
            // 清理失败不阻断主流程
        }
    }

    private Path resolveTemplatePath(String templateFileName) throws IOException {
        Path inProfile = templateDirectory().resolve(templateFileName);
        if (Files.isRegularFile(inProfile)) {
            return inProfile;
        }
        ClassPathResource resource = new ClassPathResource(CLASSPATH_TEMPLATE_PREFIX + templateFileName);
        if (!resource.exists()) {
            throw new BizException(ErrorCode.BAD_REQUEST, "未找到 Markdown 模板：" + templateFileName
                    + "（请置于 " + inProfile + " 或 classpath:" + CLASSPATH_TEMPLATE_PREFIX + templateFileName + "）");
        }
        Files.createDirectories(templateDirectory());
        try (InputStream in = resource.getInputStream()) {
            Files.copy(in, inProfile, StandardCopyOption.REPLACE_EXISTING);
        }
        return inProfile;
    }

    private static String applyPlaceholders(String template, Map<String, String> placeholders) {
        if (placeholders == null || placeholders.isEmpty()) {
            return template;
        }
        String result = template;
        for (Map.Entry<String, String> entry : placeholders.entrySet()) {
            String key = entry.getKey();
            if (!StringUtils.hasText(key)) {
                continue;
            }
            String value = entry.getValue() != null ? entry.getValue() : "";
            result = result.replace("{" + key + "}", value);
        }
        return result;
    }
}
