# IA-Fit — point d'entrée unique (voir CLAUDE.md, « Le contrat du Makefile »).

SHELL := bash
.DEFAULT_GOAL := help

# Vérificateur de types des annotations JSDoc (tsc --checkJs, ADR 0007). Outil de
# développement seulement, installé dans build/tools, jamais publié. Apache-2.0.
TYPESCRIPT_VERSION := 5.9.2
TOOLS := build/tools
TSC := $(TOOLS)/node_modules/.bin/tsc
# Types de Node pour vérifier server/ (même version majeure que Node 24 de
# l'image de production). Outil de développement seulement. MIT.
TYPES_NODE_VERSION := 24.10.1
TYPES_NODE := $(TOOLS)/node_modules/@types/node/package.json
# Analyse des scripts shell, dans Docker pour ne rien installer sur le PC.
SHELLCHECK_IMAGE := koalaman/shellcheck:v0.10.0
DEV_PORT := 8080
# make serve : le serveur de production (server/) sur le site assemblé.
SERVE_PORT := 3000
SERVE_DATA := build/data

# Publication (lot 1f, docs/deploiement.md). APP_DIR et SITE_BUILD peuvent être
# changés à l'appel : tests/test_site.sh assemble ainsi son site d'essai hors de
# build/.
APP_DIR := app
SITE_BUILD := build
SITE := $(SITE_BUILD)/site
# Ce qui, dans app/, n'est jamais publié : fichiers cachés, tests, restes
# d'éditeur.
SITE_EXCLUDE := .[!./]* *.test.js *~ *.swp *.orig

.PHONY: help setup dev serve test test-docs test-unit test-site lint site package deploy-prod

help: ## Liste les commandes disponibles
	@echo "IA-Fit : commandes disponibles"
	@grep -E '^[a-zA-Z0-9_-]+:.*## ' $(MAKEFILE_LIST) \
		| awk 'BEGIN { FS = ":.*## " } { printf "  make %-14s %s\n", $$1, $$2 }'

setup: $(TSC) $(TYPES_NODE) ## Installe les outils de développement (idempotent)

$(TSC) $(TYPES_NODE) &:
	npm install --silent --no-audit --no-fund --prefix $(TOOLS) typescript@$(TYPESCRIPT_VERSION) @types/node@$(TYPES_NODE_VERSION)

dev: ## Sert l'app en local sur le port 8080 (Ctrl+C pour arrêter)
	@echo "App : http://localhost:$(DEV_PORT)/"
	@python3 -m http.server $(DEV_PORT) --directory app

serve: site ## Lance le serveur de production (relais, OAuth, MCP) sur build/site, port 3000
	@echo "Serveur : http://localhost:$(SERVE_PORT)/ (données dans $(SERVE_DATA))"
	@PORT=$(SERVE_PORT) SITE_DIR=$(SITE) DATA_DIR=$(SERVE_DATA) PUBLIC_URL=http://localhost:$(SERVE_PORT) node server/main.js

test: test-docs test-unit ## Lance tous les tests (dont test-site si Docker répond)
	@if docker info >/dev/null 2>&1; then $(MAKE) --no-print-directory test-site; \
	else echo "test-site sauté : Docker indisponible, l'image de production n'est pas vérifiée."; fi

test-docs: ## Vérifie la forme des ADR et du glossaire
	@scripts/check-docs.sh

test-unit: ## Tests du domaine et de l'architecture (node --test)
	@node --test 'tests/**/*.test.js'

lint: $(TSC) $(TYPES_NODE) ## Vérifie les types (JSDoc), la syntaxe et les scripts shell
	@$(TSC) -p tsconfig.json
	@$(TSC) -p tsconfig.server.json
	@for f in $$(find app server tests -name '*.js'); do node --check "$$f" || exit 1; done
	@if command -v shellcheck >/dev/null; then shellcheck scripts/*.sh tests/*.sh; \
	else docker run --rm -v "$(CURDIR):/mnt:ro" -w /mnt $(SHELLCHECK_IMAGE) scripts/*.sh tests/*.sh; fi
	@echo "Lint : OK"

# Parcours dans un vrai navigateur (ADR 0007) : Chromium de l'image Playwright,
# le paquet playwright (Apache-2.0) installé dans build/browser-tools, jamais
# publié. Captures 412×915 et poids transféré dans build/shots/.
PLAYWRIGHT_VERSION := 1.48.2
PLAYWRIGHT_IMAGE := mcr.microsoft.com/playwright:v$(PLAYWRIGHT_VERSION)-noble
BROWSER_TOOLS := build/browser-tools
PLAYWRIGHT := $(BROWSER_TOOLS)/node_modules/playwright/package.json
# Lecture du QR code de la synchro dans une capture d'écran, pour le parcours
# seulement (jamais publié) : jsQR (Apache-2.0) et pngjs (MIT).
JSQR_VERSION := 1.4.0
PNGJS_VERSION := 7.0.0
QR_READER := $(BROWSER_TOOLS)/node_modules/jsqr/package.json

$(PLAYWRIGHT) $(QR_READER) &:
	npm install --silent --no-audit --no-fund --prefix $(BROWSER_TOOLS) playwright@$(PLAYWRIGHT_VERSION) jsqr@$(JSQR_VERSION) pngjs@$(PNGJS_VERSION)

# Le parcours de la synchro (relais, appariement, OAuth) parle au vrai serveur
# (server/main.js), lancé ici avec Node de l'hôte (Node 24, comme en production ;
# celui de l'image Playwright est trop ancien) sur un port libre, avec un
# DATA_DIR temporaire effacé à la fin. Il sert le site assemblé (make site,
# service worker actif), copié dans un dossier temporaire que le parcours
# modifie pour publier une « deuxième version » (bandeau de mise à jour). Le
# conteneur partage le réseau de l'hôte pour joindre le serveur.
# Icônes PNG de l'écran d'accueil (192, 512, maskable 512, apple-touch-icon 180),
# dessinées depuis les SVG de app/icons/ par le Chromium de l'image Playwright
# (scripts/icons.cjs), puis allégées par optipng s'il est installé. Les PNG sont
# commités : à relancer seulement quand un SVG change.
.PHONY: icons
icons: $(PLAYWRIGHT) ## Régénère les icônes PNG depuis app/icons/*.svg (Docker)
	@docker run --rm --init --ipc=host -u "$$(id -u):$$(id -g)" -e HOME=/tmp \
		-v "$(CURDIR)/$(APP_DIR)/icons:/icons" -v "$(CURDIR)/scripts:/scripts:ro" \
		-v "$(CURDIR)/$(BROWSER_TOOLS):/tools:ro" \
		$(PLAYWRIGHT_IMAGE) node /scripts/icons.cjs /icons
	@if command -v optipng >/dev/null; then optipng -quiet -o7 -strip all $(APP_DIR)/icons/*.png; \
	else echo "optipng absent : PNG non optimisés."; fi
	@ls -l $(APP_DIR)/icons/*.png

.PHONY: test-browser
test-browser: $(PLAYWRIGHT) $(QR_READER) ## Parcours Playwright de l'app, captures dans build/shots/ (Docker)
	@mkdir -p build/shots
	@tmp="$$(mktemp -d)"; data="$$tmp/data"; site="$$tmp/build/site"; \
	trap 'kill $$pid 2>/dev/null; rm -rf -- "$$tmp"' EXIT; \
	$(MAKE) --no-print-directory site SITE_BUILD="$$tmp/build" >/dev/null || exit 1; \
	port="$$(node -e 'const s=require("node:net").createServer().listen(0,"127.0.0.1",()=>{console.log(s.address().port);s.close()})')"; \
	PORT="$$port" SITE_DIR="$$site" DATA_DIR="$$data" PUBLIC_URL="http://127.0.0.1:$$port" \
		node server/main.js >"$$tmp/server.log" 2>&1 & pid=$$!; \
	for _ in $$(seq 50); do curl -sf -o /dev/null "http://127.0.0.1:$$port/" && break; sleep 0.1; done; \
	curl -sf -o /dev/null "http://127.0.0.1:$$port/" || { echo "Le serveur ne démarre pas :"; cat "$$tmp/server.log"; exit 1; }; \
	docker run --rm --init --ipc=host --network host -u "$$(id -u):$$(id -g)" -e HOME=/tmp \
		-v "$(CURDIR)/$(APP_DIR):/app:ro" -v "$(CURDIR)/tests/browser:/tests:ro" -v "$$site:/site" \
		-v "$(CURDIR)/$(BROWSER_TOOLS):/tools:ro" -v "$(CURDIR)/build/shots:/shots" \
		$(PLAYWRIGHT_IMAGE) node /tests/parcours.cjs /app /shots "http://127.0.0.1:$$port/"

test-site: ## Construit l'image de production en local et vérifie ce qu'elle sert (Docker)
	@tests/test_site.sh

# Le site tel qu'il sera publié, reconstruit entièrement à chaque appel :
# - tout le contenu de app/ tel qu'il est au moment de l'assemblage (aucune
#   liste en dur : un module ajouté est publié), sauf SITE_EXCLUDE ;
# - version.json (commit publié) ;
# - sw.js, complété par la liste de tous ces fichiers et leur empreinte
#   (scripts/service-worker.sh).
site: ## Assemble le site publié dans build/site/
	@[ -f "$(APP_DIR)/sw.js" ] || { echo "$(APP_DIR)/sw.js absent"; exit 1; }
	@rm -rf -- "$(SITE)"
	@mkdir -p "$(SITE)"
	@tar -C "$(APP_DIR)" $(foreach p,$(SITE_EXCLUDE),--exclude='$(p)') -cf - . | tar -C "$(SITE)" -xf -
	@printf '{"commit": "%s"}\n' "$$(git rev-parse HEAD)" > "$(SITE)/version.json"
	@scripts/service-worker.sh "$(SITE)"
	@echo "Site assemblé : $(SITE)/ ($$(find "$(SITE)" -type f | wc -l) fichiers)"

# L'archive envoyée à CapRover : captain-definition, Dockerfile, le site, le
# serveur (server/), le domaine dont il dépend (app/domain/) et package.json
# (modules ES), sans les fichiers exclus du site. CapRover construit l'image
# (une simple copie) sur le serveur.
package: site ## Prépare l'archive de déploiement build/ia-fit.tar
	@rm -rf -- "$(SITE_BUILD)/deploy"
	@cp -r deploy "$(SITE_BUILD)/deploy"
	@cp -r "$(SITE)" "$(SITE_BUILD)/deploy/site"
	@mkdir -p "$(SITE_BUILD)/deploy/server" "$(SITE_BUILD)/deploy/app/domain"
	@tar -C server $(foreach p,$(SITE_EXCLUDE),--exclude='$(p)') -cf - . | tar -C "$(SITE_BUILD)/deploy/server" -xf -
	@tar -C "$(APP_DIR)/domain" $(foreach p,$(SITE_EXCLUDE),--exclude='$(p)') -cf - . | tar -C "$(SITE_BUILD)/deploy/app/domain" -xf -
	@cp package.json "$(SITE_BUILD)/deploy/package.json"
	@tar -cf "$(SITE_BUILD)/ia-fit.tar" -C "$(SITE_BUILD)/deploy" .
	@echo "Archive prête : $(SITE_BUILD)/ia-fit.tar"

deploy-prod: ## Publie main sur CapRover (voir docs/deploiement.md)
	@scripts/deploy.sh
