.PHONY: help build build-cli build-cli-all run test clean vet tidy check run-check db-dir

help: ## 显示帮助信息
	@echo "======================================"
	@echo "用户管理系统 - Makefile"
	@echo "======================================"
	@echo "可用命令:"
	@echo "  make check       - 全面检查（依赖+vet+编译+测试）"
	@echo "  make build       - 构建应用"
	@echo "  make build-cli   - 构建 UMS CLI"
	@echo "  make build-cli-all - 交叉编译所有平台"
	@echo "  make run         - 运行应用"
	@echo "  make test        - 运行测试"
	@echo "  make vet         - 代码静态检查"
	@echo "  make tidy        - 整理依赖"
	@echo "  make db-dir      - 创建数据库目录"
	@echo "  make clean       - 清理构建文件"
	@echo ""

# CLI 构建配置
CLI_NAME = ums
VERSION = 1.0.0
COMMIT = $(shell git rev-parse --short HEAD 2>/dev/null || echo "dev")
BUILD_DATE = $(shell date -u '+%Y-%m-%d_%H:%M:%S')
LDFLAGS = -ldflags "-X github.com/user-management-system/cmd/ums/cmd.Version=$(VERSION) -X github.com/user-management-system/cmd/ums/cmd.Commit=$(COMMIT) -X github.com/user-management-system/cmd/ums/cmd.BuildDate=$(BUILD_DATE)"

# 平台列表
PLATFORMS = darwin/amd64 darwin/arm64 linux/amd64 linux/arm64 windows/amd64

check: tidy vet build build-cli test ## 全面检查：依赖+静态检查+编译+测试

tidy: ## 整理Go模块依赖
	@echo "整理依赖..."
	go mod tidy
	go mod download

vet: ## 运行静态代码检查
	@echo "运行静态检查..."
	go vet ./...

build: db-dir ## 构建应用
	@echo "构建应用..."
	go build -o bin/server cmd/server/main.go

build-cli: ## 构建 UMS CLI（当前平台）
	@echo "构建 UMS CLI..."
	CGO_ENABLED=0 go build $(LDFLAGS) -o bin/$(CLI_NAME) cmd/ums/main.go

build-cli-all: $(PLATFORMS) ## 构建所有平台的 CLI
	@echo "所有平台构建完成"

build-cli-%:
	@platform=$(patsubst %/%,%,$@); \
	os=$(platform%%/*); \
	arch=$(platform##*/); \
	echo "Building for $$os/$$arch"; \
	CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build $(LDFLAGS) -o bin/$(CLI_NAME)-$$os-$$arch cmd/ums/main.go

run: db-dir ## 运行应用
	@echo "运行应用..."
	go run cmd/server/main.go

test: ## 运行测试
	@echo "运行测试..."
	go test -short -race ./...

db-dir: ## 创建数据库目录
	@if [ ! -d "data" ]; then mkdir data; fi

clean: ## 清理构建文件
	@echo "清理构建文件..."
	rm -rf bin/
	rm -f server.exe
