#!/bin/bash
# Telemetry failure alert - called when telemetry health check fails

ALERT_FILE="/home/ccuser/shared/kpi/telemetry-alerts.log"
TELEMETRY_FILE="/home/ccuser/shared/kpi/marketing-telemetry.json"

echo "=========================================" >> "$ALERT_FILE"
echo "TELEMETRY FAILURE ALERT - $(date)" >> "$ALERT_FILE"
echo "=========================================" >> "$ALERT_FILE"

# Get failure details
if [ -f "$TELEMETRY_FILE" ]; then
    jq '.' "$TELEMETRY_FILE" >> "$ALERT_FILE" 2>/dev/null || echo "Could not read telemetry file" >> "$ALERT_FILE"
else
    echo "Telemetry file missing: $TELEMETRY_FILE" >> "$ALERT_FILE"
fi

echo "" >> "$ALERT_FILE"

# Also alert via fleet system (if available)
if command -v node &> /dev/null; then
    node /home/ccuser/shared/scripts/fleet-cli.js alert sentinel "Telemetry pipeline failure - check /home/ccuser/shared/kpi/telemetry-alerts.log" 2>/dev/null || true
fi
