.PHONY := help install run start stop docker-build docker-rebuild docker-run docker-stop docker-logs docker-shell clean

PROJECT_NAME ?= lifefaq
IMAGE_NAME ?= $(PROJECT_NAME):latest
CONTAINER_NAME ?= $(PROJECT_NAME)-app
PYTHON ?= python3
UVICORN ?= uvicorn
APP_MODULE ?= app.main:app
PORT ?= 8000
HOST_PORT ?= $(PORT)

help:
	@printf "Available targets:\n"
	@grep -E '^[a-zA-Z_-]+:.*?##' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "} {printf "  %-18s %s\n", $$1, $$2}' | sort

install: ## Install Python dependencies
	$(PYTHON) -m pip install -r requirements.txt

run: ## Run the FastAPI app using app.py (no auto-reload)
	$(PYTHON) app.py

start: ## Start the FastAPI app with uvicorn auto-reload (foreground)
	$(UVICORN) $(APP_MODULE) --reload --host 0.0.0.0 --port $(PORT)

stop: ## Stop local uvicorn processes started via make start (best effort)
	-pkill -f "$(UVICORN).*$(APP_MODULE)"

docker-build: ## Build the Docker image
	docker build -t $(IMAGE_NAME) .

docker-rebuild: ## Rebuild the Docker image without cache
	docker build --no-cache -t $(IMAGE_NAME) .

docker-run: ## Run the Docker container in the background
	docker run --rm -d -p $(HOST_PORT):$(PORT) --name $(CONTAINER_NAME) -e PORT=$(PORT) $(IMAGE_NAME)

docker-stop: ## Stop the running Docker container
	-docker stop $(CONTAINER_NAME)

docker-logs: ## Tail logs from the Docker container
	docker logs -f $(CONTAINER_NAME)

docker-shell: ## Open a shell inside the running Docker container
	docker exec -it $(CONTAINER_NAME) /bin/sh

clean: ## Remove Python cache artifacts
	find . -name '__pycache__' -type d -prune -exec rm -rf {} +
