#!/bin/bash

# Momentry Redis 監控 (Layer 5)
# 路徑: /Users/accusys/momentry_core_0.1/monitor/database/redis_monitor.sh

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="/Users/accusys/momentry/log/monitor"

mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/redis_check.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

REDIS_PASS="accusys"

# 記錄指標
record_metric() {
    local value=$1
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_databases (db_type, db_name, metric_name, metric_value, checked_at)
VALUES ('redis', 'redis', '$1', '$2', NOW());
EOF
}

# 獲取 Redis INFO
get_info() {
    redis-cli -a "$REDIS_PASS" INFO 2>/dev/null
}

# 主程序
echo "========================================"
echo "Layer 5: Redis Monitoring"
echo "Time: $(date)"
echo "========================================"
echo ""

# 檢查 Redis 是否可用
if ! redis-cli -a "$REDIS_PASS" ping > /dev/null 2>&1; then
    echo "Redis 不可用"
    log "Redis unavailable"
    exit 1
fi

info=$(get_info)

# 提取關鍵指標
echo "關鍵指標:"
echo "----------------------------------------"

# 內存使用
used_memory=$(echo "$info" | grep "^used_memory_human:" | cut -d: -f2 | tr -d '\r')
echo "  內存使用: $used_memory"

# 連線數
connected_clients=$(echo "$info" | grep "^connected_clients:" | cut -d: -f2 | tr -d '\r')
echo "  客戶端連線: $connected_clients"

# 命中率
keyspace_hits=$(echo "$info" | grep "^keyspace_hits:" | cut -d: -f2 | tr -d '\r')
keyspace_misses=$(echo "$info" | grep "^keyspace_misses:" | cut -d: -f2 | tr -d '\r')
total_ops=$((keyspace_hits + keyspace_misses))
if [ $total_ops -gt 0 ]; then
    hit_rate=$((keyspace_hits * 100 / total_ops))
    echo "  命中率: ${hit_rate}%"
else
    echo "  命中率: N/A"
fi

# 持久化
rdb_changes=$(echo "$info" | grep "^rdb_changes_since_last_save:" | cut -d: -f2 | tr -d '\r')
echo "  RDB 變更: $rdb_changes"

# 總鍵數
echo ""
echo "鍵數據庫:"
db0_info=$(echo "$info" | grep "^db0:" | head -1)
if [ -n "$db0_info" ]; then
    keys=$(echo "$db0_info" | sed 's/.*keys=\([0-9]*\).*/\1/')
    expires=$(echo "$db0_info" | sed 's/.*expires=\([0-9]*\).*/\1/')
    echo "  db0: $keys keys, $expires 有過期時間"
fi

# 記錄到資料庫
record_metric "used_memory" "'$used_memory'"
record_metric "connected_clients" "$connected_clients"
record_metric "keyspace_hits" "$keyspace_hits"
record_metric "keyspace_misses" "$keyspace_misses"

# 檢查閾值
echo ""
echo "閾值檢查:"
memory_percent=$(echo "$info" | grep "^used_memory:" | cut -d: -f2)
maxmemory=$(redis-cli -a "$REDIS_PASS" CONFIG GET maxmemory 2>/dev/null | tail -1)
if [ -n "$maxmemory" ] && [ "$maxmemory" -gt 0 ]; then
    mem_pct=$((memory_percent * 100 / maxmemory))
    echo "  內存使用: ${mem_pct}%"
    if [ $mem_pct -gt 80 ]; then
        echo "  ⚠️  內存使用超過 80%"
    fi
fi

if [ $connected_clients -gt 100 ]; then
    echo "  ⚠️  客戶端連線過多"
fi

echo ""
echo "========================================"
log "Redis check completed"
