#!/bin/bash
# app-restart.sh — Restart a product app on its correct Caddy port
# Usage: app-restart.sh <slug>
# Always use this instead of manually killing/starting apps.

set -euo pipefail

SLUG="${1:-}"
PORTS_FILE="/home/aria/.openclaw/workspace/agency/infra/caddy-ports.json"
LOGS_DIR="/home/aria/projects/.aria-logs"

if [[ -z "$SLUG" ]]; then
  echo "Usage: app-restart.sh <slug>" >&2
  exit 1
fi

# Look up correct port
PORT=$(python3 -c "
import json, sys
data = json.load(open('$PORTS_FILE'))
allocated = data.get('allocated', data)
slug = '$SLUG'
if slug in allocated:
    print(allocated[slug])
else:
    sys.exit(1)
" 2>/dev/null)

if [[ -z "$PORT" ]]; then
  echo "ERROR: Slug '$SLUG' not found in caddy-ports.json" >&2
  exit 1
fi

# Find app directory
APP_DIR=""
for candidate in \
  "/home/aria/products/$SLUG/apps/main" \
  "/home/aria/projects/$SLUG" \
  "/home/aria/products/$SLUG"; do
  if [[ -f "$candidate/package.json" ]]; then
    APP_DIR="$candidate"
    break
  fi
done

if [[ -z "$APP_DIR" ]]; then
  echo "ERROR: Could not find app directory for '$SLUG'" >&2
  exit 1
fi

echo "→ Slug:    $SLUG"
echo "→ Port:    $PORT"
echo "→ Dir:     $APP_DIR"

# Kill existing process on that port
if lsof -ti :"$PORT" > /dev/null 2>&1; then
  echo "→ Killing existing process on :$PORT..."
  lsof -ti :"$PORT" | xargs kill -9 2>/dev/null || true
  sleep 2
fi

# Start app
mkdir -p "$LOGS_DIR"
LOG_FILE="$LOGS_DIR/$SLUG.log"
echo "→ Starting on port $PORT..."
cd "$APP_DIR"
nohup npm run start -- -p "$PORT" > "$LOG_FILE" 2>&1 &
PID=$!
echo "→ PID: $PID"

# Wait and verify
sleep 5
if curl -s -o /dev/null -w "%{http_code}" "http://localhost:$PORT/" | grep -qE "^[23]"; then
  echo "✅ $SLUG is up at http://localhost:$PORT (external: https://$SLUG.dev.apps.symph.co)"
else
  echo "⚠️  App started but not responding yet — check $LOG_FILE"
fi
