#!/bin/bash
# Sales Prospector Monitor

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="$SCRIPT_DIR/logs/monitor-$(date +%Y%m%d).log"
STATE_FILE="$SCRIPT_DIR/state/prospector-state.json"

echo "=== Sales Prospector Monitor ($(date)) ==="
echo ""

# Check if running
if [[ -f "$SCRIPT_DIR/run.pid" ]]; then
    PID=$(cat "$SCRIPT_DIR/run.pid")
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "✅ RUNNING - PID: $PID"
        ps -p "$PID" -o pid,etime,args | tail -1
    else
        echo "❌ NOT RUNNING (PID file exists but process dead)"
    fi
else
    echo "❌ NOT RUNNING (No PID file)"
fi

echo ""
echo "=== Recent Activity ==="
tail -10 "$SCRIPT_DIR/logs/prospector-$(date +%Y%m%d).log" 2>/dev/null || echo "No log"

echo ""
echo "=== State ==="
if [[ -f "$STATE_FILE" ]]; then
    jq '{currentMetroIndex, leadsFound: (.leadsFound // 0)}' "$STATE_FILE" 2>/dev/null || cat "$STATE_FILE"
else
    echo "No state file"
fi

echo ""
echo "=== CRM Leads Today ==="
TWENTY_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5M2FmNGFmNS0zZWQ0LTQ1ZDMtOWE5Zi01MDMzZjc3YTY3MjMiLCJ0eXBlIjoiQVBJX0tFWSIsIndvcmtzcGFjZUlkIjoiOTNhZjRhZjUtM2VkNC00NWQzLTlhOWYtNTAzM2Y3N2E2NzIzIiwiaWF0IjoxNzczMzI4NDQzLCJleHAiOjE4MDQ3ODE2NDIsImp0aSI6IjIwZjEyYzkwLTRkMDctNGJmNi1iMzk3LTZjNmU3MzlmMThjOCJ9.zeM5NvwCSGEcz99m2LYtgb0sVD6WUXcCF7SwonFg930"
curl -s "https://salesforce.hoaledgeriq.com/rest/notes" \
    -H "Authorization: Bearer $TWENTY_TOKEN" 2>/dev/null | \
    jq '[.data.notes[] | select(.title | contains("🎯"))] | length' 2>/dev/null || echo "0"

echo ""
echo "=== Complete ==="
