#!/bin/bash

# Momentry Qdrant 監控 (Layer 5)
# 路徑: /Users/accusys/momentry_core_0.1/monitor/database/qdrant_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/qdrant_check.log"

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

QDRANT_HOST="http://localhost:6333"
QDRANT_API_KEY="Test3200Test3200Test3200"

# 記錄指標
record_metric() {
    local collection=$1
    local metric_name=$2
    local value=$3
    
    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 ('qdrant', '$collection', '$metric_name', '$value', NOW());
EOF
}

# 記錄 Collection
record_collection() {
    local name=$1
    local vectors=$2
    local points=$3
    local disk_size=$4
    local status=$5
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_qdrant_collections (collection_name, vectors_count, points_count, disk_size_bytes, status, snapshot_at)
VALUES ('$name', $vectors, $points, $disk_size, '$status', NOW())
ON CONFLICT (collection_name) DO UPDATE SET
    vectors_count = EXCLUDED.vectors_count,
    points_count = EXCLUDED.points_count,
    disk_size_bytes = EXCLUDED.disk_size_bytes,
    status = EXCLUDED.status,
    snapshot_at = NOW();
EOF
}

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

# 檢查 Qdrant 是否可用
http_code=$(curl -s -o /dev/null -w "%{http_code}" \
    -H "api-key: $QDRANT_API_KEY" \
    "$QDRANT_HOST/collections" 2>/dev/null || echo "000")
if [ "$http_code" = "000" ]; then
    echo "Qdrant 不可用"
    log "Qdrant unavailable"
    exit 1
fi

echo "Qdrant 狀態: HTTP $http_code"
echo ""

# 獲取 Collection 列表
collections=$(curl -s -H "api-key: $QDRANT_API_KEY" "$QDRANT_HOST/collections" 2>/dev/null)

if [ "$http_code" = "200" ]; then
    collection_count=$(echo "$collections" | jq '.result.collections | length' 2>/dev/null || echo "0")
    echo "Collection 數量: $collection_count"
    echo ""
    
    # 遍歷每個 Collection
    echo "Collections:"
    echo "----------------------------------------"
    
    for i in $(seq 0 $((collection_count - 1))); do
        name=$(echo "$collections" | jq -r ".result.collections[$i].name")
        
        # 獲取 Collection 詳情
        details=$(curl -s -H "api-key: $QDRANT_API_KEY" "$QDRANT_HOST/collections/$name" 2>/dev/null)
        
        vectors_count=$(echo "$details" | jq -r '.result.indexed_vectors_count // 0' 2>/dev/null || echo "0")
        points_count=$(echo "$details" | jq -r '.result.points_count // 0' 2>/dev/null || echo "0")
        disk_size=$(echo "$details" | jq -r '.result.disk_size_bytes // 0' 2>/dev/null || echo "0")
        status=$(echo "$details" | jq -r '.result.status // "unknown"' 2>/dev/null || echo "unknown")
        
        # 格式化大小
        if [ "$disk_size" -gt 1073741824 ]; then
            size_str="$((disk_size / 1073741824))GB"
        elif [ "$disk_size" -gt 1048576 ]; then
            size_str="$((disk_size / 1048576))MB"
        elif [ "$disk_size" -gt 1024 ]; then
            size_str="$((disk_size / 1024))KB"
        else
            size_str="${disk_size}B"
        fi
        
        echo "  - $name"
        echo "    狀態: $status"
        echo "    Vectors: $vectors_count"
        echo "    Points: $points_count"
        echo "    大小: $size_str"
        
        # 記錄到資料庫
        record_collection "$name" "$vectors_count" "$points_count" "$disk_size" "$status"
        record_metric "$name" "vectors_count" "$vectors_count"
        record_metric "$name" "points_count" "$points_count"
        record_metric "$name" "disk_size" "$disk_size"
    done
else
    echo "無法獲取 Collection 列表"
    log "Failed to get collections: HTTP $http_code"
fi

echo ""
echo "========================================"
log "Qdrant check completed"
