/**
 * Baseline Comparison — PR-16
 *
 * 比较 Current RC 与 Previous Stable Baseline，发现结构规模异常变化。
 *
 * 纯函数：不读写任何文件、环境变量或数据库。
 *
 * 输入：
 *   { baseline: {...}, candidate: {...} }
 *
 * 输出：
 *   {
 *     status: "pass" | "warn" | "fail",
 *     changes: [{ metric, baseline, candidate, delta, deltaPercent }],
 *     blockers: string[],
 *     warnings: string[]
 *   }
 *
 * @module compare-release-candidate-baseline
 */

import {
  COMPARE_PASS,
  COMPARE_WARN,
  COMPARE_FAIL,
  DEFAULT_THRESHOLDS,
  METRICS,
  getMetricValue,
} from "./baseline-thresholds.mjs";

/**
 * 比较 baseline 与 candidate 的结构指标。
 *
 * @param {object}  baseline  — 上一稳定版本的快照数据
 * @param {object}  candidate — 当前 RC 的快照数据
 * @param {object}  [options] — 可选配置
 * @param {number}  [options.warnPercent=20] — 触发 warning 的百分比阈值
 * @param {number}  [options.failPercent=50] — 触发 fail 的百分比阈值
 * @returns {object}
 */
export function compareReleaseCandidateBaseline(baseline, candidate, options) {
  const opts = { ...DEFAULT_THRESHOLDS, ...(options || {}) };

  // 空输入保护
  if (!baseline || !candidate || typeof baseline !== "object" || typeof candidate !== "object") {
    return _buildResult(COMPARE_FAIL, [], ["Baseline 或 Candidate 数据缺失 — 无法比较"]);
  }

  const changes = [];
  const blockers = [];
  const warnings = [];

  for (const metricDef of METRICS) {
    const baselineVal = getMetricValue(baseline, metricDef.path);
    const candidateVal = getMetricValue(candidate, metricDef.path);

    if (baselineVal === null || candidateVal === null) {
      // 某个数据缺失 → 跳过该指标（不阻塞）
      warnings.push(`${metricDef.label}: 数据缺失，跳过比较`);
      continue;
    }

    const delta = candidateVal - baselineVal;
    const deltaPercent = baselineVal !== 0
      ? parseFloat(((delta / baselineVal) * 100).toFixed(2))
      : (candidateVal !== 0 ? 100 : 0);

    const absPct = Math.abs(deltaPercent);

    const change = {
      metric: metricDef.key,
      label: metricDef.label,
      baseline: baselineVal,
      candidate: candidateVal,
      delta,
      deltaPercent,
    };

    changes.push(change);

    // ── 阈值判定 ──
    if (absPct > opts.failPercent) {
      const direction = delta > 0 ? "增加" : "减少";
      blockers.push(
        `${metricDef.label}: baseline=${baselineVal} → candidate=${candidateVal} (${direction} ${absPct}%，超过严重阈值 ${opts.failPercent}%)`
      );
    } else if (absPct > opts.warnPercent) {
      const direction = delta > 0 ? "增加" : "减少";
      warnings.push(
        `${metricDef.label}: baseline=${baselineVal} → candidate=${candidateVal} (${direction} ${absPct}%，超过警示阈值 ${opts.warnPercent}%)`
      );
    }
  }

  // 无任何数据 → fail
  if (changes.length === 0) {
    return _buildResult(COMPARE_FAIL, [], ["所有指标数据缺失 — 无法进行比较"]);
  }

  // 判定最终状态
  let status;
  if (blockers.length > 0) {
    status = COMPARE_FAIL;
  } else if (warnings.length > 0) {
    status = COMPARE_WARN;
  } else {
    status = COMPARE_PASS;
  }

  return _buildResult(status, changes, blockers, warnings);
}

// ─── 内部工具 ────────────────────────────────────────

function _buildResult(status, changes, blockers, warnings) {
  return {
    status,
    changes: changes || [],
    blockers: blockers || [],
    warnings: warnings || [],
  };
}
