/**
 * Developer Sovereignty — 交付前 raw diff 展示、证据链、回滚路径、否决入口。
 * R11 advisory: 不 hard block，提供信息供开发者决策。
 *
 * 职责:
 * - preDeliveryReview: 交付前预览（raw diff + 风险摘要 + 证据链 + 回滚命令）
 * - vetoDelivery: 开发者否决入口
 */
import { buildDeliveryEvidenceChain } from "./semantic_evidence.js";
import { debug } from "../core/logger.js";
/**
 * 交付前预览 — 收集 raw diff、风险摘要、证据链、回滚命令。
 * 使用 git_deps.GitOperations 获取真实 diff 统计和 commit/branch 信息。
 */
export async function preDeliveryReview(taskContext, gitOps, projectPath) {
    debug("开发者主权", "preDeliveryReview() 开始 — taskId:", taskContext.task_id);
    const changedFiles = taskContext.execution?.changed_files ?? [];
    const attemptCount = taskContext.execution?.attempt_count ?? 0;
    const failureCount = taskContext.execution?.failure_history?.length ?? 0;
    const risk = taskContext.classification?.risk ?? "low";
    // Diff 摘要 — 合并 unstaged 和 cached diff（按文件）
    const [unstaged, staged] = await Promise.all([
        gitOps.getDiff(projectPath, { cached: false }),
        gitOps.getDiff(projectPath, { cached: true }),
    ]);
    const diffFiles = new Set(changedFiles);
    // 合并by file: sum additions/deletions from both sources
    const merged = new Map();
    for (const h of [...unstaged, ...staged]) {
        if (!diffFiles.has(h.file))
            continue;
        const existing = merged.get(h.file);
        if (existing) {
            existing.additions += h.additions;
            existing.deletions += h.deletions;
        }
        else {
            merged.set(h.file, { file_path: h.file, additions: h.additions, deletions: h.deletions });
        }
    }
    // 未出现在 diff 输出中的变更文件，补充零计数字段
    for (const f of changedFiles) {
        if (!merged.has(f)) {
            merged.set(f, { file_path: f, additions: 0, deletions: 0 });
        }
    }
    const fileDetails = [...merged.values()];
    const totalAdditions = fileDetails.reduce((s, d) => s + d.additions, 0);
    const totalDeletions = fileDetails.reduce((s, d) => s + d.deletions, 0);
    const diffSummary = {
        changed_files: changedFiles,
        additions: totalAdditions,
        deletions: totalDeletions,
        file_details: fileDetails,
    };
    // 风险摘要
    const riskFactors = [];
    if (risk === "high")
        riskFactors.push(`任务风险: ${risk}`);
    if (attemptCount > 1)
        riskFactors.push(`多次尝试: ${attemptCount} 次`);
    if (failureCount > 0)
        riskFactors.push(`历史失败: ${failureCount} 次`);
    if (changedFiles.length > 10)
        riskFactors.push(`变更文件多: ${changedFiles.length} 个`);
    const riskLevel = riskFactors.length === 0 ? "low" : riskFactors.length <= 2 ? "medium" : "high";
    debug("开发者主权", "风险评估 — level:", riskLevel, "factors:", riskFactors.join(", "));
    // 证据链
    const chain = buildDeliveryEvidenceChain(taskContext);
    const evidenceChain = chain
        ? {
            requirements: chain.requirement_points,
            coverage_summary: chain.completeness.advisory,
            uncovered_points: chain.completeness.uncovered_points,
        }
        : null;
    // 回滚命令 — 绑定真实 commit hash
    let commitHash = "HEAD";
    try {
        commitHash = await gitOps.getHeadCommitHash(projectPath);
    }
    catch (e) {
        debug("开发者主权", "获取commit hash失败，使用默认值 —", e);
    }
    const rollbackCommand = `git revert ${commitHash} --no-edit`;
    // can_deliver advisory 逻辑: advisory 级阻断，非 hard block
    const deliveryBlockers = [];
    if (riskLevel === "high") {
        deliveryBlockers.push("advisory: 高风险 — 建议交付前人工审查");
    }
    if (evidenceChain && evidenceChain.uncovered_points.length > 0) {
        deliveryBlockers.push(`advisory:  个未覆盖的需求点`);
    }
    // eslint-disable-next-line eqeqeq -- 同时检查 null 和 undefined
    const hasVerification = taskContext.verification?.summary != null;
    if (!hasVerification && changedFiles.length > 0) {
        deliveryBlockers.push("advisory: 无验证结果 — 建议交付前运行测试");
    }
    debug("开发者主权", "delivery blockers:", deliveryBlockers.length > 0 ? deliveryBlockers.join("; ") : "无");
    // can_deliver 始终为 true（advisory 模式，非 hard block），但阻断信息供开发者参考
    const canDeliver = true;
    return {
        task_id: taskContext.task_id,
        diff_summary: diffSummary,
        risk_summary: {
            risk_level: riskLevel,
            factors: riskFactors,
            advisory: riskLevel === "high"
                ? "advisory: 高风险交付，建议人工审查后再继续"
                : riskLevel === "medium"
                    ? "advisory: 中等风险，交付前请审查变更"
                    : "低风险，可安全继续",
        },
        evidence_chain: evidenceChain,
        rollback_command: rollbackCommand,
        can_deliver: canDeliver,
        delivery_blockers: deliveryBlockers,
        advisory: deliveryBlockers.length > 0
            ? deliveryBlockers.join("; ")
            : "确认交付前请审查 diff 和证据链",
    };
}
/**
 * 否决交付 — 开发者行使否决权。
 * 返回 VetoResult 记录否决事件，不修改任何状态。
 */
export function vetoDelivery(taskId, reason) {
    debug("开发者主权", "vetoDelivery() — taskId:", taskId, "原因:", reason);
    return {
        vetoed: true,
        task_id: taskId,
        reason,
        timestamp: new Date().toISOString(),
        advisory: "交付已被开发者否决 — 未提交或推送任何代码变更",
    };
}
//# sourceMappingURL=developer_sovereignty.js.map