.PHONY: help check-deps create-cluster delete-cluster install upgrade uninstall status logs port-forward test clean

# Load environment variables from .env file if it exists
-include .env
export

# Variables
CLUSTER_NAME := ftrack-test
NAMESPACE := ftrack
RELEASE_NAME := ftrack
KIND_CONFIG := kind-config.yaml
VALUES_FILE := values-test.yaml
KUBE_CONTEXT := kind-$(CLUSTER_NAME)

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

help: ## Show this help message
	@echo "$(BLUE)ftrack Helm Chart Testing - Available targets:$(NC)"
	@echo ""
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "  $(GREEN)%-20s$(NC) %s\n", $$1, $$2}'
	@echo ""

check-deps: ## Check if all required dependencies are installed
	@echo "$(BLUE)Checking dependencies...$(NC)"
	@command -v docker >/dev/null 2>&1 || { echo "$(RED)✗ Docker is not installed$(NC)"; exit 1; }
	@echo "$(GREEN)✓ Docker is installed$(NC)"
	@docker info >/dev/null 2>&1 || { echo "$(RED)✗ Docker is not running$(NC)"; exit 1; }
	@echo "$(GREEN)✓ Docker is running$(NC)"
	@command -v kubectl >/dev/null 2>&1 || { echo "$(RED)✗ kubectl is not installed$(NC)"; exit 1; }
	@echo "$(GREEN)✓ kubectl is installed$(NC)"
	@command -v helm >/dev/null 2>&1 || { echo "$(RED)✗ Helm is not installed$(NC)"; exit 1; }
	@echo "$(GREEN)✓ Helm is installed$(NC)"
	@command -v kind >/dev/null 2>&1 || { echo "$(RED)✗ Kind is not installed$(NC)"; exit 1; }
	@echo "$(GREEN)✓ Kind is installed$(NC)"
	@echo "$(GREEN)All dependencies are satisfied!$(NC)"

create-cluster: check-deps ## Create a new Kind cluster for testing
	@echo "$(BLUE)Creating Kind cluster: $(CLUSTER_NAME)...$(NC)"
	@if kind get clusters | grep -q "^$(CLUSTER_NAME)$$"; then \
		echo "$(YELLOW)Cluster $(CLUSTER_NAME) already exists$(NC)"; \
	else \
		mkdir -p /tmp/ftrack-data && \
		kind create cluster --name $(CLUSTER_NAME) --config $(KIND_CONFIG) && \
		echo "$(GREEN)✓ Cluster created successfully$(NC)" && \
		kubectl cluster-info --context $(KUBE_CONTEXT); \
	fi
	@$(MAKE) fix-permissions

delete-cluster: ## Delete the Kind cluster
	@echo "$(BLUE)Deleting Kind cluster: $(CLUSTER_NAME)...$(NC)"
	@if kind get clusters | grep -q "^$(CLUSTER_NAME)$$"; then \
		kind delete cluster --name $(CLUSTER_NAME) && \
		echo "$(GREEN)✓ Cluster deleted successfully$(NC)"; \
	else \
		echo "$(YELLOW)Cluster $(CLUSTER_NAME) does not exist$(NC)"; \
	fi
	@rm -rf /tmp/ftrack-data

fix-permissions: ## Fix persistent volume permissions on Kind node
	@echo "$(BLUE)Setting correct permissions for persistent volume...$(NC)"
	@PV_PATH=$$(yq e '.localPersistentVolume.path' $(VALUES_FILE) 2>/dev/null || echo "/ftrack/data"); \
	docker exec $(CLUSTER_NAME)-control-plane chown -R 500:500 $$PV_PATH && \
	docker exec $(CLUSTER_NAME)-control-plane chmod -R 775 $$PV_PATH && \
	echo "$(GREEN)✓ Permissions set for $$PV_PATH (UID:GID 500:500)$(NC)"

verify-cluster: ## Verify the cluster is running and accessible
	@echo "$(BLUE)Verifying cluster...$(NC)"
	@kubectl cluster-info --context $(KUBE_CONTEXT)
	@kubectl get nodes --context $(KUBE_CONTEXT)

create-namespace: ## Create the ftrack namespace
	@echo "$(BLUE)Creating namespace: $(NAMESPACE)...$(NC)"
	@kubectl --context $(KUBE_CONTEXT) create namespace $(NAMESPACE) 2>/dev/null || \
		echo "$(YELLOW)Namespace $(NAMESPACE) already exists$(NC)"

install: create-namespace ## Install the ftrack Helm chart
	@echo "$(BLUE)Installing ftrack Helm chart...$(NC)"
	@helm --kube-context $(KUBE_CONTEXT) install $(RELEASE_NAME) . \
		--namespace $(NAMESPACE) \
		--values $(VALUES_FILE) \
		$$([ -n "$$IMAGE_REGISTRY_PASSWORD" ] && echo "--set imageRegistry.password=$$IMAGE_REGISTRY_PASSWORD") \
		--wait \
		--timeout 10m && \
	echo "$(GREEN)✓ Chart installed successfully$(NC)"

install-debug: create-namespace ## Install with verbose debug output
	@echo "$(BLUE)Installing ftrack Helm chart (debug mode)...$(NC)"
	@helm --kube-context $(KUBE_CONTEXT) install $(RELEASE_NAME) . \
		--namespace $(NAMESPACE) \
		--values $(VALUES_FILE) \
		$$([ -n "$$IMAGE_REGISTRY_PASSWORD" ] && echo "--set imageRegistry.password=$$IMAGE_REGISTRY_PASSWORD") \
		--debug \
		--wait \
		--timeout 10m

upgrade: ## Upgrade the existing ftrack installation
	@echo "$(BLUE)Upgrading ftrack Helm chart...$(NC)"
	@helm --kube-context $(KUBE_CONTEXT) upgrade $(RELEASE_NAME) . \
		--namespace $(NAMESPACE) \
		--values $(VALUES_FILE) \
		$$([ -n "$$IMAGE_REGISTRY_PASSWORD" ] && echo "--set imageRegistry.password=$$IMAGE_REGISTRY_PASSWORD") \
		--wait \
		--timeout 10m && \
	echo "$(GREEN)✓ Chart upgraded successfully$(NC)"

uninstall: ## Uninstall the ftrack Helm chart
	@echo "$(BLUE)Uninstalling ftrack Helm chart...$(NC)"
	@helm --kube-context $(KUBE_CONTEXT) uninstall $(RELEASE_NAME) \
		--namespace $(NAMESPACE) && \
	echo "$(GREEN)✓ Chart uninstalled successfully$(NC)"

port-forward: ## Forward port 8080 to access ftrack locally
	@echo "$(BLUE)Port forwarding ftrack service to localhost:8080...$(NC)"
	@echo "$(GREEN)Access ftrack at: http://localhost:8080$(NC)"
	@echo "$(YELLOW)Press Ctrl+C to stop port forwarding$(NC)"
	@kubectl --context $(KUBE_CONTEXT) port-forward -n $(NAMESPACE) svc/nginx 8080:80

test: ## Run Helm chart tests
	@echo "$(BLUE)Running Helm chart tests...$(NC)"
	@helm --kube-context $(KUBE_CONTEXT) test $(RELEASE_NAME) -n $(NAMESPACE)

lint: ## Lint the Helm chart
	@echo "$(BLUE)Linting Helm chart...$(NC)"
	@helm lint . --values $(VALUES_FILE) && \
	echo "$(GREEN)✓ Chart lint passed$(NC)"

template: ## Generate and display the templated manifests
	@echo "$(BLUE)Generating templated manifests...$(NC)"
	@helm template $(RELEASE_NAME) . --values $(VALUES_FILE) --namespace $(NAMESPACE)

dry-run: ## Perform a dry-run installation
	@echo "$(BLUE)Performing dry-run installation...$(NC)"
	@helm --kube-context $(KUBE_CONTEXT) install $(RELEASE_NAME) . \
		--namespace $(NAMESPACE) \
		--values $(VALUES_FILE) \
		$$([ -n "$$IMAGE_REGISTRY_PASSWORD" ] && echo "--set imageRegistry.password=$$IMAGE_REGISTRY_PASSWORD") \
		--dry-run --debug

describe-pod: ## Describe a specific pod for debugging
	@echo "$(BLUE)Select a pod to describe:$(NC)"
	@kubectl --context $(KUBE_CONTEXT) get pods -n $(NAMESPACE) --no-headers | \
		awk '{print NR") "$$1" ("$$3")"}' | \
		while read line; do echo "  $$line"; done
	@echo ""
	@read -p "Enter pod number: " pod_num; \
	pod_name=$$(kubectl --context $(KUBE_CONTEXT) get pods -n $(NAMESPACE) --no-headers | \
		awk "NR==$$pod_num {print \$$1}"); \
	if [ -n "$$pod_name" ]; then \
		echo "$(BLUE)Describing $$pod_name...$(NC)"; \
		kubectl --context $(KUBE_CONTEXT) describe pod $$pod_name -n $(NAMESPACE); \
	else \
		echo "$(RED)Invalid selection$(NC)"; \
	fi

shell: ## Open a shell in a running pod
	@echo "$(BLUE)Select a pod to shell into:$(NC)"
	@kubectl --context $(KUBE_CONTEXT) get pods -n $(NAMESPACE) --no-headers | \
		grep Running | \
		awk '{print NR") "$$1}' | \
		while read line; do echo "  $$line"; done
	@echo ""
	@read -p "Enter pod number: " pod_num; \
	pod_name=$$(kubectl --context $(KUBE_CONTEXT) get pods -n $(NAMESPACE) --no-headers | \
		grep Running | \
		awk "NR==$$pod_num {print \$$1}"); \
	if [ -n "$$pod_name" ]; then \
		echo "$(BLUE)Opening shell in $$pod_name...$(NC)"; \
		kubectl --context $(KUBE_CONTEXT) exec -it $$pod_name -n $(NAMESPACE) -- /bin/sh || \
		kubectl --context $(KUBE_CONTEXT) exec -it $$pod_name -n $(NAMESPACE) -- /bin/bash; \
	else \
		echo "$(RED)Invalid selection$(NC)"; \
	fi

events: ## Show recent Kubernetes events
	@echo "$(BLUE)Recent events in $(NAMESPACE) namespace:$(NC)"
	@kubectl --context $(KUBE_CONTEXT) get events -n $(NAMESPACE) --sort-by='.lastTimestamp'

get-host-ip: ## Get the host IP accessible from Kind cluster
	@echo "$(BLUE)Getting host IP accessible from Kind cluster...$(NC)"
	@docker exec $(CLUSTER_NAME)-control-plane ip route | grep default | awk '{print $$3}' || \
		(echo "$(YELLOW)Alternative method:$(NC)" && ifconfig | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $$2}' | head -1)

debug-db: ## Test database connectivity from a pod
	@echo "$(BLUE)Testing database connectivity...$(NC)"
	@echo "$(YELLOW)This will create a temporary pod to test DB connection$(NC)"
	@kubectl --context $(KUBE_CONTEXT) run -n $(NAMESPACE) -it --rm debug-db \
		--image=mysql:8.0 --restart=Never -- \
		mysql -h $$(yq e '.database.host' $(VALUES_FILE)) \
		-P $$(yq e '.database.port' $(VALUES_FILE)) \
		-u $$(yq e '.database.user' $(VALUES_FILE)) \
		-p$$(yq e '.database.password' $(VALUES_FILE)) \
		-e "SELECT 1"

clean: uninstall delete-cluster ## Clean up everything (uninstall chart and delete cluster)
	@echo "$(GREEN)✓ Cleanup complete$(NC)"

full-setup: create-cluster install ## Complete setup (create cluster and install chart)
	@echo "$(GREEN)✓ Full setup complete$(NC)"
	@echo "$(BLUE)Run 'make port-forward' to access ftrack at http://localhost:8080$(NC)"

restart: uninstall install ## Restart the ftrack installation
	@echo "$(GREEN)✓ Restart complete$(NC)"

.DEFAULT_GOAL := help
