#!/bin/bash

#===============================================================================
# Momentry Node.js 監控腳本
# 路徑: /Users/accusys/momentry_core_0.1/monitor/service/node_monitor.sh
# 
# 監控重點:
#   - n8n 使用的 Node.js 版本鎖定 (22.x)
#   - 進程數量與狀態
#   - 資源使用情況
#
# 使用方式:
#   ./node_monitor.sh status    # 顯示監控狀態
#   ./node_monitor.sh baseline # 建立版本基線
#   ./node_monitor.sh check    # 檢查版本變化
#===============================================================================

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/node_check.log"

# 顏色定義
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 鎖定的 Node.js 版本
LOCKED_NODE_VERSION="22"
LOCKED_NODE_MINOR="22"

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

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

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

log_warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] ⚠️  $1${NC}" | tee -a "$LOG_FILE"
}

#===============================================================================
# 記錄到資料庫
#===============================================================================
record_node_baseline() {
    local runtime_name=$1
    local current_version=$2
    local process_path=$3
    local pid=$4
    
    local required_version="${LOCKED_NODE_VERSION}.x"
    local is_compliant="false"
    if [[ "$current_version" == "${LOCKED_NODE_VERSION}".* ]]; then
        is_compliant="true"
    fi
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO node_version_baseline (runtime_name, required_version, current_version, process_name, process_path, is_compliant, locked_path, checked_at)
VALUES ('$runtime_name', '$required_version', '$current_version', 'node', '$process_path', $is_compliant, '$process_path', NOW())
ON CONFLICT DO NOTHING;
EOF
}

record_node_history() {
    local process_name=$1
    local old_version=$2
    local new_version=$3
    local old_path=$4
    local new_path=$5
    
    # node_version_history table does not exist - skip recording
    true
}

record_monitor_service() {
    local service=$1
    local status=$2
    local version=$3
    local error_msg=$4
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO monitor_services (service_name, service_type, status, response_time_ms, error_message, checked_at)
VALUES ('$service', 'node', '$status', 0, '$version - $error_msg', NOW());
EOF
}

#===============================================================================
# 發現 Node.js 進程
#===============================================================================
discover_node_processes() {
    log "發現 Node.js 進程..."
    
    echo ""
    echo "========================================"
    echo "Node.js 監控狀態"
    echo "時間: $(date)"
    echo "========================================"
    echo ""
    
    # 獲取所有 node 進程
    local node_pids=$(pgrep -f "node" 2>/dev/null)
    
    if [ -z "$node_pids" ]; then
        echo -e "${RED}沒有運行中的 Node.js 進程${NC}"
        record_monitor_service "node" "down" "N/A" "No processes"
        return 1
    fi
    
    echo "鎖定版本: Node.js ${LOCKED_NODE_VERSION}.x (n8n 專用)"
    echo ""
    echo "----------------------------------------"
    echo "發現的 Node.js 進程:"
    echo "----------------------------------------"
    
    local total_processes=0
    local n8n_processes=0
    local version_issues=0
    
    for pid in $node_pids; do
        # 獲取進程命令
        local cmd=$(ps -o args= -p $pid 2>/dev/null | head -1)
        
        # 獲取 Node.js 版本
        local node_path=$(lsof -p $pid 2>/dev/null | grep "txt" | grep "node" | head -1 | awk '{print $NF}' | grep -v "dylib")
        
        if [ -n "$node_path" ] && [ -f "$node_path" ]; then
            local node_version=$($node_path --version 2>/dev/null | sed 's/v//')
            local node_major=$(echo "$node_version" | cut -d. -f1)
            local node_minor=$(echo "$node_version" | cut -d. -f2)
        else
            local node_version="unknown"
            local node_major="unknown"
        fi
        
        # 內存使用
        local mem=$(ps -o rss= -p $pid 2>/dev/null | awk '{print int($1/1024)}')
        
        # CPU 使用
        local cpu=$(ps -o %cpu= -p $pid 2>/dev/null | awk '{print int($1)}')
        
        # 運行時間
        local time=$(ps -o etime= -p $pid 2>/dev/null | tr -d ' ')
        
        # 識別服務類型
        local service_type="other"
        if echo "$cmd" | grep -q "n8n"; then
            service_type="n8n"
            n8n_processes=$((n8n_processes + 1))
        elif echo "$cmd" | grep -q "worker"; then
            service_type="n8n-worker"
            n8n_processes=$((n8n_processes + 1))
        fi
        
        # 版本檢查
        local version_status="✅"
        if [ "$service_type" = "n8n" ] || [ "$service_type" = "n8n-worker" ]; then
            if [ "$node_major" != "$LOCKED_NODE_VERSION" ]; then
                version_status="❌ 版本錯誤!"
                version_issues=$((version_issues + 1))
                log_error "n8n 使用 Node.js $node_version (應為 ${LOCKED_NODE_VERSION}.x)"
            fi
        fi
        
        echo "  PID: $pid"
        echo "    命令: ${cmd:0:60}..."
        echo "    Node.js: $node_version $version_status"
        echo "    路徑: $node_path"
        echo "    內存: ${mem}MB | CPU: ${cpu}% | 運行: $time"
        echo "    類型: $service_type"
        echo ""
        
        total_processes=$((total_processes + 1))
        
        # 記錄基線
        record_node_baseline "$service_type" "$node_version" "$node_path" "$pid"
    done
    
    echo "----------------------------------------"
    echo "總結:"
    echo "  總進程數: $total_processes"
    echo "  n8n 相關: $n8n_processes"
    echo "  版本問題: $version_issues"
    echo "========================================"
    
    # 記錄到資料庫
    if [ $version_issues -gt 0 ]; then
        record_monitor_service "node" "degraded" "${LOCKED_NODE_VERSION}.x" "$version_issues version issues"
        return 1
    else
        record_monitor_service "node" "up" "${LOCKED_NODE_VERSION}.x" "OK"
        return 0
    fi
}

#===============================================================================
# 版本基線檢查
#===============================================================================
check_baseline() {
    log "檢查 Node.js 版本基線..."
    
    # 檢查 n8n 進程
    local n8n_pid=$(pgrep -f "n8n start" | head -1)
    
    if [ -z "$n8n_pid" ]; then
        log_error "n8n 進程未運行"
        return 1
    fi
    
    # 獲取 n8n 使用的 Node.js 版本
    local node_path=$(lsof -p $n8n_pid 2>/dev/null | grep "txt" | grep "node" | head -1 | awk '{print $NF}' | grep -v "dylib")
    
    if [ -n "$node_path" ] && [ -f "$node_path" ]; then
        local node_version=$($node_path --version 2>/dev/null | sed 's/v//')
        local node_major=$(echo "$node_version" | cut -d. -f1)
        
        echo "n8n 當前 Node.js 版本: $node_version"
        
        if [ "$node_major" = "$LOCKED_NODE_VERSION" ]; then
            log_success "版本正確: Node.js $node_version"
            return 0
        else
            log_error "版本錯誤: Node.js $node_version (應為 ${LOCKED_NODE_VERSION}.x)"
            return 1
        fi
    else
        log_error "無法確定 Node.js 版本"
        return 1
    fi
}

#===============================================================================
# 顯示狀態
#===============================================================================
show_status() {
    discover_node_processes
}

#===============================================================================
# 主程序
#===============================================================================
command=${1:-status}

case $command in
    status|check)
        show_status
        ;;
    baseline)
        check_baseline
        ;;
    *)
        echo "用法: $0 {status|baseline}"
        echo ""
        echo "  status   - 顯示 Node.js 監控狀態"
        echo "  baseline - 檢查版本基線"
        exit 1
        ;;
esac
