#!/bin/bash

# 知识盒子前端构建脚本
# 用于生产环境打包

echo "================================================"
echo "      知识盒子 - 前端项目构建脚本"
echo "================================================"
echo ""

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

# 检查 Node.js 是否安装
if ! command -v node &> /dev/null; then
    echo -e "${RED}错误: 未检测到 Node.js，请先安装 Node.js${NC}"
    exit 1
fi

# 检查 npm 是否安装
if ! command -v npm &> /dev/null; then
    echo -e "${RED}错误: 未检测到 npm，请先安装 npm${NC}"
    exit 1
fi

# 显示版本信息
echo -e "${GREEN}✓ Node.js 版本:${NC} $(node -v)"
echo -e "${GREEN}✓ npm 版本:${NC} $(npm -v)"
echo ""

# 检查 node_modules 是否存在
if [ ! -d "node_modules" ]; then
    echo -e "${YELLOW}⚠ 未检测到 node_modules 目录${NC}"
    echo "正在安装依赖..."
    npm install
    echo ""
fi

# 清理旧的构建文件
if [ -d "build" ]; then
    echo -e "${YELLOW}清理旧的构建文件...${NC}"
    rm -rf build
    echo -e "${GREEN}✓ 清理完成${NC}"
    echo ""
fi

# 开始构建
echo -e "${BLUE}🔨 开始构建生产版本...${NC}"
echo ""

npm run build

# 检查构建是否成功
if [ $? -eq 0 ]; then
    echo ""
    echo "================================================"
    echo -e "${GREEN}✓ 构建成功！${NC}"
    echo "================================================"
    echo ""
    echo "构建文件位置: ./build"
    echo ""
    echo "部署步骤:"
    echo "  1. 将 build 目录上传到服务器"
    echo "  2. 配置 Nginx 或 Apache 指向 build 目录"
    echo "  3. 确保配置 URL 重写支持 React Router"
    echo ""
    echo "示例 Nginx 配置:"
    echo "  location / {"
    echo "    root /path/to/build;"
    echo "    index index.html;"
    echo "    try_files \$uri /index.html;"
    echo "  }"
    echo ""
else
    echo ""
    echo "================================================"
    echo -e "${RED}✗ 构建失败${NC}"
    echo "================================================"
    echo ""
    echo "请检查上方错误信息并修复后重试"
    exit 1
fi

