# ============================================================
# go-sms(Go-sms)开发工具集(Day 1)
# 常用:make up | make down | make logs | make test | make build
# ============================================================
COMPOSE_FILE := docker-compose.dev.yaml
COMPOSE       := docker compose -f $(COMPOSE_FILE)

GO      ?= go
SERVICE ?= gateway
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
GOPROXY ?= $(shell $(GO) env GOPROXY 2>/dev/null || echo https://proxy.golang.org,direct)

.DEFAULT_GOAL := help
.PHONY: help up wait-healthy down restart logs ps tidy build test vet fmt lint config docker-build run run-consumer dev dev-stop

help: ## 显示帮助信息
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-16s\033[0m %s\n", $$1, $$2}'

up: ## 启动全部开发中间件容器并等待 healthy
	$(COMPOSE) up -d
	@$(MAKE) --no-print-directory wait-healthy

wait-healthy: ## 等待全部容器健康检查通过(最长 3 分钟;仅统计定义了 healthcheck 的容器,prometheus/alertmanager 无则不阻塞)
	@echo ">> 等待所有服务通过健康检查..."
	@ok=0; \
	for i in $$(seq 1 90); do \
		total=$$($(COMPOSE) ps -a --format json 2>/dev/null | grep -c '"Health":"[a-z]' || true); \
		healthy=$$($(COMPOSE) ps -a --format json 2>/dev/null | grep -c '"Health":"healthy"' || true); \
		if [ "$$total" -gt 0 ] && [ "$$healthy" -eq "$$total" ]; then ok=1; break; fi; \
		sleep 2; \
	done; \
	if [ "$$ok" -ne 1 ]; then \
		echo "!! 超时:部分容器未达到 healthy,请执行 make logs 排查"; \
		$(COMPOSE) ps; exit 1; \
	fi; \
	echo ">> 全部 $$healthy 个容器均已 healthy"

down: ## 停止并完全清理开发环境(含数据卷)
	$(COMPOSE) down -v --remove-orphans
	@echo ">> 开发环境已完全清理"

restart: ## 重启开发环境容器
	$(COMPOSE) restart
	@$(MAKE) --no-print-directory wait-healthy

logs: ## 跟踪查看全部容器日志(最近 100 行)
	$(COMPOSE) logs -f --tail=100

ps: ## 查看容器运行状态
	$(COMPOSE) ps

tidy: ## 整理 Go 依赖(go mod tidy)
	$(GO) mod tidy

build: ## 编译全部包(go build ./...)
	$(GO) build ./...

test: ## 运行单元测试(竞态检测 + 覆盖率)
	$(GO) test -race -cover ./...

vet: ## Go 官方静态检查
	$(GO) vet ./...

fmt: ## 格式化代码
	$(GO) fmt ./...

lint: ## golangci-lint v2 检查(安装: GOTOOLCHAIN=go1.25.0 go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.1.6)
	golangci-lint run

config: ## 校验 docker-compose 配置语法
	$(COMPOSE) config -q && echo ">> docker-compose 配置语法正确"

run: ## 本地编译并运行网关(固定路径 bin/gateway,便于进程管理)
	@mkdir -p bin logs
	$(GO) build -o bin/gateway ./cmd/gateway
	GOSMS_LOG_FILE_PATH=$${GOSMS_LOG_FILE_PATH:-./logs/app.log} ./bin/gateway

run-consumer: ## 本地编译并运行 submit 消费者(Day48;bin/consumer,日志 logs/consumer.log)
	@mkdir -p bin logs
	$(GO) build -o bin/consumer ./cmd/consumer
	GOSMS_LOG_FILE_PATH=$${GOSMS_LOG_FILE_PATH:-./logs/consumer.log} ./bin/consumer

init-topics: ## 预创建四个核心 Kafka Topic(A-0.4)
	sh scripts/init_kafka_topics.sh

init-mysql: ## 初始化 MySQL 基础库(建库 gosms)
	docker exec -i go-sms-mysql mysql -uroot -proot123 < scripts/init_mysql.sql && \
		echo ">> MySQL gosms 库初始化完成"

init-schema: ## 执行 36 张表 DDL(幂等,IF NOT EXISTS)
	docker exec -i go-sms-mysql mysql -uroot -proot123 gosms < scripts/init_schema.sql && \
		echo ">> 36 张表 DDL 执行完成"

ci-local: ## 本地模拟 CI 流水线(test → build → deploy-dev,需 kind 集群 go-sms-dev)
	@echo ">> [1/3] test:go vet + go test"
	$(GO) vet ./... && $(GO) test -race -cover ./...
	@echo ">> [2/3] build:docker build(镜像 go-sms-$(SERVICE):$(VERSION))"
	docker build --build-arg SERVICE=$(SERVICE) --build-arg VERSION=$(VERSION) \
		--build-arg GOPROXY=$(GOPROXY) -t go-sms-$(SERVICE):$(VERSION) .
	@echo ">> [3/3] deploy-dev:kind load + kubectl rollout"
	kind load docker-image go-sms-$(SERVICE):$(VERSION) --name go-sms-dev
	kubectl -n go-sms-dev set image deployment/go-sms-$(SERVICE) $(SERVICE)=go-sms-$(SERVICE):$(VERSION)
	kubectl -n go-sms-dev rollout restart deployment/go-sms-$(SERVICE)
	kubectl -n go-sms-dev rollout status deployment/go-sms-$(SERVICE) --timeout=180s
	@echo ">> CI 流水线本地模拟完成:curl http://127.0.0.1:30080/health 验证"
	@echo ">> 注意:deployment.yaml 的 image 基线为 go-sms-\$$(SERVICE):dev;"
	@echo ">>       使用其他 VERSION 部署后,请勿直接 apply 覆盖(会回退基线镜像)"

docker-build: ## 构建服务镜像(默认 gateway,可 SERVICE=business 等)
	docker build --build-arg SERVICE=$(SERVICE) --build-arg VERSION=$(VERSION) \
		--build-arg GOPROXY=$(GOPROXY) -t go-sms-$(SERVICE):$(VERSION) .

# ---- Web 端线上测试(Day 36 增补;Mock 模式零依赖,无需后端/中间件) ----
WEB_PORT ?= 5173

web-dev: ## 启动 Web 线上测试(Mock 模式,后台常驻;WEB_PORT=5173 可覆盖)
	@mkdir -p logs
	@if ss -tln 2>/dev/null | grep -q ":$(WEB_PORT) "; then \
		echo ">> 端口 $(WEB_PORT) 已被占用(可能已在运行): make web-log 查看 / make web-stop 停止"; exit 1; fi
	@nohup ./web/node_modules/.bin/vite web --host 0.0.0.0 --port $(WEB_PORT) --strictPort > logs/web-dev.log 2>&1 &
	@ok=0; for i in $$(seq 1 30); do sleep 1; \
		curl -sf -o /dev/null http://127.0.0.1:$(WEB_PORT)/ && { ok=1; break; }; done; \
	if [ "$$ok" != 1 ]; then echo ">> 启动失败,查看 logs/web-dev.log"; exit 1; fi
	@ss -tlnp 2>/dev/null | grep ":$(WEB_PORT) " | grep -oP 'pid=\K[0-9]+' | head -1 > logs/web-dev.pid
	@echo ">> Web 线上测试已启动(Mock 模式,pid=$$(cat logs/web-dev.pid))"
	@echo ">>   本机:   http://127.0.0.1:$(WEB_PORT)"
	@echo ">>   局域网: http://<服务器IP>:$(WEB_PORT)  (Mock 登录: admin/admin123 或 customer/123456)"
	@echo ">> 日志: make web-log | 停止: make web-stop"

web-stop: ## 停止 Web 线上测试(端口占用兜底清理)
	@if [ -f logs/web-dev.pid ] && kill -0 $$(cat logs/web-dev.pid) 2>/dev/null; then \
		kill $$(cat logs/web-dev.pid); fi
	@sleep 1
	@if ss -tln 2>/dev/null | grep -q ":$(WEB_PORT) "; then \
		pkill -f "vite web --host .*--port $(WEB_PORT)" && echo ">> 已停止(兜底 pkill)"; \
	else echo ">> 已停止"; fi
	@rm -f logs/web-dev.pid

web-log: ## 查看 Web 启动日志(尾部 30 行)
	@tail -n 30 logs/web-dev.log 2>/dev/null || echo ">> 无日志(尚未启动?)"

web-test: ## Web 质量门:lint + Vitest + build(与 L1 DoD 一致)
	cd web && ./node_modules/.bin/eslint . --ext .ts,.vue --max-warnings 0 \
		&& ./node_modules/.bin/vitest run && npm run build

# ---- 真实模式联调(Day 31:网关 :8081 + Web real;首启先 make seed-admin) ----
GW_PORT ?= 8081

seed-admin: ## 首启引导:迁移 + 内置超管 admin(密码仅打印一次;已有账号则跳过)
	go run ./cmd/migrate -config configs/config.dev.yaml seed-admin

gw-start: ## 启动网关(后台,:8081;8080 被宿主旧进程占用故用 8081,可用 GW_PORT 覆盖)
	@mkdir -p logs
	@if ss -tln 2>/dev/null | grep -q ":$(GW_PORT) "; then echo ">> 网关已在 :$(GW_PORT) 运行"; exit 0; fi
	@go build -o bin/gateway ./cmd/gateway
	@nohup env GOSMS_LOG_FILE_PATH=./logs/app.log GOSMS_SERVER_HTTP_ADDR=:$(GW_PORT) ./bin/gateway > logs/gateway-run.log 2>&1 & echo $! > logs/gateway.pid
	@sleep 2
	@curl -sf http://127.0.0.1:$(GW_PORT)/health || { echo ">> 启动失败,查看 logs/gateway-run.log"; exit 1; }
	@echo ""
	@echo ">> 网关已启动(:$(GW_PORT),pid=$$(cat logs/gateway.pid))"

gw-stop: ## 停止网关
	@if [ -f logs/gateway.pid ] && kill -0 $$(cat logs/gateway.pid) 2>/dev/null; then \
		kill $$(cat logs/gateway.pid); echo ">> 已停止"; else echo ">> 未在运行"; fi

web-real: ## 启动 Web 真实模式(依赖 gw-start;vite proxy 已指向 :8081)
	@$(MAKE) gw-start
	@if [ ! -f web/.env.development.local ]; then \
		echo 'VITE_API_MODE=real' > web/.env.development.local; \
		echo ">> 已创建 web/.env.development.local(不入库)"; fi
	@if ss -tln 2>/dev/null | grep -q ":$(WEB_PORT) "; then echo ">> Web 已在 :$(WEB_PORT) 运行"; \
		else $(MAKE) web-dev; fi
	@echo ">> 真实模式就绪: http://<服务器IP>:$(WEB_PORT)  (登录: make seed-admin 打印的 admin 密码)"

svc-status: ## 三服务健康一览(网关/Web/MySQL)
	@printf '%-12s' 'gateway:'; curl -sf -m 2 http://127.0.0.1:$(GW_PORT)/health > /dev/null \
		&& echo "OK (:$(GW_PORT))" || echo "DOWN"
	@printf '%-12s' 'web(5173):'; curl -sf -m 2 -o /dev/null http://127.0.0.1:$(WEB_PORT)/ \
		&& echo "OK" || echo "DOWN"
	@printf '%-12s' 'mysql:'; docker exec go-sms-mysql mysql -uroot -proot123 -e 'SELECT 1' > /dev/null 2>&1 \
		&& echo "OK" || echo "DOWN"

# ---- 一键开发环境(scripts/dev_up.sh:中间件→DB→seed-admin→网关→Web,全程幂等) ----

dev: ## 一键启动前后端(详见 scripts/dev_up.sh;API_MODE/GW_PORT/WEB_PORT/WITH_CONSUMER/SKIP_INIT 可覆盖)
	@bash scripts/dev_up.sh

dev-stop: ## 一键停止前后端(Web+网关+consumer;中间件不动)
	@bash scripts/dev_down.sh

