#!/bin/zsh

# --- Extract bare domain from URL argument ---------------------------------
url=$1
domain=${url#*://}          # strip scheme (http://, https://, anything://)
domain=${domain%%/*}        # strip path
domain=${domain%%:*}        # strip port (e.g. :8443)
domain=${domain#www.}       # strip leading www.

# --- Tag the browser window so we can find our way back --------------------
hyprctl dispatch tagwindow +browser "title:.*qutebrowser"

# --- Pick an entry (UUID hidden in field 1) --------------------------------
line=$(
  rbw list --raw \
    | jq -r '.[] | [.id, .name, .user // "-", ((.uris // []) | map(sub("^https?://";"") | sub("/.*$";"")) | join(","))] | @tsv' \
    | column -t -s$'\t' -o$'\t' \
    | fzf --delimiter=$'\t' --with-nth=2.. --tabstop=1 --no-hscroll \
          --select-1 --query="$domain" \
          --prompt='rbw > ' --header='NAME  USER  URIS'
) || { hyprctl dispatch tagwindow -- -browser "title:.*qutebrowser"; exit 0; }

uuid=${line%%$'\t'*}
uuid=${uuid%% *}

output=("${(@f)$(rbw get --full "$uuid")}")
password=$output[1]
username=${output[2]#* }

# --- Return to browser and type credentials --------------------------------
hyprctl dispatch focuswindow "tag:browser"
hyprctl dispatch tagwindow -- -browser "title:.*qutebrowser"

wtype -k Esc
wtype "i"
sleep 0.1
wtype -- "$username"
wtype -k Tab
wtype -- "$password"
