#!/bin/bash
set -e

# 配置
APP_ID="cli_a929ae22e0b8dcc8"
APP_SECRET="OtFjMy7p3qE3VvLbMdcWidwgHOnGD4FJ"
FILE_PATH="/root/.openclaw/workspace/2026年3月硬件渠道数据汇总.xlsx"
FILE_NAME="2026年3月硬件渠道数据汇总.xlsx"
FILE_TYPE="xls"
RECEIVE_ID="ou_e63ce6b760ad39382852472f28fbe2a2"
RECEIVE_ID_TYPE="open_id"

# Step 1: 获取 tenant_access_token
TOKEN_RESP=$(curl -s -X POST "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" \
  -H "Content-Type: application/json" \
  -d "{\"app_id\":\"${APP_ID}\",\"app_secret\":\"${APP_SECRET}\"}")

TOKEN=$(echo "$TOKEN_RESP" | grep -o '"tenant_access_token":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "ERROR: 获取 tenant_access_token 失败"
  echo "$TOKEN_RESP"
  exit 1
fi
echo "Step 1 OK: token acquired"

# Step 2: 上传文件获取 file_key
UPLOAD_RESP=$(curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/files" \
  -H "Authorization: Bearer ${TOKEN}" \
  -F "file_type=${FILE_TYPE}" \
  -F "file_name=${FILE_NAME}" \
  -F "file=@${FILE_PATH}")

FILE_KEY=$(echo "$UPLOAD_RESP" | grep -o '"file_key":"[^"]*"' | cut -d'"' -f4)

if [ -z "$FILE_KEY" ]; then
  echo "ERROR: 文件上传失败"
  echo "$UPLOAD_RESP"
  exit 1
fi
echo "Step 2 OK: file_key=${FILE_KEY}"

# Step 3: 发送文件消息
SEND_RESP=$(curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=${RECEIVE_ID_TYPE}" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{\"receive_id\":\"${RECEIVE_ID}\",\"msg_type\":\"file\",\"content\":\"{\\\"file_key\\\":\\\"${FILE_KEY}\\\"}\"}")

MSG_ID=$(echo "$SEND_RESP" | grep -o '"message_id":"[^"]*"' | cut -d'"' -f4)

if [ -z "$MSG_ID" ]; then
  echo "ERROR: 消息发送失败"
  echo "$SEND_RESP"
  exit 1
fi
echo "Step 3 OK: 文件已发送，message_id=${MSG_ID}"
