VENV ?= .venv
PYTHON ?= $(VENV)/bin/python
VENV_PY ?= $(PYTHON)
PIP ?= $(VENV)/bin/pip
VPS_FORGE ?= $(VENV)/bin/vps-forge
ANSIBLE_PLAYBOOK ?= $(VENV)/bin/ansible-playbook
ANSIBLE_GALAXY ?= $(VENV)/bin/ansible-galaxy
CONFIG ?= config.yaml
EXPORT_OUTPUT ?= dist/vps-forge-template.zip

.PHONY: help setup lint test syntax-check dry-run apply doctor doctor-deep smoke-test export-template clean

help:
	@echo "vps-forge Makefile targets:"
	@echo "  make setup            Create .venv, install deps, and install Ansible collections"
	@echo "  make lint             Run ruff lint checks"
	@echo "  make test             Run pytest unit tests"
	@echo "  make syntax-check     Run ansible-playbook --syntax-check"
	@echo "  make dry-run          Run vps-forge apply --dry-run"
	@echo "  make apply            Run vps-forge apply"
	@echo "  make doctor           Run local TCP port probe"
	@echo "  make doctor-deep      Run local TCP + remote SSH read-only deep probe"
	@echo "  make smoke-test       Run Stage 3 local container smoke test"
	@echo "  make export-template  Export clean template archive to $(EXPORT_OUTPUT)"
	@echo "  make clean            Remove caches and build/dist artifacts (preserves .venv, config.yaml, output, inventory)"

setup:
	@if [ ! -f "$(VENV)/pyvenv.cfg" ] || [ ! -x "$(PYTHON)" ]; then \
		python3 -m venv "$(VENV)" 2>/dev/null || { rm -rf "$(VENV)" && python3 -m venv --without-pip "$(VENV)"; }; \
	fi
	@if [ ! -x "$(PIP)" ]; then \
		pip3 --python "$(PYTHON)" install pip; \
	fi
	"$(PIP)" install -e ".[dev]"
	"$(ANSIBLE_GALAXY)" collection install -r ansible/requirements.yml

lint:
	$(PYTHON) -m ruff check vps_forge tests scripts/smoke_test.py ansible/roles/modules/monitor/files/health_server.py

test:
	$(PYTHON) -m pytest -v

syntax-check:
	ANSIBLE_CONFIG=ansible/ansible.cfg $(ANSIBLE_PLAYBOOK) -i "localhost," ansible/site.yml --syntax-check

dry-run:
	$(VPS_FORGE) apply -c $(CONFIG) --dry-run

apply:
	$(VPS_FORGE) apply -c $(CONFIG)

doctor:
	$(VPS_FORGE) doctor -c $(CONFIG)

doctor-deep:
	$(VPS_FORGE) doctor -c $(CONFIG) --deep

smoke-test:
	$(VENV_PY) scripts/smoke_test.py

export-template:
	$(VENV_PY) -m vps_forge.exporter --output "$(EXPORT_OUTPUT)"

clean:
	rm -rf build dist .pytest_cache .ruff_cache .mypy_cache *.egg-info
	find . \( -path './.venv' -o -path './venv' -o -path './.git' \) -prune -o \
		-type d -name '__pycache__' -prune -exec rm -rf {} +
	find . \( -path './.venv' -o -path './venv' -o -path './.git' \) -prune -o \
		-type f \( -name '*.pyc' -o -name '*.pyo' \) -exec rm -f {} +
