# Variables
# Derive version from Python package (__version__) only
VERSION := $(shell python -c "import pymergetic.core; print(pymergetic.core.__version__)" 2>/dev/null)
ifeq ($(strip $(VERSION)),)
  $(error VERSION is empty; ensure pymergetic.core is importable and __version__ is set)
endif
ifeq ($(VERSION),0.0.0)
  $(warning VERSION is 0.0.0 (fallback); ensure proper version is set or tag exists)
endif
# Compute NEXT_VERSION by bumping patch of VERSION (override if needed)
NEXT_VERSION ?= $(shell python -c "import pymergetic.core,re; v=pymergetic.core.__version__; m=re.match(r'^v?(\\d+)\\.(\\d+)\\.(\\d+)', v or '0.0.0'); maj,mi,pa = m.groups() if m else ('0','0','0'); print(f'{maj}.{mi}.{int(pa)+1}')" 2>/dev/null)
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 Python __version__)"
	@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 *.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 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: tag build publish
	@echo "Release completed: $(VERSION)"

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

.PHONY: version-source
version-source:
	@python -c "import pymergetic.core; print(pymergetic.core.__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=$*

