import { defineConfig, type Plugin } from "i18next-cli";

/**
 * Plugin to remove false positive keys generated by dynamic namespace patterns
 * like useTranslation([i18nLibrary]) and t("key", { ns: configNamespace }).
 * These keys already exist in their correct runtime namespaces.
 */
function ignoreDynamicNamespaceKeys(): Plugin {
  // Keys that the extractor misattributes to the wrong namespace
  // because it can't resolve dynamic ns values at build time.
  const falsePositiveKeys = new Set([
    // From useTranslation([i18nLibrary]) in ClassificationCard.tsx
    // Already in views/classificationModel and views/faceLibrary
    "details.unknown",
    "details.none",
    // From t("key", { ns: configNamespace }) in DetectorHardwareField.tsx
    // Already in config/global
    "detectors.type.label",
    // From t(`${prefix}`) template literals producing empty/partial keys
    "",
    "_one",
    "_other",
  ]);

  return {
    name: "ignore-dynamic-namespace-keys",
    onEnd: async (keys) => {
      for (const key of keys.keys()) {
        // Each map key is "ns:actualKey" format
        const separatorIndex = key.indexOf(":");
        const actualKey =
          separatorIndex >= 0 ? key.slice(separatorIndex + 1) : key;
        if (falsePositiveKeys.has(actualKey)) {
          keys.delete(key);
        }
      }
    },
  };
}

export default defineConfig({
  locales: ["en"],
  extract: {
    input: ["src/**/*.{ts,tsx}"],
    output: "public/locales/{{language}}/{{namespace}}.json",
    defaultNS: "common",
    removeUnusedKeys: false,
    sort: false,
  },
  plugins: [ignoreDynamicNamespaceKeys()],
});
