#!/bin/bash

GOOGLE_CHAT_WEBHOOK_URL="https://chat.googleapis.com/v1/spaces/AAAA7hXAOCM/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=YupvEeDhNq2aF9ldCAf8TeJw8kmafVAXpj3xJWIzRGw%3D"

# === 第一次訊息：建立 thread ===
echo "Generate the Thread Title ..."
response=$(curl -s -X POST -H "Content-Type: application/json" \
  -d '{"text":"[主題] 這是 thread 開始訊息"}' \
  "$GOOGLE_CHAT_WEBHOOK_URL")

# 取得 thread.name
#thread_name=$(echo "$response" | grep -o '"thread":{[^}]*}' | grep -o '"name":"[^"]*"' | cut -d'"' -f4)
#if [[ -z "$thread_name" ]]; then
#  echo "Error: Can not get the thread.name"
#  echo "Response: $response"
#  exit 1
#fi

thread_name=$(echo "$response" | jq -r '.thread.name')
if [[ "$thread_name" == "null" || -z "$thread_name" ]]; then
  echo "Error: Can not get the thread.name"
  echo "Response: $response"
  exit 1
fi
echo "Get the thread.name successfully: $thread_name ..."
echo

# === 定義要發送的訊息清單 ===
messages=(
  "第 1 條回覆訊息：系統初始化完成"
  "第 2 條回覆訊息：正在同步資料中"
  "第 3 條回覆訊息：任務完成，狀態為 SUCCESS"
  "第 4 條回覆訊息：全部流程已結束"
)

# === 逐條訊息發送至同一 thread ===
for msg in "${messages[@]}"; do
  echo "Send Messages：$msg"
  curl -s -X POST -H "Content-Type: application/json" \
    -d '{
          "text": "'"$msg"'",
          "thread": { "name": "'"$thread_name"'" }
        }' \
    "$GOOGLE_CHAT_WEBHOOK_URL"
  echo "Finised."
  sleep 1  # 可視需要調整節奏
done

echo
echo "All messages send to the same thread"
