# Konduktor Go Build
# Makefile for building and testing Konduktor

.PHONY: all build build-konduktor build-konduktorctl test clean deps fmt lint run

# Build configuration
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
GIT_COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
BUILD_TIME ?= $(shell date -u '+%Y-%m-%dT%H:%M:%SZ')
LDFLAGS := -X main.Version=$(VERSION) -X main.GitCommit=$(GIT_COMMIT) -X main.BuildTime=$(BUILD_TIME)

# Output directories
BIN_DIR := bin

all: deps build

# Download dependencies
deps:
	@echo "==> Downloading dependencies..."
	go mod download
	go mod tidy

# Build all binaries
build: build-konduktor build-konduktorctl

# Build konduktor server
build-konduktor:
	@echo "==> Building konduktor..."
	@mkdir -p $(BIN_DIR)
	go build -ldflags "$(LDFLAGS)" -o $(BIN_DIR)/konduktor ./cmd/konduktor

# Build konduktorctl CLI
build-konduktorctl:
	@echo "==> Building konduktorctl..."
	@mkdir -p $(BIN_DIR)
	go build -ldflags "$(LDFLAGS)" -o $(BIN_DIR)/konduktorctl ./cmd/konduktorctl

# Run tests
test:
	@echo "==> Running tests..."
	go test -v -race -cover ./...

# Run tests with coverage report
test-coverage:
	@echo "==> Running tests with coverage..."
	go test -v -race -coverprofile=coverage.out ./...
	go tool cover -html=coverage.out -o coverage.html
	@echo "Coverage report: coverage.html"

# Format code
fmt:
	@echo "==> Formatting code..."
	go fmt ./...
	goimports -w .

# Lint code
lint:
	@echo "==> Linting code..."
	golangci-lint run ./...

# Run the server (development)
run: build-konduktor
	@echo "==> Running konduktor..."
	./$(BIN_DIR)/konduktor -c ../config.yaml

# Clean build artifacts
clean:
	@echo "==> Cleaning..."
	rm -rf $(BIN_DIR)
	rm -f coverage.out coverage.html

# Install binaries to GOPATH/bin
install: build
	@echo "==> Installing binaries..."
	cp $(BIN_DIR)/konduktor $(GOPATH)/bin/
	cp $(BIN_DIR)/konduktorctl $(GOPATH)/bin/

# Generate mocks (for testing)
generate:
	@echo "==> Generating code..."
	go generate ./...

# Docker build
docker-build:
	@echo "==> Building Docker image..."
	docker build -t konduktor:$(VERSION) .

# Show help
help:
	@echo "Konduktor Build System"
	@echo ""
	@echo "Usage: make [target]"
	@echo ""
	@echo "Targets:"
	@echo "  all              Download deps and build all binaries"
	@echo "  deps             Download and tidy dependencies"
	@echo "  build            Build all binaries"
	@echo "  build-konduktor  Build the server binary"
	@echo "  build-konduktorctl Build the CLI binary"
	@echo "  test             Run tests"
	@echo "  test-coverage    Run tests with coverage report"
	@echo "  fmt              Format code"
	@echo "  lint             Lint code"
	@echo "  run              Build and run the server"
	@echo "  clean            Clean build artifacts"
	@echo "  install          Install binaries to GOPATH/bin"
	@echo "  docker-build     Build Docker image"
	@echo "  help             Show this help"
