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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./common.sh
source "$SCRIPT_DIR/common.sh"

ensure_repo_root

MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
ORCH_DIR=".mosaic/orchestrator"
PID_FILE="$ORCH_DIR/orchestrator.pid"
LOG_FILE="$ORCH_DIR/logs/daemon.log"

usage() {
  cat <<USAGE
Usage: $(basename "$0") <start|drain|stop|status> [--poll-sec N] [--no-sync]

Commands:
  start    Run orchestrator drain loop in background (detached)
  drain    Run orchestrator drain loop in foreground (until queue drained)
  stop     Stop background orchestrator if running
  status   Show background orchestrator status

Options:
  --poll-sec N   Poll interval (default: 15)
  --no-sync      Skip docs/TASKS.md -> orchestrator queue sync before run
USAGE
}

cmd="${1:-status}"
if [[ $# -gt 0 ]]; then
  shift
fi

poll_sec=15
sync_arg=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --poll-sec)
      poll_sec="${2:-15}"
      shift 2
      ;;
    --no-sync)
      sync_arg="--no-sync"
      shift
      ;;
    *)
      echo "[agent-framework] unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

mkdir -p "$ORCH_DIR/logs" "$ORCH_DIR/results"

is_running() {
  [[ -f "$PID_FILE" ]] || return 1
  local pid
  pid="$(cat "$PID_FILE" 2>/dev/null || true)"
  [[ -n "$pid" ]] || return 1
  kill -0 "$pid" 2>/dev/null
}

case "$cmd" in
  start)
    if is_running; then
      echo "[agent-framework] orchestrator already running (pid=$(cat "$PID_FILE"))"
      exit 0
    fi
    nohup "$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-drain" --poll-sec "$poll_sec" $sync_arg >"$LOG_FILE" 2>&1 &
    echo "$!" > "$PID_FILE"
    echo "[agent-framework] orchestrator started (pid=$!, log=$LOG_FILE)"
    ;;
  drain)
    exec "$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-drain" --poll-sec "$poll_sec" $sync_arg
    ;;
  stop)
    if ! is_running; then
      echo "[agent-framework] orchestrator not running"
      rm -f "$PID_FILE"
      exit 0
    fi
    pid="$(cat "$PID_FILE")"
    kill "$pid" || true
    rm -f "$PID_FILE"
    echo "[agent-framework] orchestrator stopped (pid=$pid)"
    ;;
  status)
    if is_running; then
      echo "[agent-framework] orchestrator running (pid=$(cat "$PID_FILE"), log=$LOG_FILE)"
    else
      echo "[agent-framework] orchestrator not running"
      rm -f "$PID_FILE"
    fi
    ;;
  *)
    usage
    exit 1
    ;;
esac
