#!/bin/bash
# kimi-mention-watcher.sh — Watches for @KimiClaw mentions in Gitea
# Polls notifications, finds unread mentions, dispatches response via OpenClaw

set -euo pipefail

KIMI_TOKEN=$(cat /Users/apayne/.timmy/kimi_gitea_token | tr -d '[:space:]')
BASE="http://100.126.61.75:3000/api/v1"
LOG="/tmp/kimi-mentions.log"
PROCESSED="/tmp/kimi-mentions-processed.txt"

touch "$PROCESSED"

log() { echo "[$(date '+%H:%M:%S')] $*" | tee -a "$LOG"; }

# Get unread notifications for KimiClaw
notifications=$(curl -s -H "Authorization: token $KIMI_TOKEN" \
  "$BASE/notifications?status-types=unread&limit=20" 2>/dev/null)

if [ -z "$notifications" ] || [ "$notifications" = "null" ] || [ "$notifications" = "[]" ]; then
  exit 0
fi

echo "$notifications" | python3 -c "
import json, sys
notifs = json.load(sys.stdin)
for n in notifs:
    subject = n.get('subject', {})
    repo = n.get('repository', {}).get('full_name', '')
    title = subject.get('title', '')
    url = subject.get('latest_comment_url', '') or subject.get('url', '')
    nid = n.get('id', '')
    print(f'{nid}|{repo}|{title}|{url}')
" 2>/dev/null | while IFS='|' read -r nid repo title url; do
  [ -z "$nid" ] && continue
  
  # Skip if already processed
  grep -q "^$nid$" "$PROCESSED" && continue
  
  log "MENTION: $repo — $title"
  
  # Get the actual comment content
  if [ -n "$url" ]; then
    comment_body=$(curl -s -H "Authorization: token $KIMI_TOKEN" "$url" 2>/dev/null | \
      python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('body','')[:500])" 2>/dev/null)
  else
    comment_body="(no comment body available)"
  fi
  
  # Extract issue number from URL
  issue_num=$(echo "$url" | grep -o '/issues/[0-9]*' | grep -o '[0-9]*' || echo "")
  comment_id=$(echo "$url" | grep -o '/comments/[0-9]*' | grep -o '[0-9]*' || echo "")
  
  # Dispatch to OpenClaw for response
  prompt="You are KimiClaw, Timmy's apprentice on Gitea. Someone mentioned you.

CONTEXT:
Repo: $repo
Issue/PR: $title
Comment: $comment_body

YOUR TASK:
Respond helpfully to the mention. If they asked a question, answer it.
If they asked you to do something, do it or explain what you need.

Post your response as a comment on the issue.
Gitea API: $BASE, use token from /Users/apayne/.timmy/kimi_gitea_token
Repo: $repo, Issue: $issue_num"

  openclaw agent --agent main --message "$prompt" > /dev/null 2>&1 &
  
  # Mark notification as read
  curl -s -X PATCH -H "Authorization: token $KIMI_TOKEN" \
    "$BASE/notifications/threads/$nid" > /dev/null 2>&1
  
  # Mark as processed
  echo "$nid" >> "$PROCESSED"
  
  log "DISPATCHED response for notification $nid"
done

log "Mention check complete."
