#!/bin/bash
# Gateway Type 3 Stop Script
# Gracefully stops the gateway with fallback to force kill
# Handles both service mode and standalone mode
#
# Output: RESULT:stopped=true|false,mode=service|standalone

set -e

# Get script directory and project directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# If running from node_modules, find the actual install dir
if [[ "$PROJECT_DIR" == *"node_modules"* ]]; then
    INSTALL_DIR="$(cd "$PROJECT_DIR/../.." && pwd)"
else
    INSTALL_DIR="$PROJECT_DIR"
fi

# Configuration
ENV_FILE="${INSTALL_DIR}/.env"
PID_FILE="${INSTALL_DIR}/gateway.pid"
SERVICE_MODE_FILE="${INSTALL_DIR}/.service-mode"
SERVICE_NAME="langmart-gateway"
service_mode=false

# Load .env for GATEWAY_PORT
if [ -f "$ENV_FILE" ]; then
    set -a
    source "$ENV_FILE"
    set +a
fi

GATEWAY_PORT="${GATEWAY_PORT:-8083}"

# Log function
log() {
    local level="${2:-INFO}"
    local timestamp=$(date +"%H:%M:%S")
    echo "[$level] $timestamp - $1"
}

# Check if running in service mode
check_service_mode() {
    if [ -f "$SERVICE_MODE_FILE" ]; then
        local mode=$(cat "$SERVICE_MODE_FILE" 2>/dev/null || echo "")
        if [ "$mode" = "systemd" ]; then
            if systemctl list-unit-files 2>/dev/null | grep -q "^${SERVICE_NAME}.service"; then
                service_mode=true
                return 0
            fi
        fi
    fi
    service_mode=false
    return 1
}

log "=== Gateway Type 3 Stop Script ==="
log "Install directory: $INSTALL_DIR"
log "Port: $GATEWAY_PORT"

# ============================================
# CHECK SERVICE MODE
# ============================================
check_service_mode
if [ "$service_mode" = true ]; then
    log "Service mode detected (systemd)"

    service_status=$(systemctl is-active "$SERVICE_NAME" 2>/dev/null || echo "inactive")

    if [ "$service_status" != "active" ]; then
        log "Service is not running" "SUCCESS"
        [ -f "$PID_FILE" ] && rm -f "$PID_FILE"
        echo "RESULT:stopped=true,mode=service"
        exit 0
    fi

    log "Stopping service via systemctl..."
    if sudo systemctl stop "$SERVICE_NAME" 2>/dev/null || systemctl stop "$SERVICE_NAME" 2>/dev/null; then
        sleep 2
        check_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
        if [ -z "$check_pid" ]; then
            log "Service stopped successfully" "SUCCESS"
            rm -f "$PID_FILE"
            echo "RESULT:stopped=true,mode=service"
            exit 0
        fi
    fi
    log "Service stop via systemctl failed, trying direct stop..." "WARN"
fi

# ============================================
# STANDALONE MODE / FALLBACK
# ============================================
[ "$service_mode" != true ] && log "Running in standalone mode"

# Check if running
existing_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)

if [ -z "$existing_pid" ]; then
    log "Gateway is not running on port $GATEWAY_PORT" "SUCCESS"
    [ -f "$PID_FILE" ] && rm -f "$PID_FILE"
    echo "RESULT:stopped=true,mode=standalone"
    exit 0
fi

log "Found gateway running on port $GATEWAY_PORT (PID: $existing_pid)"

# Get host IP for API call
HOST_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "localhost")
[ -z "$HOST_IP" ] && HOST_IP="localhost"

# Try graceful shutdown via API
log "Attempting graceful shutdown via API..."
if curl -s -X POST "http://$HOST_IP:$GATEWAY_PORT/shutdown" > /dev/null 2>&1; then
    log "Shutdown signal sent"
    sleep 2

    check_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
    if [ -z "$check_pid" ]; then
        log "Gateway stopped gracefully" "SUCCESS"
        rm -f "$PID_FILE"
        echo "RESULT:stopped=true,mode=standalone"
        exit 0
    fi
fi

# Fallback: Force kill
log "Graceful shutdown failed, forcing stop..." "WARN"
kill -9 $existing_pid 2>/dev/null || true
sleep 1

# Verify stopped
check_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
if [ -z "$check_pid" ]; then
    log "Gateway stopped (forced)" "SUCCESS"
    rm -f "$PID_FILE"
    echo "RESULT:stopped=true,mode=standalone"
    exit 0
else
    log "Failed to stop gateway" "ERROR"
    echo "RESULT:stopped=false,mode=standalone"
    exit 1
fi
