# Reads the current version string from pyproject.toml (e.g. "0.1.0")
CURRENT := $(shell python3 -c "import re; print(re.search(r'version = \"(.+?)\"', open('pyproject.toml').read()).group(1))")

.PHONY: release release-exact _do_release

# ──────────────────────────────────────────────────────────────
# make release BUMP=patch|minor|major
#
# Automatically calculates the next version from the current one.
#   patch: 0.1.0 → 0.1.1
#   minor: 0.1.0 → 0.2.0
#   major: 0.1.0 → 1.0.0
# Then builds, uploads to PyPI, commits, and tags.
# ──────────────────────────────────────────────────────────────
release:
ifndef BUMP
	$(error Usage: make release BUMP=patch|minor|major)
endif
	# Calculate the next version by splitting CURRENT on dots,
	# incrementing the appropriate part, and zeroing everything after it.
	$(eval VERSION := $(shell python3 -c "\
		v = '$(CURRENT)'.split('.'); \
		bump = '$(BUMP)'; \
		i = {'major':0,'minor':1,'patch':2}[bump]; \
		v[i] = str(int(v[i]) + 1); \
		v[i+1:] = ['0'] * (2-i); \
		print('.'.join(v))"))
	@$(MAKE) _do_release VERSION=$(VERSION)

# ──────────────────────────────────────────────────────────────
# make release-exact VERSION=0.2.0
#
# Set an exact version instead of bumping. Useful for pre-releases
# or when you want full control over the version number.
# ──────────────────────────────────────────────────────────────
release-exact:
ifndef VERSION
	$(error Usage: make release-exact VERSION=0.2.0)
endif
	@$(MAKE) _do_release VERSION=$(VERSION)

# ──────────────────────────────────────────────────────────────
# Internal target that does the actual release work.
# Called by both `release` and `release-exact` with VERSION set.
#
# Steps:
#   1. Update the version in pyproject.toml
#   2. Build source dist (.tar.gz) and wheel (.whl) into dist/
#   3. Upload both to PyPI via twine (requires ~/.pypirc credentials)
#   4. Commit the version bump and create a git tag
# ──────────────────────────────────────────────────────────────
_do_release:
	@echo "Releasing v$(VERSION) (was v$(CURRENT))..."
	# Step 1: Write the new version into pyproject.toml
	sed -i '' 's/^version = ".*"/version = "$(VERSION)"/' pyproject.toml
	# Step 2: Clean old build artifacts and build new ones
	rm -rf dist/
	python3 -m build
	# Step 3: Upload to PyPI (reads credentials from ~/.pypirc)
	twine upload dist/*
	# Step 4: Commit the version change and tag the release
	git add pyproject.toml
	git commit -m "release v$(VERSION)"
	git tag "v$(VERSION)"
	@echo "Done. Published spotify-streamd v$(VERSION) to PyPI."
