#!/bin/bash
# Verify rdev deployment

set -e

# Ensure kubeconfig is set
if [[ -z "$KUBECONFIG" ]]; then
    echo "Error: KUBECONFIG not set"
    echo "Run: export KUBECONFIG=~/.kube/orchard9-k3sf.yaml"
    exit 1
fi

echo "=== rdev Deployment Verification ==="
echo ""

# Check namespace
echo "1. Checking namespace..."
if kubectl get namespace rdev > /dev/null 2>&1; then
    echo "   ✅ Namespace 'rdev' exists"
else
    echo "   ❌ Namespace 'rdev' not found"
    exit 1
fi

# Check PVC
echo ""
echo "2. Checking PVC..."
PVC_STATUS=$(kubectl get pvc claudebox-workspace -n rdev -o jsonpath='{.status.phase}' 2>/dev/null || echo "NotFound")
if [[ "$PVC_STATUS" == "Bound" ]]; then
    echo "   ✅ PVC 'claudebox-workspace' is Bound"
else
    echo "   ⚠️  PVC status: $PVC_STATUS"
fi

# Check secret
echo ""
echo "3. Checking credentials secret..."
if kubectl get secret claude-credentials -n rdev > /dev/null 2>&1; then
    echo "   ✅ Secret 'claude-credentials' exists"
else
    echo "   ❌ Secret 'claude-credentials' not found"
    echo "      Run: ./scripts/create-credentials-secret.sh"
fi

# Check pod
echo ""
echo "4. Checking claudebox pod..."
POD_STATUS=$(kubectl get pod claudebox-0 -n rdev -o jsonpath='{.status.phase}' 2>/dev/null || echo "NotFound")
if [[ "$POD_STATUS" == "Running" ]]; then
    echo "   ✅ Pod 'claudebox-0' is Running"
else
    echo "   ❌ Pod status: $POD_STATUS"
    if [[ "$POD_STATUS" != "NotFound" ]]; then
        echo ""
        echo "   Pod events:"
        kubectl describe pod claudebox-0 -n rdev | grep -A 10 "Events:" | head -15
    fi
    exit 1
fi

# Check Claude CLI
echo ""
echo "5. Checking Claude CLI..."
CLAUDE_VERSION=$(kubectl exec -n rdev claudebox-0 -- claude --version 2>/dev/null || echo "Error")
if [[ "$CLAUDE_VERSION" != "Error" ]]; then
    echo "   ✅ Claude CLI: $CLAUDE_VERSION"
else
    echo "   ❌ Claude CLI not responding"
    exit 1
fi

# Test Claude (optional)
echo ""
echo "6. Testing Claude response..."
echo "   Running: claude \"respond with only the word: working\""
RESPONSE=$(kubectl exec -n rdev claudebox-0 -- claude "respond with only the word: working" --print 2>/dev/null | head -5 || echo "Error")
if [[ "$RESPONSE" != "Error" ]]; then
    echo "   ✅ Claude responded:"
    echo "   $RESPONSE"
else
    echo "   ⚠️  Claude did not respond (may need authentication)"
    echo "      Check credentials: kubectl exec -n rdev claudebox-0 -- ls -la /root/.claude/"
fi

echo ""
echo "=== Verification Complete ==="
