# =============================================================================
# CUSTOM FUNCTIONS
# =============================================================================

# -----------------------------------------------------------------------------
# Function: clip (Cross-platform clipboard)
# -----------------------------------------------------------------------------
clip() {
  local cmd
  local args=()

  if command -v pbcopy >/dev/null 2>&1; then
    cmd="pbcopy" # macOS
  elif grep -qi "microsoft" /proc/version 2>/dev/null && command -v clip.exe >/dev/null 2>&1; then
    cmd="clip.exe" # WSL
  elif [ "$XDG_SESSION_TYPE" = "wayland" ] && command -v wl-copy >/dev/null 2>&1; then
    cmd="wl-copy" # Linux Wayland
  elif command -v xclip >/dev/null 2>&1; then
    cmd="xclip" # Linux X11 (Fallback 1)
    args=("-selection" "clipboard")
  elif command -v xsel >/dev/null 2>&1; then
    cmd="xsel" # Linux X11 (Fallback 2)
    args=("--clipboard" "--input")
  else
    printf "Error: No supported clipboard utility found.\n" >&2
    return 1
  fi

  if [ $# -gt 0 ]; then
    if [ -f "$1" ]; then
      "$cmd" "${args[@]}" < "$1"
      echo "Copied contents of '$1' to clipboard."
    else
      printf "Error: File '%s' not found.\n" "$1" >&2
      return 1
    fi
  else
    "$cmd" "${args[@]}"
  fi
}

# -----------------------------------------------------------------------------
# Function: open_file (Cross-platform file/directory opener)
# -----------------------------------------------------------------------------
open_file() {
    local target="${1:-.}"
    
    if [[ "$OSTYPE" == "darwin"* ]]; then
        command open "$target"
    elif grep -qi "microsoft" /proc/version 2>/dev/null; then
        if command -v wslpath >/dev/null 2>&1 && command -v explorer.exe >/dev/null 2>&1; then
            explorer.exe "$(wslpath -w "$target")"
        else
            printf "Error: 'wslpath' or 'explorer.exe' not found.\n" >&2
            return 1
        fi
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        if command -v xdg-open >/dev/null 2>&1; then
            xdg-open "$target"
        else
            printf "Error: 'xdg-open' not found.\n" >&2
            return 1
        fi
    fi
}
alias open='open_file'

# -----------------------------------------------------------------------------
# Function: clear_history (Supports shell and Claude)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# Function: clear_history (Supports shell and Claude)
# -----------------------------------------------------------------------------
clear_history() {
  case "$1" in
    claude)
      if [ -d "$HOME/.claude/projects" ]; then
        # Use 'yes' to skip prompts and -f to ignore non-existent files
        yes | rm -rf "$HOME/.claude/projects"/*
        echo "Claude project history/cache cleared."
      fi
      ;;
      
    *)
      # 1. Truncate the file
      : > "$HISTFILE" 

      # 2. Clear RAM by briefly setting history size to 0
      local old_histsize=$HISTSIZE
      HISTSIZE=0
      HISTSIZE=$old_histsize
      
      echo "Shell history cleared."
      ;;
  esac
}

# -----------------------------------------------------------------------------
# Function: claude (Includes --yolo and clear shortcuts)
# -----------------------------------------------------------------------------
claude() {
  # Shortcut for clearing cache
  if [[ "$1" == "clear" ]]; then
    clear_history claude
    return 0
  fi

  # Check if binary exists
  if ! whence -p claude >/dev/null 2>&1; then
    printf "Error: 'claude' CLI is not installed or not in your PATH.\n" >&2
    return 1
  fi

  # Handle --yolo mode
  if [[ "$1" == "--yolo" ]]; then
    shift
    command claude --dangerously-skip-permissions "$@"
    return $?
  fi

  command claude "$@"
}

# -----------------------------------------------------------------------------
# Function: create (Efficiently create file + parent dirs)
# -----------------------------------------------------------------------------
create() {
  if ! command -v install >/dev/null 2>&1; then
    printf "Error: 'install' coreutil is not available.\n" >&2
    return 1
  fi

  if [ $# -eq 0 ]; then
    printf "Usage: create <file> [file ...]\n" >&2
    return 2
  fi

  for p in "$@"; do
    # Expand tilde manually if shell doesn't
    [[ "$p" == "~/"* ]] && p="${HOME}/${p#\~/}"

    if [ -z "$p" ] || [ "$p" = "/" ]; then
      printf "create: refusing to operate on '%s'\n" "$p" >&2
      continue
    fi

    if [ -e "$p" ]; then
      printf "create: '%s' already exists. Skipping.\n" "$p" >&2
      continue
    fi

    if install -D /dev/null "$p"; then
      echo "Created '$p'"
    fi
  done
}

# -----------------------------------------------------------------------------
# Function: check_port
# -----------------------------------------------------------------------------
check_port() {
  local PORT=$1
  if [ -z "$PORT" ]; then
    printf "Usage: check_port <port_number>\n" >&2
    return 1
  fi

  if [[ "$OSTYPE" == "darwin"* ]]; then
    lsof -i :"$PORT" || echo "Port $PORT is FREE"
  else
    sudo ss -tulnp | grep ":$PORT " || echo "Port $PORT is FREE"
  fi
}

# -----------------------------------------------------------------------------
# Function: append_path (Adds to session PATH if exists)
# -----------------------------------------------------------------------------
append_path() {
    local dir="$1"
    if [ -d "$dir" ]; then
        case ":$PATH:" in
            *":$dir:"*) ;; 
            *) PATH="$PATH:$dir" ;;
        esac
    elif [ "${SUPPRESS_WARNINGS:-0}" -ne 1 ]; then
        echo "Warning: $dir does not exist." >&2
    fi
}

# -----------------------------------------------------------------------------
# Function: add_path_to_config (Fixed awk/sed injection)
# -----------------------------------------------------------------------------
add_path_to_config() {
  local new_path="$1"
  local config_file="$HOME/.bashrc"
  [[ "$SHELL" == *"zsh"* ]] && config_file="$HOME/.zshrc"

  if [ -z "$new_path" ]; then
    printf "Usage: add_path_to_config <directory>\n" >&2
    return 1
  fi

  new_path="${new_path/#\~/$HOME}"

  if [ ! -d "$new_path" ]; then
    printf "Warning: '%s' does not exist. Add anyway? (y/N) " "$new_path"
    read -r REPLY
    [[ ! $REPLY =~ ^[Yy]$ ]] && return 1
  fi

  # Check if already exists in file
  if grep -Fq "append_path \"$new_path\"" "$config_file"; then
    printf "Notice: Already in %s.\n" "$config_file"
    return 0
  fi

  # Robust Injection: Use sed to insert before export PATH or just append
  if grep -q "^export PATH" "$config_file"; then
    sed -i.bak "/^export PATH/i append_path \"$new_path\"" "$config_file"
  else
    echo "append_path \"$new_path\"" >> "$config_file"
    echo "export PATH" >> "$config_file"
  fi

  printf "✅ Success: Added to %s\n" "$config_file"
  append_path "$new_path" && export PATH
}