#!/usr/bin/env bash
# scripts/tg_notify.sh — Code Review Telegram 告警工具
# 用法：bash scripts/tg_notify.sh <info|warn|error> "<HTML 訊息>"
set -euo pipefail

LEVEL="${1:-info}"
MESSAGE="${2:-}"

TOKEN="${TELEGRAM_BOT_TOKEN:-}"
CHAT_IDS_RAW="${TELEGRAM_CHAT_IDS:-}"

if [[ -z "$TOKEN" ]]; then
  echo "[tg_notify] TELEGRAM_BOT_TOKEN 未設定，跳過通知" >&2
  exit 0
fi
if [[ -z "$CHAT_IDS_RAW" ]]; then
  echo "[tg_notify] TELEGRAM_CHAT_IDS 未設定，跳過通知" >&2
  exit 0
fi

case "$LEVEL" in
  info)  PREFIX="ℹ️" ;;
  warn)  PREFIX="⚠️" ;;
  error) PREFIX="🚨" ;;
  *)     PREFIX="📌" ;;
esac

FULL_MSG="${PREFIX} ${MESSAGE}"

# 解析 CHAT_IDS JSON 陣列
if command -v jq &>/dev/null; then
  CHAT_IDS=$(echo "$CHAT_IDS_RAW" | jq -r '.[]' 2>/dev/null)
else
  CHAT_IDS=$(echo "$CHAT_IDS_RAW" | tr -d '[]" ' | tr ',' '\n')
fi

if [[ -z "$CHAT_IDS" ]]; then
  echo "[tg_notify] CHAT_IDS 解析結果為空，跳過通知" >&2
  exit 0
fi

while IFS= read -r CHAT_ID; do
  [[ -z "$CHAT_ID" ]] && continue
  printf '%s' "$FULL_MSG" | curl -s --max-time 10 -X POST \
    "https://api.telegram.org/bot${TOKEN}/sendMessage" \
    -d "chat_id=${CHAT_ID}" \
    --data-urlencode "text@-" \
    -d "parse_mode=HTML" > /dev/null || \
    echo "[tg_notify] 發送到 ${CHAT_ID} 失敗（不阻斷流程）" >&2
done <<< "$CHAT_IDS"
