import type { FactCheckReasonCode, FactCheckResult } from "./ReviewFactGate.ts";

const REASON_LABELS: Record<FactCheckReasonCode, string> = {
  acceptance_contract_failed: "正式验收合同中的一项或多项原始证据确定性校验失败",
  acceptance_contract_needs_pm: "正式验收合同不完整或证据存在多种合理解释，需要 PM 裁决",
  acceptance_contract_missing: "正式 TASK 缺少机器可读的验收合同，需要 PM 确认合同 revision 后再结算",
  qa_business_fail: "QA 已完成验收但业务结论为 FAIL，需要 PM 决定后续工作，不能自动结案",
  qa_acceptance_evidence_missing:
    "QA 验收报告缺少测试数据、模拟用户操作、预期/实际结果或可追溯证据",
  browser_evidence_required:
    "报告声明了真实布局、响应式或下载验收，但缺少 Playwright 或真实浏览器证据",
  missing_test_evidence: "REPORT 声称测试/命令执行，但动作日志缺少可核对的 command.run 证据",
  missing_data_evidence: "REPORT 声称数据查询，但动作日志缺少 data.query 证据",
  missing_file_evidence: "REPORT 声称文件变更，但动作日志缺少 file.read / 变更证据",
  missing_row_count_evidence:
    "REPORT 明确声称库表/SQL 查询结果，但缺少带 row_count 的 data.query 证据",
  missing_stats_evidence:
    "REPORT 含表格或数字统计，但动作日志缺少 command.run、file.read 或 data.query 等执行证据",
  test_exit_code_mismatch: "测试命令退出码与 REPORT「通过」结论不一致",
  evidence_inconclusive: "动作证据不足以支撑 REPORT 结论",
  session_evidence_gap: "动作日志与 REPORT session_id 无法对齐",
  no_claims_detected: "REPORT 正文缺少可核查的交付/测试/数据声明",
  evidence_verified: "动作日志与 REPORT 声明一致，证据可核查",
  ack_only_done_report: "REPORT 仅进度确认，不足以支撑 status=done",
  encoding_invalid: "治理文件不是严格 UTF-8，或包含明显乱码",
  third_party_source_conflict: "REPORT 中的事实与已注册第三方事实源不一致",
  third_party_source_unavailable: "任务绑定了第三方事实源，但源数据当前不可用",
  third_party_source_invalid: "第三方事实源或事实标准注册配置无效",
};

/** Human-readable title for a fact-check reason code. */
export function factCheckReasonLabel(code: FactCheckReasonCode | string): string {
  const key = String(code).trim() as FactCheckReasonCode;
  return REASON_LABELS[key] ?? `事实核查未通过（${code}）`;
}

/** One-paragraph judgment summary for REVIEW body and PM attention. */
export function formatFactCheckJudgmentSummary(result: FactCheckResult): string {
  const title = factCheckReasonLabel(result.reason_code);
  const lines: string[] = [];

  if (result.verdict === "pass") {
    lines.push("程序事实核查记录：执行证据**可核对**，等待 PM 作业务验收。");
    if (result.reason_code === "evidence_verified") {
      lines.push(`${title}，仅表示证据链可进入正常验收流程，不表示业务已通过。`);
    } else {
      lines.push("未检测到需强证据绑定的声明；该观察不替代 PM 审查。");
    }
    return lines.join("\n");
  }

  if (result.verdict === "needs_admin") {
    lines.push("程序事实核查记录：证据当前**不可确定**，需要 PM 通过聊天或补证处理。");
    lines.push(`原因：${title}。`);
  } else {
    lines.push("程序事实核查记录：发现确定性证据缺口或冲突；程序不自动改写 REPORT、不自动返工。");
    lines.push(`原因：${title}。`);
  }

  if (result.unsupported_claims.length) {
    lines.push(
      `不支持的声明：${result.unsupported_claims.map((c) => `「${c}」`).join("；")}。`,
    );
  }
  if (result.required_changes.length) {
    lines.push(`建议整改：${result.required_changes.join("；")}。`);
  }

  return lines.join("\n");
}

/** Compact reason for task frontmatter `pm_attention_reason` (Panel tooltip). */
export function buildPmAttentionReason(result: FactCheckResult): string {
  const title = factCheckReasonLabel(result.reason_code);
  const prefix = result.verdict === "needs_admin"
    ? "事实核查需 PM 关注"
    : "事实核查发现证据缺口";
  const parts = [`${prefix}：${title}`];
  for (const c of result.unsupported_claims) {
    parts.push(c);
  }
  for (const c of result.required_changes) {
    parts.push(`建议：${c}`);
  }
  return parts.filter(Boolean).join("；");
}
