#!/bin/bash

set -e

CLIP_CMD=""
QUIET="true"
DEBUG="false"
# FILE_COUNT=0  # Initialize the file counter

usage() {
    cat << EOF
llmcat - Prepare files and directories for LLM consumption

Usage: llmcat [options] [path]
       llmcat (interactive mode with fzf)

Options:
    -h, --help              Show this help message
    -i, --ignore PATTERN    Additional ignore patterns (fd exclude format: glob pattern)
    -t, --tree-only         Only output directory tree
    -q, --quiet             Silent mode (only copy to clipboard)
    -p, --print             Print copied files/content, and also copy to clipboard (default: quiet)
    -P, --print-only        Print copied files/content, but DON'T copy to clipboard (default: quiet)
    -n, --no-ignore         Don't respect gitignore/ignore files
    -H, --hidden            Include hidden files/directories
    --debug                 Enable debug output

Interactive Mode (fzf):
    tab          - Select/mark multiple files
    shift-tab    - Unselect/unmark file
    ctrl-/       - Toggle preview window
    ctrl-d       - Select directory mode
    ctrl-f       - Select file mode
    enter        - Confirm selection(s)
    esc          - Exit

Examples:
    # Interactive file selection
    llmcat

    # Process specific file
    llmcat path/to/file.txt

    # Process directory with custom ignore
    llmcat -i "*.log" -i "*.tmp" ./src/

    # Print content while copying
    llmcat -p ./src/file.txt

    # Print content without copying to clipboard
    llmcat -P ./src/file.txt

Features:
    - Interactive fuzzy finder with file preview
    - Auto-copies output to clipboard
    - Automatically respects .gitignore, .ignore, and .fdignore files
    - Directory tree visualization
    - Multi-file selection
    - Cross-platform (Linux/OSX)

See Also:
      https://github.com/azer/llmcat
EOF
}

debug() {
  if [ "${DEBUG}" = "true" ]; then
    printf 'DEBUG: %s\n' "$*" >&2
  fi
}

detect_os() {
  case "$(uname)" in
    "Darwin")
      CLIP_CMD="pbcopy"
      ;;
    "Linux")
      if command -v pbcopy >/dev/null; then
        CLIP_CMD="pbcopy"
      elif command -v wl-copy >/dev/null 2>&1; then
        CLIP_CMD="wl-copy"
      elif command -v xclip >/dev/null 2>&1; then
        CLIP_CMD="xclip -selection clipboard"
      elif command -v xsel >/dev/null 2>&1; then
        CLIP_CMD="xsel --clipboard --input"
      else
        echo "Error: Install xclip or xsel for clipboard support" >&2
        exit 1
      fi
      ;;
    *)
      echo "Error: Unsupported OS" >&2
      exit 1
      ;;
  esac
}

find_root() {
  if git rev-parse --git-dir >/dev/null 2>&1; then
    git rev-parse --show-toplevel
  else
    pwd
  fi
}

check_dependencies() {
  missing=false
  if ! command -v fd >/dev/null 2>&1; then
    echo "Interactive mode requires fd. Install with:"
    echo "  brew install fd    # macOS"
    echo "  apt install fd-find     # Ubuntu (available as 'fdfind')"
    echo "  https://github.com/sharkdp/fd#installation"
    missing=true
  fi
  if ! command -v fzf >/dev/null 2>&1; then
    echo "Interactive mode requires fzf. Install with:"
    echo "  brew install fzf    # macOS"
    echo "  apt install fzf     # Ubuntu"
    echo
    missing=true
  fi
  [ "${missing}" = "true" ] && return 1 || return 0
}

run_fzf() {
  fd_opts="$1"
  root_dir=$(find_root)

  debug "Running fzf from: ${root_dir}"

  preview_cmd='
      if [ -f {} ]; then
          bat --style=numbers --color=always {} 2>/dev/null || cat {}
      elif [ -d {} ]; then
          echo "\n  Directory: {}\n"
          tree -C {} 2>/dev/null || ls -la {} 2>/dev/null
      fi'

  (cd "${root_dir}" && {
    fd_cmd="fd . --color=never ${fd_opts}"
    debug "Fd command: ${fd_cmd}"

    # Execute fd command and pipe to fzf, adding the current directory
    # to maintain original behavior
    (echo "."; eval "${fd_cmd}") | fzf \
      --preview "${preview_cmd}" \
      --preview-window 'right:60%:border-left' \
      --bind 'ctrl-/:toggle-preview' \
      --bind "ctrl-d:change-prompt(Select directories > )+reload(echo \".\"; fd . --type directory --color=never ${fd_opts})" \
      --bind "ctrl-f:change-prompt(Select files > )+reload(fd . --type file --color=never ${fd_opts})" \
      --bind 'tab:toggle+up' \
      --height '80%' \
      --border=rounded \
      --prompt '⚡ Select files/dirs > ' \
      --multi \
      --color 'fg+:252,bg+:-1,hl:148,hl+:154,pointer:032,marker:010,prompt:064,border:240,separator:240'
  })
}

get_relative_path() {
  path="$1"
  root_dir=$(find_root)
  # shellcheck disable=SC2250,SC2295
  echo "${path#$root_dir/}"
}

process_file() {
  file="$1"
  rel_path=$(get_relative_path "${file}")
  # Note: Don't increment counter here since this runs in a subshell
  {
    echo "## File: ${rel_path}"
    echo "---"
    cat "${file}"
    echo
  }
}

process_dir() {
  dir="$1"
  fd_opts="$2"
  tree_only="$3"
  rel_path=$(get_relative_path "${dir}")

  {
    echo "# Directory: ${rel_path}"
    echo "---"
    echo

    if command -v tree >/dev/null 2>&1; then
      # use tree command if available with ignore patterns
      tree_output=$(cd "${dir}" && tree)
    else
      # use fd + sed to simulate a tree view
      fd_tree_cmd="cd \"${dir}\" && fd . --color=never ${fd_opts}"
      tree_output=$(eval "${fd_tree_cmd}" | sed -e "s/[^-][^\/]*\// |--/g" -e "s/|\([^ ]\)/|-\1/")
    fi
    echo "${tree_output}"

    # process files only if not tree_only
    if [ "${tree_only}" != "true" ]; then
      # find all files with fd
      fd_files_cmd="cd \"${dir}\" && fd . --type file --color=never ${fd_opts}"
      # process each file
      eval "${fd_files_cmd}" | while IFS= read -r file; do
        echo
        process_file "${dir}/${file}"
      done
    fi
  }
}

output_handler() {
  content="$1"
  # copy to clipboard unless -P option was used
  if [ "${NOCLIP}" = "false" ]; then
    printf '%s' "${content}" | eval "${CLIP_CMD}"
  fi
  # print if not quiet or if it's tree-only mode
  if [ "${QUIET}" = "false" ] || [ "${tree_only}" = "true" ]; then
    echo "${content}"
  fi
  # show feedback only for file copies, not tree-only mode
  if [ "${tree_only}" != "true" ]; then
    if [ "${NOCLIP}" = "false" ]; then
      echo "Copied ${FILE_COUNT} file(s) to clipboard" >&2
    else
      echo "Copied ${FILE_COUNT} file(s) to STDOUT" >&2
    fi
  fi
}

# process multiple targets
process_targets() {
  output=""
  fd_opts="$1"
  shift

  # reset file counter before processing
  FILE_COUNT=0

  for target in "$@"; do
    debug "Processing: ${target}"
    if [ -f "${target}" ]; then
      FILE_COUNT=$((FILE_COUNT + 1))
      output="${output}$(process_file "${target}")"
    elif [ -d "${target}" ]; then
      # for directories, we need to count the files inside
      if [ "${tree_only}" != "true" ]; then
        # count files in directory
        file_count_in_dir=$(cd "${target}" && fd . --type file --color=never "${fd_opts}" | wc -l)
        FILE_COUNT=$((FILE_COUNT + file_count_in_dir))
      fi
      output="${output}$(process_dir "${target}" "${fd_opts}" "${tree_only}")"
    else
      echo "Warning: Target not found - ${target}" >&2
      continue
    fi
    # output="${output}$'\n\n'"
  done
  output_handler "${output}"
}

main() {
  fd_opts=""
  tree_only="false"
  targets=""

  # Parse arguments
  while [ $# -gt 0 ]; do
    case $1 in
      -h|--help) usage; exit 0 ;;
      -i|--ignore) 
          fd_opts="${fd_opts} --exclude \"$2\""; 
          shift 2 ;;
      -n|--no-ignore) 
          fd_opts="${fd_opts} --no-ignore"; 
          shift ;;
      -H|--hidden) 
          fd_opts="${fd_opts} --hidden"; 
          shift ;;
      -t|--tree-only) 
          tree_only="true"; 
          shift ;;
      -q|--quiet) 
          QUIET="true"; 
          NOCLIP="false";
          shift ;;
      -p|--print) 
          QUIET="false"; 
          NOCLIP="false";
          shift ;;
      -P|--print-only)
          QUIET="false";
          NOCLIP="true";
          shift ;;
      --debug) 
          DEBUG="true"; 
          shift ;;
      *) 
        targets="${targets}($1)"; 
          shift ;;
    esac
  done

  detect_os

  # interactive mode if no targets
  if [ ${#targets[@]} -eq 0 ]; then
    debug "Starting interactive mode"
    # shellcheck disable=SC2310
    if check_dependencies; then
        debug "Running fzf selection"
        selected=$(run_fzf "${fd_opts}")

        if [ -n "${selected}" ]; then
          debug "Processing selection"
          while IFS= read -r line; do
            [ -n "${line}" ] && targets="${targets}(${line})"
          done <<EOF
${selected}
EOF
        else
          debug "No selection made"
          exit 0
        fi
    else
        exit 1
    fi
  fi

  if [ ${#targets[@]} -gt 0 ]; then
    debug "Processing ${#targets[@]} targets"
    process_targets "${fd_opts}" "${targets}"
  fi
}

main "$@"
