import { readFile, writeFile, mkdir } from "node:fs/promises";
import path from "node:path";

const root = process.cwd();
const localesDir = path.join(root, "client", "src", "i18n", "locales");
const androidResDir = path.join(root, "android", "app", "src", "main", "res");

const localeMap = {
  en: "values",
  de: "values-de",
  es: "values-es",
  fr: "values-fr",
  it: "values-it",
  ja: "values-ja",
  th: "values-th",
  tl: "values-tl",
  zh: "values-zh-rCN"
};

const keyMap = {
  label_nick: "label_nick",
  label_gender: "label_gender",
  label_age: "label_age",
  label_country: "label_country",
  button_start_chat: "button_start_chat",
  gender_female: "gender_female",
  gender_male: "gender_male",
  gender_pair: "gender_pair",
  gender_trans_mf: "gender_trans_mf",
  gender_trans_fm: "gender_trans_fm",
  menu_search: "tab_search",
  menu_inbox: "tab_inbox",
  menu_history: "tab_history",
  button_send: "button_send",
  search_username_includes: "search_username_includes",
  search_from_age: "search_from_age",
  search_to_age: "search_to_age",
  search_country: "search_country",
  search_genders: "search_genders",
  search_all: "search_all",
  search_button: "search_button",
  search_no_results: "search_no_results",
  search_min_age_error: "search_min_age_error",
  history_empty: "history_empty",
  button_block_user: "block",
  button_unblock_user: "unblock",
  tooltip_send_image: "button_image"
};

function xmlEscape(value) {
  return String(value)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, '\\"')
    .replace(/'/g, "\\'");
}

for (const [locale, folder] of Object.entries(localeMap)) {
  const sourcePath = path.join(localesDir, `${locale}.json`);
  const targetDir = path.join(androidResDir, folder);
  const targetPath = path.join(targetDir, "strings.generated.xml");

  const raw = await readFile(sourcePath, "utf8");
  const json = JSON.parse(raw);
  const lines = ["<resources>"];

  for (const [webKey, androidKey] of Object.entries(keyMap)) {
    const value = json[webKey];
    if (!value || typeof value !== "string") continue;
    lines.push(`    <string name="${androidKey}">${xmlEscape(value.replace(/<[^>]+>/g, "").trim())}</string>`);
  }

  lines.push("</resources>", "");
  await mkdir(targetDir, { recursive: true });
  await writeFile(targetPath, lines.join("\n"), "utf8");
}

console.log("Android i18n files generated from web locales.");
