#!/usr/bin/env bash
# imajin-manage service runner
# Usage: ./run [start|stop|restart|dev|logs|status]

set -euo pipefail
SERVICE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/service" && pwd)"
cd "$SERVICE_DIR"

LOG_FILE="/tmp/imajin-manage.log"
PORT=8015
APP="src.main:app"

_pid() {
  ss -tlnp "sport = :${PORT}" 2>/dev/null | grep -oP 'pid=\K[0-9]+' | head -1 || true
}

cmd="${1:-status}"

case "$cmd" in
  start)
    existing=$(_pid)
    if [[ -n "$existing" ]]; then
      echo "Already running (PID $existing)"
      exit 0
    fi
    nohup .venv/bin/python -m uvicorn "$APP" --host 0.0.0.0 --port "$PORT" --log-level info \
      > "$LOG_FILE" 2>&1 &
    echo "Started PID $! — logs: $LOG_FILE"
    ;;
  stop)
    pid=$(_pid)
    if [[ -n "$pid" ]]; then
      kill "$pid" && echo "Stopped PID $pid"
      else
      echo "Not running"
    fi
    ;;
  restart)
    "$0" stop
    sleep 1
    "$0" start
    ;;
  dev)
    exec .venv/bin/python -m uvicorn "$APP" --host 0.0.0.0 --port "$PORT" --reload
    ;;
  logs)
    exec tail -f "$LOG_FILE"
    ;;
  status)
    pid=$(_pid)
    if [[ -n "$pid" ]]; then
      echo "Running (PID $pid)"
      curl -s "http://localhost:${PORT}/health" && echo ""
    else
      echo "Stopped"
    fi
    ;;
  *)
    echo "Usage: $0 [start|stop|restart|dev|logs|status]"
    exit 1
    ;;
esac
