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

# -----------------------------------------------------------------------------
# Function: clip
# -----------------------------------------------------------------------------
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 (Cross-platform file/directory opener)
# -----------------------------------------------------------------------------
open_file() {
    local target="${1:-.}"
    
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # Use native macOS open
        command open "$target"
    elif grep -qi "microsoft" /proc/version 2>/dev/null; then
        # Use WSL Explorer
        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. Windows interop might be disabled.\n" >&2
            return 1
        fi
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # Use Linux xdg-open
        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
# -----------------------------------------------------------------------------
clear_history() {
  history -p
}

# -----------------------------------------------------------------------------
# Function: claude
# -----------------------------------------------------------------------------
claude() {
  if ! command -v claude >/dev/null 2>&1; then
    printf "Error: 'claude' CLI is not installed or not in your PATH.\n" >&2
    return 1
  fi

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

  command claude "$@"
}

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

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

  for p in "$@"; do
    if [ "${p#\~}" != "$p" ]; then
      p="${HOME}${p#\~}"
    fi

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

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

    if ! install -D /dev/null "$p"; then
      printf "create: failed to create '%s'\n" "$p" >&2
      return 1
    fi
  done
  return 0
}

# -----------------------------------------------------------------------------
# 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
    if lsof -i :"$PORT" >/dev/null 2>&1; then
      echo "Port $PORT is IN USE"
      lsof -i :"$PORT"
    else
      echo "Port $PORT is FREE"
    fi
  else
    if ! command -v ss >/dev/null 2>&1; then
      printf "Error: 'ss' command not found. This function requires Linux iproute2 utilities.\n" >&2
      return 1
    fi

    if sudo ss -tulnp | grep -q ":$PORT "; then
      echo "Port $PORT is IN USE"
      sudo ss -tulnp | grep ":$PORT "
    else
      echo "Port $PORT is FREE"
    fi
  fi
}

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

# -----------------------------------------------------------------------------
# Function: add_path_to_config
# -----------------------------------------------------------------------------
add_path_to_config() {
  local new_path="$1"
  local config_file="$HOME/.bashrc"

  if [[ "$SHELL" == *"zsh"* ]]; then
    config_file="$HOME/.zshrc"
  fi

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

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

  if [ ! -d "$new_path" ]; then
    printf "Warning: '%s' does not exist.\n" "$new_path" >&2
    read -p "Do you still want to add it to your config? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      return 1
    fi
  fi

  if grep -Fq "append_path \"$new_path\"" "$config_file" || grep -Fq "append_path '$new_path'" "$config_file"; then
    printf "Notice: '%s' is already in your %s.\n" "$new_path" "$config_file"
    return 0
  fi

  if grep -q "^export PATH" "$config_file"; then
    awk -v new_cmd="append_path \"$new_path\"" '/^export PATH/{print new_cmd}1' "$config_file" > "${config_file}.tmp" && mv "${config_file}.tmp" "$config_file"
  else
    echo "append_path \"$new_path\"" >> "$config_file"
    echo "export PATH" >> "$config_file"
  fi

  printf "✅ Success: Added '%s' to %s\n" "$new_path" "$config_file"

  if type append_path >/dev/null 2>&1; then
    append_path "$new_path"
    export PATH
    printf "🚀 Path is now active in your current session!\n"
  fi
}

append_path "$HOME/.local/bin"
export PATH
