#!/bin/bash
# System Risk Check Script
# Checks for system risks like disk space, large directories, etc.

# Feishu notification settings (hardcoded for cronjob)
APP_ID="cli_a91c042e98b8dcc9"
APP_SECRET="BZVSYgxVdAIAVkYzH7aa7c3sOzv7oczq"
USER_ID="ou_f442e20fd980363ea486b5a6cd8d2a2f"

# Thresholds
DISK_WARNING=80  # Warn if disk usage > 80%
DISK_CRITICAL=90  # Critical if disk usage > 90%
LARGE_DIR_THRESHOLD=15G  # Warn if any directory > 500M

ALERTS=""

# Check disk space
DISK_USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
DISK_AVAIL=$(df -h / | tail -1 | awk '{print $4}')

if [ "$DISK_USAGE" -ge "$DISK_CRITICAL" ]; then
    ALERTS="$ALERTS\n🚨 **Disk Space CRITICAL**: ${DISK_USAGE}% used (${DISK_AVAIL} available)"
elif [ "$DISK_USAGE" -ge "$DISK_WARNING" ]; then
    ALERTS="$ALERTS\n⚠️ **Disk Space Warning**: ${DISK_USAGE}% used (${DISK_AVAIL} available)"
fi

# Check openclaw-config directory sizes (threshold: 15GB = 15360MB)
LARGE_DIRS=$(du -sh ~/openclaw-config/* 2>/dev/null | awk '
{
    size=$1
    unit=substr(size, length(size))
    value=substr(size, 1, length(size)-1)
    
    # Convert to MB
    if (unit == "G") value = value * 1024
    else if (unit == "K") value = value / 1024
    
    # Force numeric comparison
    if ((value + 0) > 15360) {
        print $2 ": " $1
    }
}' | sort -hr)

if [ -n "$LARGE_DIRS" ]; then
    ALERTS="$ALERTS\n\n📁 **Large Directories in ~/openclaw-config:**\n$LARGE_DIRS"
fi

# Check for vector_memory size (can grow large)
VECTOR_MEM_SIZE=$(du -sh ~/.openclaw/workspace/vector_memory 2>/dev/null | awk '{print $1}')
if [ -n "$VECTOR_MEM_SIZE" ]; then
    # Extract numeric value
    VECTOR_NUM=$(echo "$VECTOR_MEM_SIZE" | sed 's/[GM]//')
    UNIT=$(echo "$VECTOR_MEM_SIZE" | sed 's/[0-9.]//')
    
    if [ "$UNIT" = "G" ] && [ "$(echo "$VECTOR_NUM >= 10" | bc)" = 1 ]; then
        ALERTS="$ALERTS\n\n🧠 **Vector Memory Large**: ${VECTOR_MEM_SIZE} - consider clearing"
    fi
fi

# Send alert if any issues found
if [ -n "$ALERTS" ]; then
    # Build simple message
    MESSAGE="System Risk Check - Large dirs detected:"
    MESSAGE="$MESSAGE $(du -sh ~/openclaw-config/* 2>/dev/null | grep 'G' | awk '{print $1,$2}' | tr '\n' ' ')"
    MESSAGE="$MESSAGE Time: $(date '+%Y-%m-%d %H:%M')"
    
    # Send to Feishu via API
    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\"}" | python3 -c "import sys,json; print(json.load(sys.stdin).get('tenant_access_token',''))")
    
    if [ -n "$TOKEN" ]; then
        curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id" \
            -H "Authorization: Bearer $TOKEN" \
            -H "Content-Type: application/json" \
            -d "{\"receive_id\": \"$USER_ID\", \"msg_type\": \"text\", \"content\": \"{\\\"text\\\": \\\"$MESSAGE\\\"}\"}" 2>/dev/null
    fi
    
    echo "Alert sent for system risks"
    exit 1
fi

echo "✅ System OK - No risks detected"
exit 0
