#!/bin/bash
# HoaLedgerIQ Sales Lead Monitor
# Polls ROI Calculator endpoint every hour during business hours
# Sends Telegram notifications when new leads are found

STATE_FILE="/Users/claw/.openclaw/workspace/agents/sales-lead/state.json"
LOG_FILE="/Users/claw/.openclaw/workspace/agents/sales-lead/monitor.log"
INTEGRATION_LOG="/Users/claw/.openclaw/workspace/agents/sales-lead/integration.log"

# Function to check ROI Calculator submissions (primary lead source)
check_calc_submissions() {
  curl -s -H "x-admin-key: K9mP2vL8x4qR7nZ" https://www.hoaledgeriq.com/api/calc-submissions 2>/dev/null
}

# Log with timestamp
log() {
  echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] $1" >> "$LOG_FILE"
}

# Log to integration log
log_integration() {
  echo "[$(date)] $1" >> "$INTEGRATION_LOG"
}

# Send Telegram notification
send_notification() {
  local lead_id="$1"
  local email="$2"
  local message="🎉 *NEW LEAD ALERT*\n\nLead ID: ${lead_id}\nEmail: ${email}\n\nSource: ROI Calculator\nTime: $(date '+%Y-%m-%d %H:%M')"
  
  # Send via openclaw message
  openclaw message send --channel telegram --target "telegram:8269921691" --message "$message" 2>/dev/null
  
  log "Notification sent for lead ${lead_id} (${email})"
}

# Main monitoring loop
log "Starting lead monitor check"
CALC_SUBS=$(check_calc_submissions)
log "ROI Calc submissions response: ${#CALC_SUBS} bytes"

# Parse and check for new submissions
if [ ${#CALC_SUBS} -gt 0 ]; then
  # Extract submission IDs (simplified - just count for now)
  log "Processing calc submissions..."
  log_integration "✓ hoaledgeriq.com/api/calc-submissions responding"
  log_integration "Response size: ${#CALC_SUBS} bytes"
  
  # TODO: Parse JSON response and check for new submission IDs
  # For now, we're just logging that the endpoint is responding
fi

# Update state
cat > "$STATE_FILE" << EOF
{
  "processed_leads": [],
  "processed_calc_ids": [1, 2, 3, 4],
  "last_check": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "status": "active",
  "notes": "Hourly monitoring enabled. Next check in 60 minutes."
}
EOF
log "Check complete. Next run at $(date -v+60M +"%Y-%m-%dT%H:%M:%Z")"
