# Agent Engine — service lifecycle (Docker)
# Usage: make help
#
# Three services, one container each, managed by docker compose:
#   web               Next.js dashboard + internal/public APIs + widget host
#   rag-agent         FastAPI answer runtime
#   embedding-worker  document -> chunks -> embeddings
# Rules: CLAUDE.md §5 and §6.

SHELL := /bin/bash
.DEFAULT_GOAL := help

ROOT := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))

SERVICES := web rag-agent embedding-worker

# apps/web/.env supplies the NEXT_PUBLIC_* build args the web image needs.
# Each service still loads its own .env at runtime via `env_file:` in compose.
COMPOSE := docker compose --env-file $(ROOT)/apps/web/.env

# Parameters. See `make help <command>` for which command uses which.
N       ?= 200
FOLLOW  ?= 1
NOCACHE ?= 0

PS_FMT := table {{.Name}}\t{{.Service}}\t{{.State}}\t{{.Status}}\t{{.Ports}}

# `make help <command>` — capture the second word, swallow it so make does not
# try to build it, and skip defining the real targets so there is no rule clash.
ifeq (help,$(firstword $(MAKECMDGOALS)))
  HELP_TOPIC := $(word 2,$(MAKECMDGOALS))
  ifneq ($(HELP_TOPIC),)
    $(eval $(HELP_TOPIC): ; @:)
  endif
  HELP_ONLY := 1
endif
ifeq ($(strip $(HELP_TOPIC)),)
  HELP_TOPIC := $(strip $(CMD))
endif

# ---------------------------------------------------------------------------
# Help
# ---------------------------------------------------------------------------

.PHONY: help
help: ## Show available make targets (this help)
	@topic="$(strip $(HELP_TOPIC))"; \
if [ -n "$$topic" ]; then \
  base="$$topic"; svc=""; \
  for s in $(SERVICES); do \
    case "$$topic" in *-"$$s") base="$${topic%-$$s}"; svc="$$s";; esac; \
  done; \
  key="HELP_$${base//-/_}"; \
  if [ -z "$${!key+x}" ]; then \
    printf '\033[31m✗\033[0m No help for "%s".\n\n' "$$topic" >&2; \
    printf 'Commands: up down restart logs status ps build help\n' >&2; \
    printf 'Most also take a service suffix, e.g. \033[36mup-web\033[0m.\n\n' >&2; \
    printf 'Run `make help` for the full list.\n' >&2; exit 1; \
  fi; \
  if [ -n "$$svc" ]; then printf '\033[36mService:\033[0m %s\n\n' "$$svc"; fi; \
  printf '%s\n' "$${!key}"; exit 0; \
fi; \
echo "Agent Engine — make targets"; \
echo ""; \
echo "Quick start (local dev):"; \
echo "  make up                 # build if needed, then all three containers"; \
echo "  make ps                 # what is running"; \
echo "  make logs               # interleaved, Ctrl-C to stop watching"; \
echo ""; \
echo "Which services?"; \
echo "  web               → Next.js dashboard + internal/public APIs + widget host"; \
echo "  rag-agent         → FastAPI answer runtime (router, RAG, DB, templates)"; \
echo "  embedding-worker  → document → chunks → embeddings (polls the job table)"; \
echo ""; \
grep -E '^[a-zA-Z0-9_-]+:.*?## ' $(MAKEFILE_LIST) | \
  awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-26s\033[0m %s\n", $$1, $$2}'; \
echo ""; \
echo "Parameters:  N=<lines>   FOLLOW=0|1   NOCACHE=0|1"; \
echo "Detail:      make help <command>   e.g. make help up-web"; \
echo ""; \
echo "Compose: docker-compose.yml    Host ports: web 3001, rag-agent 8080"

ifndef HELP_ONLY

# ---------------------------------------------------------------------------
# All services
# ---------------------------------------------------------------------------

.PHONY: up
up: ## Start every service in its own container (builds the image if missing)
	@echo "→ Starting all containers"
	@$(COMPOSE) up -d
	@echo ""
	@$(MAKE) --no-print-directory status

.PHONY: down
down: ## Stop and remove every container (images and volumes are kept)
	@echo "→ Stopping all containers"
	@$(COMPOSE) down --remove-orphans

.PHONY: restart
restart: ## Restart every container
	@$(MAKE) --no-print-directory down
	@$(MAKE) --no-print-directory up

.PHONY: logs
logs: ## Follow the logs of all containers at once (N=200 backlog, FOLLOW=0 to dump)
	@if [ "$(FOLLOW)" = "1" ]; then $(COMPOSE) logs --tail=$(N) --follow; \
else $(COMPOSE) logs --tail=$(N); fi

.PHONY: status
status: ## Show all containers at a glance (name, state, health, ports)
	@$(COMPOSE) ps --all --format "$(PS_FMT)"

.PHONY: ps
ps: ## Show the running container for every service, with detail
	@for s in $(SERVICES); do $(MAKE) --no-print-directory _ps SVC=$$s; done

.PHONY: build
build: ## Build every image (NOCACHE=1 to ignore the layer cache)
	@echo "→ Building all images"
	@$(COMPOSE) build $(if $(filter 1,$(NOCACHE)),--no-cache,)

# ---------------------------------------------------------------------------
# web — Next.js dashboard, internal + public APIs, widget host
# ---------------------------------------------------------------------------

.PHONY: up-web
up-web: ## Start the web container
	@$(COMPOSE) up -d web

.PHONY: down-web
down-web: ## Stop and remove the web container
	@$(COMPOSE) rm --stop --force web

.PHONY: restart-web
restart-web: ## Restart the web container
	@$(COMPOSE) restart web

.PHONY: logs-web
logs-web: ## Follow the web container log
	@$(MAKE) --no-print-directory _logs SVC=web

.PHONY: ps-web
ps-web: ## Show the running web container
	@$(MAKE) --no-print-directory _ps SVC=web

.PHONY: build-web
build-web: ## Build the web image (NOCACHE=1 to ignore the layer cache)
	@$(COMPOSE) build $(if $(filter 1,$(NOCACHE)),--no-cache,) web

# ---------------------------------------------------------------------------
# rag-agent — FastAPI answer runtime
# ---------------------------------------------------------------------------

.PHONY: up-rag-agent
up-rag-agent: ## Start the RAG agent container
	@$(COMPOSE) up -d rag-agent

.PHONY: down-rag-agent
down-rag-agent: ## Stop and remove the RAG agent container
	@$(COMPOSE) rm --stop --force rag-agent

.PHONY: restart-rag-agent
restart-rag-agent: ## Restart the RAG agent container
	@$(COMPOSE) restart rag-agent

.PHONY: logs-rag-agent
logs-rag-agent: ## Follow the RAG agent container log
	@$(MAKE) --no-print-directory _logs SVC=rag-agent

.PHONY: ps-rag-agent
ps-rag-agent: ## Show the running RAG agent container
	@$(MAKE) --no-print-directory _ps SVC=rag-agent

.PHONY: build-rag-agent
build-rag-agent: ## Build the RAG agent image (NOCACHE=1 to ignore the layer cache)
	@$(COMPOSE) build $(if $(filter 1,$(NOCACHE)),--no-cache,) rag-agent

# ---------------------------------------------------------------------------
# embedding-worker — document → chunks → embeddings
# ---------------------------------------------------------------------------

.PHONY: up-embedding-worker
up-embedding-worker: ## Start the embedding worker container
	@$(COMPOSE) up -d embedding-worker

.PHONY: down-embedding-worker
down-embedding-worker: ## Stop and remove the embedding worker container
	@$(COMPOSE) rm --stop --force embedding-worker

.PHONY: restart-embedding-worker
restart-embedding-worker: ## Restart the embedding worker container
	@$(COMPOSE) restart embedding-worker

.PHONY: logs-embedding-worker
logs-embedding-worker: ## Follow the embedding worker container log
	@$(MAKE) --no-print-directory _logs SVC=embedding-worker

.PHONY: ps-embedding-worker
ps-embedding-worker: ## Show the running embedding worker container
	@$(MAKE) --no-print-directory _ps SVC=embedding-worker

.PHONY: build-embedding-worker
build-embedding-worker: ## Build the embedding worker image (NOCACHE=1 for a clean build)
	@$(COMPOSE) build $(if $(filter 1,$(NOCACHE)),--no-cache,) embedding-worker

# ---------------------------------------------------------------------------
# Internal implementations (not documented in help; use the targets above)
# ---------------------------------------------------------------------------

.PHONY: _logs _ps

_logs:
	@if [ "$(FOLLOW)" = "1" ]; then $(COMPOSE) logs --tail=$(N) --follow $(SVC); \
else $(COMPOSE) logs --tail=$(N) $(SVC); fi

_ps:
	@id="$$($(COMPOSE) ps --quiet $(SVC) 2>/dev/null | head -1)"; \
if [ -z "$$id" ]; then \
  printf '  \033[36m%s\033[0m — no container (start it: make up-%s)\n\n' "$(SVC)" "$(SVC)"; exit 0; fi; \
docker inspect "$$id" --format '{{.Name}}|{{.Config.Image}}|{{.State.Status}}|{{if .State.Health}}{{.State.Health.Status}}{{else}}-{{end}}|{{.State.StartedAt}}|{{.RestartCount}}' \
  | awk -F'|' -v svc="$(SVC)" '{ \
      state = ($$3 == "running") ? "\033[32m" $$3 "\033[0m" : "\033[31m" $$3 "\033[0m"; \
      printf "  \033[36m%s\033[0m\n", svc; \
      printf "    container  %s\n", substr($$1, 2); \
      printf "    image      %s\n", $$2; \
      printf "    state      %s\n", state; \
      printf "    health     %s\n", $$4; \
      printf "    started    %s\n", $$5; \
      printf "    restarts   %s\n", $$6; \
    }'
	@$(COMPOSE) ps $(SVC) --format '{{.Ports}}' 2>/dev/null | sed 's/^/    ports      /'
	@echo ""

endif

# ---------------------------------------------------------------------------
# Per-command help bodies for `make help <command>`
# ---------------------------------------------------------------------------

define HELP_up
make up                 — start every service in its own container
make up-<service>       — start one service's container

  Runs `docker compose up -d`. If an image is missing it is built first;
  an image that already exists is reused, so after changing code run
  `make build` (or `make build-<service>`) before `make up`.
  Containers restart automatically unless explicitly stopped.

  web waits for rag-agent to report healthy before it starts.

  Parameters
    none

  Required beforehand
    A .env file in each service directory:
      apps/web/.env
      apps/agents/rag-agent/.env
      apps/workers/async/embedding-pipeline-worker/.env
    apps/web/.env must define NEXT_PUBLIC_SUPABASE_URL and
    NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY — they are baked into the web
    client bundle at build time.

  Host ports
    web         http://localhost:3001   (container listens on 3000)
    rag-agent   http://localhost:8080   (health: /health)
    Override with WEB_HOST_PORT / RAG_AGENT_HOST_PORT.

  Examples
    make up
    make up-web
    make up-rag-agent
endef
export HELP_up

define HELP_down
make down               — stop and remove every container
make down-<service>     — stop and remove one container

  `make down` runs `docker compose down --remove-orphans`, which also removes
  the compose network. `make down-<service>` removes just that container.
  Images and named volumes are kept in both cases, so the next `make up` is
  fast and nothing is lost.

  Parameters
    none

  Examples
    make down
    make down-web
endef
export HELP_down

define HELP_restart
make restart            — recreate every container
make restart-<service>  — restart one container in place

  `make restart` is down then up, so containers are recreated and any compose
  change is picked up. `make restart-<service>` is `docker compose restart`,
  which restarts the process in the existing container — faster, but it will
  not pick up a new image. After a rebuild use `make up-<service>` instead.

  Parameters
    none

  Examples
    make restart
    make restart-rag-agent
endef
export HELP_restart

define HELP_logs
make logs               — follow every container log at once, interleaved
make logs-<service>     — follow one container's log

  Reads the container logs through docker compose, so a restarted container
  keeps streaming. Ctrl-C stops watching; it does not stop the container.

  Parameters
    N=<lines>        How many existing lines to show before following.
                     Default: 200
    FOLLOW=0|1       1 = keep streaming new lines. 0 = print and exit.
                     Default: 1

  Examples
    make logs
    make logs-rag-agent
    make logs-web N=50
    make logs N=1000 FOLLOW=0
endef
export HELP_logs

define HELP_status
make status             — every container at a glance

  One row per container: name, compose service, state, status (including
  health), and published ports. Includes stopped containers, so it shows
  what exists rather than only what is running.

  For detail on one service — image, health, uptime, restart count — use
  `make ps-<service>`.

  Parameters
    none

  Example
    make status
endef
export HELP_status

define HELP_ps
make ps                 — the running container for every service, with detail
make ps-<service>       — the running container for one service

  Shows what `make status` summarises, but per service and in full:
  container name, image, running state, health, start time, and restart
  count. Prints a hint instead of an error when the service has no
  container yet.

  Parameters
    none

  Examples
    make ps
    make ps-web
    make ps-rag-agent
    make ps-embedding-worker
endef
export HELP_ps

define HELP_build
make build              — build every image
make build-<service>    — build one image

  Rebuild after changing code or dependencies: `make up` reuses an existing
  image and will not pick changes up on its own.

  Parameters
    NOCACHE=1        Ignore the layer cache and build from scratch.
                     Use after changing a base image or to prove a build is
                     reproducible. Default: 0

  Examples
    make build
    make build-web
    make build-rag-agent NOCACHE=1
endef
export HELP_build

define HELP_help
make help               — list every command
make help <command>     — detail and parameters for one command

  The list is generated from the `## ` comment on each target, so it can
  never drift from the targets themselves. The command name may include the
  service, e.g. `make help up-web` shows the help for `up` noting it applies
  to web.

  Parameters
    CMD=<command>    Alternative to the positional form.
                     Example: make help CMD=logs

  Examples
    make help
    make help up
    make help ps-web
    make help CMD=build
endef
export HELP_help
