(() => {
  const MAX_HABIT_CHARS = 1000;
  const SENSITIVE_PATTERN = /(?:cookie|password|passwd|authorization|access[_-]?token|refresh[_-]?token|session[_-]?id|api\s*[_-]?\s*key|登录密码|验证码|密钥)/i;

  function normalizePreferences(raw = {}) {
    const dialogueHabit = clean(raw.dialogue_habit ?? raw.dialogueHabit);
    const operationHabit = clean(raw.operation_habit ?? raw.operationHabit);
    return {
      dialogue_habit: dialogueHabit,
      operation_habit: operationHabit,
      configured_count: Number(Boolean(dialogueHabit)) + Number(Boolean(operationHabit)),
      updated_at: String(raw.updated_at || raw.updatedAt || "")
    };
  }

  function validatePreferences(raw = {}) {
    const normalized = normalizePreferences(raw);
    for (const [label, value] of [["对话习惯", normalized.dialogue_habit], ["操作习惯", normalized.operation_habit]]) {
      if (value.length > MAX_HABIT_CHARS) return { ok: false, message: `${label}最多输入 ${MAX_HABIT_CHARS} 个字符。` };
      if (SENSITIVE_PATTERN.test(value)) return { ok: false, message: `${label}不能包含密码、Cookie、验证码、Token 或密钥。` };
    }
    return { ok: true, value: normalized };
  }

  function clean(value) {
    return String(value || "").replace(/\0/g, "").trim();
  }

  window.MMWQianchuanPersonalPreferences = Object.freeze({
    MAX_HABIT_CHARS,
    normalizePreferences,
    validatePreferences
  });
})();
