#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORKFLOW_FILE="$ROOT_DIR/.gitea/workflows/code_check.yml"

fail() {
  echo "ERROR: $*" >&2
  exit 1
}

i18n_shared="$(
  sed -n "s/^[[:space:]]*i18n_shared='\(.*\)'/\1/p" "$WORKFLOW_FILE"
)"

if [ -z "$i18n_shared" ]; then
  fail "could not find i18n_shared pattern in Code Check workflow"
fi

assert_i18n_shared_match() {
  local path="$1"
  printf '%s\n' "$path" | grep -Eq "$i18n_shared" ||
    fail "Code Check i18n_shared must match root/userfront locale path: $path"
}

assert_i18n_shared_match "locales/template.toml"
assert_i18n_shared_match "locales/ko.toml"
assert_i18n_shared_match "locales/en.toml"
assert_i18n_shared_match "common/locales/template.toml"
assert_i18n_shared_match "userfront/assets/translations/ko.toml"

grep -Fq 'if matches "$global|$i18n_shared|^userfront/"; then userfront=true; fi' \
  "$WORKFLOW_FILE" || fail "userfront output must depend on i18n_shared"
grep -Fq 'if matches "$global|$i18n_shared|^userfront/|^scripts/summarize_flutter_coverage\.mjs"; then userfront_coverage=true; fi' \
  "$WORKFLOW_FILE" || fail "userfront_coverage output must depend on i18n_shared"
grep -Fq 'if matches "$global|$i18n_shared|^userfront/|^userfront-e2e/"; then userfront_e2e=true; fi' \
  "$WORKFLOW_FILE" || fail "userfront_e2e output must depend on i18n_shared"

echo "OK: root locale changes trigger userfront Code Check jobs"
