#!/bin/bash

# Set directory path for Vimwiki files
WIKI_DIR="$HOME/org/wiki"  # Replace with the path to your Vimwiki directory
# Get the list of existing note titles, replacing underscores with spaces for display
EXISTING_TITLES=$(find "$WIKI_DIR/notes" -type f -name "*.wiki" -exec basename {} .wiki \; | tr '_' ' ')
# Use fzf to let the user select an existing title or type a new one
TITLE=$( (echo "$EXISTING_TITLES" && echo "[New Note]") | fzf --prompt="Select or enter title: " --print-query)

# Check if the user chose an existing title or opted for a new note
if [[ "$TITLE" = "[New Note]" || -z "$TITLE" ]]; then
  # Prompt for a new title if "New Note" was selected
  TITLE=$(echo "" | fzf --prompt="Enter title for new entry: ")
fi

# Exit if no title was entered
if [[ -z "$TITLE" ]]; then
  echo "No title entered. Exiting."
  exit 1
fi

# Format the filename by replacing spaces with underscores and lowercasing
FILENAME_TIMESTAMP=$(date +"%Y%m%d%H%M")
FILENAME="${FILENAME_TIMESTAMP}-$(echo "$TITLE" | tr ' ' '_' | tr '[:upper:]' '[:lower:]').wiki"
NEW_FILE="$WIKI_DIR/notes/$FILENAME"

# Check if a file with this title already exists
EXISTING_FILE=$(find "$WIKI_DIR/notes" -type f -name "$(echo "$TITLE" | tr ' ' '_' | tr '[:upper:]' '[:lower:]').wiki")

if [[ -n "$EXISTING_FILE" ]]; then
  # Open the existing file in Neovim if found
  nvim "$EXISTING_FILE"
else
  # Create a new file with the specified template if it does not exist
  TIMESTAMP=$(date +"%Y-%m-%d %H:%M")

  echo "= $TITLE =
*Created:* $TIMESTAMP

== Summary ==

== Tasks ==

== Notes ==

== Resources ==
* [[wiki link]] for additional content
* [[other wiki link|Desc]]
" > "$NEW_FILE"

  # Add a link to the new file at the bottom of index.wiki
  echo "- [[$FILENAME|$TITLE]]" >> "$WIKI_DIR/index.wiki"

  # Open the new file in Neovim
  nvim "$NEW_FILE"
fi
