# Variables
# For releases, compute version from latest git tag and bump patch
# Filter out problematic tags (those with .post or .dev)
LATEST_TAG := $(shell git tag -l | grep -v "\.post\|\.dev" | sort -V | tail -1 || echo "v0.0.0")
# Extract version and validate format (must be X.Y.Z)
LATEST_VERSION := $(shell TAG=$$(echo $(LATEST_TAG) | sed 's/^v//'); if echo "$$TAG" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$$'; then echo "$$TAG"; else echo "0.0.0"; fi)
# Increment patch version, ensuring we have valid input
NEXT_VERSION := $(shell echo $(LATEST_VERSION) | awk -F. -v OFS=. '{if (NF != 3 || $$1 == "" || $$2 == "" || $$3 == "") {print "0.0.1"} else {$$3++; print}}')

# Use NEXT_VERSION for releases, or allow VERSION to be overridden
VERSION ?= $(NEXT_VERSION)
PYTHON ?= python
PIP ?= python -m pip

# Helper
# Strip leading 'v' from git tag for version (v0.2.1 -> 0.2.1)
PKG_VERSION := $(patsubst v%,%,$(VERSION))

.PHONY: help
help:
	@echo "Targets:"
	@echo "  build           - Build python sdist/wheel"
	@echo "  publish         - Publish python package to PyPI (twine)"
	@echo "  tag             - Create and push git tag v$(VERSION) (uses latest tag + 1)"
	@echo "  tag-<ver>       - e.g., make tag-$(NEXT_VERSION) (shorthand for VERSION=<ver>)"
	@echo "  release         - Tag git, push tag, build & publish PyPI"
	@echo "  release-<ver>   - e.g., make release-$(NEXT_VERSION) (shorthand for VERSION=<ver>)"
	@echo "  version         - Show current version (from Python __version__)"
	@echo "  version-source  - Show version and source (metadata|setuptools_scm)"

.PHONY: build
build:
	@echo "Building python package"
	export SETUPTOOLS_SCM_LOCAL_SCHEME=no-local-version && \
	rm -rf dist build/lib build/bdist.* build/*.egg-info *.egg-info src/*.egg-info && \
	$(PIP) install -U build twine && \
	$(PYTHON) -m build

.PHONY: publish
publish:
	@echo "Publishing python package"
	export SETUPTOOLS_SCM_LOCAL_SCHEME=no-local-version && \
	$(PYTHON) -m twine upload --repository pymergetic-os-builder dist/*

.PHONY: tag
tag:
	@git tag -a v$(VERSION) -m "Release $(VERSION)"
	@git push origin v$(VERSION)

.PHONY: tag-push
tag-push:
	@git push origin v$(VERSION)

.PHONY: release
release:
	@echo "Releasing version $(VERSION)"
	@$(MAKE) tag VERSION=$(VERSION)
	@$(MAKE) build
	@$(MAKE) publish
	@echo "Release completed: $(VERSION)"

# Show current version
.PHONY: version
version:
	@python -c "import pymergetic.os.builder; print(pymergetic.os.builder.__version__)"

.PHONY: version-source
version-source:
	@python -c "import pymergetic.os.builder; print(pymergetic.os.builder.__version_source__)"

# Convenience pattern targets: make tag-0.2.1 / make release-0.2.1
.PHONY: tag-%
tag-%:
	@$(MAKE) tag VERSION=$*

.PHONY: release-%
release-%:
	@$(MAKE) release VERSION=$*

