#!/bin/bash
# Installation Script for LangMart Gateway Type 3
# Run this script ON the target server to install the gateway
#
# Usage (from npm/unpkg - recommended):
#   curl -fsSL https://unpkg.com/langmart-gateway-type3/scripts/install.sh | bash -s -- [OPTIONS]
#
# Usage (from npm/jsdelivr):
#   curl -fsSL https://cdn.jsdelivr.net/npm/langmart-gateway-type3/scripts/install.sh | bash -s -- [OPTIONS]
#
# Or download and run:
#   bash install.sh [OPTIONS]
#
# Options:
#   --platform-url URL      Platform WebSocket URL (default: ws://localhost:8081)
#   --api-key KEY           Gateway API key for authentication
#   --port PORT             Gateway port (default: 8083)
#   --install-dir DIR       Installation directory (default: /opt/langmart-gateway)
#   --capabilities CAPS     Gateway capabilities: session,llm or llm (default: llm)
#   --full                  Enable full capabilities (Automation + LLM routing)
#   --service               Install as systemd service
#   --help                  Show this help message

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Default configuration
INSTALL_DIR="/opt/langmart-gateway"
GATEWAY_PORT="8083"
PLATFORM_URL="ws://localhost:8081"
GATEWAY_API_KEY=""
GATEWAY_CAPABILITIES=""
INSTALL_SERVICE=false
GITHUB_TOKEN=""

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --platform-url)
            PLATFORM_URL="$2"
            shift 2
            ;;
        --api-key)
            GATEWAY_API_KEY="$2"
            shift 2
            ;;
        --port)
            GATEWAY_PORT="$2"
            shift 2
            ;;
        --install-dir)
            INSTALL_DIR="$2"
            shift 2
            ;;
        --service)
            INSTALL_SERVICE=true
            shift
            ;;
        --capabilities)
            GATEWAY_CAPABILITIES="$2"
            shift 2
            ;;
        --full)
            GATEWAY_CAPABILITIES="session,llm"
            shift
            ;;
        --github-token)
            GITHUB_TOKEN="$2"
            shift 2
            ;;
        --help)
            echo "LangMart Gateway Type 3 - Remote Installation Script"
            echo ""
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --platform-url URL      Platform WebSocket URL (default: ws://localhost:8081)"
            echo "  --api-key KEY           Gateway API key for authentication"
            echo "  --port PORT             Gateway port (default: 8083)"
            echo "  --install-dir DIR       Installation directory (default: /opt/langmart-gateway)"
            echo "  --service               Install as systemd service"
            echo "  --capabilities CAPS     Gateway capabilities: session,llm or llm (default: llm only)"
            echo "  --full                  Enable full capabilities (session + llm) - Automation mode"
            echo "  --github-token TOKEN    GitHub token for npm package access"
            echo "  --help                  Show this help message"
            echo ""
            echo "Example:"
            echo "  $0 --platform-url ws://10.0.1.117:8081 --api-key sk-test-key --full --service"
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            exit 1
            ;;
    esac
done

echo -e "${BLUE}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     LangMart Gateway Type 3 - Remote Installation         ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${YELLOW}Warning: Not running as root. You may need sudo for some operations.${NC}"
fi

# Check Node.js installation
echo -e "${CYAN}[1/6] Checking Node.js installation...${NC}"
if ! command -v node &> /dev/null; then
    echo -e "${YELLOW}Node.js not found. Installing Node.js 20.x...${NC}"

    # Detect OS
    if [ -f /etc/debian_version ]; then
        # Debian/Ubuntu
        curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
        sudo apt-get install -y nodejs
    elif [ -f /etc/redhat-release ]; then
        # RHEL/CentOS/Fedora
        curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
        sudo yum install -y nodejs
    elif [ "$(uname)" == "Darwin" ]; then
        # macOS
        if command -v brew &> /dev/null; then
            brew install node@20
        else
            echo -e "${RED}Please install Homebrew first: https://brew.sh${NC}"
            exit 1
        fi
    else
        echo -e "${RED}Unsupported OS. Please install Node.js 18+ manually.${NC}"
        exit 1
    fi
fi

NODE_VERSION=$(node -v)
echo -e "${GREEN}✓ Node.js ${NODE_VERSION} installed${NC}"

# Check npm
if ! command -v npm &> /dev/null; then
    echo -e "${RED}npm not found. Please install npm.${NC}"
    exit 1
fi

NPM_VERSION=$(npm -v)
echo -e "${GREEN}✓ npm ${NPM_VERSION} installed${NC}"

# Create installation directory
echo -e "${CYAN}[2/6] Creating installation directory...${NC}"
sudo mkdir -p "$INSTALL_DIR"
sudo chown -R $(whoami):$(whoami) "$INSTALL_DIR"
cd "$INSTALL_DIR"
echo -e "${GREEN}✓ Directory created: ${INSTALL_DIR}${NC}"

# Configure npm for GitHub Packages
echo -e "${CYAN}[3/6] Configuring npm registry...${NC}"
if [ -n "$GITHUB_TOKEN" ]; then
    echo "@langmart:registry=https://npm.pkg.github.com" > .npmrc
    echo "//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}" >> .npmrc
    echo -e "${GREEN}✓ GitHub Packages configured${NC}"
else
    echo -e "${YELLOW}No GitHub token provided. Using public npm registry fallback...${NC}"
    # For public packages or when cloning directly
fi

# Initialize package.json if not exists
if [ ! -f package.json ]; then
    echo '{"name": "langmart-gateway-instance", "version": "1.0.0", "private": true}' > package.json
fi

# Install the gateway package
echo -e "${CYAN}[4/6] Installing langmart-gateway-type3...${NC}"
# Install from npm (no token needed for public packages)
npm install langmart-gateway-type3@latest
echo -e "${GREEN}✓ Gateway package installed${NC}"

# Create environment file
echo -e "${CYAN}[5/6] Creating environment configuration...${NC}"

# Generate vault password
VAULT_PWD=$(openssl rand -base64 32)

cat > .env << EOF
# LangMart Gateway Type 3 Configuration
# Generated by install-remote.sh on $(date)

# Gateway identification
INSTANCE_ID=gw3-$(hostname)-$(date +%s | tail -c 5)
GATEWAY_PORT=${GATEWAY_PORT}

# Platform connection
PLATFORM_URL=${PLATFORM_URL}

# Gateway authentication
GATEWAY_API_KEY=${GATEWAY_API_KEY}

# Gateway capabilities (session,llm = full Automation mode, llm = LLM routing only)
GATEWAY_CAPABILITIES=${GATEWAY_CAPABILITIES:-llm}

# Local vault configuration
VAULT_PATH=.vault/credentials.enc
VAULT_PASSWORD=${VAULT_PWD}

# Environment
NODE_ENV=production
EOF

echo -e "${GREEN}✓ Environment file created${NC}"

# Create start/stop scripts
cat > start.sh << 'STARTEOF'
#!/bin/bash
cd "$(dirname "$0")"

# Export all variables from .env file
if [ -f .env ]; then
    set -a
    source .env
    set +a
fi

if [ -d node_modules/langmart-gateway-type3 ]; then
    # Installed via npm
    node node_modules/langmart-gateway-type3/dist/index-server.js
else
    # Direct installation
    node dist/index-server.js
fi
STARTEOF
chmod +x start.sh

cat > stop.sh << 'STOPEOF'
#!/bin/bash
PORT=${GATEWAY_PORT:-8083}
PID=$(lsof -ti:$PORT)
if [ -n "$PID" ]; then
    kill $PID
    echo "Gateway stopped (PID: $PID)"
else
    echo "Gateway not running"
fi
STOPEOF
chmod +x stop.sh

# Install as systemd service if requested
if [ "$INSTALL_SERVICE" = true ]; then
    echo -e "${CYAN}[6/6] Installing systemd service...${NC}"

    sudo tee /etc/systemd/system/langmart-gateway.service > /dev/null << EOF
[Unit]
Description=LangMart Gateway Type 3
After=network.target

[Service]
Type=simple
User=$(whoami)
WorkingDirectory=${INSTALL_DIR}
EnvironmentFile=${INSTALL_DIR}/.env
ExecStart=/usr/bin/node ${INSTALL_DIR}/start.sh
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl enable langmart-gateway
    echo -e "${GREEN}✓ Systemd service installed${NC}"
    echo -e "${CYAN}  Start:   sudo systemctl start langmart-gateway${NC}"
    echo -e "${CYAN}  Stop:    sudo systemctl stop langmart-gateway${NC}"
    echo -e "${CYAN}  Status:  sudo systemctl status langmart-gateway${NC}"
    echo -e "${CYAN}  Logs:    sudo journalctl -u langmart-gateway -f${NC}"
else
    echo -e "${CYAN}[6/6] Skipping systemd service installation...${NC}"
fi

echo ""
echo -e "${GREEN}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║           Installation Complete!                           ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${CYAN}Installation Directory: ${INSTALL_DIR}${NC}"
echo -e "${CYAN}Gateway Port: ${GATEWAY_PORT}${NC}"
echo -e "${CYAN}Platform URL: ${PLATFORM_URL}${NC}"
if [ -n "$GATEWAY_CAPABILITIES" ] && [ "$GATEWAY_CAPABILITIES" = "session,llm" ]; then
    echo -e "${CYAN}Mode: Full (Automation + LLM Routing)${NC}"
else
    echo -e "${CYAN}Mode: LLM Routing Only${NC}"
fi
echo ""
echo -e "${YELLOW}Before starting, configure your API key:${NC}"
echo -e "  ${CYAN}1. Edit ${INSTALL_DIR}/.env${NC}"
echo -e "  ${CYAN}2. Set GATEWAY_API_KEY=your-api-key${NC}"
echo ""
echo -e "${YELLOW}To start the gateway:${NC}"
if [ "$INSTALL_SERVICE" = true ]; then
    echo -e "  ${CYAN}sudo systemctl start langmart-gateway${NC}"
else
    echo -e "  ${CYAN}cd ${INSTALL_DIR} && ./start.sh${NC}"
fi
echo ""
echo -e "${YELLOW}To verify installation:${NC}"
echo -e "  ${CYAN}curl http://localhost:${GATEWAY_PORT}/health${NC}"
echo ""
