#!/bin/bash

# Complete Cleanup Script for Kind + Colima + Skaffold Environment
# This script removes all resources, images, and configurations

set -e

echo "🧹 Complete Cleanup for Bakery IA Development Environment"
echo "========================================================"

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

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"
}

# Show what will be cleaned up
show_cleanup_plan() {
    echo ""
    print_warning "This script will clean up:"
    echo "  🚀 Skaffold deployments and resources"
    echo "  🐋 Docker images (bakery/* images)"
    echo "  ☸️  Kubernetes resources in bakery-ia namespace"
    echo "  🔒 cert-manager and TLS certificates"
    echo "  🌐 NGINX Ingress Controller"
    echo "  📦 Kind cluster (bakery-ia-local)"
    echo "  🐳 Colima Docker runtime"
    echo "  📝 Local certificate files"
    echo "  🗂️  /etc/hosts entries (optional)"
    echo ""
    read -p "❓ Do you want to continue? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_status "Cleanup cancelled"
        exit 0
    fi
}

# 1. Cleanup Skaffold deployments
cleanup_skaffold() {
    print_status "🚀 Cleaning up Skaffold deployments..."

    if command -v skaffold &> /dev/null; then
        # Try to delete with different profiles
        skaffold delete --profile=dev 2>/dev/null || true
        skaffold delete --profile=debug 2>/dev/null || true
        skaffold delete 2>/dev/null || true
        print_success "Skaffold deployments cleaned up"
    else
        print_warning "Skaffold not found, skipping Skaffold cleanup"
    fi
}

# 2. Cleanup Kubernetes resources
cleanup_kubernetes() {
    print_status "☸️  Cleaning up Kubernetes resources..."

    if command -v kubectl &> /dev/null && kubectl cluster-info &> /dev/null; then
        # Delete application namespace and all resources
        kubectl delete namespace bakery-ia --ignore-not-found=true

        # Delete cert-manager
        kubectl delete -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.2/cert-manager.yaml --ignore-not-found=true 2>/dev/null || true

        # Delete NGINX Ingress
        kubectl delete -f https://kind.sigs.k8s.io/examples/ingress/deploy-ingress-nginx.yaml --ignore-not-found=true 2>/dev/null || true

        # Delete any remaining cluster-wide resources
        kubectl delete clusterissuers --all --ignore-not-found=true 2>/dev/null || true
        kubectl delete clusterroles,clusterrolebindings -l app.kubernetes.io/name=cert-manager --ignore-not-found=true 2>/dev/null || true

        print_success "Kubernetes resources cleaned up"
    else
        print_warning "Kubectl not available or cluster not running, skipping Kubernetes cleanup"
    fi
}

# 3. Cleanup Docker images in Colima
cleanup_docker_images() {
    print_status "🐋 Cleaning up Docker images..."

    if command -v docker &> /dev/null && docker info &> /dev/null; then
        # Remove bakery-specific images
        print_status "Removing bakery/* images..."
        docker images --format "table {{.Repository}}:{{.Tag}}" | grep "^bakery/" | xargs -r docker rmi -f 2>/dev/null || true

        # Remove dangling images
        print_status "Removing dangling images..."
        docker image prune -f 2>/dev/null || true

        # Remove unused images (optional - uncomment if you want aggressive cleanup)
        # print_status "Removing unused images..."
        # docker image prune -a -f 2>/dev/null || true

        # Remove build cache
        print_status "Cleaning build cache..."
        docker builder prune -f 2>/dev/null || true

        print_success "Docker images cleaned up"
    else
        print_warning "Docker not available, skipping Docker cleanup"
    fi
}

# 4. Delete Kind cluster
cleanup_kind_cluster() {
    print_status "📦 Deleting Kind cluster..."

    if command -v kind &> /dev/null; then
        # Delete the specific cluster
        kind delete cluster --name bakery-ia-local 2>/dev/null || true

        # Also clean up any other bakery clusters
        kind get clusters 2>/dev/null | grep -E "(bakery|dev)" | xargs -r -I {} kind delete cluster --name {} 2>/dev/null || true

        print_success "Kind cluster deleted"
    else
        print_warning "Kind not found, skipping cluster cleanup"
    fi
}

# 5. Stop and clean Colima
cleanup_colima() {
    print_status "🐳 Cleaning up Colima..."

    if command -v colima &> /dev/null; then
        # Stop the specific profile
        colima stop --profile k8s-local 2>/dev/null || true

        # Delete the profile (removes all data)
        read -p "❓ Do you want to delete the Colima profile (removes all Docker data)? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            colima delete --profile k8s-local --force 2>/dev/null || true
            print_success "Colima profile deleted"
        else
            print_warning "Colima profile kept (stopped only)"
        fi
    else
        print_warning "Colima not found, skipping Colima cleanup"
    fi
}

# 6. Cleanup local files
cleanup_local_files() {
    print_status "📝 Cleaning up local files..."

    # Remove certificate files
    rm -f bakery-ia-ca.crt 2>/dev/null || true
    rm -f *.crt *.key 2>/dev/null || true

    # Remove any Skaffold cache (if exists)
    rm -rf ~/.skaffold/cache 2>/dev/null || true

    print_success "Local files cleaned up"
}

# 7. Cleanup /etc/hosts entries (optional)
cleanup_hosts_file() {
    print_status "🗂️  Cleaning up /etc/hosts entries..."

    if grep -q "bakery-ia.local" /etc/hosts 2>/dev/null; then
        read -p "❓ Remove bakery-ia entries from /etc/hosts? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            # Backup hosts file first
            sudo cp /etc/hosts /etc/hosts.backup.$(date +%Y%m%d_%H%M%S)

            # Remove entries
            sudo sed -i '' '/bakery-ia.local/d' /etc/hosts
            sudo sed -i '' '/api.bakery-ia.local/d' /etc/hosts
            sudo sed -i '' '/monitoring.bakery-ia.local/d' /etc/hosts

            print_success "Hosts file entries removed"
        else
            print_warning "Hosts file entries kept"
        fi
    else
        print_status "No bakery-ia entries found in /etc/hosts"
    fi
}

# 8. Show system status after cleanup
show_cleanup_summary() {
    echo ""
    print_success "🎉 Cleanup completed!"
    echo ""
    print_status "System status after cleanup:"

    # Check remaining Docker images
    if command -v docker &> /dev/null && docker info &> /dev/null; then
        local bakery_images=$(docker images --format "table {{.Repository}}:{{.Tag}}" | grep "^bakery/" | wc -l)
        echo "  🐋 Bakery Docker images remaining: $bakery_images"
    fi

    # Check Kind clusters
    if command -v kind &> /dev/null; then
        local clusters=$(kind get clusters 2>/dev/null | wc -l)
        echo "  📦 Kind clusters remaining: $clusters"
    fi

    # Check Colima status
    if command -v colima &> /dev/null; then
        local colima_status=$(colima status --profile k8s-local 2>/dev/null | head -n1 || echo "Not running")
        echo "  🐳 Colima k8s-local status: $colima_status"
    fi

    echo ""
    print_status "To restart development environment:"
    echo "  🚀 Quick start: ./skaffold-dev.sh"
    echo "  🔒 With HTTPS: ./setup-https.sh"
    echo "  🏗️  Manual: colima start --cpu 4 --memory 8 --disk 50 --runtime docker --profile k8s-local"
}

# Main execution
main() {
    show_cleanup_plan
    cleanup_skaffold
    cleanup_kubernetes
    cleanup_docker_images
    cleanup_kind_cluster
    cleanup_colima
    cleanup_local_files
    cleanup_hosts_file
    show_cleanup_summary
}

# Run main function
main "$@"