/**
 * 知识配置读取器（core/ 内部副本）。
 *
 * 此文件是 knowledge/knowledge_config_loader.ts 的精简版本，
 * 仅供 core/ 模块使用，避免 core/ 反向依赖 knowledge/。
 *
 * knowledge/ 子目录的完整版本包含缓存、路径重映射等高级功能。
 * core/ 版本仅保留 loadKnowledgeConfig + extractNumberRule 两个核心函数。
 */
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import matter from "gray-matter";
import { debug } from "./logger.js";
/** 知识配置缓存 */
const configCache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 缓存有效期：5 分钟
/** 包内模板知识库根目录 */
function getTemplatesRoot() {
    const thisDir = path.dirname(fileURLToPath(import.meta.url));
    // src/engine/core/ → ../../../ → 项目根 → templates
    return path.resolve(thisDir, "..", "..", "..", "templates");
}
/** 项目知识库根目录 */
function getKnowledgeRoot(projectPath) {
    return path.join(projectPath ?? process.cwd(), ".soloforge", "knowledge");
}
/**
 * 将旧的知识路径映射到新的类型优先路径。
 */
function remapLegacyPath(relativePath) {
    let mapped = relativePath.replace(/^patterns\/core\//, "internal/patterns/");
    if (!mapped.startsWith("patterns/core/")) {
        mapped = mapped.replace(/^patterns\/(?!core)/, "patterns/");
    }
    if (mapped.startsWith("rules/") && !mapped.startsWith("rules/shared/")) {
        mapped = mapped.replace(/^rules\//, "internal/rules/");
    }
    mapped = mapped.replace(/^review_rules\//, "rules/shared/");
    mapped = mapped.replace(/^acceptance_templates\//, "artifacts/shared/");
    mapped = mapped.replace(/^product_profiles\//, "profiles/");
    return mapped;
}
/**
 * 从知识库中加载指定 .md 文件的 frontmatter 和 body。
 * @param relativePath - 相对于 knowledge/ 的路径
 * @param projectPath - 项目根目录
 * @returns frontmatter data + body，文件不存在时返回 null
 */
export function loadKnowledgeConfig(relativePath, projectPath) {
    debug("CoreKnowledgeConfigLoader", "加载知识配置", relativePath);
    const projectRoot = projectPath ?? process.cwd();
    const cacheKey = `${projectRoot}::${relativePath}`;
    const projectFile = path.join(getKnowledgeRoot(projectPath), relativePath);
    const templateFile = path.join(getTemplatesRoot(), remapLegacyPath(relativePath));
    const useProject = fs.existsSync(projectFile);
    const filePath = useProject ? projectFile : templateFile;
    if (!fs.existsSync(filePath)) {
        debug("CoreKnowledgeConfigLoader", "知识文件不存在", filePath);
        return null;
    }
    let mtime = 0;
    if (useProject) {
        try {
            mtime = fs.statSync(filePath).mtimeMs;
        }
        catch { /* 忽略 */ }
    }
    const cached = configCache.get(cacheKey);
    if (cached) {
        const mtimeMatch = !useProject || cached.mtime === mtime;
        if (mtimeMatch && Date.now() - cached.loadedAt < CACHE_TTL) {
            return { data: cached.data, body: cached.body };
        }
    }
    try {
        const raw = fs.readFileSync(filePath, "utf-8");
        const { data, content: body } = matter(raw);
        configCache.set(cacheKey, { data: data, body, mtime, loadedAt: Date.now() });
        return { data: data, body };
    }
    catch {
        debug("CoreKnowledgeConfigLoader", "读取知识文件失败", filePath);
        return null;
    }
}
/**
 * 从知识文件的决策规则中提取指定键的数值。
 */
export function extractNumberRule(body, key) {
    const regex = new RegExp(`${key.replace(/_/g, "[_ ]")}\\s*=\\s*([\\d.]+)`, "i");
    const match = body.match(regex);
    return match ? parseFloat(match[1]) : undefined;
}
/**
 * 清除知识配置缓存（测试用）。
 */
export function clearConfigCache() {
    debug("CoreKnowledgeConfigLoader", "清除配置缓存");
    configCache.clear();
}
//# sourceMappingURL=knowledge_config_loader.js.map