PYTHON ?= python3
VENV_DIR ?= .venv
VENV_BIN := $(VENV_DIR)/bin
VENV_PYTHON := $(VENV_BIN)/python
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

.PHONY: deps build install install-local check-binary clean help test test-e2e

help:
	@printf "Targets:\n"
	@printf "  make deps          Create .venv and install build+dev dependencies\n"
	@printf "  make build         Build standalone binary at dist/flow\n"
	@printf "  make install       Build and install to ~/.local/bin/flow\n"
	@printf "  make install-local Install binary to ~/.local/bin/flow\n"
	@printf "  make check-binary  Run dist/flow --help\n"
	@printf "  make test          Run unit tests\n"
	@printf "  make test-e2e      Run end-to-end container tests (FLOW_RUN_E2E=1)\n"
	@printf "  make clean         Remove build artifacts\n"

deps:
	@set -eu; \
	if [ ! -x "$(VENV_PYTHON)" ]; then \
		if ! $(PYTHON) -m venv "$(VENV_DIR)" >/dev/null 2>&1; then \
			if command -v apt-get >/dev/null 2>&1; then \
				echo "venv support missing; installing python3-venv via apt-get (sudo required)"; \
				sudo apt-get update; \
				sudo apt-get install -y python3-venv; \
			elif command -v dnf >/dev/null 2>&1; then \
				echo "venv support missing; installing python3 via dnf (sudo required)"; \
				sudo dnf install -y python3; \
			elif command -v brew >/dev/null 2>&1; then \
				echo "venv support missing; installing python via Homebrew"; \
				brew install python; \
			else \
				echo "Unable to create virtualenv automatically. Install python venv support and rerun make deps."; \
				exit 1; \
			fi; \
			$(PYTHON) -m venv "$(VENV_DIR)"; \
		fi; \
	fi; \
	. "$(VENV_BIN)/activate"; \
	python -m pip install --upgrade pip; \
	python -m pip install -e ".[build,dev]"

build: deps
	@set -eu; \
	. "$(VENV_BIN)/activate"; \
	python -m PyInstaller --noconfirm --clean --onefile --name flow --paths "$(SRC_DIR)" "$(ENTRYPOINT)"

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

install: deps build install-local

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

test:
	$(VENV_PYTHON) -m pytest tests/ -q

test-e2e:
	FLOW_RUN_E2E=1 $(VENV_PYTHON) -m pytest tests/e2e/ -v

clean:
	rm -rf "$(BUILD_DIR)" "$(DIST_DIR)" "$(SPEC_FILE)"
