SHELL := /bin/bash

.DEFAULT_GOAL := help

.PHONY: help guard-dev-tag down dev dev-build dev-up

FRONTEND_DIR := Frontend
FRONTEND_DIST_DIR := $(FRONTEND_DIR)/dist
BACKEND_DIR := Backend
BACKEND_TMP_DIR := $(BACKEND_DIR)/tmp
EARTHLY ?= earthly
COMPOSE ?= docker compose

help: ## Show this help message
	@echo "Usage: make [target]"
	@echo ""
	@echo "Available targets:"
	@awk 'BEGIN {FS = ":.*## "}; /^[a-zA-Z0-9_.-]+:.*## / {printf "  %-12s %s\n", $$1, $$2}' $(MAKEFILE_LIST)

guard-dev-tag:
	@if [ -z "$(DEV_TAG)" ]; then \
		echo "Error: DEV_TAG is not set. Please provide a tag for the development image."; \
		exit 1; \
	fi

down: ## Stop all servers and clean up temporary files
	@DEV_TAG=$${DEV_TAG:-dummy} $(COMPOSE) -f docker-compose.dev.yaml down --remove-orphans -v
	@rm -rf "$(BACKEND_TMP_DIR)" "$(FRONTEND_DIST_DIR)"

dev: guard-dev-tag ## Start the development server
	@$(MAKE) dev-build DEV_TAG=$(DEV_TAG)
	@$(MAKE) dev-up DEV_TAG=$(DEV_TAG)

dev-build: guard-dev-tag ## Build the development image for the frontend
	@cd "$(FRONTEND_DIR)" && $(EARTHLY) +dev-image --REGISTRY="registry.mangopig.tech" --IMAGE_NAME="boost-ai/demo-frontend-dev" --TAG=$(DEV_TAG)

dev-up: guard-dev-tag ## Start the development server using docker compose
	@DEV_TAG=$(DEV_TAG) $(COMPOSE) -f docker-compose.dev.yaml up -d --remove-orphans --force-recreate
