#!/bin/bash
set -e

# 配置
CONFIG_DIR="/root/.openclaw/credentials/xiaoyan"
OUTPUT_DIR="/root/.openclaw/workspace-xiaobian/tmp/lessons"
mkdir -p $OUTPUT_DIR

# 获取tenant access token
APP_ID=$(cat $CONFIG_DIR/config.json | jq -r '.apps[0].appId')
APP_SECRET=$(cat $CONFIG_DIR/config.json | jq -r '.apps[0].appSecret')
TOKEN=$(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\"}" | jq -r '.tenant_access_token')

echo "Token: $TOKEN"

# S1 Lesson 列表
LESSONS=(
  # U0 秘密基地
  "K4SUw0c08iRkTekzhEmcHgOpntc:U0-1_准备好啦"
  "SmRAwmvEYiu1V9kXQ2xcTObUnGb:U0-2_认识新朋友"
  "PgQjwwNWgiApRUkv089cmDdEnub:U0-3_紧急修理"
  "HQORwpmPWi144RkeCFzceTAWnFc:U0-4_泥巴大作战"
  "NcZPwVtXJi1BWskM4mEcDK2fnkb:U0-5_森林救援"
  
  # U1 友谊之钥
  "HnuYw7dsuilNqYkjABbcudwLnsb:U1-1_秘密基地"
  "BWMKwzleOiVLQGkBDNUc3TtNnse:U1-2_教室怪谈"
  "Gr46whnuRiTmZVk59yPct96TnPf:U1-3_美食机器人"
  "XLyQwFy8MivABGkvux2czUYBnke:U1-4_怪兽捉迷藏"
  "WMkRwLAvRilElVkYcQ3cHwHvnBg:U1-5_飞船焕彩"
  
  # U4 音乐之声
  "SWevw3MFbiTspqkL4FhcRDmCn0d:U4-1_隐藏曲目"
  "JkO3wGtlZiAHvbkXTGPcivOEnHf:U4-2_谁是大胃王"
  "NxYowYt7RijLcokvluRcQLYXnHf:U4-3_病毒大作战"
  "VrKyw1Vn9i0X8skwKICcnOiYnmt:U4-4_宝藏猎人"
  "GjtYwzwhjifKQHkhjwPcJkEKnWc:U4-5_鱼王争霸"
)

for L in "${LESSONS[@]}"; do
  NODE_TOKEN=$(echo $L | cut -d: -f1)
  FILE_NAME=$(echo $L | cut -d: -f2)
  echo "Processing $FILE_NAME ($NODE_TOKEN)..."
  
  # 获取obj_token
  OBJ_TOKEN=$(LARKSUITE_CLI_CONFIG_DIR=$CONFIG_DIR lark-cli wiki spaces get_node --params "{\"token\":\"$NODE_TOKEN\"}" --as bot 2>/dev/null | jq -r '.data.node.obj_token')
  echo "OBJ_TOKEN: $OBJ_TOKEN"
  
  # 读取文档内容
  LARKSUITE_CLI_CONFIG_DIR=$CONFIG_DIR lark-cli docs +fetch --doc "$OBJ_TOKEN" --as bot 2>/dev/null > "$OUTPUT_DIR/$FILE_NAME.md"
  echo "Saved to $OUTPUT_DIR/$FILE_NAME.md"
  sleep 1
done

echo "✅ 所有文档下载完成！"
