#!/bin/bash
# One API 完整构建脚本
# 预编译 Go 二进制和前端，加速 Docker 部署

set -e

VERSION=$(cat VERSION 2>/dev/null || echo "v0.0.0")
if [ -z "$VERSION" ]; then
    VERSION="v0.0.0"
fi
echo "=== Building One API $VERSION ==="

# 1. 构建前端（default 主题，其他主题可选）
echo ""
echo "--- Building frontend (default theme) ---"
cd web/default
npm install --legacy-peer-deps 2>/dev/null || npm install
DISABLE_ESLINT_PLUGIN='true' REACT_APP_VERSION="$VERSION" npm run build
cd ../..

# 2. 复制前端构建到 web/build
echo ""
echo "--- Copying frontend build ---"
mkdir -p web/build
cp -r web/default/build/* web/build/ 2>/dev/null || true

# 3. 构建 Go 后端（静态编译）
echo ""
echo "--- Building Go backend ---"
go mod download
go build -trimpath -ldflags "-s -w -X 'github.com/songquanpeng/one-api/common.Version=$VERSION'" -o one-api

echo ""
echo "=== Build complete! ==="
echo "Binary: one-api"
echo "Frontend: web/build/"
echo ""
echo "Now you can run:"
echo "  docker build -t redline-api .  # 快速构建（使用预编译文件）"
echo "  # 或直接运行:"
echo "  ./one-api --port 3000 --log-dir ./logs"