# oo shell function — source this file to enable 'oo mode' in the current shell
# Delegates mode/use to the current worktree branch (so exports propagate),
# everything else to $OOSH_DIR/oo as a normal command.

private.oo.shim.findLatest() {
  local ooshReal
  ooshReal=$(readlink -f "$HOME/oosh" 2>/dev/null \
    || readlink "$HOME/oosh" 2>/dev/null \
    || echo "$HOME/oosh")
  local base
  base=$(dirname "$ooshReal")
  if [ ! -d "$base/main" ]; then
    if [ -n "$OOSH_WORKTREE_BASE" ] && [ -d "$OOSH_WORKTREE_BASE" ]; then
      base="$OOSH_WORKTREE_BASE"
    else
      echo "$ooshReal"
      return
    fi
  fi
  # Pick most recently modified git worktree dir (skip config/, init/, etc.)
  local dir
  for dir in $(ls -dt "$base"/*/ 2>/dev/null); do
    dir="${dir%/}"
    [ -d "$dir/.git" ] || [ -f "$dir/.git" ] || continue
    echo "$dir"
    return
  done
  echo "$ooshReal"
}

oo() {
  case "$1" in
    mode|use)
      local ooCmd="$1"
      shift
      # Pick up env from a previous subprocess run of 'oo mode'
      local envFile="$HOME/.config/oosh/mode-env.bash"
      if [ -f "$envFile" ]; then
        local envTmp="${envFile}.$$"
        mv "$envFile" "$envTmp" 2>/dev/null && source "$envTmp" && rm -f "$envTmp"
      fi
      local ooLatest
      ooLatest=$(private.oo.shim.findLatest)
      # Source in current shell so exports (OOSH_DIR, OOSH_MODE) propagate
      export STARTED=true
      export OO_FROM_LATEST=1
      source "$ooLatest/this" 2>/dev/null
      source "$ooLatest/oo" 2>/dev/null
      # Verify the function was loaded, fall back to command dispatch if not
      # Prefer compound sub-method if it exists (e.g., mode.stage over mode)
      if [ -n "$1" ] && declare -F "oo.$ooCmd.$1" >/dev/null 2>&1; then
        local subMethod=$1; shift
        "oo.$ooCmd.$subMethod" "$@"
      elif declare -F "oo.$ooCmd" >/dev/null 2>&1; then
        "oo.$ooCmd" "$@"
      else
        error.log "oo.$ooCmd not found after sourcing $ooLatest/oo" 2>/dev/null
        command "${OOSH_DIR:-$HOME/oosh}/oo" "$ooCmd" "$@"
      fi
      ;;
    *)
      # All other oo subcommands run as normal command
      command "${OOSH_DIR:-$HOME/oosh}/oo" "$@"
      ;;
  esac
}
