/**
 * chat-templates.js
 *
 * 运行时询价话术模板。每个模板接收 askContext 对象做字段插值。
 * askContext 来自 customer_service_chats.ask_context (JSONB)，当前主数据来自 standardized_results。
 * 典型结构:
 *   { standardized_name, original_name, standardized_spec, original_spec, quantity, standardized_unit,
 *     brand, category, primary_search_term, alt_search_terms, notes, delivery_address, invoice_type, product_type }
 */

import process from "node:process";

const MAX_RUNTIME_ROUNDS = 100;

const DEFAULT_ROUND_CONFIGS = [
  null,
  {
    round: 1,
    name: "货源基础摸底",
    templateText: "老板，请问【标准化名称】目前有现货吗？",
    passCondition: "商家确认有现货或可调货",
  },
  {
    round: 2,
    name: "规格与起订量确认",
    templateText: "我们需要【标准化规格】，起订量【数量】【单位】能做吗？",
    passCondition: "商家确认可满足规格和起订量要求",
  },
  {
    round: 3,
    name: "核心商务谈判",
    templateText: "如果按照【数量】【单位】采购，最低什么价格？交期到【收货地址】大概要多久？",
    passCondition: "商家给出明确报价和交期",
  },
  {
    round: 4,
    name: "合规与资质核验",
    templateText: "我们需要【发票种类】，备注要求是【备注】，请问能满足吗？",
    passCondition: "商家确认可满足开票与备注要求",
  },
];

const VARIABLE_RESOLVERS = {
  商品标题: (ctx) => ctx.title || ctx.standardized_name || ctx.original_name || ctx.material_name || ctx["商品标题"] || ctx["物料名称"] || "该商品",
  物料名称: (ctx) => ctx.standardized_name || ctx.original_name || ctx.material_name || ctx.title || ctx["物料名称"] || ctx["商品标题"] || "该商品",
  规格型号: (ctx) => ctx.standardized_spec || ctx.original_spec || ctx.specification || ctx.spec || ctx["规格型号"] || ctx.standardized_name || ctx.original_name || ctx.title || "该商品",
  数量: (ctx) => ctx.quantity || ctx["数量"] || "",
  单位: (ctx) => ctx.standardized_unit || ctx.unit || ctx["单位"] || "",
  品牌: (ctx) => ctx.brand || ctx["品牌"] || "",
  技术标准: (ctx) => ctx.technical_standard || ctx["技术标准"] || "国标",
  物料要求: (ctx) => ctx.material_requirement || ctx.notes || ctx["物料要求"] || "",
  标准化名称: (ctx) => ctx.standardized_name || ctx.original_name || ctx.material_name || ctx.title || ctx["标准化名称"] || "该商品",
  原始名称: (ctx) => ctx.original_name || ctx.standardized_name || ctx.material_name || ctx.title || ctx["原始名称"] || "该商品",
  标准化规格: (ctx) => ctx.standardized_spec || ctx.original_spec || ctx.specification || ctx["标准化规格"] || "",
  原始规格: (ctx) => ctx.original_spec || ctx.standardized_spec || ctx.specification || ctx["原始规格"] || "",
  分类: (ctx) => ctx.category || ctx["分类"] || "",
  主搜索词: (ctx) => ctx.primary_search_term || ctx["主搜索词"] || "",
  备选搜索词: (ctx) => ctx.alt_search_terms || ctx["备选搜索词"] || "",
  备注: (ctx) => ctx.notes || ctx.material_requirement || ctx["备注"] || ctx["物料要求"] || "无特殊要求",
  收货地址: (ctx) => ctx.delivery_address || ctx["收货地址"] || "项目地",
  发票种类: (ctx) => ctx.invoice_type || ctx["发票种类"] || "发票",
  产品类型: (ctx) => ctx.product_type || ctx["产品类型"] || "",
};

function normalizeRoundConfig(round, index) {
  const fallback = DEFAULT_ROUND_CONFIGS[index];
  const value = round && typeof round === "object" ? round : {};
  const templateText = String(value.templateText ?? fallback?.templateText ?? "").trim();

  return {
    round: index,
    name: String(value.name ?? fallback?.name ?? `第 ${index} 轮`).trim() || fallback?.name || `第 ${index} 轮`,
    templateText,
    passCondition: String(value.passCondition ?? fallback?.passCondition ?? "").trim(),
  };
}

function getDefaultRoundConfigs() {
  return DEFAULT_ROUND_CONFIGS.slice(1).map((round, index) => normalizeRoundConfig(round, index + 1));
}

function loadRuntimeRoundConfigs() {
  const raw = process.env.CHAT_FUNNEL_CONFIG_JSON;
  if (!raw) {
    return getDefaultRoundConfigs();
  }

  try {
    const parsed = JSON.parse(raw);
    const rounds = Array.isArray(parsed?.rounds)
      ? parsed.rounds
      : Array.isArray(parsed)
        ? parsed
        : [];

    if (rounds.length === 0) {
      return [];
    }

    return rounds
      .filter((round) => round && typeof round === "object" && round.enabled !== false)
      .slice(0, MAX_RUNTIME_ROUNDS)
      .map((round, index) => normalizeRoundConfig(round, index + 1))
      .filter((round) => round.templateText);
  } catch (error) {
    console.warn(`CHAT_FUNNEL_CONFIG_JSON 解析失败，回退默认话术: ${error instanceof Error ? error.message : String(error)}`);
    return getDefaultRoundConfigs();
  }
}

function resolvePlaceholderValue(name, askContext) {
  const variableName = String(name ?? "").trim();
  if (!variableName) {
    return "";
  }

  const resolver = VARIABLE_RESOLVERS[variableName];
  if (resolver) {
    return String(resolver(askContext) ?? "").trim();
  }

  return String(askContext[variableName] ?? "").trim();
}

function renderTemplate(templateText, askContext = {}) {
  return templateText.replace(/【([^】]+)】/g, (_matched, variableName) => resolvePlaceholderValue(variableName, askContext));
}

const ACTIVE_ROUND_CONFIGS = [null, ...loadRuntimeRoundConfigs()];

export function getRoundConfig(round) {
  const roundConfig = ACTIVE_ROUND_CONFIGS[round];
  if (!roundConfig) {
    throw new Error(`无效轮次: ${round}，有效范围 1-${ACTIVE_ROUND_CONFIGS.length - 1}`);
  }
  return roundConfig;
}

/**
 * 获取指定轮次的话术文本
 * @param {number} round  轮次 1-N
 * @param {object} askContext  话术插值上下文
 * @returns {string}
 */
export function getMessageForRound(round, askContext = {}) {
  return renderTemplate(getRoundConfig(round).templateText, askContext);
}

/** 总轮次数 */
export const TOTAL_ROUNDS = ACTIVE_ROUND_CONFIGS.length - 1;
