UV ?= uv
SRC_DIR := $(CURDIR)/src
ENTRYPOINT := src/flow/__main__.py
DIST_DIR := dist
BUILD_DIR := build
SPEC_FILE := flow.spec
BINARY := $(DIST_DIR)/flow
INSTALL_DIR ?= $(HOME)/.local/bin
VERSION := $(shell sed -n 's/^__version__ = "\(.*\)"/\1/p' src/flow/__init__.py)
RELEASE_ROOT := $(BUILD_DIR)/flow-$(VERSION)-python
RELEASE_ARCHIVE := $(DIST_DIR)/flow-$(VERSION)-python.tar.gz

.PHONY: help deps test test-e2e test-e2e-cmds check package release-package build binary install install-local check-binary clean distclean

help:
	@printf "Targets:\n"
	@printf "  make deps          Sync locked dev/build dependencies into .venv\n"
	@printf "  make test          Run unit tests\n"
	@printf "  make test-e2e      Run Docker/Podman e2e tests (FLOW_RUN_E2E=1)\n"
	@printf "  make test-e2e-cmds Run focused disposable-container CLI command checks (FLOW_RUN_E2E=1)\n"
	@printf "  make check         Run unit tests and CLI smoke check\n"
	@printf "  make package       Build wheel and sdist into dist/\n"
	@printf "  make release-package Build installable Python release tarball\n"
	@printf "  make build         Build standalone binary at dist/flow\n"
	@printf "  make install       Build and install binary to ~/.local/bin/flow\n"
	@printf "  make check-binary  Run dist/flow --help\n"
	@printf "  make clean         Remove generated build/test artifacts\n"
	@printf "  make distclean     Also remove local virtualenvs\n"

deps:
	$(UV) sync --locked --extra build --extra dev

test:
	$(UV) run pytest tests/ -q --ignore=tests/e2e

test-e2e:
	FLOW_RUN_E2E=1 $(UV) run pytest tests/e2e/ -v

test-e2e-cmds:
	FLOW_RUN_E2E=1 $(UV) run pytest tests/e2e/test_dotfiles_e2e.py::test_cli_paths_run_in_disposable_container -q

check: test
	$(UV) run python -m flow --help >/dev/null
	$(UV) run python -m flow --version >/dev/null

package: deps
	$(UV) build

release-package: deps
	rm -rf "$(RELEASE_ROOT)" "$(RELEASE_ARCHIVE)" "$(RELEASE_ARCHIVE).sha256"
	mkdir -p "$(RELEASE_ROOT)/wheelhouse"
	$(UV) build
	cp dist/flow-$(VERSION)-py3-none-any.whl "$(RELEASE_ROOT)/wheelhouse/"
	cp packaging/install.sh "$(RELEASE_ROOT)/install.sh"
	chmod 755 "$(RELEASE_ROOT)/install.sh"
	tar -czf "$(RELEASE_ARCHIVE)" -C "$(BUILD_DIR)" "flow-$(VERSION)-python"
	if command -v sha256sum >/dev/null 2>&1; then sha256sum "$(RELEASE_ARCHIVE)" > "$(RELEASE_ARCHIVE).sha256"; else shasum -a 256 "$(RELEASE_ARCHIVE)" > "$(RELEASE_ARCHIVE).sha256"; fi

build binary: deps
	$(UV) run pyinstaller --noconfirm --clean --onefile --name flow --paths "$(SRC_DIR)" "$(ENTRYPOINT)"

install-local install: build
	mkdir -p "$(INSTALL_DIR)"
	install -m 755 "$(BINARY)" "$(INSTALL_DIR)/flow"
	@printf "Installed flow to $(INSTALL_DIR)/flow\n"

check-binary:
	"$(BINARY)" --help

clean:
	rm -rf "$(BUILD_DIR)" "$(DIST_DIR)" "$(SPEC_FILE)" .coverage coverage.xml htmlcov .pytest_cache .ruff_cache .mypy_cache

distclean: clean
	rm -rf .venv venv
