#!/bin/bash
# Copyright 2026, Jiri Eischmann <jiri@eischmann.cz> and the meshy contributors
# SPDX-License-Identifier: GPL-3.0-or-later
# Regenerate .pot template and update .po files.
# Also checks for source files with translatable strings missing from POTFILES.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
BUILD_DIR="$PROJECT_DIR/_build"
POTFILES="$SCRIPT_DIR/POTFILES"

# Ensure build directory exists
if [ ! -f "$BUILD_DIR/build.ninja" ]; then
    echo "Setting up build directory..."
    meson setup "$BUILD_DIR" "$PROJECT_DIR"
fi

# Check for source files missing from POTFILES
echo "Checking POTFILES completeness..."
missing=()

# Python files with _() calls
while IFS= read -r f; do
    rel="${f#"$PROJECT_DIR/"}"
    if ! grep -qxF "$rel" "$POTFILES"; then
        missing+=("$rel")
    fi
done < <(grep -rlnP '(?<![_\w])_\(' "$PROJECT_DIR/src/" --include="*.py" 2>/dev/null | sort)

# UI files with translatable="yes"
while IFS= read -r f; do
    rel="${f#"$PROJECT_DIR/"}"
    if ! grep -qxF "$rel" "$POTFILES"; then
        missing+=("$rel")
    fi
done < <(grep -rln 'translatable="yes"' "$PROJECT_DIR/data/" --include="*.ui" 2>/dev/null | sort)

if [ ${#missing[@]} -gt 0 ]; then
    echo "WARNING: Files with translatable strings not listed in POTFILES:"
    for f in "${missing[@]}"; do
        echo "  $f"
    done
    echo ""
    echo "Add them to po/POTFILES if they contain user-facing strings."
    echo ""
fi

# Regenerate .pot and update .po files
echo "Regenerating .pot template..."
meson compile -C "$BUILD_DIR" meshy-pot 2>/dev/null

echo "Updating .po files..."
meson compile -C "$BUILD_DIR" meshy-update-po 2>/dev/null

# Print statistics
echo ""
echo "=== Translation statistics ==="
pot_count=$(grep -c "^msgid " "$SCRIPT_DIR/meshy.pot")
echo "Total strings in .pot: $pot_count"
echo ""
for po in "$SCRIPT_DIR"/*.po; do
    [ -f "$po" ] || continue
    lang=$(basename "$po" .po)
    stats=$(msgfmt --statistics "$po" 2>&1)
    echo "$lang: $stats"
done
