#!/usr/bin/env bash
# Extract, merge and compile the ModuleDesk translation catalogs.
#
# Run this after adding or editing ANY user-facing string. It is safe to re-run:
# extraction is automatic, existing translations are preserved, edited strings
# come back marked "fuzzy" for review, and deleted ones are dropped.
#
# The compiled .mo files are committed to the repo — same rule as tailwind.css —
# so production needs no build step. Restart the service afterwards: systemd
# runs gunicorn with no auto-reload, so a fresh catalog is invisible until then.
#
#   ./scripts/build-i18n.sh            # extract + update + compile
#   ./scripts/build-i18n.sh es         # also initialise a NEW language

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_ROOT"

PYBABEL="venv/bin/pybabel"
TRANSLATIONS="supporthub/app/translations"
POT="$TRANSLATIONS/messages.pot"

mkdir -p "$TRANSLATIONS"

echo "→ Extracting strings…"
"$PYBABEL" extract -F babel.cfg \
  --keyword=_l --keyword=lazy_gettext --keyword=t \
  --project=ModuleDesk \
  --copyright-holder="Smart Modules" \
  --no-location \
  --sort-by-file \
  -o "$POT" .

if [ $# -gt 0 ]; then
  for lang in "$@"; do
    if [ -d "$TRANSLATIONS/$lang" ]; then
      echo "→ $lang already exists, skipping init"
    else
      echo "→ Initialising $lang…"
      "$PYBABEL" init -i "$POT" -d "$TRANSLATIONS" -l "$lang"
    fi
  done
fi

echo "→ Checking for unescaped '%' …"
venv/bin/python scripts/check-i18n-percent.py "$POT"

if compgen -G "$TRANSLATIONS/*/LC_MESSAGES/messages.po" > /dev/null; then
  echo "→ Merging into existing catalogs…"
  # No --no-fuzzy-matching: carrying an edited string's old translation over
  # as "fuzzy" is exactly the review signal we want.
  "$PYBABEL" update -i "$POT" -d "$TRANSLATIONS" --ignore-obsolete

  venv/bin/python scripts/check-i18n-percent.py "$TRANSLATIONS"/*/LC_MESSAGES/messages.po

  echo "→ Compiling…"
  "$PYBABEL" compile -d "$TRANSLATIONS" --statistics
fi

echo
echo "Done. Restart the app so the new catalogs are loaded:"
echo "  sudo systemctl restart supporthub"
