#!/bin/sh
# ~/.local/bin/tmux-niri-title — POSIX sh, runs on Linux and macOS.
# Builds the context segment for tmux set-titles-string (e.g. a Niri title).
# Priority: ssh target > nvim file > git branch > cwd basename
# Args: $1 pane_current_command  $2 pane_current_path  $3 pane_tty  $4 pane_title

cmd=$1 path=$2 tty=$3 title=$4

# 1) Remote session → "󰣀 user@host"
case "$cmd" in
ssh | mosh-client | autossh | et)
    target=$(ps -o args= -t "$tty" 2>/dev/null | awk '
        /(^|\/)((auto)?ssh|mosh-client|et) / {
            for (i = 2; i <= NF; i++)
                if ($i !~ /^-/) { print $i; exit }
        }')
    printf '󰣀 %s' "${target:-remote}"
    exit 0
    ;;
esac

# 2) Editor → pane title (nvim sets "file – NVIM" when vim.opt.title = true)
case "$cmd" in
nvim | vim)
    if [ -n "$title" ] && [ "$title" != "$(hostname)" ]; then
        printf ' %s' "$title"
        exit 0
    fi
    ;;
esac

# 3) Git repo → "dir  branch"
branch=$(git -C "$path" branch --show-current 2>/dev/null)
if [ -n "$branch" ]; then
    printf '%s  %s' "$(basename "$path")" "$branch"
    exit 0
fi

# 4) Fallback → cwd basename
basename "$path"
