/**
 * 门禁检查模块 — 共享辅助函数。
 */
import fs from "node:fs";
import path from "node:path";
import { errorMessage } from "../../core/helpers.js";
/**
 * 从缓存读取文件，避免重复 I/O。
 */
export function safeReadCached(filePath, cache) {
    if (cache.has(filePath))
        return cache.get(filePath);
    try {
        const content = fs.readFileSync(filePath, "utf8");
        cache.set(filePath, content);
        return content;
    }
    catch {
        cache.set(filePath, null);
        return null;
    }
}
/**
 * 安全读取文件（无缓存）。
 */
export function safeRead(filePath) {
    try {
        return fs.readFileSync(filePath, "utf8");
    }
    catch {
        return null;
    }
}
/**
 * 递归查找指定扩展名的文件。
 */
export function findFilesRecursive(dir, ext) {
    const results = [];
    if (!fs.existsSync(dir))
        return results;
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const full = path.join(dir, entry.name);
        if (entry.isDirectory())
            results.push(...findFilesRecursive(full, ext));
        else if (entry.name.endsWith(ext))
            results.push(full);
    }
    return results;
}
/**
 * 动态 import 并验证导出存在性。
 */
export async function importAndVerify(_ctx, distPath, exportName) {
    try {
        const mod = await import(distPath);
        if (!mod[exportName]) {
            return { mod, error: `导出 ${exportName} 不存在` };
        }
        return { mod };
    }
    catch (e) {
        return { mod: null, error: errorMessage(e) };
    }
}
/**
 * 构建门禁上下文（在入口处调用一次）。
 */
export function buildGateContext(rootDir) {
    const srcDir = path.join(rootDir, "src");
    const testDir = path.join(rootDir, "tests");
    const knowledgeDir = path.join(rootDir, "templates", "knowledge");
    const ctx = {
        rootDir,
        toolsText: "",
        cliText: "",
        typesText: "",
        srcFiles: [],
        testFiles: [],
        knowledgeFiles: [],
        readCache: new Map(),
    };
    // 预读高频文件
    ctx.toolsText = safeRead(path.join(rootDir, "src", "adapters", "claude_code", "tools.ts")) ?? "";
    ctx.cliText = safeRead(path.join(rootDir, "src", "bin", "soloforge.ts")) ?? "";
    ctx.typesText = safeRead(path.join(rootDir, "src", "types.ts")) ?? "";
    // 预扫描文件列表
    ctx.srcFiles = findFilesRecursive(srcDir, ".ts");
    ctx.testFiles = findFilesRecursive(testDir, ".ts");
    ctx.knowledgeFiles = findFilesRecursive(knowledgeDir, ".md");
    return ctx;
}
//# sourceMappingURL=helpers.js.map