#!/bin/bash
# run_standalone.sh - Headless production launcher for TFM aInventory
# manages Backend, Frontend, and SSL Proxies in a single process group.

echo "🚀 Starting TFM aInventory in Standalone Mode..."

# Trapping termination signals to clean up child processes
trap "echo 'Stopping all processes...'; kill 0" SIGINT SIGTERM EXIT

# --- CONFIGURATION (Default values, overridden by network_config.env) ---
BACKEND_PORT=8000
FRONTEND_PORT=3001
BACKEND_SSL_PORT=3002
FRONTEND_SSL_PORT=3003
SERVER_IP="localhost"

# Load Configuration from file if it exists
CONFIG_PATH="$(cd "$(dirname "$0")" && pwd)/config/network_config.env"
if [ -f "$CONFIG_PATH" ]; then
    echo "⚙️  Loading network configuration from $CONFIG_PATH..."
    export $(grep -v '^#' "$CONFIG_PATH" | xargs)
fi

# 1. Activate Environment
if [ -d ".venv" ]; then
    source .venv/bin/activate
fi

# 1.5 Sync Network Config to Frontend
echo "🔌 Syncing network configuration to frontend..."
mkdir -p frontend/public
cat <<EOF > frontend/public/network.json
{
  "SERVER_IP": "$SERVER_IP",
  "BACKEND_PORT": $BACKEND_PORT,
  "BACKEND_SSL_PORT": $BACKEND_SSL_PORT,
  "FRONTEND_PORT": $FRONTEND_PORT,
  "FRONTEND_SSL_PORT": $FRONTEND_SSL_PORT
}
EOF

# 2. Start Backend (No Reload for Prod)
echo "🔥 Starting Backend (Uvicorn)..."
python3 -m uvicorn backend.main:app --host 0.0.0.0 --port $BACKEND_PORT &

# 3. Start Frontend (Production Start)
echo "💻 Starting Frontend (Next.js Prod)..."
cd frontend
npm run start -- -p $FRONTEND_PORT &
cd ..

# 4. Start Proxies (via npx)
echo "🛡️  Starting HTTPS Proxies..."
npx local-ssl-proxy --source $BACKEND_SSL_PORT --target $BACKEND_PORT --hostname 0.0.0.0 > /dev/null 2>&1 &
npx local-ssl-proxy --source $FRONTEND_SSL_PORT --target $FRONTEND_PORT --hostname 0.0.0.0 > /dev/null 2>&1 &

# 5. Detection of IP for logs
if [[ "$OSTYPE" == "darwin"* ]]; then
    LOCAL_IP=$(ipconfig getifaddr en0 || ipconfig getifaddr en1 || echo "localhost")
else
    LOCAL_IP=$(hostname -I | awk '{print $1}')
fi

echo ""
echo "✅ TFM aInventory is active at https://$LOCAL_IP:$FRONTEND_SSL_PORT"
echo "   Processes are running in background. Monitoring logs..."
echo ""

# Wait for children
wait
