#!/bin/bash
# Script to debug Redis/Valkey connectivity in production

set -e

NAMESPACE="${1:-towerops}"
# Get a running pod (not terminating)
POD_NAME=$(kubectl get pods -n "$NAMESPACE" -l app=towerops --field-selector=status.phase=Running -o jsonpath='{.items[0].metadata.name}' 2>/dev/null)

if [ -z "$POD_NAME" ]; then
  echo "Error: No running towerops pods found in namespace $NAMESPACE"
  exit 1
fi

echo "=== Debugging Redis/Valkey in pod: $POD_NAME ==="
echo

echo "1. Checking if both containers are running:"
kubectl get pod "$POD_NAME" -n "$NAMESPACE" -o jsonpath='{range .status.containerStatuses[*]}{.name}{"\t"}{.ready}{"\t"}{.state}{"\n"}{end}'
echo

echo "2. Checking Valkey container logs:"
kubectl logs "$POD_NAME" -n "$NAMESPACE" -c valkey --tail=20
echo

echo "3. Testing Valkey connectivity from towerops container:"
kubectl exec "$POD_NAME" -n "$NAMESPACE" -c towerops -- sh -c 'nc -zv 127.0.0.1 6379 2>&1 || echo "Cannot connect to Redis at 127.0.0.1:6379"'
echo

echo "4. Checking Redis environment variables:"
kubectl exec "$POD_NAME" -n "$NAMESPACE" -c towerops -- env | grep -i redis
echo

echo "5. Checking if Valkey is accepting connections:"
kubectl exec "$POD_NAME" -n "$NAMESPACE" -c valkey -- valkey-cli ping 2>&1 || echo "Valkey ping failed"
echo

echo "=== Debug complete ==="
echo
echo "If Valkey is not running, try deleting the pod to restart it:"
echo "  kubectl delete pod $POD_NAME -n $NAMESPACE"
