(function (root) {
  "use strict";

  function number(value) {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : 0;
  }

  function actualCost(record) {
    return number(record?.actualTotalCost)
      || number(record?.actualMaterialCost) + number(record?.actualProcessCost) + number(record?.actualOtherCost);
  }

  function hasActualCost(record) {
    return record?.outcomeStatus === "已成交" && actualCost(record) > 0;
  }

  function evidenceText(item) {
    return [
      item?.source, item?.supplier, item?.note, item?.sourceFile,
      item?.referenceSource, item?.verifiedBy
    ].filter(Boolean).join(" ").toLowerCase();
  }

  function evidenceDate(item, snapshot) {
    return item?.referenceCheckedAt || item?.verifiedAt || item?.effectiveDate
      || snapshot?.effectiveAt || snapshot?.capturedAt || "";
  }

  function evidenceAgeDays(value, nowValue) {
    const checked = Date.parse(String(value || ""));
    const now = Date.parse(String(nowValue || "")) || Date.now();
    if (!Number.isFinite(checked) || checked > now) return null;
    return Math.floor((now - checked) / 86400000);
  }

  function costEvidence(record, nowValue) {
    const snapshot = record?.costSnapshot || record?.cost_snapshot;
    if (!snapshot || typeof snapshot !== "object") {
      return Object.freeze({
        level:"legacy", label:"厂家手动确认", total:0, confirmed:0,
        publicReference:0, missing:0, stale:0, requiresApproval:false,
        reason:"当前报价没有结构化成本快照，请按厂家已确认的手动价格复核。"
      });
    }
    const items = Array.isArray(snapshot.items) ? snapshot.items.filter(item => item && typeof item === "object") : [];
    if (!items.length) {
      return Object.freeze({
        level:"unverified", label:"缺少逐项成本证据", total:0, confirmed:0,
        publicReference:0, missing:1, stale:0, requiresApproval:true,
        reason:"当前公式没有留存逐项成本来源，发送客户前须由报价负责人复核。"
      });
    }
    let confirmed = 0;
    let publicReference = 0;
    let missing = 0;
    let stale = 0;
    items.forEach(item => {
      const text = evidenceText(item);
      const isPublicReference = /(公开|市场参考|行业参考|待本厂复核|待复核)/.test(text);
      const isConfirmed = item.verified === true || item.factoryConfirmed === true
        || /(本厂价格表|本厂确认|厂家确认|实际成本|书面报价|已复核)/.test(text);
      if (isPublicReference && !isConfirmed) publicReference += 1;
      else if (isConfirmed) confirmed += 1;
      else missing += 1;
      const age = evidenceAgeDays(evidenceDate(item, snapshot), nowValue);
      if (age !== null && age > 90) stale += 1;
    });
    const requiresApproval = publicReference > 0 || missing > 0 || stale > 0;
    const level = requiresApproval ? "review" : "verified";
    const parts = [
      `本厂/供应商已确认 ${confirmed}/${items.length}`,
      publicReference ? `公开参考 ${publicReference}` : "",
      missing ? `来源不完整 ${missing}` : "",
      stale ? `超过90天 ${stale}` : ""
    ].filter(Boolean);
    return Object.freeze({
      level,
      label: requiresApproval ? "成本来源待复核" : "成本来源已核对",
      total:items.length,
      confirmed,
      publicReference,
      missing,
      stale,
      requiresApproval,
      reason: requiresApproval
        ? `${parts.join("；")}。发送客户前须由报价负责人确认。`
        : `${parts.join("；")}。已保留在本报价快照中。`
    });
  }

  function summarize(records) {
    const quotes = Array.isArray(records) ? records : [];
    const won = quotes.filter(record => record?.outcomeStatus === "已成交");
    const actual = won.filter(hasActualCost);
    const golden = actual.filter(record => record?.goldenSample?.approved);
    const snapshots = quotes.filter(record => record?.costSnapshot || record?.formulaSnapshot);
    const errors = actual.map(record => {
      const estimate = number(record.estimatedCost)
        || number(record.estimatedMaterialCost) + number(record.estimatedProcessCost) + number(record.estimatedOtherCost);
      return estimate > 0 ? Math.abs(actualCost(record) - estimate) / estimate * 100 : null;
    }).filter(Number.isFinite).sort((a, b) => a - b);
    const middle = Math.floor(errors.length / 2);
    const medianError = !errors.length ? null
      : errors.length % 2 ? errors[middle] : (errors[middle - 1] + errors[middle]) / 2;
    const completionRate = won.length ? actual.length / won.length * 100 : 0;
    let level = "starting";
    let label = "真实成本样本不足";
    if (golden.length >= 12 && completionRate >= 80 && medianError !== null && medianError <= 8) {
      level = "verified"; label = "可用于稳定回归";
    } else if (actual.length >= 5) {
      level = "learning"; label = "已有真实样本，继续积累";
    }
    return Object.freeze({
      totalQuotes: quotes.length,
      wonQuotes: won.length,
      actualCostQuotes: actual.length,
      pendingActualCostQuotes: won.length - actual.length,
      completionRate,
      goldenSamples: golden.length,
      snapshotCoverageRate: quotes.length ? snapshots.length / quotes.length * 100 : 0,
      medianAbsoluteCostErrorPct: medianError,
      level,
      label
    });
  }

  function routeComparison(record) {
    const stored = record?.routeComparison;
    if (stored && Array.isArray(stored.candidates)) return stored;
    const currentCost = number(record?.estimatedCost)
      || number(record?.estimatedMaterialCost) + number(record?.estimatedProcessCost) + number(record?.estimatedOtherCost);
    const route = String(record?.formulaSnapshot?.input?.route || "current");
    return {
      status: "insufficient",
      candidates: currentCost > 0 ? [{
        route,
        label: "当前核价路线",
        total_cost: currentCost,
        delivery_days: 0,
        source: "报价成本快照",
        current: true,
        verified: true
      }] : [],
      recommended_route: "",
      recommended_label: "",
      recommended_cost: 0,
      note: "当前只有一条有成本依据的路线，补录另一条后才能择优。"
    };
  }

  root.JIANGLAI_QUOTE_RELIABILITY = Object.freeze({
    summarize,
    actualCost,
    hasActualCost,
    costEvidence,
    routeComparison
  });
})(typeof globalThis !== "undefined" ? globalThis : this);
