#!/usr/bin/env bash
# Emit niri workspaces as JSON for eww:
#   [{"id":<idx>,"active":<bool>,"windows":<n>}]  sorted by idx ascending
# We display the per-monitor index (.idx) as the workspace number — that's also
# what `focus-workspace <idx>` takes (see scripts/ws.sh). niri workspaces are
# dynamic & per-output, so eww.yuck renders the live list, not a fixed 1..10 set.
. "$(dirname "$0")/wm.sh"

emit() {
  local wins
  wins=$(niri msg --json windows 2>/dev/null)
  niri msg --json workspaces 2>/dev/null | jq -c --argjson wins "${wins:-[]}" '
    [ .[] | .id as $wid
      | { id:      .idx,
          active:  .is_focused,
          windows: ([ $wins[] | select(.workspace_id == $wid) ] | length) } ]
    | sort_by(.id)'
}

last=""
print_if_new() {
  local cur; cur=$(emit)
  if [ -n "$cur" ] && [ "$cur" != "$last" ]; then
    printf '%s\n' "$cur"; last="$cur"
  fi
}

print_if_new
# Newline-delimited JSON event stream; the first lines are a full snapshot, then
# deltas. We just re-emit on every event — cheap and always correct.
niri msg --json event-stream 2>/dev/null | while read -r _; do
  print_if_new
done
