#!/bin/bash
# claude-login.sh - Authenticate Claude CLI in a claudebox pod
# Usage: ./scripts/claude-login.sh <project>
# Example: ./scripts/claude-login.sh pantheon

set -e

# Check for project argument
if [ -z "$1" ]; then
    echo "Usage: $0 <project>"
    echo ""
    echo "Available projects:"
    KUBECONFIG=~/.kube/orchard9-k3sf.yaml kubectl get pods -n rdev -l app.kubernetes.io/part-of=rdev \
        --no-headers -o custom-columns=":metadata.labels.rdev\.orchard9\.ai/project" 2>/dev/null | grep -v "^$" | sort -u
    echo ""
    echo "Example: $0 pantheon"
    exit 1
fi

PROJECT="$1"
POD="claudebox-${PROJECT}-0"
NAMESPACE="rdev"

# Verify kubeconfig
export KUBECONFIG=~/.kube/orchard9-k3sf.yaml

# Check if pod exists and is running
echo "Checking pod status..."
STATUS=$(kubectl get pod "$POD" -n "$NAMESPACE" -o jsonpath='{.status.phase}' 2>/dev/null || echo "NotFound")

if [ "$STATUS" != "Running" ]; then
    echo "Error: Pod $POD is not running (status: $STATUS)"
    echo ""
    echo "Available pods:"
    kubectl get pods -n "$NAMESPACE" -l app.kubernetes.io/part-of=rdev
    exit 1
fi

echo ""
echo "=== Claude Login for $PROJECT ==="
echo ""
echo "This will open an interactive session to authenticate Claude."
echo "You'll see a URL - open it in your browser to complete authentication."
echo ""
echo "Press Ctrl+C to cancel, or Enter to continue..."
read

# Run claude interactively (will prompt for auth if needed)
echo "Starting Claude..."
kubectl exec -it "$POD" -n "$NAMESPACE" -c claudebox -- claude

echo ""
echo "=== Authentication Complete ==="
echo ""
echo "Verifying Claude is authenticated..."
kubectl exec "$POD" -n "$NAMESPACE" -c claudebox -- claude --version

echo ""
echo "Claude is now authenticated in $POD"
echo "You can run commands via the API or directly:"
echo "  kubectl exec -it $POD -n $NAMESPACE -- claude"
