#!/bin/bash
# run-smoke-tests.sh — Wrapper that runs smoke-test.js and alerts Slack on failure.
# Designed to run on the mkl production server (cron or post-deploy).
#
# Usage:
#   ./scripts/run-smoke-tests.sh                # run all, alert on fail
#   ./scripts/run-smoke-tests.sh --context=deploy  # tag alerts w/ "Post-Deploy"
#   ./scripts/run-smoke-tests.sh --quiet        # only output on failure (good for cron)
#
# Slack:
#   On failure → posts to SLACK_MKL_WEBHOOK (#mkl)
#   On pass    → no output unless --verbose

set -u

MKL_DIR="/var/www/html/mkl"
cd "$MKL_DIR" || { echo "ERR: cannot cd to $MKL_DIR"; exit 2; }

CONTEXT=""
QUIET=false
VERBOSE=false
for arg in "$@"; do
    case "$arg" in
        --context=*) CONTEXT="${arg#--context=}" ;;
        --quiet) QUIET=true ;;
        --verbose) VERBOSE=true ;;
    esac
done

LABEL="Smoke Test"
if [ -n "$CONTEXT" ]; then
    case "$CONTEXT" in
        deploy) LABEL="Post-Deploy Smoke Test" ;;
        cron)   LABEL="Scheduled Smoke Test" ;;
        *)      LABEL="Smoke Test ($CONTEXT)" ;;
    esac
fi

OUT=$(/usr/bin/node "$MKL_DIR/scripts/smoke-test.js" --json 2>&1)
RC=$?

if [ $RC -eq 0 ]; then
    [ "$VERBOSE" = true ] && echo "$OUT"
    [ "$QUIET" = true ] || echo "✓ $LABEL passed"
    exit 0
fi

# Parse failures from JSON (falls back to raw output if jq missing)
if command -v jq >/dev/null 2>&1; then
    FAIL_SUMMARY=$(echo "$OUT" | jq -r '.results[] | select(.status=="fail") | "• \(.name) — \(.error)"' 2>/dev/null)
    COUNTS=$(echo "$OUT" | jq -r '"\(.pass) passed, \(.fail) failed, \(.warn) warnings, \(.skip) skipped"' 2>/dev/null)
else
    FAIL_SUMMARY="(jq not installed — see full output below)"
    COUNTS=""
fi

# Print to stderr so cron sends email if MAILTO set
{
    echo "✗ $LABEL FAILED"
    echo "$COUNTS"
    echo "$FAIL_SUMMARY"
    [ "$VERBOSE" = true ] && echo "--- raw ---" && echo "$OUT"
} >&2

# Slack alert
WEBHOOK=$(grep '^SLACK_MKL_WEBHOOK=' "$MKL_DIR/.env" 2>/dev/null | cut -d= -f2- | tr -d '"\r' | head -1)
if [ -n "$WEBHOOK" ]; then
    HOST=$(hostname -s)
    PAYLOAD=$(cat <<EOF
{"text": "*${LABEL} FAILED* on \`${HOST}\`\n${COUNTS}\n\`\`\`${FAIL_SUMMARY}\`\`\`"}
EOF
)
    curl -s -X POST -H 'Content-Type: application/json' -d "$PAYLOAD" "$WEBHOOK" > /dev/null 2>&1 || true
fi

exit 1
