#!/bin/bash
# Check for new Kitt contacts and notify

LOG_FILE="/home/clawd/workspace/data/kitt-contacts.jsonl"
LAST_FILE="/home/clawd/workspace/data/.kitt-contacts-last"

if [ ! -f "$LOG_FILE" ]; then
  exit 0
fi

# Get current line count
CURRENT=$(wc -l < "$LOG_FILE")

# Get last processed count
if [ -f "$LAST_FILE" ]; then
  LAST=$(cat "$LAST_FILE")
else
  LAST=0
fi

# If new lines, process them
if [ "$CURRENT" -gt "$LAST" ]; then
  # Get new lines
  tail -n +$((LAST + 1)) "$LOG_FILE" | while read -r line; do
    email=$(echo "$line" | grep -oP '"email"\s*:\s*"\K[^"]+')
    timestamp=$(echo "$line" | grep -oP '"timestamp"\s*:\s*"\K[^"]+')
    
    if [ -n "$email" ]; then
      # Write to a notification queue file
      echo "$email|$timestamp" >> /home/clawd/workspace/data/kitt-notify-queue.txt
    fi
  done
  
  # Update last count
  echo "$CURRENT" > "$LAST_FILE"
fi
