// FFAI Agent Desktop —— Electron 主进程 i18n
//
// 极简实现：根据 app.getLocale() 选 zh-CN / en-US，落到 desktop/locales/*.json。
// frontend 的 i18n 是 renderer 内 react-i18next 的事；本文件只覆盖主进程文案
// （tray menu / OS Notification 系统级标题 / BrowserWindow title）。

import { app } from "electron";
import * as fs from "node:fs";
import * as path from "node:path";

type Locale = "zh-CN" | "en-US";

const SUPPORTED: readonly Locale[] = ["zh-CN", "en-US"];
const FALLBACK: Locale = "en-US";

let strings: Record<string, string> = {};
let current: Locale = FALLBACK;

function localesDir(): string {
  // dev: dist/ -> ../locales；prod 打包后 electron-builder 把 locales/ 一并打入 app/
  return path.join(__dirname, "..", "locales");
}

function pickLocale(): Locale {
  const sys = app.getLocale(); // BCP-47，可能 "zh-CN" "zh" "en-US" "en"
  if (SUPPORTED.includes(sys as Locale)) return sys as Locale;
  if (sys.startsWith("zh")) return "zh-CN";
  return FALLBACK;
}

export function initI18n(): void {
  current = pickLocale();
  const file = path.join(localesDir(), `${current}.json`);
  try {
    strings = JSON.parse(fs.readFileSync(file, "utf8"));
  } catch {
    // locale 文件缺失时回退英文，确保打包错配不致命
    const fb = path.join(localesDir(), `${FALLBACK}.json`);
    try {
      strings = JSON.parse(fs.readFileSync(fb, "utf8"));
      current = FALLBACK;
    } catch {
      strings = {};
    }
  }
}

export function t(key: string): string {
  const v = strings[key];
  if (v !== undefined) return v;
  // dev 时控制台 warn 一次，便于 PR11.5 "missing key = 0" 校验脚本捕获
  console.warn(`[ffai-desktop][i18n] missing key: ${key} (locale=${current})`);
  return key;
}

export function getCurrentLocale(): Locale {
  return current;
}
