#!/bin/bash

# run-oneof-debug-tests.sh - Run the oneOf debugging e2e tests
# This script will run our comprehensive debugging tests to help identify the root cause
# of the IBM VPC oneOf constraint errors

set -euo pipefail

# Configuration
KUBECONFIG_PATH="${KUBECONFIG_PATH:-./kubeconfig}"
NAMESPACE="${NAMESPACE:-karpenter}"

echo "=== Karpenter IBM OneOf Debugging Test Runner ==="
echo "Kubeconfig: $KUBECONFIG_PATH"
echo "Namespace: $NAMESPACE"
echo

# Check prerequisites
if [[ ! -f "$KUBECONFIG_PATH" ]]; then
    echo "ERROR: Kubeconfig not found at $KUBECONFIG_PATH"
    exit 1
fi

if ! kubectl --kubeconfig="$KUBECONFIG_PATH" cluster-info >/dev/null 2>&1; then
    echo "ERROR: Cannot connect to Kubernetes cluster"
    exit 1
fi

# Build the latest version
echo "Building latest karpenter-ibm-controller..."
make build

echo "=== Running OneOf Debugging E2E Tests ==="
echo "These tests will:"
echo "  1. Test static instance type (should work)"
echo "  2. Test dynamic instance type (likely to fail with oneOf error)"
echo "  3. Collect comprehensive debugging information"
echo

# Set environment variables for tests
export KUBECONFIG="$KUBECONFIG_PATH"
export E2E_NAMESPACE="$NAMESPACE"

# Run the specific oneOf debugging tests
echo "Starting OneOf debugging tests..."
go test -v -timeout=15m -tags=e2e ./test/e2e -run "TestOneOfDebugging"

echo
echo "=== OneOf Debugging Tests Complete ==="
echo "Check the test output above for:"
echo "  - Detailed JSON payloads sent to IBM VPC API"
echo "  - OneOf discriminator field analysis"
echo "  - Full error messages from IBM VPC"
echo "  - Comparison between static vs dynamic instance type selection"
echo
echo "Next steps:"
echo "  1. Review the collected debugging information"
echo "  2. Check Karpenter controller logs: kubectl logs -n $NAMESPACE -l app.kubernetes.io/name=karpenter-ibm --tail=100"
echo "  3. Apply any fixes based on the debugging output"