#!/usr/bin/env bash
# fzf-ai-resume <agent> <session_id> <source> [cwd]
#
# cd into the session's original working directory (if it still exists) and
# re-launch the correct CLI with the correct resume flag.
set -euo pipefail

print_only=0
if [[ ${1:-} == "--print-cmd" ]]; then
  print_only=1
  shift
fi

agent=${1:?agent required}
sid=${2:?session id required}
source=${3:-}
cwd=${4:-}
cwd=${cwd%"${cwd##*[![:space:]]}"}

# Expand "~/…" we emit from the indexer back to $HOME. Use a literal tilde
# pattern so bash doesn't do its own tilde expansion inside the substitution.
case "$cwd" in
  "~")        cwd="$HOME" ;;
  "~/"*)      cwd="$HOME/${cwd#\~/}" ;;
esac

cd_ok=0
if [[ -n "$cwd" && -d "$cwd" ]]; then
  cd "$cwd" && cd_ok=1
fi

print_cmd() {
  if (( cd_ok )); then
    printf 'cd %q && ' "$cwd"
  fi
  printf '%q ' "$@"
  printf '\n'
  exit 0
}

run_cmd() {
  if (( print_only )); then
    print_cmd "$@"
  fi
  exec "$@"
}

case "$agent" in
  claude)
    # claude resumes from cwd; if we couldn't cd, it still works but the
    # session's file references may be wrong.
    run_cmd claude --resume "$sid"
    ;;
  codex)
    # Pass -C explicitly so codex never prompts to switch directories. When
    # we know the cwd we feed it; otherwise we leave codex to use the pwd.
    if (( cd_ok )); then
      run_cmd codex resume -C "$cwd" "$sid"
    else
      run_cmd codex resume "$sid"
    fi
    ;;
  opencode)
    # opencode takes the project directory as a positional and the session
    # id via --session. Passing the directory explicitly means we don't
    # even need to cd.
    if [[ -n "$cwd" && -d "$cwd" ]]; then
      run_cmd opencode "$cwd" --session "$sid"
    else
      run_cmd opencode --session "$sid"
    fi
    ;;
  droid)
    run_cmd droid --resume "$sid"
    ;;
  pi)
    # pi supports both: --resume <id> and --session <path>. The path form is
    # the most reliable because pi organises sessions by encoded cwd.
    if [[ -n "$source" && -f "$source" ]]; then
      run_cmd pi --session "$source"
    else
      run_cmd pi --resume "$sid"
    fi
    ;;
  *)
    echo "fzf-ai-resume: unknown agent '$agent'" >&2
    exit 2
    ;;
esac
