import { resolveIntent } from './ack-intent.mjs';
import { selectBuilder } from './ack-builders.mjs';

function readConfig(config) {
  return {
    randomEnabled: config?.ackRandomEnabled !== false,
    nicknameEnabled: config?.ackNicknameEnabled !== false,
  };
}

// intent: normalizeWechatInboundIntent output ({ msgType, agentText, ... })
// nickname: resolved display name string (empty string if unavailable)
// config: loadWechatMpConfig output (plus ackRandomEnabled, ackNicknameEnabled)
// fallbackText: config.ackText — returned on any error
export function buildAckText({ intent, nickname, config, fallbackText }) {
  try {
    const cfg = readConfig(config);
    const ctx = {
      msgType: String(intent?.msgType ?? 'text'),
      nickname: String(nickname ?? ''),
      intent: resolveIntent(intent?.msgType, intent?.agentText),
      randomEnabled: cfg.randomEnabled,
      nicknameEnabled: cfg.nicknameEnabled,
    };
    return selectBuilder(ctx).build(ctx);
  } catch {
    return fallbackText ?? '已收到，正在处理，完成后发到这里。';
  }
}
