################################################################################
#                              SimStadt in Python                              #
################################################################################

help:     ## Show this help.
	@egrep -h '(\s##\s|^##\s)' $(MAKEFILE_LIST) | egrep -v '^--' | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[32m  %-35s\033[0m %s\n", $$1, $$2}'

tests: ## Run detailed tests
	uv run pytest -v

coverage: ## Run tests, and save coverage
	uv run pytest --cov --cov-report=html:coverage
	gio open coverage/index.html

simple_tests: ## Run simple tests, without running SimStadt
	uv run pytest -v -m "not integration"

simstadt: ## Run simstadt script, and display info about SimStadt
	uv run simstadt

shell: ## Start bash
	@echo "${green}Start shell${no_color}"
	docker run --rm -it simstadt/simstadt:cli bash

docker-build: ## Build the base and cli Docker images (cli also tagged :latest)
	docker build --target base -t simstadt/simstadt:base .
	docker build --target cli -t simstadt/simstadt:cli -t simstadt/simstadt:latest .

docker-tests: docker-build ## Run the full test suite (incl. integration tests) against the published PyPI package inside Docker
	docker run --rm simstadt/simstadt:cli uv run --no-sync pytest -v

_check_docker_push:
	@echo -n "Are you sure you want to push the Docker images to Docker Hub? [y/N] " && read ans && [ $${ans:-N} = y ]

docker-push: _check_docker_push docker-build ## Push the base, cli, and latest images to Docker Hub (requires prior `docker login`)
	docker push simstadt/simstadt:base
	docker push simstadt/simstadt:cli
	docker push simstadt/simstadt:latest

tests_installed_package: ## Tests the installed simstadt package
	pytest --pyargs simstadt -v

clean: ## Remove pyc and pycache
	find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete
	rm -f dist/*.tar.gz
	rm -f dist/*.whl

build: clean tests ## Build PyPI package
	uv build
	unzip -l dist/*.whl

_check_upload:
	@echo -n "Are you sure you want to upload the package to PyPI? [y/N] " && read ans && [ $${ans:-N} = y ]

upload_package_to_testpypi: _check_upload build ## Upload PyPI package to https://test.pypi.org/
	$(MAKE) _upload SERVER=testpypi URL=https://test.pypi.org/legacy/

upload_package_to_pypi: _check_upload build ## Upload PyPI package to https://pypi.org/
	$(MAKE) _upload SERVER=pypi

_upload:
	@token=$$(python3 -c "import configparser, os; c=configparser.ConfigParser(); c.read(os.path.expanduser('~/.pypirc')); print(c.get('$(SERVER)', 'password', fallback=''))"); \
	[ -n "$$token" ] || { echo "No token found for [$(SERVER)] in ~/.pypirc"; exit 1; }; \
	UV_PUBLISH_TOKEN=$$token uv publish --verbose $(if $(URL),--publish-url $(URL),)

install_editable: ## Install package in dev mode
	pip install -e .

.PHONY: help tests simstadt build coverage docker-build docker-test docker-push
