#!/bin/bash

#===============================================================================
# Momentry Python 監控腳本
# 路徑: /Users/accusys/momentry_core_0.1/monitor/service/python_monitor.sh
# 
# 監控重點:
#   - Momentry Python 腳本版本鎖定 (3.11.14)
#   - 進程數量與狀態
#   - 腳本執行狀態
#
# 使用方式:
#   ./python_monitor.sh status    # 顯示監控狀態
#   ./python_monitor.sh baseline  # 建立版本基線
#   ./python_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/python_check.log"

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

# 鎖定的 Python 版本
LOCKED_PYTHON_VERSION="3.11.14"
LOCKED_PYTHON_MAJOR="3"
LOCKED_PYTHON_MINOR="11"

# Momentry Python 腳本
MOMENTRY_SCRIPTS=(
    "/Users/accusys/momentry_core_0.1/scripts/asr_processor.py"
    "/Users/accusys/momentry_core_0.1/scripts/thumbnail_extractor.py"
)

#===============================================================================
# 記錄函數
#===============================================================================
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_python_baseline() {
    local runtime_name=$1
    local current_version=$2
    local interpreter_path=$3
    
    local required_version="${LOCKED_PYTHON_VERSION}"
    local is_compliant="false"
    if [[ "$current_version" == "${LOCKED_PYTHON_VERSION}" ]]; then
        is_compliant="true"
    fi
    
    psql -U accusys -h localhost -d momentry << EOF 2>/dev/null
INSERT INTO python_version_baseline (runtime_name, required_version, current_version, interpreter_path, is_compliant, checked_at)
VALUES ('$runtime_name', '$required_version', '$current_version', '$interpreter_path', $is_compliant, NOW())
ON CONFLICT DO NOTHING;
EOF
}

record_python_history() {
    local script_name=$1
    local old_version=$2
    local new_version=$3
    local old_path=$4
    local new_path=$5
    
    # python_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', 'python', '$status', 0, '$version - $error_msg', NOW());
EOF
}

#===============================================================================
# 發現 Python 進程
#===============================================================================
discover_python_processes() {
    log "發現 Python 進程..."
    
    echo ""
    echo "========================================"
    echo "Python 監控狀態"
    echo "時間: $(date)"
    echo "========================================"
    echo ""
    
    echo "鎖定版本: Python ${LOCKED_PYTHON_VERSION} (Momentry 專用)"
    echo ""
    
    # 檢查 Momentry 腳本
    echo "----------------------------------------"
    echo "Momentry Python 腳本:"
    echo "----------------------------------------"
    
    local script_issues=0
    
    for script in "${MOMENTRY_SCRIPTS[@]}"; do
        if [ -f "$script" ]; then
            # 獲取腳本使用的 Python
            local shebang=$(head -1 "$script")
            local python_path=""
            
            if [[ "$shebang" == *"/python3.11"* ]]; then
                python_path="/opt/homebrew/bin/python3.11"
            elif [[ "$shebang" == *"/python3"* ]]; then
                # 檢查系統 python3
                python_path=$(which python3 2>/dev/null)
            fi
            
            if [ -n "$python_path" ] && [ -f "$python_path" ]; then
                local python_version=$($python_path --version 2>&1 | sed 's/Python //')
                local python_major=$(echo "$python_version" | cut -d. -f1)
                local python_minor=$(echo "$python_version" | cut -d. -f2)
                
                # 檢查版本
                local version_status="✅"
                if [ "$python_major" = "$LOCKED_PYTHON_MAJOR" ] && [ "$python_minor" = "$LOCKED_PYTHON_MINOR" ]; then
                    log_success "$(basename $script): $python_version"
                else
                    version_status="❌ 版本錯誤!"
                    script_issues=$((script_issues + 1))
                    log_error "$(basename $script): $python_version (應為 ${LOCKED_PYTHON_VERSION})"
                fi
                
                echo "  $(basename $script)"
                echo "    路徑: $python_path"
                echo "    版本: $python_version $version_status"
                echo "    shebang: $shebang"
                echo ""
                
                # 記錄基線
                record_python_baseline "python_${LOCKED_PYTHON_VERSION}" "$python_version" "$python_path"
            else
                log_error "$(basename $script): 無法確定 Python 路徑"
                script_issues=$((script_issues + 1))
            fi
        else
            log_warn "$(basename $script): 文件不存在"
            script_issues=$((script_issues + 1))
        fi
    done
    
    # 檢查運行中的 Python 進程
    echo "----------------------------------------"
    echo "運行中的 Python 進程:"
    echo "----------------------------------------"
    
    local python_pids=$(pgrep -f "python" 2>/dev/null)
    local total_processes=0
    
    if [ -n "$python_pids" ]; then
        for pid in $python_pids; do
            # 獲取進程命令
            local cmd=$(ps -o args= -p $pid 2>/dev/null | head -1 | cut -c1-80)
            
            # 獲取 Python 路徑
            local python_path=$(lsof -p $pid 2>/dev/null | grep "txt" | grep "Python" | head -1 | awk '{print $NF}' | grep -v "dylib")
            
            if [ -n "$python_path" ] && [ -f "$python_path" ]; then
                local python_version=$($python_path --version 2>&1 | sed 's/Python //')
            else
                local python_version="unknown"
            fi
            
            # 內存使用
            local mem=$(ps -o rss= -p $pid 2>/dev/null | awk '{print int($1/1024)}')
            
            echo "  PID $pid: $cmd"
            echo "    Python: $python_version"
            echo "    內存: ${mem}MB"
            echo ""
            
            total_processes=$((total_processes + 1))
        done
    else
        echo "  (無運行中的 Python 進程)"
    fi
    
    echo "----------------------------------------"
    echo "總結:"
    echo "  總進程數: $total_processes"
    echo "  腳本問題: $script_issues"
    echo "========================================"
    
    # 記錄到資料庫
    if [ $script_issues -gt 0 ]; then
        record_monitor_service "python" "degraded" "${LOCKED_PYTHON_VERSION}" "$script_issues issues"
        return 1
    else
        record_monitor_service "python" "up" "${LOCKED_PYTHON_VERSION}" "OK"
        return 0
    fi
}

#===============================================================================
# 版本基線檢查
#===============================================================================
check_baseline() {
    log "檢查 Python 版本基線..."
    
    local script_issues=0
    
    for script in "${MOMENTRY_SCRIPTS[@]}"; do
        if [ -f "$script" ]; then
            local shebang=$(head -1 "$script")
            
            if [[ "$shebang" == *"/python3.11"* ]]; then
                log_success "$(basename $script): 使用正確版本"
            else
                log_error "$(basename $script): 未使用 python3.11"
                script_issues=$((script_issues + 1))
            fi
        fi
    done
    
    if [ $script_issues -gt 0 ]; then
        return 1
    else
        return 0
    fi
}

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

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

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