#!/bin/bash
# 组件Oops率每日定时统计任务
# 执行时间：每天9:00
# 输出：Excel报表，发送到指定群

# 配置环境变量
export PATH=/root/.nvm/versions/node/v24.14.0/bin:$PATH

# 配置参数
DB_HOST="bj-postgres-16pob4sg.sql.tencentcdb.com"
DB_PORT="28591"
DB_NAME="vala_bi"
DB_USER="ai_member"
DB_PASS='LdfjdjL83h3h3^$&**YGG*'
STAT_DATE=$(date +%Y-%m-%d -d "yesterday")
TODAY=$(date +%Y%m%d)
SQL_L1_OOPS="/root/.openclaw/workspace/skills/vala-component-practice-stat/scripts/stat_l1.sql"
SQL_L2_OOPS="/root/.openclaw/workspace/skills/vala-component-practice-stat/scripts/stat_l2.sql"
SQL_L1_EXIT="/root/.openclaw/workspace/skills/vala-component-practice-stat/scripts/stat_l1_exit_rate.sql"
SQL_L2_EXIT="/root/.openclaw/workspace/skills/vala-component-practice-stat/scripts/stat_l2_exit_rate.sql"
OUTPUT_CSV_L1_OOPS="/tmp/l1_oops_${TODAY}.csv"
OUTPUT_CSV_L2_OOPS="/tmp/l2_oops_${TODAY}.csv"
OUTPUT_CSV_L1_EXIT="/tmp/l1_exit_${TODAY}.csv"
OUTPUT_CSV_L2_EXIT="/tmp/l2_exit_${TODAY}.csv"
OUTPUT_EXCEL="/root/.openclaw/workspace/output/组件练习质量统计_${TODAY}.xlsx"
TARGET_CHAT="chat:oc_248d0efbc02d97d81d592d0417b6b296"
LOG_FILE="/var/log/component_oops_stat.log"

# 记录日志
echo "[$(date +'%Y-%m-%d %H:%M:%S')] 开始执行组件Oops率每日统计任务，统计日期：${STAT_DATE}" >> $LOG_FILE

# SQL已配置为自动取前一天日期，无需手动替换

# 1. 运行统计SQL
export PGPASSWORD=$DB_PASS
# 统计Oops率
psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME --csv -f $SQL_L1_OOPS > $OUTPUT_CSV_L1_OOPS 2>> $LOG_FILE
if [ $? -ne 0 ]; then
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] L1 Oops率统计SQL执行失败" >> $LOG_FILE
    exit 1
fi

psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME --csv -f $SQL_L2_OOPS > $OUTPUT_CSV_L2_OOPS 2>> $LOG_FILE
if [ $? -ne 0 ]; then
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] L2 Oops率统计SQL执行失败" >> $LOG_FILE
    exit 1
fi

# 统计退出率
psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME --csv -f $SQL_L1_EXIT > $OUTPUT_CSV_L1_EXIT 2>> $LOG_FILE
if [ $? -ne 0 ]; then
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] L1退出率统计SQL执行失败" >> $LOG_FILE
    exit 1
fi

psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME --csv -f $SQL_L2_EXIT > $OUTPUT_CSV_L2_EXIT 2>> $LOG_FILE
if [ $? -ne 0 ]; then
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] L2退出率统计SQL执行失败" >> $LOG_FILE
    exit 1
fi

# 2. 生成Excel
python3 /root/.openclaw/workspace/skills/vala-component-practice-stat/scripts/generate_excel.py \
    $OUTPUT_CSV_L1_OOPS \
    $OUTPUT_CSV_L2_OOPS \
    $OUTPUT_CSV_L1_EXIT \
    $OUTPUT_CSV_L2_EXIT \
    $OUTPUT_EXCEL 2>> $LOG_FILE

if [ $? -ne 0 ]; then
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] Excel生成失败" >> $LOG_FILE
    exit 1
fi

# 3. 发送到指定群（curl两步：上传文件 + 发送文件消息）
APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaoxi/config.json)
APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaoxi/config.json)
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')

# 先发文本消息
curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"receive_id\":\"oc_248d0efbc02d97d81d592d0417b6b296\",\"msg_type\":\"text\",\"content\":\"{\\\"text\\\":\\\"【每日自动统计】$(date +%Y年%m月%d日)组件练习质量统计结果（统计日期：${STAT_DATE}，包含Oops率和退出率双指标），共4个sheet，请查收。\\\"}\"}" >> $LOG_FILE 2>&1

# 上传Excel文件
FILE_KEY=$(curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/files" \
  -H "Authorization: Bearer $TOKEN" \
  -F "file_type=xls" \
  -F "file_name=组件练习质量统计_$(date +%Y%m%d).xlsx" \
  -F "file=@$OUTPUT_EXCEL" | jq -r '.data.file_key')

if [ -z "$FILE_KEY" ] || [ "$FILE_KEY" = "null" ]; then
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] 文件上传失败" >> $LOG_FILE
    exit 1
fi

# 发送文件消息到群
SEND_RESP=$(curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"receive_id\":\"oc_248d0efbc02d97d81d592d0417b6b296\",\"msg_type\":\"file\",\"content\":\"{\\\"file_key\\\":\\\"${FILE_KEY}\\\"}\"}")
SEND_CODE=$(echo "$SEND_RESP" | jq -r '.code')

if [ "$SEND_CODE" != "0" ]; then
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] 消息发送失败: $SEND_RESP" >> $LOG_FILE
    exit 1
fi

# 清理临时文件
rm -f $OUTPUT_CSV_L1_OOPS $OUTPUT_CSV_L2_OOPS $OUTPUT_CSV_L1_EXIT $OUTPUT_CSV_L2_EXIT
echo "[$(date +'%Y-%m-%d %H:%M:%S')] 任务执行完成，文件已发送到群" >> $LOG_FILE
exit 0
