#!/bin/bash
# 构建脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 函数定义
log() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Docker 是否安装
if ! command -v docker &> /dev/null; then
    error "Docker 未安装，请先安装 Docker"
    exit 1
fi

# 检查 docker-compose 是否安装
if ! command -v docker-compose &> /dev/null; then
    warn "docker-compose 未安装，尝试使用 docker compose"
    DOCKER_COMPOSE="docker compose"
else
    DOCKER_COMPOSE="docker-compose"
fi

# 获取参数
ENVIRONMENT=${1:-production}
VERSION=${2:-latest}
REGISTRY=${3:-""}

log "开始构建考培练系统前端..."
log "环境: $ENVIRONMENT"
log "版本: $VERSION"

# 设置镜像名称
IMAGE_NAME="kaopeilian-frontend"
if [ -n "$REGISTRY" ]; then
    FULL_IMAGE_NAME="$REGISTRY/$IMAGE_NAME:$VERSION"
else
    FULL_IMAGE_NAME="$IMAGE_NAME:$VERSION"
fi

# 构建镜像
log "构建 Docker 镜像: $FULL_IMAGE_NAME"

if [ "$ENVIRONMENT" = "development" ]; then
    docker build --target development -t "$FULL_IMAGE_NAME-dev" .
    log "开发环境镜像构建完成: $FULL_IMAGE_NAME-dev"
else
    docker build --target production -t "$FULL_IMAGE_NAME" .
    log "生产环境镜像构建完成: $FULL_IMAGE_NAME"
fi

# 清理悬挂镜像
log "清理悬挂镜像..."
docker image prune -f

log "构建完成！"

# 显示镜像信息
log "镜像信息:"
docker images | grep "$IMAGE_NAME" | head -5
