/**
 * 项目阶段检测器 — 问题六十五。
 *
 * 综合项目状态（配置、知识、设计产物、任务）判断当前项目生命周期阶段。
 * 不只看一个字段，综合 config、knowledge、design、task 多维信号。
 */
import fs from "node:fs";
import path from "node:path";
import { resolveProjectConfig, getProjectKnowledgeDir } from "../../knowledge/loader.js";
import { debug } from "../core/logger.js";
import { safeJsonParse } from "../core/helpers.js";
/**
 * 检测项目当前所处阶段。
 * 综合判断: config 存在性/确认状态、knowledge 可用性、设计产物状态、任务执行状态。
 */
export async function detectProjectStage(projectPath) {
    debug("项目阶段检测", "开始检测", projectPath);
    const soloforgeDir = path.join(projectPath, ".soloforge");
    const configPath = path.join(soloforgeDir, "config.yaml");
    // 1. 未初始化
    if (!fs.existsSync(soloforgeDir)) {
        return "uninitialized";
    }
    // 2. 已初始化但未持久化配置，不能重复建议 init
    if (!fs.existsSync(configPath)) {
        return "configuration_pending";
    }
    // 3. 配置未确认
    const evidencePath = path.join(soloforgeDir, "config.evidence.json");
    if (!fs.existsSync(evidencePath)) {
        return "configuration_pending";
    }
    try {
        const evidenceRaw = safeJsonParse(fs.readFileSync(evidencePath, "utf-8"));
        if (!evidenceRaw)
            return "configuration_pending";
        const confirmedFields = Object.values(evidenceRaw.fields ?? {});
        const allConfirmed = confirmedFields.length > 0
            && confirmedFields.every((f) => f.confidence === "high"
                && (f.confidence_source === "confirmed" || f.confidence_source === "detected"));
        if (!allConfirmed) {
            return "configuration_pending";
        }
    }
    catch {
        return "configuration_pending";
    }
    // 3. 知识就绪检查
    let config;
    try {
        const resolved = await resolveProjectConfig(projectPath);
        config = resolved.config;
    }
    catch {
        return "configuration_pending";
    }
    const knowledgeDir = getProjectKnowledgeDir(config);
    const hasKnowledge = fs.existsSync(knowledgeDir);
    if (!hasKnowledge) {
        return "knowledge_ready";
    }
    // 4-6. 检查任务状态和设计产物
    const stateDir = path.join(soloforgeDir, "state");
    let hasDesignInProgress = false;
    let hasDesignReady = false;
    let hasExecutingTask = false;
    let hasVerifiedDeliveryReady = false;
    let hasDelivered = false;
    if (fs.existsSync(stateDir)) {
        const taskFiles = fs.readdirSync(stateDir).filter((f) => f.startsWith("task-") && f.endsWith(".json"));
        for (const tf of taskFiles) {
            try {
                const task = safeJsonParse(fs.readFileSync(path.join(stateDir, tf), "utf-8"));
                if (!task)
                    continue;
                // 设计产物检查
                const designPack = task.design_artifact_pack;
                if (designPack) {
                    if (designPack.status === "implementation_ready" || designPack.status === "confirmed") {
                        hasDesignReady = true;
                    }
                    else if (designPack.status && designPack.status !== "superseded") {
                        hasDesignInProgress = true;
                    }
                }
                // 任务执行状态
                const status = task.status;
                if (["executing", "verifying", "learning"].includes(status)) {
                    hasExecutingTask = true;
                }
                // 交付就绪 — 验证通过：兼容新旧格式
                // 新格式：main_path_integration.passed / summary 含"通过"
                // 旧格式：verification.status === "passed"（运行时 JSON 可能有旧字段）
                const verifAny = task.verification;
                const verificationPassed = verifAny?.main_path_integration !== undefined
                    && verifAny.main_path_integration?.passed === true
                    || verifAny?.summary !== undefined && typeof verifAny.summary === "string" && (verifAny.summary.includes("通过") || verifAny.summary === "passed")
                    || verifAny?.status === "passed";
                if (status === "done" && verificationPassed) {
                    // 已交付：delivery 存在且 actions_performed 非空或 commit_hash 存在
                    // 兼容旧格式 delivery_executed 字段
                    const deliveryAny = task.delivery;
                    const deliveryDone = deliveryAny
                        && (deliveryAny.commit_hash !== undefined && deliveryAny.commit_hash !== null
                            || (Array.isArray(deliveryAny.actions_performed) && deliveryAny.actions_performed.length > 0)
                            || deliveryAny.delivery_executed === true);
                    if (deliveryDone) {
                        hasDelivered = true;
                    }
                    else {
                        hasVerifiedDeliveryReady = true;
                    }
                }
            }
            catch {
                // 忽略损坏的任务文件
            }
        }
    }
    // 8. 已发布
    if (hasDelivered) {
        return "released";
    }
    // 7. 交付就绪
    if (hasVerifiedDeliveryReady) {
        return "delivery_ready";
    }
    // 6. 开发中
    if (hasExecutingTask) {
        return "development_in_progress";
    }
    // 5. 实现就绪（设计通过审计）
    if (hasDesignReady) {
        return "implementation_ready";
    }
    // 4. 设计进行中
    if (hasDesignInProgress) {
        return "design_in_progress";
    }
    // 3. 知识就绪（默认）
    return "knowledge_ready";
}
/** 项目阶段中文标签映射 */
const PROJECT_STAGE_LABELS = {
    uninitialized: "未初始化",
    configuration_pending: "配置待确认",
    knowledge_ready: "可以开发",
    design_in_progress: "设计进行中",
    implementation_ready: "实现就绪",
    development_in_progress: "开发进行中",
    delivery_ready: "交付就绪",
    released: "已发布",
};
/** 项目阶段中文描述 */
const PROJECT_STAGE_DESCRIPTIONS = {
    uninitialized: "项目尚未运行 soloforge init，缺少 .soloforge/ 目录或配置文件",
    configuration_pending: "配置文件存在但字段尚未确认，建议运行 soloforge config confirm 确认关键字段",
    knowledge_ready: "配置已确认，可以开始接收开发任务。知识库未建立时使用内置知识，可随时补充。",
    design_in_progress: "架构/数据库/API 设计产物正在进行中，尚未通过审计",
    implementation_ready: "设计产物已通过审计复验，可以开始编码实现",
    development_in_progress: "已有任务在编码/验证阶段",
    delivery_ready: "任务已通过验证，准备交付",
    released: "已发布上线",
};
/** 项目阶段必要证据 */
const PROJECT_STAGE_EVIDENCE = {
    uninitialized: [],
    configuration_pending: [".soloforge/config.yaml 存在"],
    knowledge_ready: ["config 已确认"],
    design_in_progress: ["design_artifact_pack 状态非 implementation_ready"],
    implementation_ready: ["design_artifact_pack.status === implementation_ready"],
    development_in_progress: ["存在 executing/verifying/learning 状态任务"],
    delivery_ready: ["任务验证通过", "delivery readiness 评估通过"],
    released: ["delivery 已执行"],
};
/** 项目阶段可能的下一阶段 */
const PROJECT_STAGE_NEXT = {
    uninitialized: ["configuration_pending"],
    configuration_pending: ["knowledge_ready", "uninitialized"],
    knowledge_ready: ["design_in_progress", "development_in_progress"],
    design_in_progress: ["implementation_ready"],
    implementation_ready: ["development_in_progress"],
    development_in_progress: ["delivery_ready"],
    delivery_ready: ["released"],
    released: [],
};
/**
 * 获取项目阶段的中文解释。
 */
export function explainProjectStage(stage) {
    return {
        stage,
        level: "project",
        label_zh: PROJECT_STAGE_LABELS[stage],
        description_zh: PROJECT_STAGE_DESCRIPTIONS[stage],
        required_evidence: PROJECT_STAGE_EVIDENCE[stage],
        next_possible_stages: PROJECT_STAGE_NEXT[stage],
    };
}
//# sourceMappingURL=project_stage_detector.js.map