/**
 * @deprecated [DC-3] 仅被 status_transitions.ts 消费，待门禁管线完善后迁移。
 *
 * 门禁引擎 — 根据 templates gates/ 下的 YAML 配置执行阶段门禁校验。
 *
 * 门禁标准从 templates 目录加载，不硬编码。
 * 每个管线阶段可配置多个门禁检查项，全部通过才放行。
 */
import fs from "node:fs";
import path from "node:path";
import { debug } from "../core/logger.js";
/**
 * 执行阶段门禁校验。
 * 加载对应阶段的 gate YAML 配置，逐项校验。
 */
export function executeStageGate(stage, artifacts, templatesDir, system_type) {
    debug("门禁引擎", "执行门禁校验, 阶段=%s, system_type=%s", stage, system_type ?? "default");
    // 按优先级尝试：系统专属 → 共享 → 放行
    const candidates = [];
    if (system_type === "existing_system") {
        candidates.push(path.join(templatesDir, "gates", "existing-system", `gate-${stage}.yaml`));
    }
    candidates.push(path.join(templatesDir, "gates", "shared", `gate-${stage}.yaml`));
    let gatePath;
    for (const candidate of candidates) {
        if (fs.existsSync(candidate)) {
            gatePath = candidate;
            break;
        }
    }
    if (!gatePath) {
        debug("门禁引擎", "门禁配置不存在, 阶段=%s, 尝试路径=%s", stage, candidates.join("; "));
        // 安全修复: 配置不存在 = 门禁未定义，默认不通过（安全侧失败）
        return {
            gate_id: `gate-${stage}`,
            stage,
            passed: false,
            checks: [],
            blocking_reason_zh: `门禁配置不存在，阶段 "${stage}" 无法通过`,
        };
    }
    const checks = [];
    // 安全修复: 默认不通过，配置解析成功且所有检查通过才改为 true
    let allPassed = false;
    let blockingReason = null;
    try {
        const content = fs.readFileSync(gatePath, "utf-8");
        const gateConfig = parseSimpleYaml(content);
        const checkItems = gateConfig["checks"] ?? [];
        // 解析成功，先假设全部通过
        allPassed = true;
        for (const item of checkItems) {
            const name = item["name"] ?? item["检查项"] ?? "unknown";
            const requiredArtifact = item["required_artifact"] ?? item["必需产物"] ?? "";
            const hasArtifact = requiredArtifact
                ? !!artifacts[requiredArtifact]
                : true;
            const passed = hasArtifact;
            if (!passed)
                allPassed = false;
            checks.push({
                name,
                passed,
                message_zh: passed ? `${name}: 通过` : `${name}: 缺少必需产物 "${requiredArtifact}"`,
            });
            if (!passed && !blockingReason) {
                blockingReason = `门禁校验未通过: ${name} — 缺少必需产物 "${requiredArtifact}"`;
            }
        }
    }
    catch (err) {
        debug("门禁引擎", "门禁配置解析失败, 阶段=%s, 错误=%s", stage, err);
    }
    return {
        gate_id: `gate-${stage}`,
        stage,
        passed: allPassed,
        checks,
        blocking_reason_zh: allPassed ? null : blockingReason,
    };
}
/** 加载门禁配置（简化 YAML 解析） */
export function loadGateConfig(gatePath) {
    if (!fs.existsSync(gatePath))
        return null;
    try {
        const content = fs.readFileSync(gatePath, "utf-8");
        return parseSimpleYaml(content);
    }
    catch {
        return null;
    }
}
/** 简化 YAML 解析（仅支持简单键值对和列表） */
function parseSimpleYaml(content) {
    const result = {};
    let currentKey = "";
    let currentList = [];
    for (const line of content.split("\n")) {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith("#"))
            continue;
        if (trimmed.includes(":") && !trimmed.startsWith("-")) {
            if (currentKey && currentList.length > 0) {
                result[currentKey] = currentList;
                currentList = [];
            }
            const colonIdx = trimmed.indexOf(":");
            currentKey = trimmed.slice(0, colonIdx).trim();
            const value = trimmed.slice(colonIdx + 1).trim();
            if (value)
                result[currentKey] = value;
        }
        else if (trimmed.startsWith("- ")) {
            currentList.push(trimmed.slice(2).trim());
        }
    }
    if (currentKey && currentList.length > 0) {
        result[currentKey] = currentList;
    }
    return result;
}
//# sourceMappingURL=stage_gate_engine.js.map