#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

echo "======================================="
echo "Registry Verification Script"
echo "======================================="
echo ""

# 1. Check if registry container is running
print_status "Checking if kind-registry container is running..."
if docker ps | grep -q "kind-registry"; then
    print_success "Registry container is running"
    REGISTRY_STATUS=$(docker ps --filter "name=kind-registry" --format "{{.Status}}")
    echo "  Status: $REGISTRY_STATUS"
else
    print_error "Registry container is not running!"
    echo "  Run: ./kubernetes_restart.sh setup"
    exit 1
fi

# 2. Check if registry is accessible on localhost:5001
print_status "Checking if registry is accessible on localhost:5001..."
if curl -s http://localhost:5001/v2/_catalog > /dev/null 2>&1; then
    print_success "Registry is accessible"
    CATALOG=$(curl -s http://localhost:5001/v2/_catalog)
    echo "  Catalog: $CATALOG"
else
    print_error "Registry is not accessible on localhost:5001"
    exit 1
fi

# 3. Check if registry is connected to Kind network
print_status "Checking if registry is connected to Kind network..."
NETWORK_CHECK=$(docker inspect -f='{{json .NetworkSettings.Networks.kind}}' kind-registry 2>/dev/null)
if [ "$NETWORK_CHECK" != "null" ] && [ -n "$NETWORK_CHECK" ]; then
    print_success "Registry is connected to Kind network"
else
    print_warning "Registry is not connected to Kind network"
    print_status "Connecting registry to Kind network..."
    docker network connect "kind" "kind-registry"
    if [ $? -eq 0 ]; then
        print_success "Registry connected successfully"
    else
        print_error "Failed to connect registry to Kind network"
        exit 1
    fi
fi

# 4. Check if Kind cluster exists
print_status "Checking if Kind cluster exists..."
if kind get clusters | grep -q "bakery-ia-local"; then
    print_success "Kind cluster 'bakery-ia-local' exists"
else
    print_error "Kind cluster 'bakery-ia-local' not found"
    echo "  Run: ./kubernetes_restart.sh setup"
    exit 1
fi

# 5. Check if registry is documented in cluster
print_status "Checking if registry is documented in cluster..."
if kubectl get configmap -n kube-public local-registry-hosting &>/dev/null; then
    print_success "Registry is documented in cluster"
    REG_HOST=$(kubectl get configmap -n kube-public local-registry-hosting -o jsonpath='{.data.localRegistryHosting\.v1}' 2>/dev/null | grep -o 'host: "[^"]*"' | cut -d'"' -f2)
    echo "  Registry host: $REG_HOST"
else
    print_warning "Registry ConfigMap not found in cluster"
    print_status "Creating ConfigMap..."
    kubectl apply -f - <<EOF
apiVersion: v1
kind: ConfigMap
metadata:
  name: local-registry-hosting
  namespace: kube-public
data:
  localRegistryHosting.v1: |
    host: "localhost:5001"
    help: "https://kind.sigs.k8s.io/docs/user/local-registry/"
EOF
    if [ $? -eq 0 ]; then
        print_success "ConfigMap created successfully"
    fi
fi

# 6. Test pushing a test image
print_status "Testing image push to registry..."
print_status "Pulling busybox image..."
docker pull busybox:latest > /dev/null 2>&1

print_status "Tagging image for local registry..."
docker tag busybox:latest localhost:5001/test/busybox:latest

print_status "Pushing image to local registry..."
if docker push localhost:5001/test/busybox:latest > /dev/null 2>&1; then
    print_success "Successfully pushed test image to registry"
else
    print_error "Failed to push image to registry"
    exit 1
fi

print_status "Verifying image in registry catalog..."
CATALOG=$(curl -s http://localhost:5001/v2/_catalog)
if echo "$CATALOG" | grep -q "test/busybox"; then
    print_success "Test image found in registry catalog"
else
    print_warning "Test image not found in catalog, but push succeeded"
fi

# 7. Clean up test image
print_status "Cleaning up test images..."
docker rmi localhost:5001/test/busybox:latest > /dev/null 2>&1
docker rmi busybox:latest > /dev/null 2>&1

echo ""
echo "======================================="
print_success "Registry verification completed!"
echo "======================================="
echo ""
print_status "Summary:"
echo "  - Registry URL: localhost:5001"
echo "  - Registry container: kind-registry"
echo "  - Connected to Kind network: Yes"
echo "  - Accessible from host: Yes"
echo "  - Test push: Successful"
echo ""
print_status "Next steps:"
echo "  1. Ensure your Tiltfile has: default_registry('localhost:5001')"
echo "  2. Run: tilt up"
echo "  3. Images will be automatically pushed to localhost:5001/bakery/<service>"
echo ""
