#!/usr/bin/env bash
# Starts all three NMDPRA services via a user systemd unit so they bind on the
# real host network (Cursor agent shells use a private network namespace).

set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
UNIT=tankfarm-platform.service
CONTROL_UNIT=tankfarm-control.service

PORTAL_PORT=6123
DASH_PORT=6010
CONS_UI_PORT=6001
CONS_API_PORT=6002
SUPPLY_UI_PORT=6003
SUPPLY_API_PORT=6004
LISTEN_HOST=0.0.0.0

echo "══════════════════════════════════════════════════════════"
echo "  NMDPRA Central Platform — Full Stack Startup"
echo "══════════════════════════════════════════════════════════"

for req in \
  "$ROOT/nmdpr_consumption/backend/node_modules" \
  "$ROOT/nmdpr_consumption/frontend/node_modules" \
  "$ROOT/nmdpr_supply/frontend/node_modules" \
  "$ROOT/nmdpr_supply/backend/.venv/bin/python"
do
  if [ ! -e "$req" ]; then
    echo "Missing dependency: $req"
    echo "Install first (see README), then retry."
    exit 1
  fi
done

if [ ! -L "$ROOT/dashboard/node_modules" ] && [ ! -d "$ROOT/dashboard/node_modules" ]; then
  ln -sfn ../nmdpr_consumption/frontend/node_modules "$ROOT/dashboard/node_modules"
fi

if ! grep -qE '^MYSQL_HOST=' "$ROOT/nmdpr_consumption/backend/.env" \
   || ! grep -qE '^MYSQL_HOST=' "$ROOT/nmdpr_supply/backend/.env"; then
  echo "MySQL is not configured in backend .env files."
  echo "Run: ./scripts/setup-mysql.sh"
  exit 1
fi
(cd "$ROOT/nmdpr_consumption/backend" && node db/seed.js)
mkdir -p "$ROOT/nmdpr_consumption/backend/uploads"
(cd "$ROOT/nmdpr_supply/backend" && .venv/bin/python seed.py >/dev/null 2>&1 || true)

# Persistent user unit so the stack comes back after hibernate / reboot.
UNIT_FILE="$HOME/.config/systemd/user/$UNIT"
mkdir -p "$HOME/.config/systemd/user"
cat > "$UNIT_FILE" <<EOF
[Unit]
Description=NMDPRA Tankfarm application stack (6001-6004 / 6010)
After=network.target

[Service]
Type=simple
WorkingDirectory=$ROOT
Environment=HOST=$LISTEN_HOST
ExecStart=/bin/bash $ROOT/scripts/run-platform.sh
KillMode=control-group
Restart=on-failure
RestartSec=5
TimeoutStopSec=25
LimitNOFILE=65535

[Install]
WantedBy=default.target
EOF

CONTROL_UNIT_FILE="$HOME/.config/systemd/user/$CONTROL_UNIT"
cat > "$CONTROL_UNIT_FILE" <<EOF
[Unit]
Description=NMDPRA local portal and service controls (6123)
After=default.target

[Service]
Type=simple
WorkingDirectory=$ROOT
ExecStart=/usr/bin/node $ROOT/scripts/control-server.js
Restart=always
RestartSec=2
NoNewPrivileges=true

[Install]
WantedBy=default.target
EOF

chmod +x "$ROOT/scripts/run-platform.sh" "$ROOT/scripts/control-server.js"
systemctl --user stop "$UNIT" 2>/dev/null || true
systemctl --user reset-failed "$UNIT" 2>/dev/null || true
systemctl --user daemon-reload
systemctl --user enable "$UNIT" "$CONTROL_UNIT"
systemctl --user restart "$CONTROL_UNIT"
systemctl --user start "$UNIT"
loginctl enable-linger "$USER" 2>/dev/null || true

echo "Waiting for backends…"
for PORT in "$CONS_API_PORT" "$SUPPLY_API_PORT"; do
  TRIES=0
  # Any TCP/HTTP response counts (6002 root is 404)
  until curl -s -o /dev/null --connect-timeout 1 "http://127.0.0.1:$PORT" >/dev/null 2>&1 || [ $TRIES -ge 30 ]; do
    sleep 1; TRIES=$((TRIES+1))
  done
  if [ $TRIES -ge 30 ]; then
    echo "  ⚠ Port $PORT did not respond — check: journalctl --user -u $UNIT -n 50"
  else
    echo "  ✓ Port $PORT ready"
  fi
done

echo "Waiting for UIs…"
for PORT in "$PORTAL_PORT" "$CONS_UI_PORT" "$SUPPLY_UI_PORT" "$DASH_PORT"; do
  TRIES=0
  until curl -s -o /dev/null --connect-timeout 1 "http://127.0.0.1:$PORT" >/dev/null 2>&1 || [ $TRIES -ge 40 ]; do
    sleep 1; TRIES=$((TRIES+1))
  done
  if [ $TRIES -ge 40 ]; then
    echo "  ⚠ Port $PORT did not respond — check: journalctl --user -u $UNIT -n 50"
  else
    echo "  ✓ Port $PORT ready"
  fi
done
echo ""
echo "  Listening on                 → $LISTEN_HOST"
echo "  Platform access portal       → http://localhost:$PORTAL_PORT"
echo "  Dashboard                    → http://localhost:$DASH_PORT"
echo "  nmdpr_consumption frontend   → http://localhost:$CONS_UI_PORT"
echo "  nmdpr_consumption API        → http://localhost:$CONS_API_PORT/api"
echo "  nmdpr_supply frontend        → http://localhost:$SUPPLY_UI_PORT"
echo "  nmdpr_supply API             → http://localhost:$SUPPLY_API_PORT"
echo "  nmdpr_supply API docs        → http://localhost:$SUPPLY_API_PORT/docs"
echo ""
echo "  Credentials:"
echo "    consumption admin:  admin@nmdpr.gov.ng / Admin@2024"
echo "    supply admin:       admin / Admin@NMDPRA2024"
echo ""
echo "  Stop all:      ./stop.sh"
echo "  Platform:      systemctl --user status $UNIT"
echo "  Local control: systemctl --user status $CONTROL_UNIT"
echo "══════════════════════════════════════════════════════════"
