#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
API_DIR="$ROOT_DIR/api"
WEB_DIR="$ROOT_DIR/web"
LOG_DIR="$ROOT_DIR/.logs"
PID_DIR="$ROOT_DIR/.pids"
LAUNCHD_DIR="$ROOT_DIR/scripts/launchd"
LAUNCHD_DOMAIN="gui/$(id -u)"
API_LABEL="com.skg.tk-recreate.api.dev"
WEB_LABEL="com.skg.tk-recreate.web.dev"

mkdir -p "$LOG_DIR" "$PID_DIR"

port_is_listening() {
  local port="$1"
  lsof -tiTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1
}

start_api() {
  if port_is_listening 4291; then
    echo "api already running on 4291"
    return
  fi
  if [[ ! -x "$API_DIR/.venv/bin/uvicorn" ]]; then
    echo "missing api/.venv/bin/uvicorn" >&2
    exit 1
  fi
  launchctl bootout "$LAUNCHD_DOMAIN/$API_LABEL" >/dev/null 2>&1 || true
  launchctl bootstrap "$LAUNCHD_DOMAIN" "$LAUNCHD_DIR/$API_LABEL.plist"
  launchctl kickstart -k "$LAUNCHD_DOMAIN/$API_LABEL"
  echo "api started on 4291 via launchd, log: $LOG_DIR/api.launchd.log"
}

start_web() {
  if port_is_listening 4290; then
    echo "web already running on 4290"
    return
  fi
  if ! command -v npm >/dev/null 2>&1; then
    echo "missing npm in PATH" >&2
    exit 1
  fi
  launchctl bootout "$LAUNCHD_DOMAIN/$WEB_LABEL" >/dev/null 2>&1 || true
  launchctl bootstrap "$LAUNCHD_DOMAIN" "$LAUNCHD_DIR/$WEB_LABEL.plist"
  launchctl kickstart -k "$LAUNCHD_DOMAIN/$WEB_LABEL"
  echo "web started on 4290 via launchd, log: $LOG_DIR/web.launchd.log"
}

start_api
start_web
echo "open http://localhost:4290"
