#!/usr/bin/env bash
# Notification bridge: tiramisu (headless daemon)  ->  eww UI.
# Replaces mako. Keeps a JSON history, drives the control-center list and a
# top-right popup toast, and respects a Do-not-Disturb flag.
#
#   listen        run tiramisu and feed notifications into eww   (the daemon)
#   dismiss <id>  drop one notification from the history
#   clear         empty the history
#   refresh       re-push the current history into eww (after `eww reload`)
#   popup-close   close the current toast now
#   dnd-toggle    flip Do-not-Disturb
#   dnd-get       print the DnD state (for the eww poll)
set -u

CACHE="$HOME/.cache/eww"
STORE="$CACHE/notifications.json"
DND="$CACHE/dnd"
PTIMER="$CACHE/.notif-popup-timer"
MAX=50            # keep at most this many in history
POPUP_SECS=5      # auto-dismiss the toast after N seconds

mkdir -p "$CACHE"
[ -f "$STORE" ] || echo '[]'    > "$STORE"
[ -f "$DND"   ] || echo 'false' > "$DND"

push() { eww update notifications="$(cat "$STORE")" 2>/dev/null; }

show_popup() {   # $1 = a single notification JSON object
  eww update popup="$1" 2>/dev/null
  eww open notification-popup 2>/dev/null
  [ -f "$PTIMER" ] && kill "$(cat "$PTIMER")" 2>/dev/null
  ( sleep "$POPUP_SECS"; eww close notification-popup 2>/dev/null; rm -f "$PTIMER" ) &
  echo $! > "$PTIMER"
}

case "${1:-listen}" in
  listen)
    command -v tiramisu >/dev/null 2>&1 || { echo "tiramisu not installed" >&2; exit 1; }
    push   # restore whatever is already in the history on startup
    # tiramisu -j emits one sanitized JSON object per notification.
    # NOTE: field names (.source/.summary/.body/.id) are verified against a
    # real `tiramisu -j` probe — adjust here if the probe shows other keys.
    tiramisu -j | while IFS= read -r line; do
      [ -z "$line" ] && continue
      obj=$(jq -c --arg t "$(date '+%H:%M')" '
        { id:      ((.id // "0")|tostring),
          app:     (.source // .app_name // .["app-name"] // "Notification"),
          summary: (.summary // ""),
          body:    (.body // ""),
          time:    $t }' <<<"$line" 2>/dev/null) || continue
      [ -z "$obj" ] && continue
      tmp=$(jq -c --argjson n "$obj" --argjson max "$MAX" '[$n] + . | .[0:$max]' "$STORE") || continue
      printf '%s' "$tmp" > "$STORE"
      push
      [ "$(cat "$DND" 2>/dev/null)" != "true" ] && show_popup "$obj"
    done
    ;;
  dismiss)
    tmp=$(jq -c --arg id "${2:-}" 'map(select((.id|tostring) != $id))' "$STORE") && printf '%s' "$tmp" > "$STORE"
    push
    ;;
  clear)
    echo '[]' > "$STORE"; push
    ;;
  refresh)
    push
    ;;
  popup-close)
    [ -f "$PTIMER" ] && kill "$(cat "$PTIMER")" 2>/dev/null
    rm -f "$PTIMER"
    eww close notification-popup 2>/dev/null
    ;;
  dnd-toggle)
    [ "$(cat "$DND" 2>/dev/null)" = "true" ] && echo false > "$DND" || echo true > "$DND"
    ;;
  dnd-get)
    cat "$DND" 2>/dev/null || echo false
    ;;
esac
