#!/usr/bin/env bash
set -euo pipefail

project_root="$(cd "$(dirname "$0")/.." && pwd)"
cd "${project_root}"
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "正式发布必须从 Git 工作区生成"
  exit 1
fi
git_commit="$(git rev-parse HEAD)"
if [[ -n "$(git status --porcelain --untracked-files=all)" ]]; then
  echo "源码存在未提交改动，已停止正式打包"
  exit 1
fi
version="$(node -p 'require("./package.json").version' 2>/dev/null || true)"
if [[ -z "${version}" ]]; then
  version="$(cd "${project_root}" && node -p 'require("./package.json").version')"
fi
output="${1:-${project_root}/release/chuang-employee-workspace-v${version}.tgz}"
mkdir -p "$(dirname "${output}")"
if find server web shared skills deploy -type f \( -name '.env' -o -name '.env.*' -o -name '*.pem' -o -name '*.key' -o -name 'id_rsa*' \) -print -quit | grep -q .; then
  echo "发布目录包含环境文件、证书或私钥，已停止打包"
  exit 1
fi
npm ci
npm run build
node scripts/check-build-chunks.mjs
npm test
RELEASE_GIT_COMMIT="${git_commit}" RELEASE_SOURCE_CLEAN=true node scripts/create-release-manifest.mjs
COPYFILE_DISABLE=1 tar --no-xattrs -czf "${output}" package.json package-lock.json README.md release-center-manifest.json server web shared skills scripts dist deploy
tar -tzf "${output}" | grep -qx 'shared/answer-format.mjs' || {
  echo "发布包缺少运行时 shared/answer-format.mjs，已停止发布"
  exit 1
}
if command -v sha256sum >/dev/null 2>&1; then
  sha256sum "${output}"
else
  shasum -a 256 "${output}"
fi
