#!/bin/bash
# Kenship statusline (spec §9.2) — the guaranteed channel.
# 20s cache paired with refreshInterval:20 (worst-case idle staleness ~40s);
# 1.5s timeout; degrade to last-known-good; never stall or error the UI.
# Absence is legible: no credentials → say so (m0 "silently no Kenship" trap).
CRED="$HOME/.kenship/credentials"
CACHE="$HOME/.kenship/status_cache.json"

if [ ! -f "$CRED" ]; then
  echo "◍ not signed in — npx kenship install"
  exit 0
fi
TOKEN=$(sed -n 's/.*"token"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$CRED")
SERVER=$(sed -n 's/.*"server"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$CRED")

line=""
# GNU stat first (-c; BSD rejects it with nonzero so the fallback chain works).
# BSD-first was a trap: GNU `stat -f %m` prints "?" and EXITS 0, aborting the
# arithmetic below and blanking the badge forever (review catch).
mtime=$(stat -c %Y "$CACHE" 2>/dev/null || stat -f %m "$CACHE" 2>/dev/null)
case $mtime in ''|*[!0-9]*) mtime=0;; esac
if [ -f "$CACHE" ] && [ $(( $(date +%s) - mtime )) -lt 20 ]; then
  line=$(cat "$CACHE")
else
  json=$(curl -sf -m 1.5 -H "Authorization: Bearer $TOKEN" "$SERVER/api/status" 2>/dev/null)
  if [ -n "$json" ]; then
    unread=$(echo "$json" | sed -n 's/.*"unread_count":\([0-9]*\).*/\1/p')
    reqs=$(echo "$json" | sed -n 's/.*"request_count":\([0-9]*\).*/\1/p')
    if [ "${unread:-0}" -eq 0 ] && [ "${reqs:-0}" -eq 0 ]; then
      line="◍ inbox clear"
    else
      line="◍ ${unread} unread"
      [ "${reqs:-0}" -gt 0 ] && line="$line · ${reqs} request$([ "$reqs" -gt 1 ] && echo s)"
    fi
    echo "$line" > "$CACHE"
  else
    line=$(cat "$CACHE" 2>/dev/null)   # stale beats an error; nothing beats noise
  fi
fi

echo "$line"
exit 0
