#!/usr/bin/env bash
# Kmpl: acme glue for u/complete. Triggers completion and inserts at cursor.
set -euo pipefail

cmd=${0##*/}
die() { printf '%s: %s\n' "$cmd" "$*" >&2; exit 1; }

[ -z "${winid:-}" ] || [ "$winid" = "0" ] && die "must be run from an acme window"

# Get filename for language context
filename=$(9p read acme/$winid/ctl | awk 'NR==1{print $NF}')

# Sync addr to current dot, read rune offsets
echo "addr=dot" | 9p write acme/$winid/ctl
addr=$(9p read acme/$winid/addr)
q0=$(printf '%s' "$addr" | cut -d, -f1 | tr -d '#[:space:]')
q1=$(printf '%s' "$addr" | cut -d, -f2 | tr -d '#[:space:]')

# Read prefix (before dot) and suffix (from dot onward)
printf '#0,#%s' "$q0" | 9p write acme/$winid/addr
prefix=$(9p read acme/$winid/data)

printf '#%s,$' "$q1" | 9p write acme/$winid/addr
suffix=$(9p read acme/$winid/data)

# Fetch completion
result=$(printf '%s' "$prefix" | $OLLIE/u/complete -file "$filename" -suffix "$suffix" "$@")

# Insert at cursor
echo "addr=dot" | 9p write acme/$winid/ctl
printf '%s' "$result" | 9p write acme/$winid/data
