#!/usr/bin/env bash
# Nomad Karaoke pre-commit hook (karaoke-gen variant)
#   1. Gitleaks secret scan (fail fast)
#   2. i18n auto-translation when en.json changes
# Enable: git config core.hooksPath .githooks
set -eu

# ---------------------------------------------------------------------------
# 1. Gitleaks secret scan
# ---------------------------------------------------------------------------

if command -v gitleaks >/dev/null 2>&1; then
  if ! gitleaks protect --staged --redact --no-banner; then
    printf '\n\033[31m✗ gitleaks detected a potential secret in staged changes.\033[0m\n' >&2
    printf '  • If real: remove it, rotate the credential, then re-commit.\n' >&2
    printf '  • If false positive: add an allowlist entry to .gitleaks.toml.\n' >&2
    printf '  • Emergency override (not recommended): git commit --no-verify\n' >&2
    exit 1
  fi
else
  printf '\033[33mwarn:\033[0m gitleaks not installed — skipping secret scan\n' >&2
  printf '      install: brew install gitleaks\n' >&2
fi

# ---------------------------------------------------------------------------
# 2. i18n auto-translation
# ---------------------------------------------------------------------------

STAGED_EN=$(git diff --cached --name-only --diff-filter=ACM | grep -E '(messages|translations)/en\.json$' || true)

if [ -z "$STAGED_EN" ]; then
    exit 0
fi

echo "i18n: English translations changed — running translation pipeline..."

for en_file in $STAGED_EN; do
    dir=$(dirname "$en_file")

    if [[ "$dir" == frontend/messages ]]; then
        script="frontend/scripts/translate.py"
    elif [[ "$dir" == backend/translations ]]; then
        script="frontend/scripts/translate.py"
    else
        echo "  Warning: Unknown messages dir $dir, skipping"
        continue
    fi

    echo "  Translating $dir..."
    if python "$script" --messages-dir "$dir" --target all --skip-review 2>&1 | tail -5; then
        git add "$dir"/*.json
        echo "  Done: $dir"
    else
        echo "  Warning: Translation failed for $dir (GCP auth may be missing). CI will catch this."
    fi
done

echo "i18n: Translation complete."
