#!/usr/bin/env bash
# ============================================================
#   TA-ATS Launcher (Linux / production)
#   Starts the 4 services: MCP, Django backend, FastAPI gateway,
#   Next.js frontend.
#   Usage:
#     chmod +x run_linux.sh      # once, to make it executable
#     ./run_linux.sh             # build frontend (if needed) + start all
#     ./run_linux.sh stop        # stop all services
#     FRONTEND_BUILD=1 ./run_linux.sh   # force a fresh frontend build
# ============================================================
set -u

# --- Paths ---------------------------------------------------
# BASE  = this project folder (.../ats.indovisionconsultancy.in)
# MCP   = sibling folder .../auth_mcp  (falls back to the in-project
#         auth_mcp_backup_alone if the sibling is absent)
BASE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MCP="$(cd "$BASE/.." && pwd)/auth_mcp"
[ -d "$MCP" ] || MCP="$BASE/auth_mcp_backup_alone"
LOGDIR="$BASE/logs"
PIDDIR="$BASE/.pids"
mkdir -p "$LOGDIR" "$PIDDIR"

# --- Interpreters (per-service venv, fall back to project venv) ---
pick_py () { [ -x "$1/venv/bin/python" ] && echo "$1/venv/bin/python" || echo "$BASE/venv/bin/python"; }
MCP_PY="$(pick_py "$MCP")"
BACKEND_PY="$(pick_py "$BASE/backend")"
GATEWAY_PY="$(pick_py "$BASE/gateway")"

# --- stop mode ----------------------------------------------
if [ "${1:-}" = "stop" ]; then
  echo "Stopping TA-ATS services..."
  for name in frontend gateway backend mcp; do
    if [ -f "$PIDDIR/$name.pid" ]; then
      pid="$(cat "$PIDDIR/$name.pid")"
      if kill -0 "$pid" 2>/dev/null; then
        # kill the whole process group so child workers die too
        kill -- -"$pid" 2>/dev/null || kill "$pid" 2>/dev/null
        echo "  stopped $name (pid $pid)"
      fi
      rm -f "$PIDDIR/$name.pid"
    fi
  done
  # Also free the service ports in case processes were started outside this
  # script (manual nohup, previous runs) and aren't tracked in .pids.
  for port in 3000 8000 8002 9000; do
    if command -v fuser >/dev/null 2>&1; then
      fuser -k "${port}/tcp" 2>/dev/null && echo "  freed port $port"
    fi
  done
  echo "Done."
  exit 0
fi

echo "============================================"
echo "   Starting TA-ATS (4 services)"
echo "   BASE = $BASE"
echo "   MCP  = $MCP"
echo "============================================"

# helper: start a background service in its own process group, save pid + log
start_svc () {
  local name="$1"; shift
  local dir="$1"; shift
  echo "Starting $name ..."
  ( cd "$dir" && setsid nohup "$@" > "$LOGDIR/$name.log" 2>&1 & echo $! > "$PIDDIR/$name.pid" )
}

# --- [1/4] MCP service (port 9000) --------------------------
start_svc mcp "$MCP" "$MCP_PY" server.py
sleep 3

# --- [2/4] Backend - Django (port 8002) ---------------------
# Prefer gunicorn (production WSGI); fall back to runserver if not installed.
# Invoked as a module via the chosen interpreter so it works regardless of
# whether gunicorn has a console-script in the venv's bin/.
if "$BACKEND_PY" -c "import gunicorn" 2>/dev/null; then
  start_svc backend "$BASE/backend" "$BACKEND_PY" -m gunicorn \
    config.wsgi:application --bind 0.0.0.0:8002 --workers 3 --timeout 120
else
  echo "  (gunicorn not installed — using manage.py runserver; install: $BACKEND_PY -m pip install gunicorn)"
  start_svc backend "$BASE/backend" "$BACKEND_PY" manage.py runserver 0.0.0.0:8002 --noreload
fi
sleep 4

# --- [3/4] Gateway - FastAPI (port 8000) --------------------
if "$GATEWAY_PY" -c "import gunicorn, uvicorn" 2>/dev/null; then
  start_svc gateway "$BASE/gateway" "$GATEWAY_PY" -m gunicorn \
    app.main:app -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 --workers 2 --timeout 120
else
  start_svc gateway "$BASE/gateway" "$GATEWAY_PY" -m uvicorn \
    app.main:app --host 0.0.0.0 --port 8000
fi
sleep 3

# --- [4/4] Frontend - Next.js (port 3000, PRODUCTION) -------
# Build once if there is no build yet, or when FRONTEND_BUILD=1 is set.
if [ "${FRONTEND_BUILD:-0}" = "1" ] || [ ! -d "$BASE/frontend/.next" ]; then
  echo "Building frontend (npm run build)..."
  ( cd "$BASE/frontend" && npm run build > "$LOGDIR/frontend-build.log" 2>&1 ) \
    && echo "  build OK" || echo "  !! build FAILED — see logs/frontend-build.log"
fi
start_svc frontend "$BASE/frontend" npm start

echo
echo "============================================"
echo "   All services started in the background."
echo
echo "   Frontend : http://<server-ip>:3000"
echo "   Gateway  : http://<server-ip>:8000/health"
echo "   Backend  : http://<server-ip>:8002/admin/"
echo "   MCP      : port 9000 (internal)"
echo
echo "   Logs : $LOGDIR/*.log   (tail -f logs/backend.log)"
echo "   Stop : ./run_linux.sh stop"
echo "============================================"
