#!/bin/sh

# React to anvillm events and notify on running->idle transitions

get_alias() {
	9p read "anvillm/$1/alias" 2>/dev/null
}

get_cwd() {
	9p read "anvillm/$1/cwd" 2>/dev/null
}

get_summary() {
	9p read "anvillm/$1/summary" 2>/dev/null
}

9p read anvillm/events | while read -r line; do
	type=$(echo "$line" | jq -r '.type // empty')
	
	case "$type" in
		StateChange)
			old_state=$(echo "$line" | jq -r '.data.old_state // empty')
			new_state=$(echo "$line" | jq -r '.data.new_state // empty')
			agent=$(echo "$line" | jq -r '.source // empty')
			
			if [ "$old_state" = "running" ] && [ "$new_state" = "idle" ]; then
				name=$(get_alias "$agent")
				[ -z "$name" ] && name=$agent
				cwd=$(get_cwd "$agent")
				heading=$(basename "$cwd")
				summary=$(get_summary "$agent")
				[ -z "$summary" ] && summary="completed"
				notify-send "$heading ($name)" "$summary"
			fi
			;;
		UserRecv)
			from=$(echo "$line" | jq -r '.data.from // empty')
			subject=$(echo "$line" | jq -r '.data.subject // empty')
			body=$(echo "$line" | jq -r '.data.body // empty')
			notify-send "Message from $from" "$subject"
			;;
	esac
done
