#!/bin/bash
set -e

# ==========================================
# 统一构建脚本 (CI Build Script)
# 功能：自动检测环境、安装 Node.js (不依赖系统预装)、构建项目、打包产物
# 解决：Runner 环境缺失 Node/Docker/Python 等工具导致的问题
# ==========================================

# 配置节点版本
NODE_VERSION="20.10.0"
DIST_FILE="site_dist.tgz"

echo ">>> [Init] Starting CI Build Script..."

# ----------------------------------------------------------------
# 1. 基础工具检测与安装 (curl, tar, xz)
# ----------------------------------------------------------------
ensure_tools() {
    echo ">>> [Tools] Checking basic tools..."
    local missing_tools=()
    
    for tool in curl tar xz; do
        if ! command -v "$tool" &> /dev/null; then
            missing_tools+=("$tool")
        fi
    done

    if [ ${#missing_tools[@]} -eq 0 ]; then
        echo "    All tools present."
        return 0
    fi

    echo "    Missing tools: ${missing_tools[*]}. Attempting installation..."
    
    if command -v apk &> /dev/null; then
        apk add --no-cache curl tar xz
    elif command -v apt-get &> /dev/null; then
        apt-get update && apt-get install -y curl tar xz-utils
    elif command -v yum &> /dev/null; then
        yum install -y curl tar xz
    elif command -v dnf &> /dev/null; then
        dnf install -y curl tar xz
    elif command -v zypper &> /dev/null; then
        zypper install -y curl tar xz
    else
        echo "!!! Error: Cannot install missing tools. No known package manager found."
        exit 1
    fi
}

# ----------------------------------------------------------------
# 2. 环境安装 (System Node.js - Most Reliable on Alpine)
# ----------------------------------------------------------------
install_env() {
    echo ">>> [Env] Setting up System Node.js environment..."
    
    # 尝试使用系统包管理器安装 Node.js 和 npm
    if command -v apk &> /dev/null; then
        echo "    Detected Alpine Linux. Installing nodejs and npm via apk..."
        apk add --no-cache nodejs npm
    elif command -v apt-get &> /dev/null; then
        echo "    Detected Debian/Ubuntu. Installing nodejs and npm via apt..."
        apt-get update && apt-get install -y nodejs npm
    elif command -v yum &> /dev/null; then
        yum install -y nodejs npm
    elif command -v dnf &> /dev/null; then
        dnf install -y nodejs npm
    elif command -v zypper &> /dev/null; then
        zypper install -y nodejs npm
    else
        echo "!!! Warning: No package manager found. Checking if Node is pre-installed..."
    fi

    # 验证安装
    if ! command -v node &> /dev/null; then
        echo "!!! Error: Node.js not found and could not be installed."
        exit 1
    fi
    
    if ! command -v npm &> /dev/null; then
        echo "!!! Error: npm not found and could not be installed."
        exit 1
    fi

    echo "    Node version: $(node -v)"
    echo "    npm version: $(npm -v)"
}

# ----------------------------------------------------------------
# 3. 项目构建与打包
# ----------------------------------------------------------------
build_project() {
    echo ">>> [Build] Starting project build..."
    
    # 注入环境变量
    if [ -n "$VITE_APP_BASE_URL" ]; then
        echo "    Setting VITE_APP_BASE_URL=${VITE_APP_BASE_URL}"
        # 兼容 package.json 中的 mode: pord (Typo in original project)
        echo "VITE_APP_BASE_URL=${VITE_APP_BASE_URL}" > .env.pord
        # 同时写入 .env 以防万一
        echo "VITE_APP_BASE_URL=${VITE_APP_BASE_URL}" >> .env
    fi

    echo "    Installing dependencies..."
    # 使用 npm install 而不是 npm ci，以避免因 lockfile 版本不匹配或 engines 检查导致的失败
    npm install --no-audit --progress=false

    echo "    Building..."
    # 使用 package.json 中定义的 build:prod 命令
    npm run build:prod

    echo ">>> [Package] Compressing artifacts..."
    if [ ! -d "dist" ]; then
        echo "!!! Error: 'dist' directory not found after build."
        # 列出当前目录以便调试
        ls -la
        exit 1
    fi

    # 直接打包 dist 目录下的内容
    tar -C dist -czf "$DIST_FILE" .
    
    echo "    Success! Artifact created: $DIST_FILE"
    ls -lh "$DIST_FILE"
}

# ==========================================
# Main Execution Flow
# ==========================================
ensure_tools
install_env
build_project
