#!/bin/bash
# MAKEE Interactive全员群成员每日检查脚本

# 配置参数
DOC_URL="https://makee-interactive.feishu.cn/docx/KRRXducmGoFtonxBs0Pcmu4anch"
CHAT_ID="oc_d7a8edc423d05f2fa6a5f4c0d8eb4e86"
USER_OPEN_ID="ou_7c623036b45fe81f372b032da664a4fe"

# 1. 获取文档最新成员列表
echo "=== $(date) 开始执行成员检查 ==="
doc_content=$(openclaw tool call feishu_fetch_doc --doc_id "$DOC_URL" --output json)
doc_members=$(echo "$doc_content" | jq -r '.markdown' | grep -A2 '<lark-td>[0-9]*</lark-td>' | grep '<lark-td>[a-z0-9]*</lark-td>' | sed 's/.*<lark-td>\(.*\)<\/lark-td>.*/\1/' | grep -v '^[0-9]*$' | sort)

# 2. 获取群最新成员列表
chat_members=""
page_token=""
while true; do
  resp=$(openclaw tool call feishu_chat_members --chat_id "$CHAT_ID" --member_id_type user_id --page_token "$page_token" --output json)
  members=$(echo "$resp" | jq -r '.items[].member_id' | sort)
  chat_members="$chat_members"$'\n'"$members"
  page_token=$(echo "$resp" | jq -r '.page_token')
  if [ "$page_token" == "null" ] || [ "$page_token" == "" ]; then
    break
  fi
done
chat_members=$(echo "$chat_members" | grep -v '^$' | sort)
total=$(echo "$chat_members" | wc -l)

# 3. 对比差异
added=$(comm -13 <(echo "$doc_members") <(echo "$chat_members"))
removed=$(comm -23 <(echo "$doc_members") <(echo "$chat_members"))

# 4. 生成通知消息
message="📊 MAKEE Interactive全员群每日成员检查报告
检查时间：$(date "+%Y-%m-%d %H:%M:%S")
当前群总人数：$total 人"

if [ -n "$added" ] || [ -n "$removed" ]; then
  message="$message"$'\n\n'"⚠️ 发现人员变动："
  if [ -n "$added" ]; then
    add_count=$(echo "$added" | wc -l)
    message="$message"$'\n'"✅ 新增成员 ($add_count 人)："
    for uid in $added; do
      name=$(openclaw tool call feishu_search_user --query "$uid" --output json | jq -r '.items[0].name' 2>/dev/null || echo "$uid")
      message="$message"$'\n'"- $name ($uid)"
    done
  fi
  if [ -n "$removed" ]; then
    remove_count=$(echo "$removed" | wc -l)
    message="$message"$'\n'"❌ 退出成员 ($remove_count 人)："
    for uid in $removed; do
      name=$(echo "$doc_content" | grep -B2 "$uid" | head -n1 | sed 's/.*<lark-td>\(.*\)<\/lark-td>.*/\1/' 2>/dev/null || echo "$uid")
      message="$message"$'\n'"- $name ($uid)"
    done
  fi

  # 5. 更新文档内容（重新生成整个表格）
  # 生成新的表格内容
  table_header="<lark-table rows=\"$((total+1))\" cols=\"3\" header-row=\"true\" column-widths=\"146,146,146\">

  <lark-tr>
    <lark-td>
      序号
    </lark-td>
    <lark-td>
      姓名
    </lark-td>
    <lark-td>
      租户通用 user_id
    </lark-td>
  </lark-tr>"

  index=1
  for uid in $chat_members; do
    name=$(openclaw tool call feishu_search_user --query "$uid" --output json | jq -r '.items[0].name' 2>/dev/null || echo "$uid")
    table_row="
  <lark-tr>
    <lark-td>
      $index
    </lark-td>
    <lark-td>
      $name
    </lark-td>
    <lark-td>
      $uid
    </lark-td>
  </lark-tr>"
    table_header="$table_header$table_row"
    index=$((index+1))
  done

  table_header="$table_header"$'\n'"</lark-table>"

  # 更新总人数
  openclaw tool call feishu_update_doc --doc_id "$DOC_URL" --mode replace_range --selection_with_ellipsis "总人数：[0-9]*人" --markdown "总人数：$total 人" >/dev/null 2>&1

  # 替换整个成员表格
  openclaw tool call feishu_update_doc --doc_id "$DOC_URL" --mode replace_range --selection_with_ellipsis "<lark-table rows=\"[0-9]*\" cols=\"3\" header-row=\"true\" column-widths=\"146,146,146\">.*</lark-table>" --markdown "$table_header" >/dev/null 2>&1

  message="$message"$'\n\n'"✅ 飞书文档已同步更新为最新成员列表。"
else
  message="$message"$'\n\n'"✅ 无人员变动，成员列表与文档一致。"
fi

# 6. 发送通知给用户
openclaw tool call message --action send --message "$message" --channel feishu --target "user:$USER_OPEN_ID" >/dev/null 2>&1

echo "=== 执行完成 ==="