import fieldLabels from "./validationFieldLabels.json";

/** Compatibility for legacy backend exceptions that bypass Laravel translation. */
const EXCEPTIONS: Array<[string, string]> = [
  ["The uploaded file is too large. Please upload an image smaller than 10 MB", "الملف المرفوع كبير جدًا. يرجى رفع صورة أصغر من 10 ميجابايت."],
  ["Invalid or expired OTP", "رمز التحقق غير صحيح أو انتهت صلاحيته."],
  ["Invalid or expired code", "رمز التحقق غير صحيح أو انتهت صلاحيته."],
  ["Invalid or expired activation link", "رابط تفعيل الحساب غير صحيح أو انتهت صلاحيته."],
  ["Invalid or expired reset link", "رابط إعادة تعيين كلمة المرور غير صحيح أو انتهت صلاحيته."],
  ["Invalid or expired token", "رمز التحقق غير صحيح أو انتهت صلاحيته."],
  ["Old password is incorrect", "كلمة المرور الحالية غير صحيحة."],
  ["Token or old password is required", "يرجى إدخال رمز التحقق أو كلمة المرور الحالية."],
  ["Network Error", "تعذر الاتصال بالخادم. تحقق من اتصال الإنترنت وحاول مرة أخرى."],
  ["Unauthenticated", "يرجى تسجيل الدخول للمتابعة."],
  ["Too Many Attempts", "محاولات كثيرة. يرجى الانتظار ثم المحاولة مرة أخرى."],
  ["Server Error", "حدث خطأ في الخادم. يرجى المحاولة مرة أخرى."],
];

export function localizeApiErrorText(message: string, language: string, localizedFallback?: string | null): string {
  const arabic = language.toLowerCase().startsWith("ar");
  // Older API deployments expose humanized database keys inside validation text.
  // Match only known attribute labels, so user names and other values survive.
  const labels = Object.entries(fieldLabels).flatMap(([key, [en, ar]]) =>
    [key, key.replaceAll("_", " "), en, ar].map(label => ({ label, en, ar }))
  ).sort((a, b) => b.label.length - a.label.length);
  const required = message.trim().match(/^(?:The (.+?) field is required[.!]?|حقل (.+?) مطلوب[.!؟]?)$/i);
  if (required) {
    const attribute = required[1] ?? required[2];
    const known = labels.find(({ label }) => label.toLowerCase() === attribute.toLowerCase());
    if (known) return arabic ? `حقل ${known.ar} مطلوب.` : `The ${known.en.toLowerCase()} field is required.`;
    // Unknown database labels should never leak into a translated required error.
    return arabic ? "هذا الحقل مطلوب." : "This field is required.";
  }
  if (arabic && /\p{Script=Arabic}/u.test(message)) {
    for (const { label, ar } of labels) {
      if (!/[A-Za-z]/.test(label)) continue;
      const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
      message = message.replace(new RegExp(`(?<![A-Za-z0-9_])${escaped}(?![A-Za-z0-9_])`, "gi"), ar);
    }
  }
  // Laravel may leave the post's column name untranslated in length errors.
  if (/idea_text(?:_ar|_en)?/i.test(message) && /280/.test(message) &&
      /(?:greater|exceed|maximum|max|يتجاوز|أكبر|اكبر)/i.test(message)) {
    return arabic
      ? "يجب ألا يتجاوز المنشور 280 حرفًا."
      : "The post must not exceed 280 characters.";
  }
  const normalized = message.trim().replace(/[.!]+$/, "").toLowerCase();
  const pair = EXCEPTIONS.find(([en, ar]) => en.toLowerCase() === normalized || ar.replace(/[.!]+$/, "") === message.trim().replace(/[.!]+$/, ""));
  if (pair) return arabic ? pair[1] : pair[0];
  // Preserve useful localized details (including Latin names/IDs). When a
  // legacy detail has the wrong language, prefer the API's localized summary.
  const hasArabic = /\p{Script=Arabic}/u.test(message);
  if (localizedFallback && (arabic ? !hasArabic && /[A-Za-z]/.test(message) : hasArabic)) {
    const fallbackHasArabic = /\p{Script=Arabic}/u.test(localizedFallback);
    if (arabic === fallbackHasArabic) return localizedFallback;
  }
  return message;
}
