PYTHON ?= python3
NAMESPACE_DIR := .
NAMESPACE_DIST_DIR := dist
NAMESPACE_PYPROJECT := pyproject.toml
CORE_DIR := packages/core
CORE_DIST_DIR := $(CORE_DIR)/dist
CORE_PYPROJECT := $(CORE_DIR)/pyproject.toml

.PHONY: clean-namespace-dist namespace-version check-namespace-tag build-namespace publish-namespace clean-core-dist core-version check-core-tag build-core publish-core

clean-namespace-dist:
	rm -rf "$(NAMESPACE_DIST_DIR)"

namespace-version:
	@$(PYTHON) -c 'import pathlib, re; text = pathlib.Path("$(NAMESPACE_PYPROJECT)").read_text(); match = re.search(r"^version = \"([^\"]+)\"", text, re.M); assert match, "version not found"; print(match.group(1))'

check-namespace-tag:
	@test -n "$(TAG)" || (printf 'TAG is required, e.g. TAG=v0.0.1\n' >&2; exit 1)
	@printf '%s' "$(TAG)" | $(PYTHON) -c 'import re, sys; tag = sys.stdin.read().strip(); assert re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+", tag), f"invalid semantic version tag: {tag}"'
	@version=`$(MAKE) --no-print-directory namespace-version`; \
	if [ "v$$version" != "$(TAG)" ]; then \
		printf 'tag %s does not match package version v%s\n' "$(TAG)" "$$version" >&2; \
		exit 1; \
	fi

build-namespace: clean-namespace-dist
	uvx --from build pyproject-build "$(NAMESPACE_DIR)" --outdir "$(NAMESPACE_DIST_DIR)"

publish-namespace: build-namespace
	@test -n "$$PYPI_TOKEN" || (printf 'PYPI_TOKEN is required for local publishing\n' >&2; exit 1)
	uvx --from twine twine upload -u __token__ -p "$$PYPI_TOKEN" "$(NAMESPACE_DIST_DIR)/*"

clean-core-dist:
	rm -rf "$(CORE_DIST_DIR)"

core-version:
	@$(PYTHON) -c 'import pathlib, re; text = pathlib.Path("$(CORE_PYPROJECT)").read_text(); match = re.search(r"^version = \"([^\"]+)\"", text, re.M); assert match, "version not found"; print(match.group(1))'

check-core-tag:
	@test -n "$(TAG)" || (printf 'TAG is required, e.g. TAG=v0.0.1\n' >&2; exit 1)
	@printf '%s' "$(TAG)" | $(PYTHON) -c 'import re, sys; tag = sys.stdin.read().strip(); assert re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+", tag), f"invalid semantic version tag: {tag}"'
	@version=`$(MAKE) --no-print-directory core-version`; \
	if [ "v$$version" != "$(TAG)" ]; then \
		printf 'tag %s does not match package version v%s\n' "$(TAG)" "$$version" >&2; \
		exit 1; \
	fi

build-core: clean-core-dist
	uvx --from build pyproject-build "$(CORE_DIR)" --outdir "$(CORE_DIST_DIR)"

publish-core: build-core
	@test -n "$$PYPI_TOKEN" || (printf 'PYPI_TOKEN is required for local publishing\n' >&2; exit 1)
	uvx --from twine twine upload -u __token__ -p "$$PYPI_TOKEN" "$(CORE_DIST_DIR)/*"
