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

# ========= 配置 =========
REGEX='https:\/\/www\.figma\.com\/webpack-artifacts\/assets\/figma_app(?:_beta)?-[a-f0-9]+\.min\.en\.json(?:\.br)?'
PAGES_DEFAULT=(
  "https://www.figma.com/"
  "https://www.figma.com/login"
  "https://www.figma.com/ja/"
)
IFS=' ' read -r -a PAGES <<< "${PAGES:-${PAGES_DEFAULT[*]}}"

STATE_FILE=".github/workflows/latest_url.txt"
mkdir -p "$(dirname "$STATE_FILE")"

log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*"; }

fetch_and_match() {
  local url="$1"
  log "Fetch: $url"
  curl -fsSL "$url" \
    | tr -d '\n' \
    | grep -oE "$REGEX" || true
}

pick_latest() {
  awk 'NF' | sort -u | tail -n1
}

notify_issue() {
  local new_url="$1"
  local title="Figma en locale asset updated"
  local body
  body=$(
    cat <<EOF
Detected a new Figma English locale asset.

**URL**
\`\`\`
${new_url}
\`\`\`

**Time**
$(date -u +"%Y-%m-%d %H:%M:%S UTC")

_This issue is auto-generated by workflow **check-figma-locale**._
EOF
  )

  gh api \
    --method POST \
    -H "Accept: application/vnd.github+json" \
    "/repos/${GITHUB_REPOSITORY}/issues" \
    -f title="$title" \
    -f body="$body" >/dev/null

  log "Created GitHub Issue for update."
}

commit_change() {
  local new_url="$1"
  echo "$new_url" > "$STATE_FILE"

  git config user.name  "github-actions[bot]"
  git config user.email "41898282+github-actions[bot]@users.noreply.github.com"

  git add "$STATE_FILE"
  if ! git diff --cached --quiet; then
    git commit -m "chore(i18n): update latest figma en asset url
$new_url"
    git push
    log "Committed & pushed state update."
  else
    log "No changes to commit."
  fi
}

main() {
  log "Start scanning pages…"

  tmp_matches="$(mktemp)"
  trap 'rm -f "$tmp_matches"' EXIT

  for u in "${PAGES[@]}"; do
    fetch_and_match "$u" >> "$tmp_matches"
  done

  if [[ ! -s "$tmp_matches" ]]; then
    log "No matches found for regex."
    exit 0
  fi

  latest_found="$(cat "$tmp_matches" | pick_latest)"
  if [[ -z "$latest_found" ]]; then
    log "No valid latest URL picked."
    exit 0
  fi

  log "Latest match: $latest_found"

  if [[ -f "$STATE_FILE" ]]; then
    current="$(cat "$STATE_FILE" || true)"
  else
    current=""
  fi

  if [[ "$latest_found" == "$current" ]]; then
    log "No update (same as recorded)."
    exit 0
  fi

  log "Detected update! -> will commit & notify."
  commit_change "$latest_found"

  if command -v gh >/dev/null 2>&1; then
    notify_issue "$latest_found"
  else
    log "gh CLI not found; skip issue notification."
  fi
}

main "$@"
