.PHONY: all frontend backend backend-epics backend-debug test bench race lint clean run

# --------------------------------------------------------------------------- #
# Sources — adding any file here triggers a frontend or backend rebuild        #
# --------------------------------------------------------------------------- #

FRONTEND_SRCS := $(shell find web/src -name '*.tsx' -o -name '*.ts' -o -name '*.css') \
                 $(wildcard web/vendor/*.mjs web/vendor/*.js web/vendor/*.css) \
                 tools/buildfrontend/main.go

GO_SRCS := $(shell find cmd internal -name '*.go') web/embed.go go.mod go.sum

# --------------------------------------------------------------------------- #
# Outputs                                                                      #
# --------------------------------------------------------------------------- #

FRONTEND_OUT := web/dist/main.js
BINARY       := dist/uopi

# --------------------------------------------------------------------------- #
# Top-level targets                                                            #
# --------------------------------------------------------------------------- #

all: $(BINARY)

frontend: $(FRONTEND_OUT)

backend: $(BINARY)

# --------------------------------------------------------------------------- #
# Build rules                                                                  #
# --------------------------------------------------------------------------- #

# Bundle TypeScript/TSX → web/dist/ using esbuild (pure Go, no npm)
$(FRONTEND_OUT): $(FRONTEND_SRCS)
	@mkdir -p web/dist
	go run ./tools/buildfrontend/main.go

# Compile the self-contained binary (embeds web/dist at build time)
$(BINARY): $(GO_SRCS) $(FRONTEND_OUT)
	@mkdir -p dist
	go build -ldflags="-s -w" -o $(BINARY) ./cmd/uopi

# Build with EPICS Channel Access support.
# Requires EPICS Base and:
#   EPICS_BASE=/path/to/epics/base
#   CGO_CFLAGS="-I$$EPICS_BASE/include -I$$EPICS_BASE/include/os/Linux"
#   CGO_LDFLAGS="-L$$EPICS_BASE/lib/linux-x86_64 -lca -lCom"
backend-epics: $(FRONTEND_OUT)
	@mkdir -p dist
	CGO_ENABLED=1 go build -tags epics -ldflags="-s -w" -o $(BINARY) ./cmd/uopi

# Unstripped binary for debugging
backend-debug: $(FRONTEND_OUT)
	@mkdir -p dist
	go build -o $(BINARY) ./cmd/uopi

# --------------------------------------------------------------------------- #
# Dev / CI                                                                     #
# --------------------------------------------------------------------------- #

test:
	go test ./...

# Run tests with the race detector enabled.
race:
	go test -race ./...

# Run all benchmarks and print memory allocations.
bench:
	go test -bench=. -benchmem -benchtime=3s ./internal/...

lint:
	go vet ./...

run: $(BINARY)
	$(BINARY)

clean:
	rm -rf dist/ web/dist/
