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

CHANNEL_ID="1490099048756023318"
KEYWORDS="tests passed,tests failed,build succeeded,build failed,All checks passed,exit code,ralph complete,architect approved,deslop complete,team shutdown,✅,❌,🎉,task completed,verification passed,verification failed"
ENGINE="codex"
MODE="exec"
TEAM_SIZE=""
DIR=""
TASK=""
NAME=""
MODEL="gpt-5.4"
EFFORT="xhigh"

usage() {
  cat <<EOF
Usage: dispatch.sh --dir DIR --task "DESCRIPTION" --name SESSION_NAME [OPTIONS]

Required:
  --dir DIR          Project directory to work in
  --task "DESC"      Task description / prompt
  --name NAME        tmux session name (used for monitoring)

Options:
  --engine ENGINE    codex (default) | opencode | omc
  --team N           Use OMX team mode with N parallel workers
  --ralph            Use OMX ralph persistent completion loop
  --model MODEL      Override model (default: gpt-5.4)
  --effort EFFORT    Reasoning effort: low|medium|high|xhigh (default: xhigh)
  --channel ID       Discord channel ID (default: $CHANNEL_ID)
  --keywords "k,k"   Comma-separated keywords to trigger Discord alerts
  --interactive      Launch interactive session (you type inside codex)
  --help             Show this help
EOF
  exit 0
}

INTERACTIVE=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dir) DIR="$2"; shift 2 ;;
    --task) TASK="$2"; shift 2 ;;
    --name) NAME="$2"; shift 2 ;;
    --engine) ENGINE="$2"; shift 2 ;;
    --team) MODE="team"; TEAM_SIZE="$2"; shift 2 ;;
    --ralph) MODE="ralph"; shift ;;
    --model) MODEL="$2"; shift 2 ;;
    --effort) EFFORT="$2"; shift 2 ;;
    --channel) CHANNEL_ID="$2"; shift 2 ;;
    --keywords) KEYWORDS="$2"; shift 2 ;;
    --interactive) INTERACTIVE=true; shift ;;
    --help) usage ;;
    *) echo "Unknown option: $1"; usage ;;
  esac
done

if [[ -z "$DIR" || -z "$NAME" ]]; then
  echo "Error: --dir and --name are required"
  usage
fi

if [[ "$INTERACTIVE" == false && -z "$TASK" ]]; then
  echo "Error: --task is required for non-interactive mode"
  usage
fi

DIR="$(cd "$DIR" && pwd)"

export PATH="/root/.bun/bin:/root/.cargo/bin:$PATH"

if ! clawhip status &>/dev/null; then
  echo "Starting clawhip daemon..."
  nohup clawhip start > /dev/shm/clawhip.log 2>&1 &
  sleep 2
fi

build_cmd() {
  local cmd="cd $DIR"

  case "$ENGINE" in
    codex)
      if [[ "$INTERACTIVE" == true ]]; then
        cmd="$cmd && omx --madmax --$EFFORT"
      elif [[ "$MODE" == "team" ]]; then
        cmd="$cmd && omx team ${TEAM_SIZE}:executor --madmax '${TASK//\'/\'\\\'\'}'"
      elif [[ "$MODE" == "ralph" ]]; then
        cmd="$cmd && omx ralph --madmax --$EFFORT '${TASK//\'/\'\\\'\'}'"
      else
        cmd="$cmd && omx exec --madmax --$EFFORT '${TASK//\'/\'\\\'\'}'"
      fi
      ;;
    opencode)
      cmd="$cmd && opencode run '${TASK//\'/\'\\\'\'}'"
      ;;
    omc)
      if [[ "$INTERACTIVE" == true ]]; then
        cmd="$cmd && omc --openclaw --madmax"
      else
        cmd="$cmd && omc exec --madmax '${TASK//\'/\'\\\'\'}'"
      fi
      ;;
    *)
      echo "Unknown engine: $ENGINE"
      exit 1
      ;;
  esac

  echo "$cmd"
}

CMD="$(build_cmd)"

echo "╔══════════════════════════════════════════════════╗"
echo "║  Autonomous Dev Dispatch                         ║"
echo "╠══════════════════════════════════════════════════╣"
echo "  Session:  $NAME"
echo "  Engine:   $ENGINE"
echo "  Mode:     $MODE"
echo "  Model:    $MODEL ($EFFORT)"
echo "  Dir:      $DIR"
echo "  Task:     ${TASK:-<interactive>}"
echo "  Discord:  channel $CHANNEL_ID"
echo "╚══════════════════════════════════════════════════╝"
echo ""

clawhip send --message "🚀 **Dispatching autonomous work**
**Session:** \`$NAME\`
**Engine:** $ENGINE ($MODE)
**Dir:** \`$(basename "$DIR")\`
**Task:** ${TASK:-<interactive>}" 2>/dev/null || true

clawhip tmux new -s "$NAME" \
  --channel "$CHANNEL_ID" \
  --keywords "$KEYWORDS" \
  -- "$CMD"
