# macOS ships GNU Make 3.81, which ignores .ONESHELL — so the `dev` recipe is one
# shell line (\-joined) to keep the trap + background jobs in a single shell.
SHELL := /bin/bash

TOKEN      ?= devtoken
CLOUD_PORT ?= 8770
DASH_PORT  ?= 8765
CLOUD_URL  := http://127.0.0.1:$(CLOUD_PORT)
# cloud_api.py is Postgres-backed (Phase 3). `make pg` spins a throwaway local one.
DATABASE_URL ?= postgres://postgres:pw@127.0.0.1:5432/gcontext

.PHONY: dev cloud dashboard web web-dev pg migrate help

help:
	@echo "make pg         - run a throwaway local Postgres in docker (port 5432)"
	@echo "make dev        - run cloud API + serve the built React dashboard at $(CLOUD_URL)"
	@echo "make cloud      - run only the cloud API   ($(CLOUD_URL))  [needs DATABASE_URL]"
	@echo "make web        - build the React dashboard into web/dist (served by the API)"
	@echo "make web-dev    - Vite dev server with hot reload, proxying the API to $(CLOUD_URL)"
	@echo "make dashboard  - legacy single-user dashboard.py     (http://127.0.0.1:$(DASH_PORT))"
	@echo "make migrate    - apply pending migrations/*.sql to DATABASE_URL (also runs on boot)"
	@echo
	@echo "To connect your AI client in cloud mode, set in its MCP config env:"
	@echo "    GCONTEXT_API_URL=$(CLOUD_URL)   GCONTEXT_TOKEN=$(TOKEN)"

# Throwaway local Postgres for dev/tests. Data is ephemeral.
pg:
	docker run -d --name gcontext-pg -e POSTGRES_PASSWORD=pw -e POSTGRES_DB=gcontext \
		-p 5432:5432 postgres:16

# Run the cloud API; it serves the built React dashboard (web/dist) at CLOUD_URL/.
# Run `make web` first (or `make web-dev` for hot reload against this API).
dev:
	@echo "cloud API + dashboard -> $(CLOUD_URL)  (log in / sign up there)"
	@echo "(build the dashboard first with: make web)"
	@echo "(Ctrl-C to stop)"
	DATABASE_URL=$(DATABASE_URL) GCONTEXT_DEV_TOKEN=$(TOKEN) PORT=$(CLOUD_PORT) uv run cloud_api.py

cloud:
	DATABASE_URL=$(DATABASE_URL) GCONTEXT_DEV_TOKEN=$(TOKEN) PORT=$(CLOUD_PORT) uv run cloud_api.py

# Build the React dashboard into web/dist (what cloud_api.py serves at /).
web:
	cd web && npm install && npm run build

# Vite dev server with hot reload. Proxies /rpc,/tokens,/health to the cloud API, so run
# `make cloud` alongside it. Put SUPABASE creds in web/.env.local (VITE_SUPABASE_URL/KEY).
web-dev:
	cd web && npm install && npm run dev

dashboard:
	GCONTEXT_API_URL=$(CLOUD_URL) GCONTEXT_TOKEN=$(TOKEN) uv run dashboard.py

# Apply pending migrations. The server also calls migrate() on boot, so this is just for
# applying a schema change without a full restart (or against a one-off DB).
migrate:
	DATABASE_URL=$(DATABASE_URL) uv run python -c "import cloud_api; cloud_api.migrate()"
