#!/bin/bash

# DQV/KTAC Agent Stop Script for Linux/MacOS
# This script stops the DQV/KTAC agent process gracefully

# Function to log messages with timestamp
log_message() {
    local message="$1"
    local level="${2:-INFO}"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] [$level] $message" | tee -a logs/agent/bootstrap-cli.log
}

# Function to show message
show_message() {
    local message="$1"
    local title="${2:-DQV/KTAC Agent}"
    
    log_message "$message" "INFO"
    echo "$message"
    return 0
}

# Main script execution
main() {
    # Get script directory
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    cd "$SCRIPT_DIR"
    
    # Create logs directory if it doesn't exist
    mkdir -p logs/agent
    
    log_message "Starting DQV/KTAC Agent stop process" "INFO"
    
    # Check if PID file exists
    if [ ! -f "agent.pid" ]; then
        log_message "No agent.pid file found. Agent may not be running." "WARN"
        show_message "No agent.pid file found. Agent may not be running." "DQV/KTAC Agent Stop"
        exit 0
    fi
    
    # Read PID from file
    local pid=$(cat agent.pid 2>/dev/null)
    
    if [ -z "$pid" ]; then
        log_message "PID file is empty or invalid" "WARN"
        rm -f agent.pid
        show_message "PID file is empty or invalid. Agent may not be running." "DQV/KTAC Agent Stop"
        exit 0
    fi
    
    # Check if process is running
    if ! kill -0 "$pid" 2>/dev/null; then
        log_message "Agent process (PID: $pid) is not running" "WARN"
        rm -f agent.pid
        show_message "Agent process (PID: $pid) is not running." "DQV/KTAC Agent Stop"
        exit 0
    fi
    
    log_message "Stopping DQV/KTAC Agent process (PID: $pid)" "INFO"
    
    # Try graceful shutdown first
    kill -15 "$pid" 2>/dev/null
    
    # Wait for graceful shutdown (up to 30 seconds)
    local count=0
    while [ $count -lt 30 ]; do
        if ! kill -0 "$pid" 2>/dev/null; then
            log_message "Agent process stopped gracefully" "INFO"
            rm -f agent.pid
            show_message "DQV/KTAC Agent has been stopped successfully." "DQV/KTAC Agent Stop"
            exit 0
        fi
        sleep 1
        count=$((count + 1))
    done
    
    # Force kill if graceful shutdown failed
    log_message "Graceful shutdown failed, force killing process (PID: $pid)" "WARN"
    kill -9 "$pid" 2>/dev/null
    
    # Wait a moment and check if process is gone
    sleep 2
    if ! kill -0 "$pid" 2>/dev/null; then
        log_message "Agent process force stopped" "INFO"
        rm -f agent.pid
        show_message "DQV/KTAC Agent has been force stopped." "DQV/KTAC Agent Stop"
        exit 0
    else
        log_message "ERROR: Failed to stop agent process (PID: $pid)" "ERROR"
        show_message "Failed to stop agent process (PID: $pid). You may need to stop it manually." "DQV/KTAC Agent Stop Error"
        exit 1
    fi
}

# Execute main function
main "$@"
