#!/bin/bash
# Copyright 2026, Jiri Eischmann <jiri@eischmann.cz> and the meshy contributors
# SPDX-License-Identifier: GPL-3.0-or-later
# Check .ui files for missing translatable="yes" on user-facing strings
# and verify that files with translatable content are listed in po/POTFILES.
#
# Usage:
#   scripts/check-i18n.sh              # check all .ui files in data/
#   scripts/check-i18n.sh --staged     # check only staged files (for pre-commit)
#
# False positives: if a property legitimately should NOT be translated,
# mark it with translatable="no" to suppress the warning.

set -euo pipefail

REPO_ROOT="$(git rev-parse --show-toplevel)"
POTFILES="$REPO_ROOT/po/POTFILES"
ERRORS=0

# Properties that should normally be translatable when they contain text
PROPS='title|label|tooltip-text|placeholder-text|description'

if [[ "${1:-}" == "--staged" ]]; then
    FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.ui' | grep '^data/' || true)
    READ_CMD="git show"
    READ_PREFIX=":"
else
    FILES=$(find "$REPO_ROOT/data" -name '*.ui' -printf 'data/%P\n' | sort)
    READ_CMD="cat"
    READ_PREFIX="$REPO_ROOT/"
fi

for file in $FILES; do
    content=$($READ_CMD "${READ_PREFIX}${file}")

    # Find properties with text content but no translatable="yes" (or "no")
    while IFS= read -r match; do
        lineno="${match%%:*}"
        line="${match#*:}"
        echo "  $file:$lineno:$line"
        ERRORS=$((ERRORS + 1))
    done < <(echo "$content" \
        | grep -n -E "<property name=\"($PROPS)\">[^<]" \
        | grep -v 'translatable=' \
        || true)

    # Check that files with translatable strings are in POTFILES
    if echo "$content" | grep -q 'translatable="yes"'; then
        # Normalize: POTFILES paths are relative to repo root
        potfile_entry="$file"
        if ! grep -qxF "$potfile_entry" "$POTFILES" 2>/dev/null; then
            echo "  $file: has translatable strings but is not listed in po/POTFILES"
            ERRORS=$((ERRORS + 1))
        fi
    fi
done

if [[ $ERRORS -gt 0 ]]; then
    echo ""
    echo "Found $ERRORS i18n issue(s)."
    echo "Fix: add translatable=\"yes\" to user-facing properties, or translatable=\"no\" for intentional exceptions."
    exit 1
else
    if [[ -n "${FILES:-}" ]]; then
        echo "i18n check passed."
    fi
fi
