#!/bin/zsh
#
# Alert Processor for Security Monitors
# Reads from alerts.queue and delivers via Telegram
# This script is called by the monitors to process pending alerts
#

QUEUE_FILE="/Users/mattbruce/.openclaw/workspace/scripts/security-monitors/state/alerts.queue"
LOG_FILE="/Users/mattbruce/.openclaw/workspace/scripts/security-monitors/logs/alert-processor.log"
PROCESSED_FILE="/Users/mattbruce/.openclaw/workspace/scripts/security-monitors/state/alerts-processed"

# Create directories
mkdir -p "$(dirname $LOG_FILE)" "$(dirname $QUEUE_FILE)"

# Timestamp helper
timestamp() {
  date '+%Y-%m-%d %H:%M:%S %Z'
}

# Log to file
log() {
  echo "[$(timestamp)] $1" >> "$LOG_FILE"
}

# Process a single alert
process_alert() {
  local line="$1"
  
  # Parse the queue entry
  local time_part=$(echo "$line" | cut -d'|' -f1 | tr -d ' ')
  local level=$(echo "$line" | cut -d'|' -f2 | tr -d ' ')
  local type=$(echo "$line" | cut -d'|' -f3 | tr -d ' ')
  local message=$(echo "$line" | cut -d'|' -f4-)
  
  # Format the message for Telegram
  local formatted_msg="🤖 *OpenClaw Security Alert*

*Type:* ${type:-GENERAL}
*Level:* ${level:-INFO}
*Time:* $time_part

$message"
  
  # Write to processed log
  echo "$(timestamp) | PROCESSED | $line" >> "$PROCESSED_FILE"
  
  # Output for Telegram delivery
  # The calling agent can pick this up
  echo "$formatted_msg"
  
  log "Processed $level alert: ${message:0:50}..."
}

# Main processing
main() {
  if [[ ! -f "$QUEUE_FILE" ]]; then
    # No alerts pending
    exit 0
  fi
  
  # Check if queue has content
  if [[ ! -s "$QUEUE_FILE" ]]; then
    exit 0
  fi
  
  log "Processing alert queue..."
  
  # Process each line
  local alerts_processed=0
  while IFS= read -r line; do
    [[ -z "$line" ]] && continue
    process_alert "$line"
    alerts_processed=$((alerts_processed + 1))
  done < "$QUEUE_FILE"
  
  # Clear the queue after processing
  > "$QUEUE_FILE"
  
  log "Processed $alerts_processed alerts"
}

# Run main function
main "$@"
