.PHONY: build run clean help infra-up infra-down infra-logs run-engine run-web infra-init infra-plan infra-apply release

# Command Variables
DOCKER_COMPOSE=docker compose
GO=go
NPM=npm
TOFU=tofu
ENV?=staging

## infra-init: Initialize OpenTofu provider configurations
infra-init:
	cd infra && $(TOFU) init

## infra-plan: Generate and show an OpenTofu execution plan (use ENV=staging|production)
infra-plan:
	cd infra && ($(TOFU) workspace select $(ENV) || $(TOFU) workspace new $(ENV)) && $(TOFU) plan

## infra-apply: Build or change infrastructure (use ENV=staging|production)
infra-apply:
	cd infra && ($(TOFU) workspace select $(ENV) || $(TOFU) workspace new $(ENV)) && $(TOFU) apply -auto-approve

## infra-up: Start Valkey and Redis Insight containers in the background
infra-up:
	$(DOCKER_COMPOSE) up -d

## infra-down: Stop Valkey and Redis Insight containers
infra-down:
	$(DOCKER_COMPOSE) down

## infra-logs: Follow logs of the infrastructure containers
infra-logs:
	$(DOCKER_COMPOSE) logs -f

## run-engine: Build and run the Tongo Core backend engine daemon
run-engine:
	$(MAKE) -C tongo-core run

## run-web: Run the TanStack Start frontend web terminal dev server
run-web:
	cd web-terminal && $(NPM) run dev

## clean: Stop containers and clean all build artifacts and volumes
clean: infra-down
	$(MAKE) -C tongo-core clean
	$(DOCKER_COMPOSE) down -v

## release: Create and push a new production release tag (usage: make release TAG=v1.0.0)
release:
	@if [ -z "$(TAG)" ]; then \
		echo "Error: TAG variable is required. Example: make release TAG=v1.0.0"; \
		exit 1; \
	fi
	@echo "Creating production release tag $(TAG)..."
	git tag -a $(TAG) -m "Production release $(TAG)"
	@echo "Pushing tag $(TAG) to origin..."
	git push origin $(TAG)

## help: Show this help
help:
	@grep -E '^## ' Makefile | sed 's/## //' | column -t -s ':'

ssh-git:
	@ssh -i ~/.ssh/hologrid_deploy deploy@git.holo-grid.bar
