#!/bin/bash
# ============================================
# Trading Engine Setup Script
# Deploys the compiled binary + systemd service
# Required for: Perpetual Futures, Margin Trading, Real-time Price Feeds
# ============================================

set -e

echo "=========================================="
echo "  TRADING ENGINE SETUP (Binary + systemd)"
echo "  Required for: Futures, Margin, Forex   "
echo "=========================================="

# Configuration
INSTALL_DIR="/opt/trading-engine"
SERVICE_NAME="trading-engine"
BINARY_NAME="trading-engine-linux"
BINARY_URL="https://account.codono.com/binary/trading-engine-linux"

# Load credentials
if [ ! -f /opt/credentials.yml ]; then
    echo "ERROR: /opt/credentials.yml not found!"
    echo "Please run run1_ubuntu_lemp_setup.sh first."
    exit 1
fi

# Parse credentials (UPPERCASE keys)
DOMAIN=$(grep '^DOMAIN:' /opt/credentials.yml | awk '{print $2}')
DB_NAME=$(grep 'DB_NAME:' /opt/credentials.yml | awk '{print $2}')
MYSQL_ROOT_PASSWORD=$(grep 'MYSQL_NEW_ROOT_PASSWORD:' /opt/credentials.yml | awk '{print $2}')
REDIS_PASSWORD=$(grep 'REDIS_PASSWORD:' /opt/credentials.yml | awk '{print $2}')

if [ -z "$DOMAIN" ]; then
    echo "ERROR: Could not read DOMAIN from credentials.yml"
    exit 1
fi

echo "Domain: $DOMAIN"
echo "Database: $DB_NAME"

# Create installation directory
echo "Creating installation directory..."
mkdir -p ${INSTALL_DIR}
mkdir -p ${INSTALL_DIR}/logs

# Download binary (~50MB)
echo "Downloading trading engine binary from ${BINARY_URL}..."
wget --timeout=120 --tries=3 --user-agent="Mozilla/5.0 (X11; Linux x86_64) Codono-Setup/1.0" -O "${INSTALL_DIR}/${BINARY_NAME}" "${BINARY_URL}"
if [ $? -ne 0 ]; then
    echo "ERROR: Failed to download binary. Check the URL and network connection."
    rm -f "${INSTALL_DIR}/${BINARY_NAME}"
    exit 1
fi

# Verify download is not empty/truncated
FILE_SIZE=$(stat -c%s "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null || echo "0")
if [ "$FILE_SIZE" -lt 1000000 ]; then
    echo "ERROR: Downloaded file is too small (${FILE_SIZE} bytes). Expected ~50MB."
    echo "The download may have failed or returned an error page."
    rm -f "${INSTALL_DIR}/${BINARY_NAME}"
    exit 1
fi

echo "Binary downloaded successfully (${FILE_SIZE} bytes)."
chmod +x "${INSTALL_DIR}/${BINARY_NAME}"

# Create comprehensive .env configuration
echo "Creating .env configuration..."
cat > "${INSTALL_DIR}/.env" << EOF
# =============================================================================
# CODONO TRADING ENGINE - CONFIGURATION
# =============================================================================
# Generated by run8_trading_engine.sh
# Edit this file and restart: systemctl restart trading-engine
# =============================================================================

# =============================================================================
# GENERAL SETTINGS
# =============================================================================

# Environment mode: development, production, test
NODE_ENV=production

# Log level: debug, info, warn, error, silent
LOG_LEVEL=info

# Startup retry delay when database is unavailable (milliseconds)
# The engine will keep retrying until database becomes available
STARTUP_RETRY_DELAY_MS=10000

# =============================================================================
# REDIS CONFIGURATION
# =============================================================================
# Redis is used for:
# - Real-time price caching
# - WebSocket pub/sub messaging
# - Order queue management
# - Session data

REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=${REDIS_PASSWORD}
REDIS_DB=0

# Separate Redis DB for forex module (isolated from PHP cache clearing)
# This prevents cache:clear commands from wiping forex price data
# Must match REDIS_FOREX_DB in your PHP pure_config.php
REDIS_FOREX_DB=1

# =============================================================================
# MYSQL DATABASE CONFIGURATION
# =============================================================================
# MySQL is the primary database for:
# - Order storage and history
# - Position management
# - User balances
# - Trade history
# - Symbol configuration

MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE=${DB_NAME}

# Database connection pool settings
# Max connections in the pool
MYSQL_CONNECTION_LIMIT=10

# Connection timeout (milliseconds) - how long to wait for a connection
MYSQL_CONNECT_TIMEOUT=10000

# Query timeout (milliseconds) - max time for a single query
MYSQL_QUERY_TIMEOUT=30000

# Retry settings for failed queries
MYSQL_MAX_RETRIES=3
MYSQL_RETRY_DELAY_MS=100

# =============================================================================
# QUESTDB CONFIGURATION (Time-Series Database)
# =============================================================================
# QuestDB is optional but recommended for:
# - High-frequency forex tick storage
# - Mark price history
# - Performance analytics
# If disabled, falls back to MySQL for tick storage

QUESTDB_ENABLED=true
QUESTDB_HOST=127.0.0.1
QUESTDB_PORT=9000

# =============================================================================
# WEBSOCKET SERVER
# =============================================================================
# WebSocket server for real-time updates to frontend
# Broadcasts: prices, order book, trades, positions, liquidations

WS_PORT=8081

# Maximum pending messages in retry queue per client
WS_RETRY_QUEUE_MAX_SIZE=500

# =============================================================================
# FUTURES MATCHING ENGINE
# =============================================================================
# Core trading engine settings for futures/perpetual contracts

# Order matching loop interval (milliseconds)
# Lower = faster matching but higher CPU usage
# Recommended: 10ms for production, 100ms for testing
MATCHING_INTERVAL_MS=10

# External price fetch interval for mark/index prices (milliseconds)
PRICE_UPDATE_INTERVAL_MS=1000

# External price request timeout (milliseconds)
PRICE_REQUEST_TIMEOUT_MS=5000

# Order book depth update interval (milliseconds)
# How often to fetch order book from external exchanges
DEPTH_UPDATE_INTERVAL_MS=500

# =============================================================================
# LIQUIDATION ENGINE
# =============================================================================
# Monitors positions and triggers liquidations when margin is insufficient

# How often to check positions for liquidation (milliseconds)
LIQUIDATION_CHECK_INTERVAL_MS=5000

# =============================================================================
# ADL ENGINE (Auto-Deleveraging)
# =============================================================================
# Ranks positions for auto-deleveraging when insurance fund is insufficient

# How often to update ADL rankings (milliseconds)
ADL_RANKING_INTERVAL_MS=5000

# =============================================================================
# FOREX MODULE CONFIGURATION
# =============================================================================
# Real-time forex price fetching and tick storage

# Price polling interval (milliseconds)
# How often to fetch prices from REST providers
FOREX_POLL_INTERVAL_MS=2000

# Request jitter to avoid rate limiting (milliseconds)
# Adds random delay between MIN and MAX to each request
FOREX_MIN_JITTER_MS=100
FOREX_MAX_JITTER_MS=1500

# =============================================================================
# FOREX TICK STORAGE
# =============================================================================
# Storage settings for forex price history

# Enable tick storage (set to false to disable DB writes)
FOREX_TICK_STORE_ENABLED=true

# Storage backend: 'questdb' (recommended) or 'mysql'
FOREX_TICK_STORE=questdb

# Batch flush interval (milliseconds)
# Ticks are buffered and written in batches for performance
FOREX_TICK_FLUSH_INTERVAL_MS=1000

# Maximum ticks to buffer before forcing flush
FOREX_TICK_BUFFER_SIZE=100

# Tick data retention in days (0 = keep forever)
# Old partitions/rows are automatically cleaned up daily
FOREX_TICK_RETENTION_DAYS=30

# DB flush interval for price service (milliseconds)
FOREX_DB_FLUSH_INTERVAL_MS=5000

# Maximum retries for failed Redis publishes
FOREX_MAX_PUBLISH_RETRIES=3

# =============================================================================
# FOREX PRICE PROVIDERS
# =============================================================================
# Enable/disable individual price providers
# At least one provider must be enabled to get forex prices

# -----------------------------------------------------------------------------
# FREE PROVIDERS (No API key required)
# -----------------------------------------------------------------------------

# TradingView Scanner - Primary free provider (RECOMMENDED)
# Provides: Major pairs, crosses, metals
# Rate limit: Fair use policy
FOREX_PROVIDER_TRADINGVIEW_ENABLED=true

# FreeForexAPI - Backup free provider
# Provides: Major pairs only
# Rate limit: 1000 requests/month
FOREX_PROVIDER_FREEFOREXAPI_ENABLED=false

# ExchangeRate.host - Another backup
# Provides: Major pairs, some crosses
# Rate limit: 1000 requests/month
FOREX_PROVIDER_EXCHANGERATEHOST_ENABLED=false

# -----------------------------------------------------------------------------
# MQL5 WEBSOCKET (MetaTrader Integration)
# -----------------------------------------------------------------------------
# Real-time streaming from MetaTrader broker
# Benefits: True real-time ticks, broker-specific spreads
# Requirements: Valid MT4/MT5 demo or live account

FOREX_PROVIDER_MQL5_ENABLED=false

# MQL5 Account Credentials
# Create a demo account at your broker or MetaQuotes-Demo
MQL5_LOGIN=
MQL5_PASSWORD=
MQL5_SERVER=MetaQuotes-Demo

# MQL5 Health Monitoring Settings
# Stale threshold: reconnect if no prices for this long (milliseconds)
MQL5_STALE_THRESHOLD_MS=30000

# Health check interval (milliseconds)
MQL5_HEALTH_CHECK_INTERVAL_MS=10000

# Session refresh interval (milliseconds)
# Reconnects periodically to prevent stale sessions
MQL5_SESSION_REFRESH_MS=3600000

# Ping interval to keep connection alive (milliseconds)
MQL5_PING_INTERVAL_MS=30000

# Reconnect cooldown after disconnect (milliseconds)
MQL5_RECONNECT_DELAY_MS=30000

# -----------------------------------------------------------------------------
# PAID/FREEMIUM PROVIDERS (Require API keys)
# -----------------------------------------------------------------------------
# These providers offer higher rate limits and more features
# but require API keys (some have free tiers)

# OANDA v20 API (Professional grade)
# Features: Streaming, historical data, low latency
# Pricing: Free demo, paid for live
FOREX_PROVIDER_OANDA_ENABLED=false
OANDA_API_TOKEN=
OANDA_ACCOUNT_ID=

# TwelveData API
# Features: Good coverage, reasonable pricing
# Pricing: Free tier available (800 requests/day)
FOREX_PROVIDER_TWELVEDATA_ENABLED=false
TWELVEDATA_API_KEY=

# FCS API (Forex Currency Symbols)
# Features: Wide coverage, real-time
# Pricing: Paid plans starting at \$9/month
FOREX_PROVIDER_FCSAPI_ENABLED=false
FCSAPI_API_KEY=

# Finnhub API
# Features: Stocks + Forex, good documentation
# Pricing: Free tier (60 calls/minute)
FOREX_PROVIDER_FINNHUB_ENABLED=false
FINNHUB_API_KEY=

# Alpha Vantage API
# Features: Large historical data
# Pricing: Free tier (5 calls/minute)
FOREX_PROVIDER_ALPHAVANTAGE_ENABLED=false
ALPHAVANTAGE_API_KEY=

# Polygon.io API
# Features: High quality, low latency
# Pricing: Paid plans, forex requires higher tier
FOREX_PROVIDER_POLYGON_ENABLED=false
POLYGON_API_KEY=

# =============================================================================
# PROXY CONFIGURATION (Optional)
# =============================================================================
# Use a proxy to protect your server IP from rate limiting
# Recommended for high-volume price fetching

PROXY_ENABLED=false

# Proxy URL (e.g., http://user:pass@proxy.example.com:8080)
PROXY_URL=

# Proxy type: http, https, socks4, socks5
PROXY_TYPE=http

# Enable proxy rotation (requires PROXY_LIST)
PROXY_ROTATION=false

# Comma-separated list of proxy URLs for rotation
PROXY_LIST=

# =============================================================================
# LOGGING CONFIGURATION
# =============================================================================
# Fine-tune logging behavior

# Error throttle: suppress repeated errors for this duration (milliseconds)
# Prevents log spam when services are down
LOG_ERROR_THROTTLE_MS=30000

# Maximum log buffer size for streaming/dashboard
LOG_BUFFER_SIZE=1000

# =============================================================================
# HTTP API / DASHBOARD
# =============================================================================
# Built-in HTTP API for monitoring and control

# Dashboard port (auto-increments if port in use)
DASHBOARD_PORT=8082

# Dashboard Authentication (HTTP Basic Auth)
# Enable to require username/password for dashboard access
# IMPORTANT: Set a strong password in production!
DASHBOARD_AUTH_ENABLED=false
DASHBOARD_USERNAME=admin
DASHBOARD_PASSWORD=

# =============================================================================
# PROVIDER COOLDOWN SETTINGS (Advanced)
# =============================================================================
# How long to wait before retrying a failed provider (milliseconds)

PROVIDER_COOLDOWN_TRADINGVIEW_MS=60000
PROVIDER_COOLDOWN_FREEFOREXAPI_MS=60000
PROVIDER_COOLDOWN_EXCHANGERATEHOST_MS=60000
PROVIDER_COOLDOWN_MQL5_MS=30000
PROVIDER_COOLDOWN_OANDA_MS=120000
PROVIDER_COOLDOWN_TWELVEDATA_MS=60000
PROVIDER_COOLDOWN_FCSAPI_MS=60000
PROVIDER_COOLDOWN_FINNHUB_MS=60000
PROVIDER_COOLDOWN_ALPHAVANTAGE_MS=60000
PROVIDER_COOLDOWN_POLYGON_MS=120000

# Maximum consecutive errors before cooldown
PROVIDER_MAX_ERRORS=5
EOF

# Install systemd service
echo "Installing systemd service..."
cat > /etc/systemd/system/trading-engine.service << 'SERVICEEOF'
[Unit]
Description=Codono Trading Engine
After=network.target mysql.service redis.service
Wants=mysql.service redis.service

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/opt/trading-engine
ExecStart=/opt/trading-engine/trading-engine-linux
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=trading-engine

# Environment
Environment="NODE_ENV=production"
EnvironmentFile=-/opt/trading-engine/.env

# Security hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/trading-engine/logs

# Resource limits
LimitNOFILE=65535
LimitNPROC=4096

[Install]
WantedBy=multi-user.target
SERVICEEOF

# Set ownership
echo "Setting ownership..."
chown -R www-data:www-data "${INSTALL_DIR}"

# Reload systemd
systemctl daemon-reload

# Stop existing instance if running
if systemctl is-active --quiet ${SERVICE_NAME} 2>/dev/null; then
    echo "Stopping existing trading-engine service..."
    systemctl stop ${SERVICE_NAME}
fi

# Enable and start service
echo "Enabling and starting trading-engine service..."
systemctl enable ${SERVICE_NAME}
systemctl start ${SERVICE_NAME}

# Wait for startup
sleep 3

# Check status
if systemctl is-active --quiet ${SERVICE_NAME}; then
    echo ""
    echo "=========================================="
    echo "  Trading Engine Setup Complete!          "
    echo "=========================================="
    echo ""
    echo "Installation:"
    echo "  Binary:  ${INSTALL_DIR}/${BINARY_NAME}"
    echo "  Config:  ${INSTALL_DIR}/.env"
    echo "  Logs:    ${INSTALL_DIR}/logs/"
    echo "  Service: /etc/systemd/system/trading-engine.service"
    echo ""
    echo "Service Details:"
    echo "  - WebSocket Port: 8081"
    echo "  - Dashboard Port: 8082"
    echo ""
    echo "Useful Commands:"
    echo "  systemctl status trading-engine   - Check status"
    echo "  systemctl restart trading-engine  - Restart"
    echo "  systemctl stop trading-engine     - Stop"
    echo "  journalctl -u trading-engine -f   - View logs"
    echo ""
else
    echo ""
    echo "WARNING: Service may not have started correctly."
    echo "Check logs with: journalctl -u trading-engine -n 50"
    echo ""
    systemctl status ${SERVICE_NAME} --no-pager || true
fi
