.PHONY: build run test test-db test-db-parallel test-short

COMMIT := $(shell git describe --dirty --always)
BIN ?= $(PWD)/bin

OS ?= $(shell uname | tr "[:upper:]" "[:lower:]")
ARCH ?= $(shell go env GOARCH)
DOCKER := DOCKER_BUILDKIT=1 docker

GO := CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go
LDFLAGS += -X "main.version=$(COMMIT)"
LDFLAGS += -X "main.buildTime=$(shell date -u '+%Y-%m-%dT%H:%M:%S')"

IMAGE ?= hub.pingcap.net/qa/tidbcloud-pov
IMAGE_TAG ?= latest

bin:
	@mkdir -p $(BIN)/$(OS)/$(ARCH)

build: bin
	$(GO) build -o $(BIN)/$(OS)/$(ARCH)/tidbcloud-pov -gcflags "all=-N -l" -ldflags '$(LDFLAGS)' cmd/main.go

run: build
	$(BIN)/$(OS)/$(ARCH)/tidbcloud-pov --config $(CONFIG) --secret $(SECRET)

build-image: build
	$(DOCKER) build --build-arg arch=$(ARCH) --platform $(OS)/$(ARCH) -t $(IMAGE):$(IMAGE_TAG)-$(ARCH) .

image-arm64:
	OS=linux ARCH=arm64 make -j2 build-image

image-amd64:
	OS=linux ARCH=amd64 make -j2 build-image

# Multi-arch image, support amd64 and arm64
image: image-amd64 image-arm64

image-push-amd64: image-amd64
	$(DOCKER) push $(IMAGE):$(IMAGE_TAG)-amd64

image-push-arm64: image-arm64
	$(DOCKER) push $(IMAGE):$(IMAGE_TAG)-arm64

image-push: image-push-arm64 image-push-amd64
	$(DOCKER) manifest create $(IMAGE):$(IMAGE_TAG) \
		--amend $(IMAGE):$(IMAGE_TAG)-amd64 \
		--amend $(IMAGE):$(IMAGE_TAG)-arm64
	$(DOCKER) manifest push --purge $(IMAGE):$(IMAGE_TAG)

.PHONY: website-image-dev website-image-prod
website-image-dev:
	$(DOCKER) build --platform linux/amd64 -f website/Dockerfile --build-arg APP_ENV=development -t $(IMAGE)-website:dev ./website

website-image-prod:
	$(DOCKER) build --platform linux/amd64 -f website/Dockerfile --build-arg APP_ENV=production -t $(IMAGE)-website:prod ./website

website-image-dev-push: website-image-dev
	$(DOCKER) tag $(IMAGE)-website:dev $(IMAGE)-website:$(IMAGE_TAG)-dev
	$(DOCKER) push $(IMAGE)-website:$(IMAGE_TAG)-dev

website-image-prod-push: website-image-prod
	$(DOCKER) tag $(IMAGE)-website:prod $(IMAGE)-website:$(IMAGE_TAG)-prod
	$(DOCKER) push $(IMAGE)-website:$(IMAGE_TAG)-prod

# Test targets
test: test-short test-db

test-short:
	go test -short ./...

test-db:
	@echo "Running MySQL integration tests (requires MySQL server on localhost:3306)"
	go test -v ./internal/db/mysql/...

test-db-parallel:
	@echo "Running MySQL integration tests in parallel (requires MySQL server on localhost:3306)"
	go test -v -parallel 4 ./internal/db/mysql/...
