# =============================================================================
# Makefile for a web application project
#
# Usage:
#   make              - Show available targets
#   make build        - Build the project for production
#   make dev          - Start the development server
#   make test         - Run the test suite
#   make lint         - Run linters and formatters
#   make docker-build - Build the Docker image
#   make clean        - Remove build artifacts
# =============================================================================

# --- Variables ---
APP_NAME    := myapp
VERSION     := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
BUILD_DIR   := dist
SRC_DIR     := src
NODE_BIN    := ./node_modules/.bin
DOCKER_TAG  := $(APP_NAME):$(VERSION)
PORT        := 3000
COVERAGE_DIR := coverage

# Detect OS for platform-specific commands
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Darwin)
	OPEN_CMD := open
else
	OPEN_CMD := xdg-open
endif

# --- Default target ---
.PHONY: help
help: ## Show this help message
	@echo "$(APP_NAME) v$(VERSION)"
	@echo ""
	@echo "Available targets:"
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
		awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-18s\033[0m %s\n", $$1, $$2}'

# --- Build ---
.PHONY: build
build: node_modules ## Build the project for production
	@echo "==> Building $(APP_NAME) v$(VERSION)..."
	$(NODE_BIN)/tsc --noEmit
	$(NODE_BIN)/vite build
	@echo "==> Build complete: $(BUILD_DIR)/"

.PHONY: dev
dev: node_modules ## Start the development server
	$(NODE_BIN)/vite --port $(PORT)

node_modules: package.json package-lock.json
	npm ci
	@touch node_modules

# --- Testing ---
.PHONY: test
test: node_modules ## Run the test suite
	$(NODE_BIN)/vitest run --coverage

.PHONY: test-watch
test-watch: node_modules ## Run tests in watch mode
	$(NODE_BIN)/vitest watch

.PHONY: test-e2e
test-e2e: build ## Run end-to-end tests
	$(NODE_BIN)/playwright test

.PHONY: coverage
coverage: test ## Open the coverage report in a browser
	$(OPEN_CMD) $(COVERAGE_DIR)/index.html

# --- Linting & Formatting ---
.PHONY: lint
lint: node_modules ## Run linters and formatters
	$(NODE_BIN)/eslint $(SRC_DIR) --ext .ts,.tsx --fix
	$(NODE_BIN)/prettier --write "$(SRC_DIR)/**/*.{ts,tsx,css,json}"

.PHONY: typecheck
typecheck: node_modules ## Run TypeScript type checking
	$(NODE_BIN)/tsc --noEmit

# --- Docker ---
.PHONY: docker-build
docker-build: ## Build the Docker image
	docker build -t $(DOCKER_TAG) .
	@echo "==> Image built: $(DOCKER_TAG)"

.PHONY: docker-run
docker-run: docker-build ## Build and run the Docker container
	docker run --rm -p $(PORT):$(PORT) --env-file .env $(DOCKER_TAG)

# --- Cleanup ---
.PHONY: clean
clean: ## Remove build artifacts and caches
	rm -rf $(BUILD_DIR) $(COVERAGE_DIR) .cache .vite
	@echo "==> Cleaned build artifacts"

.PHONY: clean-all
clean-all: clean ## Remove everything including node_modules
	rm -rf node_modules
	@echo "==> Cleaned all dependencies"