# AISniff — 根目录 Makefile
#
# 便捷封装，详细语义见 CLAUDE.md「测试章节（强制）」与「Dev workflow」。
#
# 端口优先级：DEBUG_PORT env > CLI --port > PORT env > config.port > 8088
# 设了 DEBUG_PORT 后，config 目录与 DuckDB 文件也会自动隔离到
# $(TMPDIR)aisniff-debug-<port>/ 下，绝不触碰用户真实的 ~/.aisniff 状态。

DEBUG_PORT ?= 18099

.PHONY: dev debug test start stop lint format clean help

# 普通启动（用户真实状态，默认端口）
start dev:
	npm start

# Debug 启动：隔离端口 + 隔离 config/DB，不影响真实 proxy
debug:
	DEBUG_PORT=$(DEBUG_PORT) npm start

# 停掉 debug 实例（只杀 DEBUG_PORT 端口的进程，绝不动默认端口上的真实 proxy）
stop:
	@lsof -ti:$(DEBUG_PORT) | xargs -r kill && echo "stopped debug instance on :$(DEBUG_PORT)" || echo "no process on :$(DEBUG_PORT)"

# 强制三项测试：单元测试 + 启动测试(debug) + app 构建，任一失败即返回非零
test:
	@echo "==> [1/3] 单元测试 (node test runner)"
	@for f in tests/*.test.js; do \
		echo "    running $$f"; \
		node "$$f" || { echo "    FAIL $$f"; exit 1; }; \
	done
	@echo "==> [2/3] 启动测试 (DEBUG_PORT=$(DEBUG_PORT), 隔离 config/DB)"
	@DEBUG_PORT=$(DEBUG_PORT) node server.js > /tmp/aisniff-debug-$(DEBUG_PORT).log 2>&1 & \
		echo $$! > /tmp/aisniff-debug-$(DEBUG_PORT).pid; \
		sleep 2; \
		code=$$(curl -s -o /dev/null -w "%{http_code}" http://localhost:$(DEBUG_PORT)/ || echo 000); \
		kill "$$(cat /tmp/aisniff-debug-$(DEBUG_PORT).pid)" 2>/dev/null; \
		if [ "$$code" = "200" ]; then echo "    server responded 200 ✓"; else echo "    server HTTP $$code ✗"; cat /tmp/aisniff-debug-$(DEBUG_PORT).log; exit 1; fi
	@echo "==> [3/3] mac app 构建"
	@cd app && make app
	@echo "==> 全部通过 ✓"

lint:
	npm run lint

format:
	npm run format

# 清理 debug 隔离目录（config/DB 临时文件）
clean:
	@rm -rf "$(TMPDIR)aisniff-debug-$(DEBUG_PORT)" 2>/dev/null; \
	rm -f /tmp/aisniff-debug-$(DEBUG_PORT).log /tmp/aisniff-debug-$(DEBUG_PORT).pid; \
	echo "cleaned debug sandbox for :$(DEBUG_PORT)"

help:
	@echo "AISniff targets:"
	@echo "  make debug       - 隔离启动 (DEBUG_PORT=$(DEBUG_PORT))"
	@echo "  make stop        - 停 debug 实例（只杀 :$(DEBUG_PORT)）"
	@echo "  make test        - 跑全部三项检查（单测/启动/app构建）"
	@echo "  make start       - 普通启动（用户真实状态）"
	@echo "  make lint        - eslint"
	@echo "  make format      - prettier"
	@echo "  make clean       - 清理 debug 隔离目录"
	@echo "  覆盖端口: make debug DEBUG_PORT=19000"
