.PHONY: build test coverage lint clean install deps fmt vet

# Build variables
BINARY_NAME=sparkmailr-sdk
VERSION?=1.0.0
BUILD_DIR=build

# Go variables
GO=go
GOFLAGS=-ldflags="-s -w"

# Test variables
COVERAGE_DIR=coverage
COVERAGE_FILE=$(COVERAGE_DIR)/coverage.out
COVERAGE_HTML=$(COVERAGE_DIR)/coverage.html

# Linting
GOLANGCI_LINT_VERSION=v1.55.2

all: deps fmt vet lint test build

# Dependencies
deps:
	$(GO) mod download
	$(GO) mod verify

# Format code
fmt:
	$(GO) fmt ./...

# Vet code
vet:
	$(GO) vet ./...

# Build
build: deps
	mkdir -p $(BUILD_DIR)
	CGO_ENABLED=0 $(GO) build $(GOFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME) ./cmd/example

# Test
test: deps
	$(GO) test -race -v ./...

# Test with coverage
coverage: deps
	mkdir -p $(COVERAGE_DIR)
	$(GO) test -race -coverprofile=$(COVERAGE_FILE) -covermode=atomic ./...
	$(GO) tool cover -html=$(COVERAGE_FILE) -o $(COVERAGE_HTML)
	@echo "Coverage report generated: $(COVERAGE_HTML)"

# Benchmark
bench: deps
	$(GO) test -bench=. -benchmem ./...

# Lint (requires golangci-lint)
lint:
	@which golangci-lint > /dev/null || (echo "Installing golangci-lint..." && \
		curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $$(go env GOPATH)/bin $(GOLANGCI_LINT_VERSION))
	golangci-lint run

# Clean
clean:
	rm -rf $(BUILD_DIR) $(COVERAGE_DIR)
	$(GO) clean

# Install as local package
install: deps
	$(GO) install ./...

# Download dependencies
mod-update:
	$(GO) get -u ./...
	$(GO) mod tidy

# Generate documentation
docs:
	godoc -http=:6060

# Examples
examples:
	$(GO) run ./examples/basic/main.go
	$(GO) run ./examples/advanced/main.go

# Security check
security:
	@which gosec > /dev/null || $(GO) install github.com/securecodewarrior/gosec/v2/cmd/gosec@latest
	gosec ./...

# Docker build
docker-build:
	docker build -t sparkmailr/go-sdk:$(VERSION) .

# CI pipeline
ci: deps fmt vet lint security test coverage

# Help
help:
	@echo "Available targets:"
	@echo "  build      - Build the SDK"
	@echo "  test       - Run tests"
	@echo "  coverage   - Run tests with coverage report"
	@echo "  lint       - Run linters"
	@echo "  fmt        - Format code"
	@echo "  vet        - Run go vet"
	@echo "  clean      - Clean build artifacts"
	@echo "  deps       - Download dependencies"
	@echo "  install    - Install as local package"
	@echo "  examples   - Run example applications"
	@echo "  docs       - Start documentation server"
	@echo "  ci         - Run full CI pipeline"
