# ragext Makefile
# Dependency management via uv; image build via docker.

IMAGE        ?= ragext
TAG          ?= latest
CONTAINER    ?= ragext
PORT         ?= 15080
WORKERS      ?= auto

# Image base + proxy for builds behind a corporate mirror. Override as needed.
PYTHON_IMAGE ?= hub.yangzhiqiang.tech/library/python:3.12-slim
HTTP_PROXY   ?= http://172.16.40.16:7280
HTTPS_PROXY  ?= http://172.16.40.16:7280

.DEFAULT_GOAL := help

.PHONY: help
help: ## Show this help
	@grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) \
		| awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-14s\033[0m %s\n", $$1, $$2}'

.PHONY: install
install: ## Sync dependencies (incl. dev) into a local venv with uv
	uv sync --extra dev

.PHONY: run
run: ## Run the API locally with reload (uvicorn on $(PORT))
	RAGEXT_PORT=$(PORT) uv run uvicorn ragext.asgi:app --host 0.0.0.0 --port $(PORT) --reload

.PHONY: test
test: ## Run the test suite (integration tests hit the configured middleware)
	uv run pytest -q

.PHONY: lint
lint: ## Lint with ruff
	uv run ruff check ragext tests

.PHONY: fmt
fmt: ## Format with ruff
	uv run ruff format ragext tests

.PHONY: build
build: ## Build the docker image ($(IMAGE):$(TAG)) behind the corporate proxy
	docker build \
		--build-arg PYTHON_IMAGE=$(PYTHON_IMAGE) \
		--build-arg http_proxy=$(HTTP_PROXY) \
		--build-arg https_proxy=$(HTTPS_PROXY) \
		-t $(IMAGE):$(TAG) .

.PHONY: up
up: ## Copy local source into the running container and restart (no image rebuild)
	@docker inspect $(CONTAINER) >/dev/null 2>&1 || { \
		echo "error: container '$(CONTAINER)' not found; run 'make docker-run' first"; \
		exit 1; \
	}
	docker cp ./ragext/. $(CONTAINER):/app/ragext/
	docker restart $(CONTAINER)

.PHONY: docker
docker: build ## Alias for `make build`

.PHONY: docker-run
docker-run: ## Run the built image as named container $(CONTAINER), passing .env through
	-docker rm -f $(CONTAINER) >/dev/null 2>&1
	docker run -d --name $(CONTAINER) -p $(PORT):8080 \
		--env-file .env \
		-e RAGEXT_WORKERS=$(WORKERS) \
		$(IMAGE):$(TAG)
	@echo "started $(CONTAINER) → http://127.0.0.1:$(PORT)  workers=$(WORKERS)"

.PHONY: stop
stop: ## Stop and remove the $(CONTAINER) container
	-docker stop $(CONTAINER) >/dev/null 2>&1
	@echo "stopped $(CONTAINER)"

.PHONY: log
log: ## Follow logs of the $(CONTAINER) container
	docker logs -f --tail 200 $(CONTAINER)

.PHONY: clean
clean: ## Remove caches and build artifacts
	rm -rf .pytest_cache .ruff_cache dist build *.egg-info
	find . -type d -name __pycache__ -prune -exec rm -rf {} +
