.PHONY: test test-short test-cover build install clean lint cross help

SHELL := /bin/bash

# Versioning (override on command line or via env for releases)
VERSION ?= dev-$(shell git describe --tags --always --dirty 2>/dev/null || echo unknown)
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)
DATE ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo unknown)

MODULE = github.com/gmgauthier/gralculator
LDFLAGS = -s -w \
	-X '$(MODULE)/internal/version.Version=$(VERSION)' \
	-X '$(MODULE)/internal/version.Commit=$(COMMIT)' \
	-X '$(MODULE)/internal/version.BuildDate=$(DATE)' \
	-X 'main.version=$(VERSION)'

test: deps
	go test ./... -v -race

test-short: deps
	go test -short ./... -v -race

test-cover: deps
	@mkdir -p build
	go test ./... -coverprofile=build/coverage.out
	go tool cover -html=build/coverage.out -o build/coverage.html
	@echo "✅ Coverage report: open build/coverage.html in your browser"

deps:
	go mod download

build: deps
	@mkdir -p build
	go build -trimpath -ldflags "$(LDFLAGS)" -o build/gralculator .
	@echo "✅ Dev build: VERSION=$(VERSION) COMMIT=$(COMMIT) DATE=$(DATE)"
	@build/gralculator -v || true

install: build
	mkdir -p ~/.local/bin
	cp build/gralculator ~/.local/bin/gralculator
	chmod +x ~/.local/bin/gralculator
	@echo "✅ gralculator installed to ~/.local/bin/gralculator"

clean:
	rm -rf build/

help:
	@echo "Common targets:"
	@echo "  make build       - build dev binary to build/gralculator"
	@echo "  make install     - build and install to ~/.local/bin/gralculator"
	@echo "  make test        - run all tests with race detector"
	@echo "  make test-short  - short tests with race"
	@echo "  make clean       - remove build/"
	@echo "  make lint        - run golangci-lint (requires golangci-lint in PATH; CI uses action)"
	@echo "  make cross       - cross-compile for linux/darwin/windows (amd64/arm64) for releases"

lint:
	@command -v golangci-lint >/dev/null 2>&1 || { echo >&2 "golangci-lint not found in PATH (install via 'go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest' or rely on CI)"; exit 1; }
	golangci-lint run ./...

cross: deps
	@mkdir -p build
	@echo "Cross-compiling gralculator (VERSION=$(VERSION) COMMIT=$(COMMIT))..."
	@for os in linux darwin windows; do \
		for arch in amd64 arm64; do \
			ext=""; if [ "$$os" = "windows" ]; then ext=".exe"; fi; \
			out="build/gralculator-$$os-$$arch$$ext"; \
			echo "  $$os/$$arch -> $$out"; \
			CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -trimpath -ldflags "$(LDFLAGS)" -o "$$out" . || exit 1; \
		done; \
	done
	@echo "✅ Cross builds complete:"
	@ls -lh build/gralculator-* 2>/dev/null | cat || true
