#!/bin/bash
# Gateway Type 3 Status Script
# Check if gateway is running and report status
# Handles both service mode and standalone mode
#
# Output: RESULT:running=true|false,port=PORT,pid=PID,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"
LOG_FILE="${INSTALL_DIR}/logs/gateway.log"
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 Status ==="
log "Install directory: $INSTALL_DIR"
log "Port: $GATEWAY_PORT"

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

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

    log "Service status: $service_status"
    log "Service enabled: $service_enabled"
else
    log "Mode: Standalone"
fi

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

if [ -n "$existing_pid" ]; then
    mode_str="standalone"
    [ "$service_mode" = true ] && mode_str="service"

    log "Status: RUNNING" "SUCCESS"
    log "PID: $existing_pid"
    log "Port: $GATEWAY_PORT"

    # Check health endpoint
    HOST_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "localhost")
    [ -z "$HOST_IP" ] && HOST_IP="localhost"

    if curl -s "http://$HOST_IP:$GATEWAY_PORT/health" > /dev/null 2>&1; then
        log "Health: OK" "SUCCESS"
    else
        log "Health: Port open but API not responding" "WARN"
    fi

    # Show PID file status
    if [ -f "$PID_FILE" ]; then
        saved_pid=$(cat "$PID_FILE")
        if [ "$existing_pid" = "$saved_pid" ]; then
            log "PID file: Match ($PID_FILE)"
        else
            log "PID file: Mismatch (saved: $saved_pid, actual: $existing_pid)" "WARN"
        fi
    else
        log "PID file: Not found" "WARN"
    fi

    # Show log file info
    if [ -f "$LOG_FILE" ]; then
        log_size=$(du -h "$LOG_FILE" 2>/dev/null | cut -f1 || echo "unknown")
        log "Log file: $LOG_FILE ($log_size)"
    fi

    # Show service-specific info
    if [ "$service_mode" = true ]; then
        log ""
        log "Service commands:"
        log "  sudo systemctl status $SERVICE_NAME"
        log "  sudo journalctl -u $SERVICE_NAME -f"
    fi

    echo "RESULT:running=true,port=$GATEWAY_PORT,pid=$existing_pid,mode=$mode_str"
    exit 0
else
    mode_str="standalone"
    [ "$service_mode" = true ] && mode_str="service"

    log "Status: NOT RUNNING" "WARN"
    log "Port: $GATEWAY_PORT (not in use)"

    # Check for stale PID file
    if [ -f "$PID_FILE" ]; then
        log "PID file exists but process not running (stale)" "WARN"
    fi

    # Service-specific info
    if [ "$service_mode" = true ]; then
        service_status=$(systemctl is-active "$SERVICE_NAME" 2>/dev/null || echo "inactive")
        if [ "$service_status" = "failed" ]; then
            log "Service is in failed state" "ERROR"
            log "Check logs: sudo journalctl -u $SERVICE_NAME -n 50"
        fi
    fi

    echo "RESULT:running=false,port=$GATEWAY_PORT,pid=,mode=$mode_str"
    exit 0
fi
