#!/bin/bash

# omarchy:summary=Launch the default AI coding harness in a project path
# omarchy:args=[--path <path>] [--prompt <prompt>] [--harness <pi|claude|codex|opencode>] [path]
# omarchy:examples=omarchy launch ai --path ~/.config/omarchy/plugins/local.clock | omarchy launch ai --harness claude --path . --prompt "Review this plugin"

set -euo pipefail

path="."
prompt=""
harness=""

usage() {
  cat <<'USAGE'
Usage: omarchy-launch-ai [--path <path>] [--prompt <prompt>] [--harness <pi|claude|codex|opencode>] [path]

Launches an interactive AI coding harness in the given path. If no harness is
provided, uses the value from `omarchy default ai`.
USAGE
}

fail() {
  echo "omarchy-launch-ai: $*" >&2
  exit 1
}

while (( $# > 0 )); do
  case "$1" in
  --path)
    path="${2:-}"
    [[ -n $path ]] || fail "--path requires a value"
    shift 2
    ;;
  --prompt)
    prompt="${2:-}"
    shift 2
    ;;
  --harness)
    harness="${2:-}"
    [[ -n $harness ]] || fail "--harness requires a value"
    shift 2
    ;;
  -h | --help)
    usage
    exit 0
    ;;
  --)
    shift
    break
    ;;
  --*)
    fail "unknown option: $1"
    ;;
  *)
    path="$1"
    shift
    ;;
  esac
done

[[ -d $path ]] || fail "path is not a directory: $path"
path=$(cd "$path" && pwd)

if [[ -z $harness ]]; then
  harness=$(omarchy-default-ai)
fi

case "$harness" in
pi | claude | codex | opencode)
  ;;
*)
  fail "unknown AI harness: $harness"
  ;;
esac

launch_in_place() {
  cd "$path"
  case "$harness" in
  pi)
    omarchy-cmd-present pi || fail "pi is not installed"
    if [[ -n $prompt ]]; then exec pi "$prompt"; else exec pi; fi
    ;;
  claude)
    omarchy-cmd-present claude || fail "claude is not installed"
    if [[ -n $prompt ]]; then exec claude "$prompt"; else exec claude; fi
    ;;
  codex)
    omarchy-cmd-present codex || fail "codex is not installed"
    if [[ -n $prompt ]]; then exec codex "$prompt"; else exec codex; fi
    ;;
  opencode)
    omarchy-cmd-present opencode || fail "opencode is not installed"
    if [[ -n $prompt ]]; then exec opencode --prompt "$prompt" .; else exec opencode .; fi
    ;;
  esac
}

if [[ -t 0 && -t 1 ]]; then
  launch_in_place
fi

quoted_path=$(printf '%q' "$path")
quoted_prompt=$(printf '%q' "$prompt")
quoted_harness=$(printf '%q' "$harness")
exec omarchy-launch-tui bash -lc "cd $quoted_path && exec omarchy-launch-ai --harness $quoted_harness --prompt $quoted_prompt --path ."
