#!/bin/bash
# ============================================================
# Vue 前端构建脚本
# ============================================================
# 用途：
#   本地构建前端产物，用于手动部署到 5.60 的 /opt/troubleshoot/dist/
#
# 使用方式：
#   ./build.sh              # 构建生产版本
#   ./build.sh --preview    # 构建后本地预览
#
# 部署到 5.60（容器已运行时）：
#   scp -r dist/* user@192.168.5.60:/opt/troubleshoot/dist/
#   # 或者：docker exec troubleshoot nginx -s reload
# ============================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DIST_DIR="${SCRIPT_DIR}/dist"

# 颜色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info() { echo -e "${GREEN}[INFO]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }

# ---------- 检查 Node ----------
if ! command -v node &> /dev/null; then
    echo "[ERROR] Node.js 未安装，请先安装: https://nodejs.org/"
    exit 1
fi

if ! command -v npm &> /dev/null; then
    echo "[ERROR] npm 未安装"
    exit 1
fi

info "Node: $(node --version)"
info "npm: $(npm --version)"

# ---------- 安装依赖 ----------
info "安装依赖..."
cd "${SCRIPT_DIR}"
npm ci --registry=https://registry.npmmirror.com

# ---------- 类型检查 ----------
info "TypeScript 类型检查..."
if npx vue-tsc --noEmit; then
    info "类型检查通过"
else
    warn "类型检查有错误，继续构建..."
fi

# ---------- 构建 ----------
info "构建生产版本..."
npm run build

# ---------- 输出 ----------
if [ -f "${DIST_DIR}/index.html" ]; then
    info "构建完成！"
    info "产物目录: ${DIST_DIR}"
    info ""
    info "文件列表:"
    ls -lh "${DIST_DIR}/"
    ls -lh "${DIST_DIR}/assets/" 2>/dev/null || true
    info ""
    info "部署到 5.60："
    info "  scp -r ${DIST_DIR}/* user@192.168.5.60:/opt/troubleshoot/dist/"
    info "  # 或在容器内: docker exec troubleshoot nginx -s reload"
else
    echo "[ERROR] 构建失败，dist/index.html 不存在"
    exit 1
fi

# ---------- 预览 ----------
if [ "${1:-}" = "--preview" ]; then
    info "启动本地预览..."
    npx vite preview --port 4173
fi
