#!/usr/bin/env -S node -r esbin
import { execSync } from "child_process"
import { resolve } from "path"
import en from "../src/shared/i18n/resources/en-US/index.json"
import { writeFormatted } from "./utils"

const languages = process.argv.slice(2).includes("-f")
  ? execSync("crowdin list languages --code=locale --plain")
      .toString()
      .trim()
      .split("\n")
      .concat("en-US")
      .sort()
  : ["de-DE", "en-US", "es-ES", "fr-CA", "fr-FR", "ja-JP", "ko-KR", "zh-CN", "zh-TW"]

const keys: string[] = Array.from(
  (function* keys(
    obj: Record<string, unknown>,
    prefixes: string[] = [],
  ): Generator<string, void, undefined> {
    for (const [key, value] of Object.entries(obj)) {
      if (value != null && typeof value === "object") {
        yield* keys(value as any, prefixes.concat(key))
      } else {
        yield prefixes.concat(key).join(".")
      }
    }
  })(en),
).sort()

const code = [
  `export const languages = ${JSON.stringify(languages, null, 2)};`,
  "",
  "export type TranslationKey =",
  keys.map(key => "  | " + JSON.stringify(key)).join("\n"),
  ";\n",
]

writeFormatted(
  resolve(__dirname, "../src/shared/i18n/data.generated.ts"),
  code.join("\n"),
)
