NAMESPACE ?= proxy
PACKAGE := ollama-proxy
SHELL := /bin/bash
REGISTRY := registry.halfakop.ru
REPOSITORY := $(NAMESPACE)/$(PACKAGE)
PLATFORM ?= --platform=linux/amd64

SOURCE_VERSION ?= $(shell cat VERSION)
SOURCE_COMMIT ?= $(shell git rev-parse --short=8 HEAD)
GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD | sed s,feature/,,g)

IMAGE_NAME_TAGGED = $(REPOSITORY):$(SOURCE_VERSION)
EXEC=service
TEST_PACKAGES := $(shell go list ./...)

all: help

help:
	@printf "\nMain make targets:\n"
	@printf "  make app              - Download deps, fix, build app (binary: %s)\n" "$(EXEC)"
	@printf "  make test             - Run unit tests\n"
	@printf "  make test-integration - Run tests with integration tag\n"
	@printf "  make run              - Build then run locally\n"
	@printf "  make dev              - Run without building (go run, with env vars)\n"
	@printf "  make clean            - Clean build artifacts\n"
	@printf "  make release          - Clean, build image, login, push\n"
	@printf "\nVariables:\n"
	@printf "  NAMESPACE=%s\n" "$(NAMESPACE)"
	@printf "  PACKAGE=%s\n" "$(PACKAGE)"
	@printf "  IMAGE_NAME_TAGGED=%s\n" "$(IMAGE_NAME_TAGGED)"
	@printf "  EXEC=%s\n\n" "$(EXEC)"

download:
	@echo "Download dependencies"
	@go mod download

fix:
	@echo "Fix code"
	@go fix ./...

app: download fix
	@echo "Build application"
	@go build -o ./${EXEC} ./src

tests: app
	@echo "Run unit tests"
	@go test -count=1 $(TEST_PACKAGES)

test-integration:
	@echo "Run integration tests (tag: integration)"
	@go test -tags=integration -count=1 $(TEST_PACKAGES)

run: app
	@echo "Run application"
	@./${EXEC}

dev:
	@echo "Run in development mode"
	@OLLAMA_BACKEND=http://localhost:11434 LISTEN_ADDR=:8080 go run ./src

clean:
	@echo "Clean build environment"
	@rm -rf ./${EXEC}

release: title clean build login push

build:
	DOCKER_BUILDKIT=0 \
	docker build $(PLATFORM) --progress=plain --compress \
		-t $(IMAGE_NAME_TAGGED) \
		-t $(REGISTRY)/$(IMAGE_NAME_TAGGED) \
		--build-arg SOURCE_VERSION=$(SOURCE_VERSION) \
		--build-arg SOURCE_COMMIT=$(SOURCE_COMMIT) \
		--build-arg GOPROXY=$(GOPROXY) \
		--build-arg GONOSUMDB=$(GONOSUMDB) \
		${DOCKER_OPTS} \
		-f Dockerfile .

login:
	$(call check-var-defined,DOCKER_USERNAME)
	$(call check-var-defined,DOCKER_PASSWORD)
	@echo ${DOCKER_PASSWORD} | \
	docker login -u ${DOCKER_USERNAME} --password-stdin $(REGISTRY)

push:
	docker push $(REGISTRY)/$(IMAGE_NAME_TAGGED)

.PHONY: tests test test-integration release build login push
