/**
 * Безопасные тексты для пользователя: без HTTP-кодов, stack trace и прочей техники.
 */
(function (global) {
  const DEFAULT_ERROR_MESSAGE = "Не удалось выполнить операцию. Попробуйте ещё раз.";

  const TECHNICAL_MESSAGE_PATTERNS = [
    /\bHTTP\s*\d{3}\b/i,
    /^\d{3}$/,
    /ошибка\s*\d{3}/i,
    /status:\s*\d+/i,
    /Failed to fetch/i,
    /NetworkError/i,
    /Load failed/i,
    /SyntaxError/i,
    /TypeError/i,
    /ReferenceError/i,
    /RangeError/i,
    /Traceback/i,
    /\bException\b/i,
    /UnicodeEncodeError/i,
    /Internal Server Error/i,
    /<html[\s>]/i,
    /<!DOCTYPE/i,
    /^Error:/i,
    /\.py:\d+/i,
    /\.js:\d+/i,
    /at\s+.+\(.+:\d+:\d+\)/,
    /Unexpected token/i,
    /SQLALCHEMY|werkzeug|flask/i,
    /date_from|date_to|YYYY-MM-DD/i,
    /\bapi\/[a-z0-9_/-]+/i,
    /zootechnician|warehouse_keeper|recipient/i,
    /Content-Disposition/i,
    /latin-1/i,
    /ordinal not in range/i,
    /GET\s+\/api\//i,
    /sync-diagnostics/i,
    /\bfail\b$/i,
    /chat fail|ping fail|summary fail|diagnostics fail|requeue fail|restart fail|runtime fail|push fail/i,
    /status fail/i,
    /no response/i,
  ];

  function plainText(message) {
    if (message instanceof Error) return "";
    if (message && typeof message === "object") {
      if (Array.isArray(message.parts)) {
        return message.parts.map((p) => (p && p.text != null ? String(p.text) : "")).join("");
      }
      if (message.text != null) return String(message.text);
    }
    return message == null ? "" : String(message);
  }

  function isTechnicalMessage(message) {
    const text = plainText(message).trim();
    if (!text) return true;
    return TECHNICAL_MESSAGE_PATTERNS.some((pattern) => pattern.test(text));
  }

  function userFacingMessage(message, fallback) {
    const fb = (fallback && String(fallback).trim()) || DEFAULT_ERROR_MESSAGE;
    if (message instanceof Error) return fb;
    const text = plainText(message).trim();
    if (!text || isTechnicalMessage(text)) return fb;
    return text;
  }

  function messageFromResponseBody(body, fallback) {
    if (!body || typeof body !== "object") {
      return userFacingMessage(null, fallback);
    }
    return userFacingMessage(body.message || body.error || null, fallback);
  }

  function safe(message, fallback) {
    return userFacingMessage(message, fallback);
  }

  global.WespUserMessages = {
    DEFAULT_ERROR_MESSAGE,
    plainText,
    isTechnicalMessage,
    userFacingMessage,
    messageFromResponseBody,
    safe,
  };
})(typeof window !== "undefined" ? window : globalThis);
