#!/bin/bash
# Collect health data for dashboard API
STATE_FILE="/home/ashraffarid2010/halavoice.store/monitor-state.json"

evo_http=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "http://127.0.0.1:4500/" 2>/dev/null || echo "000")
hala_http=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "http://127.0.0.1:5003/" 2>/dev/null || echo "000")

if [ "$evo_http" = "200" ]; then
  inst_state=$(curl -s -H "apiKey: 429683C4C977415CAAFCCE10F7D57E11" --connect-timeout 5 "http://127.0.0.1:4500/instance/connectionState/wa_f31ba15c-81cd-46d2-a2e5-9b9f88114bf5_1782087848147" 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('instance',{}).get('state','unknown'))" 2>/dev/null || echo "unknown")
else
  inst_state="unknown"
fi

DB_URL=$(grep '^DATABASE_URL=' /home/ashraffarid2010/halavoice.store/.env | cut -d= -f2-)
last_msg=$(psql "$DB_URL" -t -A -c "SELECT MAX(message_timestamp)::text FROM whatsapp_messages WHERE session_id='wa_f31ba15c-81cd-46d2-a2e5-9b9f88114bf5_1782087848147';" 2>/dev/null || echo "unknown")
msg_count=$(psql "$DB_URL" -t -A -c "SELECT COUNT(*) FROM whatsapp_messages;" 2>/dev/null || echo "0")

cat <<EOF
{
  "evolution_api": "$evo_http",
  "instance_status": "$inst_state",
  "halavoice_app": "$hala_http",
  "messages_synced": $msg_count,
  "last_message_at": "$last_msg",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF
