#!/usr/bin/env bash
set -euo pipefail

RESTART=0
if [[ "${1:-}" == "--restart" ]]; then
  RESTART=1
fi

echo "=== QuantEngine 502 Diagnosis ==="
echo "Host: $(hostname)"
echo "Time: $(date -Is)"
echo

echo "=== Service Status ==="
systemctl is-active quantengine || true
systemctl is-active nginx || true
echo

echo "=== Active Deployment ==="
readlink -f /home/kjh2064/quantengine_active || true
ls -ld /home/kjh2064/quantengine_active || true
ls -1dt /home/kjh2064/deployments/quantengine_* 2>/dev/null | head -n 5 || true
echo

echo "=== Version Marker ==="
cat /home/kjh2064/quantengine_active/wwwroot/version.json 2>/dev/null || true
echo

echo "=== Local Port Checks ==="
ss -ltnp | grep -E ':(5000|443)\s' || true
echo

echo "=== Loopback HTTP Check ==="
curl -i --max-time 10 http://127.0.0.1:5000/ || true
echo

echo "=== Favicon Checks ==="
curl -i --max-time 10 http://127.0.0.1:5000/favicon.svg || true
curl -i --max-time 10 http://127.0.0.1:5000/favicon.png || true
echo

echo "=== Public HTTP Check ==="
curl -i --max-time 15 https://quant.taxbaik.com/ || true
echo

echo "=== Nginx Config Test ==="
nginx -t || true
echo

echo "=== Recent QuantEngine Logs ==="
journalctl -u quantengine -n 120 --no-pager || true
echo

if [[ "$RESTART" -eq 1 ]]; then
  echo "=== Restarting Services ==="
  systemctl restart quantengine
  systemctl reload nginx
  sleep 2
  echo
  echo "=== Post-Restart Status ==="
  systemctl is-active quantengine || true
  systemctl is-active nginx || true
  echo
  echo "=== Post-Restart Loopback Check ==="
  curl -i --max-time 10 http://127.0.0.1:5000/ || true
  echo
  echo "=== Public Endpoint Check ==="
  curl -i --max-time 15 https://quant.taxbaik.com/ || true
fi

echo "=== Next Step ==="
echo "If http://127.0.0.1:5000/ fails, the problem is inside quantengine."
echo "If localhost works but the public domain still fails, inspect nginx/proxy config only for quant.taxbaik.com."
