import { loadUiPrefs } from "./i18n/prefs";
import type { AppLocale } from "./i18n/types";

type Rule = [RegExp, string];

const EN_TOKEN_RULES: Rule[] = [
  [/Chrome\s*crawler/gi, "Chrome"],
  [/the patrol crawler/gi, "test patrol"],
  [/crawler session/gi, "session"],
  [/crawler/gi, "local"],
  [/\bcrawling\b/gi, "analyzing"],
  [/\bcrawl\b/gi, "analyze"],
];

const RULES: Record<AppLocale, Rule[]> = {
  "zh-TW": [
    [/巡樓爬蟲/g, "測試海巡"],
    [/海巡爬蟲/g, "測試海巡"],
    [/Chrome\s*爬蟲/g, "Chrome 工作階段"],
    [/爬蟲\s*session/gi, "工作階段"],
    [/爬蟲/g, "本機"],
    ...EN_TOKEN_RULES,
  ],
  en: [
    [/巡樓爬蟲/g, "test patrol"],
    [/海巡爬蟲/g, "test patrol"],
    [/Chrome\s*爬蟲/g, "Chrome session"],
    [/爬蟲\s*session/gi, "session"],
    [/爬蟲/g, "local"],
    ...EN_TOKEN_RULES,
  ],
};

/** 後端固定中文提示 → 英文 UI 對應句（不含爬蟲字眼）。 */
const KNOWN_ZH_TO_EN: Array<[string, string]> = [
  [
    "今天沒巡到：Chrome 登入已過期。請到設定重新同步已登入的 Threads 分頁，或先關掉開發模式改走 API 搜尋。",
    "Today's patrol didn't finish: Chrome sign-in expired. Reconnect the signed-in Threads tab in Settings, or switch test patrol off and use API search.",
  ],
  ["今天沒巡到：", "Today's patrol didn't finish: "],
];

/**
 * 審查時不要把「爬蟲／crawler」漏到畫面。
 * 後端或舊擴充若仍回這類字，顯示前先換成目前語系的中性說法。
 */
export function sanitizeReviewCopy(text: string, locale?: AppLocale): string {
  const loc = locale ?? loadUiPrefs().locale;
  let s = text;
  if (loc === "en") {
    for (const [from, to] of KNOWN_ZH_TO_EN) s = s.split(from).join(to);
  }
  for (const [re, to] of RULES[loc] ?? RULES["zh-TW"]) s = s.replace(re, to);
  return s;
}
