#!/bin/bash
# Gateway Type 3 Start Script
# Designed to work from installed location (via npm install) or development
#
# Features:
# - Detect service mode vs standalone mode
# - Load configuration from .env file
# - Pre-flight checks (port, required params)
# - Use isolated Node.js if available (for older systems)
# - Output machine-readable RESULT line for automation

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 with defaults
LOG_DIR="${INSTALL_DIR}/logs"
LOG_FILE="${LOG_DIR}/gateway.log"
PID_FILE="${INSTALL_DIR}/gateway.pid"
ENV_FILE="${INSTALL_DIR}/.env"
SERVICE_MODE_FILE="${INSTALL_DIR}/.service-mode"
SERVICE_NAME="langmart-gateway"

# Output tracking
running=false
port=""
pid=""
service_mode=false

# Log function that outputs to both console and can be parsed
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
}

# Detect Node.js binary (prefer isolated installation)
detect_node() {
    if [ -f "$INSTALL_DIR/node/bin/node" ]; then
        NODE_BIN="$INSTALL_DIR/node/bin/node"
        log "Using isolated Node.js: $($NODE_BIN --version)"
    else
        NODE_BIN="node"
        local version=$(node --version 2>/dev/null || echo "not found")
        log "Using system Node.js: $version"

        if [[ "$version" != "not found" ]]; then
            major_version=$(echo "$version" | sed 's/v//' | cut -d. -f1)
            if [ "$major_version" -lt 14 ]; then
                log "WARNING: Node.js $version may not support modern JavaScript syntax" "WARN"
            fi
        fi
    fi
}

# Load .env file
load_env() {
    if [ -f "$ENV_FILE" ]; then
        log "Loading environment from $ENV_FILE"
        set -a
        source "$ENV_FILE"
        set +a
        return 0
    else
        log ".env file not found at $ENV_FILE" "WARN"
        return 1
    fi
}

# Find the correct entry file
find_entry_file() {
    if [ -f "$INSTALL_DIR/node_modules/langmart-gateway-type3/dist/index-server.js" ]; then
        ENTRY_FILE="$INSTALL_DIR/node_modules/langmart-gateway-type3/dist/index-server.js"
    elif [ -f "$PROJECT_DIR/dist/index-server.js" ]; then
        ENTRY_FILE="$PROJECT_DIR/dist/index-server.js"
    else
        log "Entry file not found!" "ERROR"
        return 1
    fi
    log "Entry file: $ENTRY_FILE"
    return 0
}

# ============================================
# MAIN SCRIPT
# ============================================

log "=== Gateway Type 3 Start Script ==="
log "Install directory: $INSTALL_DIR"

# Load environment
load_env

# Set defaults
GATEWAY_PORT="${GATEWAY_PORT:-8083}"
GATEWAY_API_KEY="${GATEWAY_API_KEY:-}"
PLATFORM_URL="${PLATFORM_URL:-ws://localhost:8081}"
GATEWAY_ID="${GATEWAY_ID:-}"

# ============================================
# 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
        existing_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
        if [ -n "$existing_pid" ]; then
            log "Service already running (PID: $existing_pid)" "SUCCESS"
            echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$existing_pid,mode=service"
            exit 0
        fi
    fi

    log "Starting via systemctl..."
    if sudo systemctl start "$SERVICE_NAME" 2>/dev/null || systemctl start "$SERVICE_NAME" 2>/dev/null; then
        sleep 3
        existing_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
        if [ -n "$existing_pid" ]; then
            log "Service started successfully (PID: $existing_pid)" "SUCCESS"
            echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$existing_pid,mode=service"
            exit 0
        else
            log "Service start command succeeded but gateway not listening" "ERROR"
            echo "RESULT:running=false,port=,pid=,mode=service"
            exit 1
        fi
    else
        log "Failed to start service (may need sudo)" "ERROR"
        echo "RESULT:running=false,port=,pid=,mode=service"
        exit 1
    fi
fi

# ============================================
# STANDALONE MODE
# ============================================
log "Running in standalone mode"

# PRE-FLIGHT CHECK: Required parameters
log "Checking required parameters..."

missing_vars=""
[ -z "$GATEWAY_API_KEY" ] && missing_vars="$missing_vars GATEWAY_API_KEY"
[ -z "$PLATFORM_URL" ] && missing_vars="$missing_vars PLATFORM_URL"

if [ -n "$missing_vars" ]; then
    log "Missing required parameters:$missing_vars" "ERROR"
    echo "RESULT:running=false,port=,pid=,mode=standalone"
    exit 1
fi

log "GATEWAY_PORT: $GATEWAY_PORT"
log "PLATFORM_URL: $PLATFORM_URL"
log "GATEWAY_API_KEY: ${GATEWAY_API_KEY:0:8}..."

# PRE-FLIGHT CHECK: Already running
existing_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
if [ -n "$existing_pid" ]; then
    log "Gateway already running on port $GATEWAY_PORT (PID: $existing_pid)" "SUCCESS"
    echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$existing_pid,mode=standalone"
    exit 0
fi
log "Port $GATEWAY_PORT is available" "SUCCESS"

# PRE-FLIGHT CHECK: Node.js
detect_node

# PRE-FLIGHT CHECK: Entry file
find_entry_file || {
    echo "RESULT:running=false,port=,pid=,mode=standalone"
    exit 1
}

# ============================================
# START GATEWAY
# ============================================
log "=== Starting Gateway ==="

mkdir -p "$LOG_DIR"
> "$LOG_FILE"

export GATEWAY_PORT GATEWAY_API_KEY PLATFORM_URL GATEWAY_ID

log "Starting with: $NODE_BIN $ENTRY_FILE"

cd "$INSTALL_DIR"
nohup "$NODE_BIN" "$ENTRY_FILE" >> "$LOG_FILE" 2>&1 &
gateway_pid=$!
disown $gateway_pid

echo $gateway_pid > "$PID_FILE"

log "Process started with PID: $gateway_pid (daemonized)"
log "Logs: $LOG_FILE"

# VERIFY GATEWAY IS LISTENING
log "Waiting for gateway to start listening..."

max_wait=15
wait_interval=2
total_waited=0
listening=false

while [ $total_waited -lt $max_wait ]; do
    sleep $wait_interval
    total_waited=$((total_waited + wait_interval))

    check_pid=$(lsof -ti:$GATEWAY_PORT 2>/dev/null || true)
    if [ -n "$check_pid" ]; then
        listening=true
        pid="$check_pid"
        break
    fi
    log "Waiting... ($total_waited/$max_wait seconds)"
done

if [ "$listening" = true ]; then
    log "Gateway confirmed listening on port $GATEWAY_PORT (PID: $pid)" "SUCCESS"
    [ -f "$LOG_FILE" ] && tail -5 "$LOG_FILE" 2>/dev/null || true
    echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$pid,mode=standalone"
    exit 0
else
    log "Gateway failed to start listening" "ERROR"
    [ -f "$LOG_FILE" ] && cat "$LOG_FILE" 2>/dev/null || true
    echo "RESULT:running=false,port=,pid=,mode=standalone"
    exit 1
fi
