/**
 * Zero-Config Init — 确定性 fingerprint 探测 + config 草案生成 + 字段级证据。
 *
 * 职责:
 * - detectFingerprint: 探测项目技术栈、目录结构、验证命令，生成确定性指纹
 * - generateConfigDraft: 基于 fingerprint 生成 config 草案
 * - generateConfigEvidence: 字段级证据记录
 *
 * 原则: 确定性探测优先，LLM 只做 advisory 解释。
 */
import fs from "node:fs/promises";
import fss from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { canAutoWriteField, getConfigFieldClass } from "./config_precedence_contract.js";
import { debug } from "../core/logger.js";
import { safeJsonParse } from "../core/helpers.js";
// ── 字段分类 ──
const FIELD_CLASS = {
    "name": "A",
    "tech_stack.backend": "A",
    "tech_stack.frontend": "A",
    "build_commands.backend": "A",
    "build_commands.frontend": "A",
    "product_profile": "B",
    "scope.backend": "B",
    "scope.frontend": "B",
    "repos": "B",
    "verify_timeout": "B",
    "scaffold.base_package": "B",
};
/** 获取配置字段分类（A/B/C 类） */
export function getFieldClass(field) {
    debug("零配置初始化", "获取字段分类", field);
    if (field in FIELD_CLASS)
        return FIELD_CLASS[field];
    return getConfigFieldClass(field);
}
/** Required fields for --auto write gate — all must be high confidence */
export const REQUIRED_FIELDS = [
    "name",
    "tech_stack",
    "build_commands",
    "product_profile",
];
// ── 检测器 ──
const BACKEND_MARKERS = [
    {
        file: "pom.xml",
        lang: "java",
        framework: "spring-boot",
        extractVersion: () => "3.x",
    },
    {
        file: "build.gradle",
        lang: "java",
        framework: "gradle",
        extractVersion: () => "8.x",
    },
    {
        file: "build.gradle.kts",
        lang: "java",
        framework: "gradle",
        extractVersion: () => "8.x",
    },
    {
        file: "go.mod",
        lang: "go",
        framework: "stdlib",
        extractVersion: (data) => {
            const m = data.match(/go\s+(\d+\.\d+)/);
            return m ? m[1] : "1.21";
        },
    },
    {
        file: "Cargo.toml",
        lang: "rust",
        framework: "cargo",
        extractVersion: () => "1.x",
    },
];
const FRONTEND_MARKERS = [
    {
        file: "package.json",
        lang: "typescript",
        framework: "react",
        extractVersion: (data) => {
            const pkg = data;
            const deps = { ...pkg.dependencies, ...pkg.devDependencies };
            if (deps.react) {
                const m = deps.react.match(/(\d+)\./);
                return m ? m[1] : "18";
            }
            return "18";
        },
    },
    {
        file: "package.json",
        lang: "typescript",
        framework: "vue",
        extractVersion: (data) => {
            const pkg = data;
            const deps = { ...pkg.dependencies, ...pkg.devDependencies };
            if (deps.vue) {
                const m = deps.vue.match(/(\d+)\./);
                return m ? m[1] : "3";
            }
            return "3";
        },
    },
    {
        file: "angular.json",
        lang: "typescript",
        framework: "angular",
        extractVersion: () => "17",
    },
];
const TEST_FRAMEWORKS = [
    { marker: "vitest", name: "vitest" },
    { marker: "jest", name: "jest" },
    { marker: "mocha", name: "mocha" },
    { marker: "pytest", name: "pytest" },
    { marker: "junit", name: "junit" },
];
const BUILD_TOOLS = [
    { marker: "vite", name: "vite" },
    { marker: "webpack", name: "webpack" },
    { marker: "esbuild", name: "esbuild" },
    { marker: "turbo", name: "turbo" },
    { marker: "nx", name: "nx" },
];
/**
 * 探测项目指纹 — 纯确定性，无 LLM 参与。
 */
export async function detectFingerprint(projectRoot) {
    debug("零配置初始化", "探测项目指纹", projectRoot);
    const advisory = [];
    const configFiles = [];
    const directories = [];
    // 检测目录
    try {
        const entries = await fs.readdir(projectRoot, { withFileTypes: true });
        for (const e of entries) {
            if (e.isDirectory() && !e.name.startsWith("."))
                directories.push(e.name);
            if (e.isFile() && isConfigFile(e.name))
                configFiles.push(e.name);
        }
    }
    catch (e) {
        debug("零配置初始化", "读取项目根目录失败", e);
        advisory.push("无法读取项目根目录");
    }
    // 一次性读取 package.json（避免重复读取 4 次）
    const pkgJsonPath = path.join(projectRoot, "package.json");
    let pkgData = null;
    if (fss.existsSync(pkgJsonPath)) {
        try {
            pkgData = safeJsonParse(await fs.readFile(pkgJsonPath, "utf-8")) ?? null;
        }
        catch {
            debug("zero_config", "package.json 解析失败，跳过");
        }
    }
    // 检测后端
    const backend = await detectBackend(projectRoot, advisory);
    // 检测前端
    const frontend = await detectFrontend(projectRoot, advisory, pkgData);
    // 检测包管理器
    const packageManagers = [];
    if (pkgData)
        packageManagers.push("npm");
    if (fss.existsSync(path.join(projectRoot, "pnpm-lock.yaml")))
        packageManagers.push("pnpm");
    if (fss.existsSync(path.join(projectRoot, "yarn.lock")))
        packageManagers.push("yarn");
    if (fss.existsSync(path.join(projectRoot, "go.sum")) || fss.existsSync(path.join(projectRoot, "go.mod")))
        packageManagers.push("go-modules");
    // 检测测试框架
    const testFrameworks = detectTestFrameworksFromPkg(pkgData, projectRoot);
    // 检测构建工具
    const buildTools = detectBuildToolsFromPkg(pkgData);
    // 检测 package.json scripts
    let pkgScripts = {};
    if (pkgData?.scripts && typeof pkgData.scripts === "object") {
        pkgScripts = pkgData.scripts;
    }
    // 计算确定性 hash
    const hashInput = [
        backend ? `${backend.lang}:${backend.framework}` : "none",
        frontend ? `${frontend.lang}:${frontend.framework}` : "none",
        ...directories.sort(),
        ...configFiles.sort(),
    ].join(",");
    const hash = crypto.createHash("sha256").update(hashInput).digest("hex").slice(0, 16);
    if (!backend && !frontend) {
        debug("零配置初始化", "未检测到前后端框架，将使用默认配置");
        advisory.push("未检测到后端或前端框架 — 配置将使用默认值");
    }
    return {
        project_root: projectRoot,
        detected_at: new Date().toISOString(),
        hash,
        backend,
        frontend,
        package_managers: packageManagers,
        build_tools: buildTools,
        test_frameworks: testFrameworks,
        directories,
        config_files: configFiles,
        pkg_scripts: pkgScripts,
        advisory,
    };
}
/**
 * 基于指纹生成配置草案 — 确定性 + advisory 解释。
 * LLM 不直接生成配置，只做 advisory 解释。
 */
export function generateConfigDraft(fingerprint) {
    debug("零配置初始化", "生成配置草案", fingerprint.hash);
    const backendLang = fingerprint.backend?.lang ?? "unknown";
    const backendFramework = fingerprint.backend?.framework ?? "unknown";
    const backendVersion = fingerprint.backend?.version ?? "unknown";
    const frontendLang = fingerprint.frontend?.lang ?? "unknown";
    const frontendFramework = fingerprint.frontend?.framework ?? "unknown";
    const frontendVersion = fingerprint.frontend?.version ?? "unknown";
    const advisoryNotes = [];
    // 推断构建命令
    const backendBuild = inferBackendCommands(fingerprint, advisoryNotes);
    const frontendBuild = inferFrontendCommands(fingerprint, advisoryNotes);
    // 推断作用域
    const backendScopeResult = inferBackendScope(fingerprint, advisoryNotes);
    const frontendScopeResult = inferFrontendScope(fingerprint, advisoryNotes);
    const backendScope = backendScopeResult.scope;
    const frontendScope = frontendScopeResult.scope;
    // 产品画像 — 优先使用确定性来源，否则使用技术形态推断
    const productProfile = detectProductEvidence(fingerprint)?.value ?? inferProductProfile(fingerprint);
    // 置信度
    const confidence = fingerprint.backend && fingerprint.frontend
        ? "high"
        : fingerprint.backend || fingerprint.frontend
            ? "medium"
            : "low";
    if (confidence === "low") {
        debug("零配置初始化", "置信度低，建议手动审查");
        advisoryNotes.push("低置信度: 未检测到框架，所有值为默认值 — 建议手动审查");
    }
    return {
        name: path.basename(fingerprint.project_root),
        tech_stack: {
            backend: { lang: backendLang, framework: backendFramework, version: backendVersion },
            frontend: { lang: frontendLang, framework: frontendFramework, version: frontendVersion },
        },
        product_profile: productProfile,
        build_commands: {
            backend: backendBuild,
            frontend: frontendBuild,
        },
        scope: {
            backend: backendScope,
            frontend: frontendScope,
        },
        advisory_notes: [...advisoryNotes, ...fingerprint.advisory],
        confidence,
    };
}
// ── 内部辅助函数 ──
async function detectBackend(root, advisory) {
    for (const marker of BACKEND_MARKERS) {
        const fp = path.join(root, marker.file);
        if (fss.existsSync(fp)) {
            try {
                const data = await fs.readFile(fp, "utf-8");
                return {
                    lang: marker.lang,
                    framework: marker.framework,
                    version: marker.extractVersion(data),
                    detected_from: marker.file,
                };
            }
            catch {
                advisory.push(`检测到 ${marker.file} 但无法解析`);
            }
        }
    }
    return null;
}
async function detectFrontend(root, advisory, pkgData) {
    // 先检查 angular.json
    if (fss.existsSync(path.join(root, "angular.json"))) {
        return {
            lang: "typescript",
            framework: "angular",
            version: "17",
            detected_from: "angular.json",
        };
    }
    // 使用已缓存的 package.json 数据
    if (pkgData) {
        try {
            const deps = { ...pkgData.dependencies, ...pkgData.devDependencies };
            if (deps.react) {
                const version = FRONTEND_MARKERS.find(m => m.framework === "react").extractVersion(pkgData);
                return {
                    lang: "typescript",
                    framework: "react",
                    version,
                    detected_from: "package.json",
                };
            }
            if (deps.vue) {
                const version = FRONTEND_MARKERS.find(m => m.framework === "vue").extractVersion(pkgData);
                return {
                    lang: "typescript",
                    framework: "vue",
                    version,
                    detected_from: "package.json",
                };
            }
            // 有 package.json 但无已知前端框架
            return {
                lang: "typescript",
                framework: "node",
                version: process.version.replace("v", ""),
                detected_from: "package.json",
            };
        }
        catch {
            advisory.push("检测到 package.json 但无法解析");
        }
    }
    return null;
}
// 从缓存的 package.json 数据检测测试框架
function detectTestFrameworksFromPkg(pkgData, projectRoot) {
    const found = [];
    if (pkgData) {
        try {
            const deps = { ...pkgData.dependencies, ...pkgData.devDependencies };
            for (const tf of TEST_FRAMEWORKS) {
                if (deps[tf.marker])
                    found.push(tf.name);
            }
        }
        catch {
            debug("zero_config", "测试框架检测失败，跳过");
        }
    }
    if (projectRoot) {
        if (fss.existsSync(path.join(projectRoot, "pytest.ini")) || fss.existsSync(path.join(projectRoot, "pyproject.toml"))) {
            if (!found.includes("pytest"))
                found.push("pytest");
        }
    }
    return found;
}
// 从缓存的 package.json 数据检测构建工具
function detectBuildToolsFromPkg(pkgData) {
    const found = [];
    if (pkgData) {
        try {
            const deps = { ...pkgData.dependencies, ...pkgData.devDependencies };
            for (const bt of BUILD_TOOLS) {
                if (deps[bt.marker])
                    found.push(bt.name);
            }
        }
        catch {
            debug("zero_config", "构建工具检测失败，跳过");
        }
    }
    return found;
}
function inferBackendCommands(fp, advisory) {
    if (!fp.backend) {
        advisory.push("未检测到后端，使用通用构建命令");
        return { build: "echo 'no backend build'", test: "echo 'no backend tests'", full: "echo 'no backend'" };
    }
    switch (fp.backend.framework) {
        case "spring-boot":
            return { build: "./mvnw compile -q", test: "./mvnw test -q", full: "./mvnw verify -q" };
        case "gradle":
            return { build: "./gradlew compileJava", test: "./gradlew test", full: "./gradlew check" };
        case "stdlib":
            return { build: "go build ./...", test: "go test ./...", full: "go test -race ./..." };
        case "cargo":
            return { build: "cargo build", test: "cargo test", full: "cargo test --all" };
        default:
            return { build: "make build", test: "make test", full: "make full" };
    }
}
function getPackageManagerRun(fp) {
    if (fp.package_managers.includes("pnpm"))
        return "pnpm";
    if (fp.package_managers.includes("yarn"))
        return "yarn";
    return "npm";
}
function inferFrontendCommands(fp, advisory) {
    if (!fp.frontend) {
        advisory.push("未检测到前端，使用通用构建命令");
        return { build: "echo 'no frontend build'", test: "echo 'no frontend tests'", full: "echo 'no frontend'" };
    }
    const pm = getPackageManagerRun(fp);
    const scripts = fp.pkg_scripts;
    const hasBuild = scripts && scripts.build;
    const hasTest = scripts && scripts.test;
    // 优先级: 项目自有 scripts > 框架默认值
    if (fp.frontend.framework === "react" || fp.frontend.framework === "vue" || fp.frontend.framework === "node") {
        if (hasBuild && hasTest) {
            const buildCmd = pm === "npm" ? "npm run build" : `${pm} run build`;
            const testCmd = pm === "npm" ? "npm test" : `${pm} test`;
            return { build: buildCmd, test: testCmd, full: `${buildCmd} && ${testCmd}` };
        }
        if (hasBuild) {
            const buildCmd = pm === "npm" ? "npm run build" : `${pm} run build`;
            const hasVite = fp.build_tools.includes("vite");
            const testCmd = hasVite ? "npx vitest run" : (pm === "npm" ? "npm test" : `${pm} test`);
            return { build: buildCmd, test: testCmd, full: `${buildCmd} && ${testCmd}` };
        }
    }
    switch (fp.frontend.framework) {
        case "react":
        case "vue":
            if (fp.build_tools.includes("vite")) {
                return { build: "npx vite build", test: "npx vitest run", full: "npx vite build && npx vitest run" };
            }
            return { build: "npm run build", test: "npm test", full: "npm run build && npm test" };
        case "angular":
            return { build: "npx ng build", test: "npx ng test", full: "npx ng build && npx ng test" };
        default:
            return { build: "npm run build", test: "npm test", full: "npm run build && npm test" };
    }
}
const EXPLICIT_BACKEND_SCOPE_DIRS = ["src", "app", "lib"];
const EXPLICIT_FRONTEND_SCOPE_DIRS = ["web", "client", "frontend", "src"];
function inferBackendScope(fp, advisory) {
    if (!fp.backend)
        return { scope: [], explicit: false };
    const dirs = fp.directories;
    for (const d of EXPLICIT_BACKEND_SCOPE_DIRS) {
        if (dirs.includes(d))
            return { scope: [`${d}/`], explicit: true };
    }
    advisory.push("无法从目录结构确定后端作用域，使用黑名单模式（仅受安全黑名单约束）");
    return { scope: [], explicit: false };
}
function inferFrontendScope(fp, _advisory) {
    if (!fp.frontend)
        return { scope: [], explicit: false };
    const dirs = fp.directories;
    for (const d of EXPLICIT_FRONTEND_SCOPE_DIRS) {
        if (dirs.includes(d))
            return { scope: [`${d}/`], explicit: true };
    }
    return { scope: [], explicit: false };
}
/**
 * Deterministic product profile detection.
 * Checks package.json for soloforge.product_profile field.
 * Returns null if no deterministic source found.
 */
function detectProductEvidence(fp) {
    const pkgPath = path.join(fp.project_root, "package.json");
    if (fss.existsSync(pkgPath)) {
        try {
            const raw = fss.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("zero_config", "package.json 产品画像读取失败，跳过");
        }
    }
    return null;
}
function inferProductProfile(fp) {
    if (fp.backend && fp.frontend)
        return "fullstack";
    if (fp.backend)
        return "backend";
    if (fp.frontend)
        return "frontend";
    return "default";
}
function isConfigFile(name) {
    return [
        "package.json", "tsconfig.json", "vite.config.ts", "vite.config.mjs",
        "webpack.config.js", "webpack.config.ts", ".eslintrc.js", ".eslintrc.json",
        "eslint.config.js", "eslint.config.mjs", "pom.xml", "build.gradle",
        "build.gradle.kts", "go.mod", "Cargo.toml", "angular.json",
    ].includes(name);
}
/**
 * 校验 config 草案结构完整性 — advisory, 不 hard block。
 * 确保核心字段存在且格式正确。缺失字段标记为 warning。
 */
export function validateConfigDraft(draft) {
    debug("零配置初始化", "校验配置草案");
    const errors = [];
    const warnings = [];
    if (!draft.tech_stack) {
        debug("零配置初始化", "tech_stack 缺失");
        errors.push("tech_stack 为必填项");
    }
    else {
        if (!draft.tech_stack.backend && !draft.tech_stack.frontend) {
            warnings.push("tech_stack 未检测到后端或前端");
        }
    }
    if (!draft.name || draft.name.trim() === "") {
        warnings.push("项目名称为空，将使用目录名");
    }
    if (!draft.scope || (draft.scope.backend.length === 0 && draft.scope.frontend.length === 0)) {
        debug("零配置初始化", "作用域为空，所有文件都将纳入范围");
        warnings.push("作用域为空，所有文件都将纳入范围");
    }
    if (draft.confidence === "low") {
        debug("零配置初始化", "整体置信度低，建议手动初始化或使用 --interactive");
        warnings.push("整体置信度低 — 建议手动初始化或使用 --interactive");
    }
    return {
        valid: errors.length === 0,
        errors,
        warnings,
    };
}
// ── 配置证据生成 ──
/**
 * 基于 fingerprint + draft 生成字段级证据。
 */
export function generateConfigEvidence(fp, draft, mode) {
    debug("零配置初始化", "生成字段级证据", mode);
    const fields = {};
    // name — 目录名是确定性检测结果
    fields["name"] = {
        value: draft.name,
        confidence: "high",
        confidence_source: "detected",
        evidence: ["目录名"],
    };
    // tech_stack.backend
    fields["tech_stack.backend"] = fp.backend
        ? {
            value: { lang: fp.backend.lang, framework: fp.backend.framework, version: fp.backend.version },
            confidence: "high",
            confidence_source: "detected",
            evidence: [fp.backend.detected_from],
        }
        : {
            value: null,
            confidence: "low",
            confidence_source: "default",
            evidence: ["未找到后端标记"],
        };
    // tech_stack.frontend
    fields["tech_stack.frontend"] = fp.frontend
        ? {
            value: { lang: fp.frontend.lang, framework: fp.frontend.framework, version: fp.frontend.version },
            confidence: "high",
            confidence_source: "detected",
            evidence: [fp.frontend.detected_from],
        }
        : {
            value: null,
            confidence: "low",
            confidence_source: "default",
            evidence: ["未找到前端标记"],
        };
    // build_commands.backend
    fields["build_commands.backend"] = fp.backend
        ? {
            value: draft.build_commands.backend,
            confidence: "high",
            confidence_source: "detected",
            evidence: [`从检测到的 ${fp.backend.framework} 推导 (${fp.backend.detected_from})`],
        }
        : {
            value: draft.build_commands.backend,
            confidence: "low",
            confidence_source: "default",
            evidence: ["无后端可推断"],
        };
    // build_commands.frontend — 检查是否基于 scripts
    const usedProjectScripts = fp.frontend && fp.pkg_scripts && (fp.pkg_scripts.build || fp.pkg_scripts.test);
    fields["build_commands.frontend"] = fp.frontend
        ? {
            value: draft.build_commands.frontend,
            confidence: "high",
            confidence_source: "detected",
            evidence: usedProjectScripts
                ? ["package.json scripts"]
                : [`从检测到的 ${fp.frontend.framework} 推导 (${fp.frontend.detected_from})`]
        }
        : {
            value: draft.build_commands.frontend,
            confidence: "low",
            confidence_source: "default",
            evidence: ["无前端可推断"],
        };
    // product_profile — 技术形态 (fullstack/backend/frontend) 不是高证据
    // 仅当存在确定性产品证据时为高（如 package.json soloforge.product_profile）
    const productEvidence = detectProductEvidence(fp);
    const isDefaultProfile = draft.product_profile === "default" || (!fp.backend && !fp.frontend);
    fields["product_profile"] = productEvidence
        ? { value: productEvidence.value, confidence: "high", confidence_source: "detected", evidence: productEvidence.evidence }
        : isDefaultProfile
            ? { value: draft.product_profile, confidence: "low", confidence_source: "default", evidence: ["未检测到产品画像"] }
            : {
                value: draft.product_profile,
                confidence: "medium",
                confidence_source: "inferred",
                evidence: [`技术形态: ${draft.product_profile}（非产品画像）`],
            };
    // scope.backend — 仅显式目录匹配时为高（非 "." 回退）
    // scope.backend — 空 scope = 黑名单模式（合法，低 confidence）
    const backendScopeExplicit = fp.backend && draft.scope.backend.length > 0;
    fields["scope.backend"] = {
        value: draft.scope.backend,
        confidence: backendScopeExplicit ? "high" : "low",
        confidence_source: backendScopeExplicit ? "detected" : "default",
        evidence: backendScopeExplicit
            ? [`explicit directory: ${draft.scope.backend[0]}`]
            : ["黑名单模式：scope 为空，仅受内置安全黑名单约束"],
    };
    // scope.frontend — 空 scope = 黑名单模式（合法，低 confidence）
    const frontendScopeExplicit = fp.frontend && draft.scope.frontend.length > 0;
    fields["scope.frontend"] = {
        value: draft.scope.frontend,
        confidence: frontendScopeExplicit ? "high" : "low",
        confidence_source: frontendScopeExplicit ? "detected" : "default",
        evidence: frontendScopeExplicit
            ? [`explicit directory: ${draft.scope.frontend[0]}`]
            : ["黑名单模式：scope 为空，仅受内置安全黑名单约束"],
    };
    return {
        schema_version: 1,
        generated_at: new Date().toISOString(),
        mode,
        project_root: fp.project_root,
        fields,
    };
}
/**
 * 检查 evidence 是否允许 --auto 写入。
 * 所有 REQUIRED_FIELDS 对应的字段必须 high confidence + detected/user_declared/confirmed。
 */
export function canAutoWrite(evidence) {
    debug("零配置初始化", "检查 --auto 写入权限");
    const blocked = [];
    for (const req of REQUIRED_FIELDS) {
        // 对于复合字段（如 "tech_stack"），检查子字段
        if (req === "tech_stack") {
            const b = evidence.fields["tech_stack.backend"];
            const f = evidence.fields["tech_stack.frontend"];
            if (!b || b.confidence !== "high" || !isAutoSource(b.confidence_source))
                blocked.push("tech_stack.backend");
            if (!f || f.confidence !== "high" || !isAutoSource(f.confidence_source))
                blocked.push("tech_stack.frontend");
        }
        else if (req === "build_commands") {
            const b = evidence.fields["build_commands.backend"];
            const f = evidence.fields["build_commands.frontend"];
            if (!b || b.confidence !== "high" || !isAutoSource(b.confidence_source))
                blocked.push("build_commands.backend");
            if (!f || f.confidence !== "high" || !isAutoSource(f.confidence_source))
                blocked.push("build_commands.frontend");
        }
        else {
            const field = evidence.fields[req];
            if (!field || field.confidence !== "high" || !isAutoSource(field.confidence_source)) {
                blocked.push(req);
            }
        }
    }
    // 使用 config_precedence_contract 的权威列表检查 C 类字段
    // scope 字段已从 REQUIRED_FIELDS 移除（黑名单模式下空 scope 合法），
    // 在此也跳过，避免因 confidence 不足而阻塞 auto 写入
    for (const [key, field] of Object.entries(evidence.fields)) {
        if (key === "scope.backend" || key === "scope.frontend")
            continue;
        const fieldClass = getFieldClass(key);
        const source = mapConfidenceSource(field.confidence_source);
        const check = canAutoWriteField(key, fieldClass, source);
        if (!check.allowed) {
            blocked.push(key);
        }
    }
    return { allowed: blocked.length === 0, blockedFields: blocked };
}
function isAutoSource(source) {
    return source === "detected" || source === "user_declared" || source === "confirmed";
}
function mapConfidenceSource(source) {
    switch (source) {
        case "detected": return "fingerprint";
        case "user_declared": return "confirmed_config";
        case "confirmed": return "confirmed_config";
        case "inferred": return "knowledge_default";
        case "default": return "global_default";
    }
}
const BLUEPRINT_PATTERNS = [
    { pattern: /spring\s*boot/i, lang: "java", framework: "spring-boot", layer: "backend" },
    { pattern: /go(?:\s+lang)?/i, lang: "go", framework: "stdlib", layer: "backend" },
    { pattern: /rust/i, lang: "rust", framework: "cargo", layer: "backend" },
    { pattern: /gradle/i, lang: "java", framework: "gradle", layer: "backend" },
    { pattern: /react/i, lang: "typescript", framework: "react", layer: "frontend" },
    { pattern: /vue/i, lang: "typescript", framework: "vue", layer: "frontend" },
    { pattern: /angular/i, lang: "typescript", framework: "angular", layer: "frontend" },
    { pattern: /next\.?js/i, lang: "typescript", framework: "react", layer: "frontend" },
    { pattern: /nuxt/i, lang: "typescript", framework: "vue", layer: "frontend" },
];
const PROFILE_PATTERNS = [
    { pattern: /b2b.*内部|内部.*管理|内部.*系统|intranet|internal/i, profile: "b2b-internal" },
    { pattern: /b2c|消费|consumer|customer/i, profile: "b2c" },
    { pattern: /saas|平台|platform/i, profile: "saas" },
];
/**
 * 规则解析蓝图文本（不调用 LLM）。
 */
export function parseBlueprint(text) {
    debug("零配置初始化", "解析蓝图文本");
    let backend = null;
    let frontend = null;
    for (const bp of BLUEPRINT_PATTERNS) {
        if (bp.pattern.test(text)) {
            const entry = { lang: bp.lang, framework: bp.framework, version: "" };
            if (bp.layer === "backend")
                backend = entry;
            else
                frontend = entry;
        }
    }
    let productProfile = null;
    for (const pp of PROFILE_PATTERNS) {
        if (pp.pattern.test(text)) {
            productProfile = pp.profile;
            break;
        }
    }
    if (!productProfile) {
        debug("零配置初始化", "蓝图无明确产品画像，根据技术栈推断");
        if (backend && frontend)
            productProfile = "fullstack";
        else if (backend)
            productProfile = "backend";
        else if (frontend)
            productProfile = "frontend";
    }
    const parsed = backend !== null || frontend !== null;
    return { parsed, tech_stack: { backend, frontend }, product_profile: productProfile };
}
/**
 * 从蓝图生成 evidence（所有字段 confidence_source = user_declared）。
 */
export function generateBlueprintEvidence(blueprintText, config, projectRoot) {
    debug("零配置初始化", "生成蓝图证据", blueprintText);
    const fields = {};
    const src = "user_declared";
    fields["name"] = { value: config.name, confidence: "high", confidence_source: src, evidence: ["--blueprint"] };
    fields["tech_stack.backend"] = {
        value: config.tech_stack.backend,
        confidence: config.tech_stack.backend?.framework ? "high" : "low",
        confidence_source: src,
        evidence: [`--blueprint: ${blueprintText}`],
    };
    fields["tech_stack.frontend"] = {
        value: config.tech_stack.frontend,
        confidence: config.tech_stack.frontend?.framework ? "high" : "low",
        confidence_source: src,
        evidence: [`--blueprint: ${blueprintText}`],
    };
    fields["build_commands.backend"] = {
        value: config.build_commands.backend,
        confidence: config.tech_stack.backend?.framework ? "high" : "low",
        confidence_source: src,
        evidence: [`--blueprint: ${blueprintText}`],
    };
    fields["build_commands.frontend"] = {
        value: config.build_commands.frontend,
        confidence: config.tech_stack.frontend?.framework ? "high" : "low",
        confidence_source: src,
        evidence: [`--blueprint: ${blueprintText}`],
    };
    fields["product_profile"] = {
        value: config.product_profile,
        confidence: config.product_profile ? "high" : "low",
        confidence_source: src,
        evidence: [`--blueprint: ${blueprintText}`],
    };
    fields["scope.backend"] = {
        value: config.scope.backend,
        confidence: config.scope.backend.length > 0 ? "high" : "medium",
        confidence_source: src,
        evidence: [`--blueprint: ${blueprintText}`],
    };
    fields["scope.frontend"] = {
        value: config.scope.frontend,
        confidence: config.scope.frontend.length > 0 ? "high" : "medium",
        confidence_source: src,
        evidence: [`--blueprint: ${blueprintText}`],
    };
    return {
        schema_version: 1,
        generated_at: new Date().toISOString(),
        mode: "blueprint",
        project_root: projectRoot,
        fields,
    };
}
//# sourceMappingURL=zero_config_init.js.map