#!/usr/bin/env bash
# Push the board document to the artifact DB via a headless Haiku session — ONLY when it changed.
# Zero cost while the board is idle; ~one small Haiku call per change. Cron: every 10 min.
set -u
cd /home/nadil/Dev/fpl-tools || exit 1
DOC=scratch/board/board-doc.json
STAMP=scratch/board/.pushed-hash
URL="https://claude.ai/code/artifact/f6ece494-cffb-48b9-9d81-d5de6ab4842e"
[ -s "$DOC" ] || { echo "$(date -u +%FT%TZ) no doc"; exit 0; }
# ignore the 'updated' stamp when deciding whether anything changed
H=$(python3 -c "import json,hashlib,sys;d=json.load(open('$DOC'));d.pop('updated',None);print(hashlib.sha1(json.dumps(d,sort_keys=True).encode()).hexdigest())")
[ -f "$STAMP" ] && [ "$(cat "$STAMP")" = "$H" ] && { echo "$(date -u +%FT%TZ) unchanged $H"; exit 0; }
PROMPT="Call the Artifact tool exactly once with action=write_db, url=$URL, db_op=set, collection=board, doc_id=current, file_path=/home/nadil/Dev/fpl-tools/$DOC. Do nothing else. Do not read any other file. Reply with one word: done."
OUT=$(timeout 240 claude -p --no-session-persistence --model claude-haiku-4-5-20251001 \
      --allowedTools Artifact --permission-mode bypassPermissions --max-turns 3 "$PROMPT" < /dev/null 2>&1)
RC=$?
echo "$(date -u +%FT%TZ) rc=$RC hash=$H out=$(echo "$OUT" | tail -c 300 | tr '\n' ' ')"
[ $RC -eq 0 ] && echo "$H" > "$STAMP"
