#!/bin/bash

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

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

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

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

# 記錄指標
record_metric() {
    local db_type="postgresql"
    local db_name=$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 ('$db_type', '$db_name', '$metric_name', '$value', NOW());
EOF
}

# 獲取資料庫列表
get_databases() {
    psql -U accusys -h localhost -t -A -c "SELECT datname FROM pg_database WHERE datistemplate = false;" 2>/dev/null
}

# 獲取表大小
get_table_sizes() {
    local db=$1
    psql -U accusys -h localhost -d "$db" -t -A -c "
        SELECT 
            schemaname,
            tablename,
            pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size,
            n_live_tup as rows
        FROM pg_stat_user_tables
        ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC
        LIMIT 10;
    " 2>/dev/null
}

# 獲取連線數
get_connections() {
    psql -U accusys -h localhost -t -A -c "
        SELECT state, count(*) 
        FROM pg_stat_activity 
        WHERE datname = current_database()
        GROUP BY state;
    " 2>/dev/null
}

# 獲取慢查詢
get_slow_queries() {
    psql -U accusys -h localhost -t -A -c "
        SELECT query, calls, mean_time 
        FROM pg_stat_statements 
        WHERE query NOT LIKE '%pg_stat_statements%'
        ORDER BY mean_time DESC 
        LIMIT 5;
    " 2>/dev/null
}

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

# 檢查 PostgreSQL 是否可用
if ! pg_isready -h localhost -p 5432 -U accusys > /dev/null 2>&1; then
    echo "PostgreSQL 不可用"
    log "PostgreSQL unavailable"
    exit 1
fi

# 記錄連線數
connections=$(get_connections)
echo "連線狀態:"
echo "$connections"
echo ""

# 記錄指標
record_metric "postgres" "connections" "'$connections'"

# 檢查各資料庫
echo "資料庫表:"
echo "----------------------------------------"

for db in $(get_databases); do
    echo ""
    echo "資料庫: $db"
    
    table_count=$(psql -U accusys -h localhost -d "$db" -t -A -c "SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public';" 2>/dev/null || echo "0")
    echo "  表數量: $table_count"
    
    record_metric "$db" "table_count" "$table_count"
    
    # 顯示大表
    echo "  大表:"
    get_table_sizes "$db" | while read -r schema table size rows; do
        [ -z "$table" ] && continue
        echo "    - $table: $size ($rows rows)"
    done
done

# 檢查慢查詢（如果 pg_stat_statements 可用）
echo ""
echo "慢查詢 (如有):"
slow_queries=$(get_slow_queries)
if [ -n "$slow_queries" ]; then
    echo "$slow_queries" | while read -r query calls time; do
        [ -z "$query" ] && continue
        echo "  - ${time}ms (調用 $calls 次)"
    done
else
    echo "  (pg_stat_statements 未啟用)"
fi

echo ""
echo "========================================"
log "PostgreSQL check completed"
