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

# Usage:
#   ./generate_emoji_json.sh [directory] [--output emojis.json]
#
# Output format:
# {
#   "version": "0.0.1",
#   "emojis": [
#     {"表情名": "表情文件名"}
#   ]
# }

DIR="."
OUT="emoji.json"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --output|-o)
      if [[ $# -lt 2 ]]; then
        echo "Error: --output requires a value" >&2
        exit 1
      fi
      OUT="$2"
      shift 2
      ;;
    *)
      DIR="$1"
      shift
      ;;
  esac
done

if [[ ! -d "$DIR" ]]; then
  echo "Error: directory not found: $DIR" >&2
  exit 1
fi

json_escape() {
  local s="$1"
  s="${s//\\/\\\\}"
  s="${s//\"/\\\"}"
  s="${s//$'\n'/\\n}"
  s="${s//$'\r'/\\r}"
  s="${s//$'\t'/\\t}"
  printf '%s' "$s"
}

shopt -s nullglob nocaseglob
files=(
  "$DIR"/*.jpg
  "$DIR"/*.jpeg
  "$DIR"/*.png
  "$DIR"/*.gif
  "$DIR"/*.webp
)

{
  echo '{'
  echo '  "version": "0.0.1",'
  echo '  "emojis": ['

  first=1
  for path in "${files[@]}"; do
    [[ -f "$path" ]] || continue

    filename="$(basename "$path")"
    emoji_name="${filename%.*}"

    escaped_name="$(json_escape "$emoji_name")"
    escaped_file="$(json_escape "$filename")"

    if [[ $first -eq 0 ]]; then
      echo ','
    fi
    first=0

    printf '    {"%s": "%s"}' "$escaped_name" "$escaped_file"
  done

  echo
  echo '  ]'
  echo '}'
} > "$OUT"

echo "JSON generated: $OUT"
