.PHONY: local-up local-down local-logs local-reset local-build help test-all test-create test-delete start

# Repository root directory
REPO_ROOT := $(shell cd ../.. && pwd)
KIND_CLUSTER_NAME := csng-dev
DOCKER_NETWORK := csng-dev-net
TIDB_OPERATOR_VERSION := v2.1.0-alpha.15
CERT_MANAGER_VERSION := v1.16.1
GITHUB_MIRROR := https://ghfast.top

# Use kind from output/bin if available, otherwise try system kind
KIND_BIN := $(shell if [ -x "$(REPO_ROOT)/output/bin/kind" ]; then echo "$(REPO_ROOT)/output/bin/kind"; else which kind 2>/dev/null || echo "kind"; fi)

help: ## Show this help
	@echo "Local Development Environment for cluster-service-ng"
	@echo ""
	@echo "Usage: make [target]"
	@echo ""
	@echo "Targets:"
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "  %-15s %s\n", $$1, $$2}'

start: ## One-click start everything (infra + executor + cluster-service)
	@./scripts/start-all.sh

local-build: ## Build mock-dpm Docker image
	@echo "Building mock-dpm Docker image..."
	cd $(REPO_ROOT) && docker build -f hack/mock-dpm/Dockerfile.local -t csng-mock-dpm:local .

local-up: ## Start local development environment
	@echo "============================================"
	@echo "Starting local development environment..."
	@echo "============================================"
	@echo ""
	@echo "Step 1: Checking local MySQL..."
	@mysql -h 127.0.0.1 -u root -e "SELECT 1" >/dev/null 2>&1 || (echo "ERROR: Local MySQL not running. Please start MySQL first." && exit 1)
	@mysql -h 127.0.0.1 -u root -e "CREATE DATABASE IF NOT EXISTS dev_local_ng"
	@echo "MySQL is ready!"
	@echo ""
	@echo "Step 2: Starting mock-dpm..."
	DOCKER_BUILDKIT=0 docker-compose up -d --build
	@echo ""
	@echo "Step 3: Creating kind cluster (if not exists)..."
	@$(KIND_BIN) get clusters 2>/dev/null | grep -q $(KIND_CLUSTER_NAME) || $(KIND_BIN) create cluster --config kind-config.yaml --name $(KIND_CLUSTER_NAME)
	@echo ""
	@echo "Step 4: Installing cert-manager..."
	@echo "Pulling cert-manager images via China mirror..."
	@docker pull m.daocloud.io/quay.io/jetstack/cert-manager-controller:$(CERT_MANAGER_VERSION) || true
	@docker pull m.daocloud.io/quay.io/jetstack/cert-manager-cainjector:$(CERT_MANAGER_VERSION) || true
	@docker pull m.daocloud.io/quay.io/jetstack/cert-manager-webhook:$(CERT_MANAGER_VERSION) || true
	@$(KIND_BIN) load docker-image m.daocloud.io/quay.io/jetstack/cert-manager-controller:$(CERT_MANAGER_VERSION) --name $(KIND_CLUSTER_NAME) || true
	@$(KIND_BIN) load docker-image m.daocloud.io/quay.io/jetstack/cert-manager-cainjector:$(CERT_MANAGER_VERSION) --name $(KIND_CLUSTER_NAME) || true
	@$(KIND_BIN) load docker-image m.daocloud.io/quay.io/jetstack/cert-manager-webhook:$(CERT_MANAGER_VERSION) --name $(KIND_CLUSTER_NAME) || true
	@curl -sL $(GITHUB_MIRROR)/https://github.com/cert-manager/cert-manager/releases/download/$(CERT_MANAGER_VERSION)/cert-manager.yaml | \
		sed 's|quay.io|m.daocloud.io/quay.io|g' | \
		kubectl apply -f - || echo "Warning: cert-manager may not have applied correctly"
	@echo "Waiting for cert-manager to be ready..."
	@kubectl -n cert-manager wait --for=condition=available deployment/cert-manager --timeout=120s 2>/dev/null || echo "Warning: cert-manager may not be ready"
	@kubectl -n cert-manager wait --for=condition=available deployment/cert-manager-webhook --timeout=120s 2>/dev/null || true
	@echo ""
	@echo "Step 5: Loading TiDB Operator image into kind..."
	@docker pull pingcap/tidb-operator:$(TIDB_OPERATOR_VERSION) || true
	@$(KIND_BIN) load docker-image pingcap/tidb-operator:$(TIDB_OPERATOR_VERSION) --name $(KIND_CLUSTER_NAME) || true
	@echo ""
	@echo "Step 6: Installing TiDB Operator..."
	@curl -sL $(GITHUB_MIRROR)/https://github.com/pingcap/tidb-operator/releases/download/$(TIDB_OPERATOR_VERSION)/tidb-operator.yaml | \
		kubectl apply --server-side -f - || echo "Warning: TiDB Operator may not have applied correctly"
	@echo "Waiting for TiDB Operator to be ready..."
	@kubectl -n tidb-admin wait --for=condition=available deployment/tidb-controller-manager --timeout=120s 2>/dev/null || echo "Warning: TiDB Operator may not be ready"
	@echo ""
	@echo "Step 7: Installing CRDs..."
	kubectl apply -f $(REPO_ROOT)/deployments/crds/ 2>/dev/null || echo "Warning: CRDs may not have applied correctly"
	@echo ""
	@echo "Step 8: Removing control-plane taint to allow scheduling..."
	@kubectl taint nodes $(KIND_CLUSTER_NAME)-control-plane node-role.kubernetes.io/control-plane:NoSchedule- 2>/dev/null || true
	@echo ""
	@echo "Step 9: Adding labels to kind nodes for local-dev scheduling..."
	@for node in $$(kubectl get nodes -o name); do \
		kubectl label $$node node-spec=4C8G --overwrite; \
		kubectl label $$node tidbcloud.com/node-pool-k8s-version=1.28 --overwrite; \
		kubectl label $$node topology.kubernetes.io/zone=us-east-1a --overwrite; \
	done
	@echo ""
	@echo "Step 10: Creating StorageClass and ClusterIssuer for local-dev..."
	@kubectl apply -f manifests/local-dev-resources.yaml
	@echo ""
	@echo "============================================"
	@echo "Local environment is ready!"
	@echo ""
	@echo "Services running:"
	@echo "  - MySQL:           localhost:3306 (local process, user: root, db: dev_local_ng)"
	@echo "  - Mock-DPM:        localhost:10001 (gRPC), localhost:8081 (admin HTTP)"
	@echo "  - Kind K8s:        kubectl is configured"
	@echo "  - TiDB Operator:   $(TIDB_OPERATOR_VERSION)"
	@echo ""
	@echo "To run cluster-service:"
	@echo "  cd $(REPO_ROOT)"
	@echo "  go run ./cmd/cluster_ng_server --config hack/local-dev/config.yaml"
	@echo ""
	@echo "To run executor:"
	@echo "  cd $(REPO_ROOT)"
	@echo "  go run ./cmd/executor --config hack/local-dev/executor-config.yaml"
	@echo ""
	@echo "Admin endpoints:"
	@echo "  - Health:  curl http://localhost:8081/healthz"
	@echo "  - Dump:    curl http://localhost:8081/dump"
	@echo "  - Reset:   curl -X POST http://localhost:8081/reset"
	@echo "============================================"

local-down: ## Stop and cleanup local development environment
	@echo "Stopping local development environment..."
	@$(KIND_BIN) delete cluster --name $(KIND_CLUSTER_NAME) 2>/dev/null || true
	docker-compose down -v
	@echo "Local environment stopped."

local-logs: ## View docker-compose logs
	docker-compose logs -f

local-reset: ## Reset mock-dpm state
	@echo "Resetting mock-dpm state..."
	curl -s -X POST http://localhost:8081/reset | jq . || curl -X POST http://localhost:8081/reset

local-status: ## Show status of local services
	@echo "Docker containers:"
	@docker-compose ps
	@echo ""
	@echo "Kind cluster:"
	@$(KIND_BIN) get clusters 2>/dev/null | grep $(KIND_CLUSTER_NAME) && echo "$(KIND_CLUSTER_NAME) is running" || echo "$(KIND_CLUSTER_NAME) is not running"
	@echo ""
	@echo "Mock-DPM health:"
	@curl -s http://localhost:8081/healthz 2>/dev/null | jq . || echo "Mock-DPM is not responding"

local-mysql: ## Connect to local MySQL CLI
	mysql -h 127.0.0.1 -u root dev_local_ng

test-check: ## Check if services are running
	@./scripts/test-workflows.sh check

test-create-sharedpool: ## Create a test SharedPool
	@./scripts/test-workflows.sh create-sharedpool

test-create-cluster: ## Create a test TiDBCluster
	@./scripts/test-workflows.sh create-cluster

test-delete-cluster: ## Delete the test TiDBCluster
	@./scripts/test-workflows.sh delete-cluster

test-delete-sharedpool: ## Delete the test SharedPool
	@./scripts/test-workflows.sh delete-sharedpool

test-list: ## List all SharedPools and TiDBClusters
	@./scripts/test-workflows.sh list-sharedpools
	@./scripts/test-workflows.sh list-clusters

test-all: ## Run all workflow tests
	@./scripts/test-workflows.sh all
