# Makefile for repsim (pybind11 + scikit-build-core)
# Usage:
#   make develop     # editable install
#   make install     # regular install
#   make uninstall   # uninstall package
#   make build       # wheel+sdist to dist/
#   make clean       # remove build artifacts
#   make rebuild     # clean + develop
#   make help        # show this help
#   make check       # twine metadata check
#   make release     # clean + build + check + push to PyPI via Twine
#   make release-test# clean + build + check + push to TestPyPI via Twine

# --- Config ---
PYTHON ?= python
PIP    ?= $(PYTHON) -m pip
PKG    ?= repsim

# --- Helpers ---
define PRINT_HELP
@echo "Targets:"
@echo "  develop       Editable install (pip install -e .)"
@echo "  install       Regular install (pip install .)"
@echo "  uninstall     Uninstall package ($(PKG))"
@echo "  build         Build wheel and sdist into dist/"
@echo "  check         Validate dist/ artifacts with twine"
@echo "  release       Clean + build + check + upload to PyPI"
@echo "  release-test  Clean + build + check + upload to TestPyPI"
@echo "  clean         Remove build artifacts and caches"
@echo "  rebuild       clean + develop"
@echo "  help          Show this help"
endef

.PHONY: develop install uninstall build check release release-test clean rebuild help

help:
	$(PRINT_HELP)

develop:
	$(PIP) install -e .

install:
	$(PIP) install .

uninstall:
	-$(PIP) uninstall -y $(PKG)

build:
	$(PYTHON) -m build --wheel --outdir dist
	$(PYTHON) -m build --sdist --outdir dist

check:
	@$(PYTHON) -c "import twine" 2>/dev/null || { \
	  echo 'twine not found. Install with: $(PYTHON) -m pip install -U twine'; exit 1; }
	@test -d dist && ls dist/* >/dev/null 2>&1 || { \
	  echo 'No artifacts in dist/. Run `make build` first.'; exit 1; }
	$(PYTHON) -m twine check dist/*

# Conservative release to PyPI:
# - clean (avoid stale wheels)
# - build wheel+sdist
# - twine check metadata
# - require TWINE_* env vars
release: clean build check
	@if [ -z "$$TWINE_USERNAME" ] || [ -z "$$TWINE_PASSWORD" ]; then \
	  echo "Set TWINE_USERNAME=__token__ and TWINE_PASSWORD=pypi-<YOUR_PYPI_TOKEN>"; exit 1; fi
	$(PYTHON) -m twine upload dist/*

# Optional: release to TestPyPI (sandbox)
release-test: clean build check
	@if [ -z "$$TWINE_USERNAME" ] || [ -z "$$TWINE_PASSWORD" ]; then \
	  echo "Set TWINE_USERNAME=__token__ and TWINE_PASSWORD=pypi-<YOUR_TESTPYPI_TOKEN>"; exit 1; fi
	$(PYTHON) -m twine upload --repository testpypi dist/*

clean:
	@echo "Cleaning build artifacts..."
	@rm -rf \
	  build/ \
	  _skbuild/ \
	  dist/ \
	  *.egg-info \
	  .eggs \
	  .pytest_cache \
	  .mypy_cache \
	  .ruff_cache \
	  .nox \
	  .tox \
	  **/__pycache__
	@# Remove compiled extensions if present (adjust path if your package lives at repo root)
	@find python/$(PKG) -maxdepth 1 -name "_$(PKG).*so" -delete 2>/dev/null || true
	@find python/$(PKG) -maxdepth 1 -name "_$(PKG).*pyd" -delete 2>/dev/null || true

rebuild: clean develop
