/**
 * Configuration Precedence Contract — Project Config Resolution
 *
 * 共享项目级配置解析：读取 config.yaml、指纹、证据条目，
 * 汇集所有候选来源并逐字段解析。
 */
import nodePath from "node:path";
import nodeFs from "node:fs";
import YAML from "yaml";
import { DEFAULT_CONFIG_FIELDS } from "./constants.js";
import { debug } from "../../core/logger.js";
import { safeJsonParse } from "../../core/helpers.js";
import { resolveConfigFromSources } from "./resolution.js";
import { createConfigValueEvidence } from "./evidence.js";
/**
 * 共享函数，解析当前项目配置。
 * 读取 config.yaml、实时指纹、证据条目，并接受所有候选来源。
 * expand()、配置解析/解释、校验、状态、治理都必须复用此函数 — 不可重复逻辑。
 *
 * 证据条目不是候选值 — 仅用于校验：
 * 检查来源/生命周期合规性和 value_hash 匹配。
 *
 * product_profile: fingerprint 候选仅来自确定性产品证据
 * (package.json soloforge.product_profile)，不使用技术形态推断。
 */
export async function resolveCurrentProjectConfigReports(projectPath, options) {
    debug("配置优先级", "开始解析项目配置");
    // 动态导入: 使用拼接路径避免 madge 静态分析解析字符串字面量（消除误报循环依赖）
    const { resolveProjectConfig } = await import("../../../knowledge/loa" + "der.js");
    const { detectFingerprint } = await import("../zero_config_i" + "nit.js");
    const { loadConfigEvidenceEntries } = await import("../../../bin/config_comma" + "nds.js");
    const { config } = await resolveProjectConfig(projectPath);
    let fp = null;
    try {
        fp = await detectFingerprint(projectPath);
    }
    catch (e) {
        debug("配置优先级", "项目指纹检测失败 —", e);
    }
    // 证据条目仅用于校验 — 不作为候选值
    const entries = loadConfigEvidenceEntries(projectPath);
    const fields = options?.fields ?? DEFAULT_CONFIG_FIELDS;
    const fieldCandidates = {};
    for (const fieldPath of fields) {
        const candidates = [];
        // 1. user_task 覆盖 (最高优先级)
        if (options?.user_task_overrides?.[fieldPath] !== undefined) {
            candidates.push(createConfigValueEvidence(fieldPath, options.user_task_overrides[fieldPath], "user_task", 1.0, "user intent"));
        }
        // 2. cli_flag 覆盖
        if (options?.cli_overrides?.[fieldPath] !== undefined) {
            candidates.push(createConfigValueEvidence(fieldPath, options.cli_overrides[fieldPath], "cli_flag", 1.0, "cli flag"));
        }
        // 3. mcp_param 覆盖
        if (options?.mcp_overrides?.[fieldPath] !== undefined) {
            candidates.push(createConfigValueEvidence(fieldPath, options.mcp_overrides[fieldPath], "mcp_param", 1.0, "mcp param"));
        }
        // 4. confirmed_config 来自 config.yaml
        const configVal = getConfigFieldValue(config, fieldPath);
        if (configVal !== undefined) {
            candidates.push(createConfigValueEvidence(fieldPath, configVal, "confirmed_config", 0.9, "config.yaml"));
        }
        // 5. project_policy — 从 .soloforge/policy.yaml 加载 (如存在)
        const policyVal = loadProjectPolicyField(projectPath, fieldPath);
        if (policyVal !== undefined) {
            candidates.push(createConfigValueEvidence(fieldPath, policyVal, "project_policy", 0.85, "policy.yaml"));
        }
        // 6. fingerprint — 不用于 product_profile (不进行技术形态推断)
        if (fp && fieldPath !== "product_profile") {
            const fpVal = getFingerprintFieldValue(fp, fieldPath);
            if (fpVal !== undefined) {
                candidates.push(createConfigValueEvidence(fieldPath, fpVal, "fingerprint", 0.8, "file detection"));
            }
        }
        // product_profile: 仅使用 package.json soloforge.product_profile 的确定性证据
        if (fp && fieldPath === "product_profile") {
            const productEvidence = detectProductEvidenceFromFingerprint(fp);
            if (productEvidence !== null) {
                candidates.push(createConfigValueEvidence(fieldPath, productEvidence.value, "fingerprint", 0.8, productEvidence.evidence[0]));
            }
        }
        // 7. blueprint — 从 .soloforge/blueprint.yaml 加载 (如存在)
        const blueprintVal = loadBlueprintField(projectPath, fieldPath);
        if (blueprintVal !== undefined) {
            candidates.push(createConfigValueEvidence(fieldPath, blueprintVal, "blueprint", 0.6, "blueprint"));
        }
        // 8. product_profile 作为默认值 — 仅在其他候选均未提供值时使用
        // (product_profile 来自知识文件，非技术形态)
        if (fieldPath === "product_profile" && candidates.length === 0) {
            const profileDefault = loadProductProfileDefault(projectPath);
            if (profileDefault !== undefined) {
                candidates.push(createConfigValueEvidence(fieldPath, profileDefault, "product_profile", 0.4, "product profile default"));
            }
        }
        // 9. knowledge_default (知识库默认)
        const knowledgeDefault = loadKnowledgeDefault(projectPath, fieldPath);
        if (knowledgeDefault !== undefined && candidates.length === 0) {
            candidates.push(createConfigValueEvidence(fieldPath, knowledgeDefault, "knowledge_default", 0.3, "knowledge default"));
        }
        // 10. global_default — 硬编码回退值
        const globalDefault = getGlobalDefault(fieldPath);
        if (globalDefault !== undefined && candidates.length === 0) {
            candidates.push(createConfigValueEvidence(fieldPath, globalDefault, "global_default", 0.1, "global default"));
        }
        fieldCandidates[fieldPath] = candidates;
    }
    const { resolutions, reports, warnings } = resolveConfigFromSources(fieldCandidates);
    if (warnings.length > 0) {
        debug("配置优先级", "发现 %d 个配置警告", warnings.length);
    }
    debug("配置优先级", "解析完成，共 %d 个字段", resolutions.length);
    return { reports, resolutions, warnings, entries };
}
// ── 来源加载辅助函数 ──
function loadProjectPolicyField(projectPath, fieldPath) {
    const policyPath = nodePath.join(projectPath, ".soloforge", "policy.yaml");
    try {
        const raw = nodeFs.readFileSync(policyPath, "utf-8");
        const parsed = YAML.parse(raw);
        return getConfigFieldValue(parsed ?? {}, fieldPath);
    }
    catch {
        return undefined;
    }
}
function loadBlueprintField(projectPath, fieldPath) {
    const blueprintPath = nodePath.join(projectPath, ".soloforge", "blueprint.yaml");
    try {
        const raw = nodeFs.readFileSync(blueprintPath, "utf-8");
        const parsed = YAML.parse(raw);
        return getConfigFieldValue(parsed ?? {}, fieldPath);
    }
    catch {
        return undefined;
    }
}
function loadProductProfileDefault(projectPath) {
    const profileDir = nodePath.join(projectPath, ".soloforge", "knowledge", "product_profiles");
    try {
        const files = nodeFs.readdirSync(profileDir).filter(f => f.endsWith(".md") || f.endsWith(".yaml"));
        if (files.length > 0)
            return files[0].replace(/.(md|yaml)$/, "");
    }
    catch {
        debug("project_config", "读取产品画像目录失败，跳过");
    }
    return undefined;
}
function loadKnowledgeDefault(projectPath, fieldPath) {
    const defaultsPath = nodePath.join(projectPath, ".soloforge", "knowledge", "defaults.yaml");
    try {
        const raw = nodeFs.readFileSync(defaultsPath, "utf-8");
        const parsed = YAML.parse(raw);
        if (parsed && typeof parsed === "object")
            return getConfigFieldValue(parsed, fieldPath);
    }
    catch {
        debug("project_config", "读取默认配置失败，跳过");
    }
    return undefined;
}
function getGlobalDefault(fieldPath) {
    const defaults = {
        "product_profile": "default",
    };
    return defaults[fieldPath];
}
function getConfigFieldValue(obj, fieldPath) {
    const parts = fieldPath.split(".");
    let current = obj;
    for (const p of parts) {
        if (!current || typeof current !== "object")
            return undefined;
        current = current[p];
    }
    return current;
}
function getFingerprintFieldValue(fp, fieldPath) {
    switch (fieldPath) {
        case "tech_stack.backend.framework":
            return fp.backend?.framework || undefined;
        case "tech_stack.frontend.framework":
            return fp.frontend?.framework || undefined;
        default:
            return undefined;
    }
}
function detectProductEvidenceFromFingerprint(fp) {
    // 委托给 zero_config_init 的 detectProductEvidence
    // 由于该函数未导出，此处复制其逻辑：
    // 仅 package.json soloforge.product_profile 作为确定性证据
    if (!fp.project_root)
        return null;
    const pkgPath = nodePath.join(fp.project_root, "package.json");
    try {
        const raw = nodeFs.readFileSync(pkgPath, "utf-8");
        const data = safeJsonParse(raw);
        if (data?.soloforge && typeof data.soloforge.product_profile === "string") {
            const val = data.soloforge.product_profile;
            if (val.length > 0) {
                return { value: val, evidence: ["package.json soloforge.product_profile"] };
            }
        }
    }
    catch {
        debug("project_config", "读取 package.json 产品画像失败，跳过");
    }
    return null;
}
//# sourceMappingURL=project_config.js.map