#!/bin/sh
set -e

# 루트 locales/*.toml -> userfront/assets/translations/ 동기화
# - userfront에서 사용하는 섹션만 추출
# - {{param}} -> {param} 변환 (easy_localization 포맷)
repo_root="$(cd "$(dirname "$0")/.." && pwd)"
src_dir="$repo_root/locales"
dest_dir="$repo_root/userfront/assets/translations"

mkdir -p "$dest_dir"

filter_toml() {
  src_file="$1"
  dest_file="$2"
  awk '
    function allowed(section) {
      return section ~ /^(ui\.userfront|msg\.userfront|err\.userfront|ui\.common|domain)(\.|$)/;
    }
    BEGIN { keep = 0; }
    {
      line = $0;
      if (match(line, /^[[:space:]]*\[[^]]+\][[:space:]]*$/)) {
        section = line;
        gsub(/^[[:space:]]*\[/, "", section);
        gsub(/\][[:space:]]*$/, "", section);
        keep = allowed(section);
        if (keep) {
          print line;
        }
        next;
      }
      if (keep) {
        print line;
      }
    }
  ' "$src_file" \
    | sed -E 's/\{\{[[:space:]]*([a-zA-Z0-9_]+)[[:space:]]*\}\}/{\1}/g' \
    > "$dest_file"
}

for file in "$src_dir"/*.toml; do
  base="$(basename "$file")"
  filter_toml "$file" "$dest_dir/$base"
done

echo "Synced locales to userfront assets: $dest_dir"
