#!/bin/bash
# scripts/pm2-heartbeat.sh
# ═══════════════════════════════════════════════════════════
# 💓 Heartbeat: هر 30 دقیقه تأیید می‌کند که سیستم کار می‌کند
# اگر این پیام نرسد = مشکلی در کل سرور وجود دارد
# ═══════════════════════════════════════════════════════════

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
ENV_FILE="$PROJECT_DIR/config/telegram.env"

source "$ENV_FILE"

# جمع‌آوری اطلاعات
HOSTNAME=$(hostname 2>/dev/null || echo "unknown")
PROC_INFO=$(pm2 jlist 2>/dev/null | node -e "
    const data = JSON.parse(require('fs').readFileSync('/dev/stdin','utf8'));
    const proc = data.find(p => p.name === '${PM2_APP_NAME}');
    if (!proc) { console.log('❌ Not Found'); process.exit(0); }
    const mem = Math.round((proc.monit?.memory || 0) / 1024 / 1024);
    const upMs = Date.now() - (proc.pm2_env?.pm_uptime || Date.now());
    const h = Math.floor(upMs/3600000);
    const m = Math.floor((upMs%3600000)/60000);
    console.log('✅ ' + proc.pm2_env.status + ' | ' + mem + 'MB | ' + proc.pm2_env.restart_time + ' restarts | up ' + h + 'h ' + m + 'm');
" 2>/dev/null || echo "❓ Cannot read")

DISK=$(df -h / | awk 'NR==2{print $3 "/" $2 " (" $5 ")"}' 2>/dev/null || echo "N/A")
MEM=$(free -m | awk '/^Mem:/{printf "%dMB/%dMB (%.0f%%)", $3, $2, ($3/$2)*100}' 2>/dev/null || echo "N/A")
LOAD=$(uptime | awk -F'load average:' '{print $2}' | xargs 2>/dev/null || echo "N/A")

curl -s --max-time 10 \
    -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
    -d "chat_id=${TELEGRAM_CHAT_ID}" \
    -d "parse_mode=HTML" \
    -d "text=💓 <b>Heartbeat — سیستم فعال است</b>

🖥 سرور: <code>${HOSTNAME}</code>
⏰ $(TZ='Europe/Berlin' date '+%Y-%m-%d %H:%M:%S %Z')

📋 <b>اسکرپر:</b> ${PROC_INFO}

📊 <b>سیستم:</b>
├ RAM: ${MEM}
├ Disk: ${DISK}
└ Load: ${LOAD}" \
    > /dev/null 2>&1
