.PHONY: build clean test lint docker-build docker-push run help

# Variables
APP_NAME := gitea-webhook-ambassador
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
LDFLAGS := -ldflags "-X main.version=$(VERSION) -s -w"
GO_FILES := $(shell find . -name "*.go" -type f)
IMAGE_NAME := freeleaps/$(APP_NAME)
IMAGE_TAG := $(VERSION)
CONFIG_FILE := config.yaml

# Go commands
GO := go
GOFMT := gofmt
GOTEST := $(GO) test
GOBUILD := $(GO) build

# Default target
.DEFAULT_GOAL := help

# Build executable
build: $(GO_FILES) 
		@echo "Building $(APP_NAME)..."
		$(GOBUILD) $(LDFLAGS) -o $(APP_NAME) .

# Clean build artifacts
clean:
		@echo "Cleaning up..."
		@rm -f $(APP_NAME)
		@rm -rf build/

# Run tests
test:
		@echo "Running tests..."
		$(GOTEST) -v ./...

# Run linter
lint:
		@which golangci-lint > /dev/null || (echo "Installing golangci-lint..." && go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest)
		golangci-lint run

# Build Docker image
docker-build:
		@echo "Building Docker image $(IMAGE_NAME):$(IMAGE_TAG)..."
		docker build -t $(IMAGE_NAME):$(IMAGE_TAG) .
		docker tag $(IMAGE_NAME):$(IMAGE_TAG) $(IMAGE_NAME):latest

# Push Docker image to registry
docker-push: docker-build
		@echo "Pushing Docker image $(IMAGE_NAME):$(IMAGE_TAG)..."
		docker push $(IMAGE_NAME):$(IMAGE_TAG)
		docker push $(IMAGE_NAME):latest

# Run locally
run: build
		./$(APP_NAME) -config=$(CONFIG_FILE)

# Show help
help:
		@echo "Gitea Webhook Ambassador - Makefile commands:"
		@echo "  build        - Build the application"
		@echo "  clean        - Remove build artifacts"
		@echo "  test         - Run tests"
		@echo "  lint         - Run linter"
		@echo "  docker-build - Build Docker image"
		@echo "  docker-push  - Build and push Docker image to registry"
		@echo "  run          - Build and run locally"
		@echo "  help         - Show this help message"