#!/usr/bin/env bash
# kilocode-loop launcher — run from anywhere inside a git repo.
#
#   kilo-loop                                        # open the dashboard launcher (pick a plan in the UI)
#   kilo-loop --goal .kilocode-loop/goal.json -n 5   # run a specific goal directly
#   kilo-loop --list-goals                           # print discovered plans + state, then exit
#   kilo-loop new-plan "My plan title"               # scaffold a kilo-loop-compatible plan, then exit
#   kilo-loop --dry-run -n 3                         # offline rehearsal
#
# Installs node_modules on first use, then runs the loop with the repo root as
# --project. Every argument is forwarded to bin/kilocode-loop.mjs.
set -euo pipefail

APP_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"

# `kilo-loop new-plan "<title> [flags]"` — deterministic plan scaffolder. Creates
# `.kilo/plans/<epoch-ms>-<slug>.md` from `.kilo/templates/plan.md` so new plans
# always carry the `- [ ]` stages kilo-loop needs. Handled here (before the loop
# runner) so it needs no goal and never starts the dashboard.
if [ "${1:-}" = "new-plan" ]; then
  shift
  exec node "$APP_DIR/new-plan.mjs" "$@"
fi

# Project = git root of the current directory (submodules resolve to themselves).
ROOT="$(git -C "$PWD" rev-parse --show-toplevel 2>/dev/null || printf '%s' "$PWD")"

if [ ! -d "$APP_DIR/node_modules" ]; then
  echo "[kilo-loop] installing dependencies in $APP_DIR ..." >&2
  (cd "$APP_DIR" && npm install --no-audit --no-fund >&2)
fi

# No default goal is injected on purpose: without --goal/--goal-text the runner
# opens the dashboard launcher, where the plan is picked in the UI. Pass --goal
# explicitly to run one directly.
exec node "$APP_DIR/bin/kilocode-loop.mjs" --project "$ROOT" "$@"
