#!/bin/bash

# QAUP 前端构建脚本
# 用于 Docker 构建过程中的前端资源构建

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
FRONTEND_DIR="$PROJECT_ROOT/qaup-ui"
BUILD_OUTPUT="$FRONTEND_DIR/dist"

echo "========================================="
echo "QAUP 前端构建开始"
echo "========================================="

# 检查前端目录
if [ ! -d "$FRONTEND_DIR" ]; then
    echo "错误: 前端目录不存在: $FRONTEND_DIR"
    exit 1
fi

cd "$FRONTEND_DIR"

# 检查 package.json
if [ ! -f "package.json" ]; then
    echo "错误: package.json 不存在"
    exit 1
fi

# 清理之前的构建
echo "清理之前的构建文件..."
rm -rf "$BUILD_OUTPUT"

# 安装依赖
echo "安装前端依赖..."
if [ -f "package-lock.json" ]; then
    npm ci
else
    npm install
fi

# 构建生产版本
echo "构建生产版本..."
npm run build:prod

# 验证构建结果
if [ ! -d "$BUILD_OUTPUT" ]; then
    echo "错误: 构建失败，输出目录不存在: $BUILD_OUTPUT"
    exit 1
fi

# 显示构建统计
echo ""
echo "========================================="
echo "前端构建完成统计:"
echo "========================================="
echo "构建输出目录: $BUILD_OUTPUT"
echo "构建文件大小:"
du -sh "$BUILD_OUTPUT"
echo ""
echo "主要文件列表:"
find "$BUILD_OUTPUT" -name "*.html" -o -name "*.js" -o -name "*.css" | head -10

echo ""
echo "前端构建完成！"