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

repo_root="$(cd "$(dirname "$0")/.." && pwd)"
whitelist_file="$repo_root/userfront/lib/core/constants/error_whitelist.dart"

extract_internal_codes() {
  awk '
    /internalErrorWhitelistMessages/ { in_map=1; next }
    in_map && /\};/ { in_map=0 }
    in_map {
      if (match($0, /'\''([a-z0-9_]+)'\''[[:space:]]*:/, m)) {
        print m[1]
      }
    }
  ' "$whitelist_file"
}

extract_ory_codes() {
  awk '
    /oryBypassErrorCodes/ { in_set=1; next }
    in_set && /\};/ { in_set=0 }
    in_set {
      if (match($0, /'\''([a-z0-9_]+)'\''/, m)) {
        print m[1]
      }
    }
  ' "$whitelist_file"
}

extract_toml_section_keys() {
  local file="$1"
  local section="$2"
  awk -v section="$section" '
    /^[[:space:]]*\[[^]]+\][[:space:]]*$/ {
      current=$0
      gsub(/^[[:space:]]*\[/, "", current)
      gsub(/\][[:space:]]*$/, "", current)
      in_section=(current == section)
      next
    }

    in_section {
      if (match($0, /^[[:space:]]*([a-zA-Z0-9_]+)[[:space:]]*=/, m)) {
        print m[1]
      }
    }
  ' "$file"
}

check_section_keys() {
  local expected_keys="$1"
  local section="$2"
  local file="$3"
  local missing

  missing="$(comm -23 \
    <(printf '%s\n' "$expected_keys" | sed '/^$/d' | sort -u) \
    <(extract_toml_section_keys "$file" "$section" | sort -u) \
  )"

  if [[ -n "$missing" ]]; then
    echo "[FAIL] ${file} -> [${section}] 누락 키:"
    printf '%s\n' "$missing" | sed 's/^/  - /'
    return 1
  fi

  echo "[OK] ${file} -> [${section}]"
}

internal_codes="$(extract_internal_codes)"
ory_codes="$(extract_ory_codes)"

if [[ -z "$internal_codes" ]]; then
  echo "[FAIL] 내부 whitelist 코드를 찾지 못했습니다."
  exit 1
fi

if [[ -z "$ory_codes" ]]; then
  echo "[FAIL] ORY bypass 코드를 찾지 못했습니다."
  exit 1
fi

files=(
  "$repo_root/locales/template.toml"
  "$repo_root/locales/ko.toml"
  "$repo_root/locales/en.toml"
  "$repo_root/userfront/assets/translations/template.toml"
  "$repo_root/userfront/assets/translations/ko.toml"
  "$repo_root/userfront/assets/translations/en.toml"
)

for file in "${files[@]}"; do
  check_section_keys "$internal_codes" "msg.userfront.error.whitelist" "$file"
  check_section_keys "$ory_codes" "msg.userfront.error.ory" "$file"
done

echo "모든 에러 코드 i18n 키 검증이 완료되었습니다."
