#!/usr/bin/env node
"use strict";

const fs = require("fs");
const path = require("path");
const { spawnSync } = require("child_process");

const ROOT = process.cwd();
const LOCALES_DIR = path.join(ROOT, "locales");
const KO_PATH = path.join(LOCALES_DIR, "ko.toml");
const EN_PATH = path.join(LOCALES_DIR, "en.toml");
const OUT_PATH = path.join(ROOT, "userfront", "lib", "i18n_data.dart");

function parseToml(filePath) {
  if (!fs.existsSync(filePath)) return new Map();
  const content = fs.readFileSync(filePath, "utf8");
  const lines = content.split(/\r?\n/);
  let section = [];
  const map = new Map();

  for (const rawLine of lines) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#")) continue;
    if (line.startsWith("[[") && line.endsWith("]]")) {
      const name = line.slice(2, -2).trim();
      section = name ? name.split(".").map((p) => p.trim()).filter(Boolean) : [];
      continue;
    }
    if (line.startsWith("[") && line.endsWith("]")) {
      const name = line.slice(1, -1).trim();
      section = name ? name.split(".").map((p) => p.trim()).filter(Boolean) : [];
      continue;
    }
    const eqIndex = line.indexOf("=");
    if (eqIndex === -1) continue;
    const key = line.slice(0, eqIndex).trim();
    const valueRaw = line.slice(eqIndex + 1).trim();
    if (!key) continue;

    let value = "";
    if (valueRaw.startsWith('"')) {
      try {
        value = JSON.parse(valueRaw);
      } catch {
        value = valueRaw.slice(1, -1);
      }
    } else if (valueRaw.startsWith("'") && valueRaw.endsWith("'")) {
      value = valueRaw.slice(1, -1);
    } else {
      value = valueRaw;
    }

    const fullKey = [...section, key].join(".");
    map.set(fullKey, value);
  }

  return map;
}

function dartStringLiteral(value) {
  return JSON.stringify(value).replace(/\$/g, "\\$");
}

function renderDartMap(name, map) {
  const keys = Array.from(map.keys()).sort();
  const lines = [];
  lines.push(`const Map<String, String> ${name} = {`);
  for (const key of keys) {
    const value = map.get(key) ?? "";
    lines.push(`  ${dartStringLiteral(key)}: ${dartStringLiteral(value)},`);
  }
  lines.push("};");
  return lines.join("\n");
}

const koMap = parseToml(KO_PATH);
const enMap = parseToml(EN_PATH);

const output = [
  "// locales/*.toml에서 생성됨",
  renderDartMap("koStrings", koMap),
  "",
  renderDartMap("enStrings", enMap),
  "",
].join("\n");

fs.writeFileSync(OUT_PATH, output, "utf8");

const formatResult = spawnSync("dart", ["format", OUT_PATH], {
  cwd: ROOT,
  stdio: "inherit",
});

if (formatResult.status !== 0) {
  process.exit(formatResult.status ?? 1);
}
