.PHONY: all build build-edge build-node tidy test test-e2e test-openai-ollama proto proto-dart portal-test portal-build-web clean

GOFLAGS ?= -trimpath
BUILD_APPS ?= edge node
LOCAL_BIN_DIR ?= bin

all: build

build:
	APPS="$(BUILD_APPS)" LOCAL_BIN_DIR="$(LOCAL_BIN_DIR)" GOFLAGS="$(GOFLAGS)" bin/build/field-binaries.sh

build-edge:
	$(MAKE) build BUILD_APPS=edge

build-node:
	$(MAKE) build BUILD_APPS=node

tidy:
	go mod tidy

test:
	go test ./...

test-e2e:
	@echo "NOTE: test-e2e runs auxiliary smoke plus fake Ollama OpenAI serving; completion still requires user-flow verification when changing runtime paths."
	./scripts/e2e-smoke.sh
	./scripts/e2e-openai-ollama.sh

test-openai-ollama:
	./scripts/e2e-openai-ollama.sh

# Requires: protoc + protoc-gen-go (go install google.golang.org/protobuf/cmd/protoc-gen-go@latest)
proto:
	protoc \
		--go_out=. \
		--go_opt=module=iop \
		--proto_path=. \
		proto/iop/runtime.proto \
		proto/iop/node.proto \
		proto/iop/control.proto \
		proto/iop/job.proto

# Try finding protoc-gen-dart in PATH or common fallback locations
PROTOC_GEN_DART := $(shell which protoc-gen-dart 2>/dev/null)
ifeq ($(PROTOC_GEN_DART),)
  PROTOC_GEN_DART := $(wildcard $(HOME)/.pub-cache/bin/protoc-gen-dart)
endif
ifeq ($(PROTOC_GEN_DART),)
  PROTOC_GEN_DART := $(wildcard /config/.pub-cache/bin/protoc-gen-dart)
endif

proto-dart:
ifeq ($(PROTOC_GEN_DART),)
	@echo "Error: protoc-gen-dart not found."
	@echo "Please install it by running: flutter pub global activate protoc_plugin"
	@exit 1
endif
	mkdir -p apps/portal/lib/gen
	protoc \
		--plugin=protoc-gen-dart=$(PROTOC_GEN_DART) \
		--dart_out=apps/portal/lib/gen \
		--proto_path=. \
		--proto_path=/config/.local/include \
		/config/.local/include/google/protobuf/struct.proto \
		proto/iop/runtime.proto \
		proto/iop/node.proto \
		proto/iop/control.proto \
		proto/iop/job.proto

portal-test:
	cd apps/portal && flutter test

portal-build-web:
	cd apps/portal && flutter build web \
		--dart-define=IOP_CONTROL_PLANE_HTTP_URL=http://localhost:9080 \
		--dart-define=IOP_CONTROL_PLANE_WIRE_URL=ws://localhost:19080/portal

clean:
	rm -f bin/iop-edge bin/iop-node bin/iop-control-plane bin/iop-worker
	rm -f bin/node bin/edge bin/control-plane bin/worker
	rm -rf dist
	rm -f iop.db
