.PHONY: check lint test fmt fmt-check build clean docker docker-test devserver devserver-stop hooks

VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
LDFLAGS := -X main.Version=$(VERSION)

# Use nix-shell to provide CGO dependencies unless they are already available
# (e.g. inside a Docker build or an existing nix-shell).
HAS_PKGCONFIG := $(shell command -v pkg-config 2>/dev/null)
ifdef HAS_PKGCONFIG
  NIX_RUN_PREFIX =
  NIX_RUN_SUFFIX =
else
  NIX_RUN_PREFIX = nix-shell -p pkg-config vips libheif golangci-lint git --run '
  NIX_RUN_SUFFIX = '
endif

# Default target: run all checks
check: fmt-check lint test

# Check formatting without modifying files
fmt-check:
	@echo "Checking formatting..."
	@test -z "$$(gofmt -l . | grep -v '^vendor/')" || (echo "Files need formatting:"; gofmt -l . | grep -v '^vendor/'; exit 1)

# Format code
fmt:
	@echo "Formatting code..."
	gofmt -w $$(find . -name '*.go' -not -path './vendor/*')

# Run linter
lint:
	@echo "Running linter..."
	$(NIX_RUN_PREFIX)golangci-lint run$(NIX_RUN_SUFFIX)

# Run tests (30-second timeout)
test:
	@echo "Running tests..."
	$(NIX_RUN_PREFIX)CGO_ENABLED=1 go test -timeout 30s -v ./...$(NIX_RUN_SUFFIX)

# Build the binary
build:
	@echo "Building pixad..."
	$(NIX_RUN_PREFIX)CGO_ENABLED=1 go build -ldflags "$(LDFLAGS)" -o ./bin/pixad ./cmd/pixad$(NIX_RUN_SUFFIX)

# Clean build artifacts
clean:
	rm -rf bin/
	rm -rf ./data

# Build Docker image
docker:
	docker build --build-arg VERSION=$(VERSION) -t pixad:$(VERSION) -t pixad:latest .

# Run tests in Docker (needed for CGO/libvips)
docker-test:
	docker build --target builder --build-arg VERSION=$(VERSION) -t pixad-builder .
	docker run --rm pixad-builder sh -c "CGO_ENABLED=1 GOTOOLCHAIN=auto go test -v ./..."

# Run local dev server in Docker
devserver: docker devserver-stop
	docker run -d --name pixad-dev -p 8080:8080 \
		-v $(CURDIR)/config.dev.yml:/etc/pixa/config.yml:ro \
		pixad:latest
	@echo "pixad running at http://localhost:8080"

# Stop dev server
devserver-stop:
	-docker stop pixad-dev 2>/dev/null
	-docker rm pixad-dev 2>/dev/null

# Install pre-commit hook
hooks:
	@printf '#!/bin/sh\nset -e\n' > .git/hooks/pre-commit
	@printf 'make check\n' >> .git/hooks/pre-commit
	@chmod +x .git/hooks/pre-commit
