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

cd "$(dirname "$0")/.."

if ! command -v zip >/dev/null 2>&1; then
  echo "zip command not found. Install zip and try again."
  exit 1
fi

STAMP="$(date +%Y%m%d_%H%M%S)"
PACKAGE_NAME="${1:-athenode_source_${STAMP}}"
DIST_DIR="${DIST_DIR:-dist}"
STAGE_DIR="$(mktemp -d)"
OUT_ROOT="${STAGE_DIR}/${PACKAGE_NAME}"

cleanup() {
  rm -rf "${STAGE_DIR}"
}
trap cleanup EXIT

mkdir -p "${OUT_ROOT}"

ITEMS=(
  "VERSION"
  "Main.py"
  "ask.py"
  "build_index.py"
  "chunk_note.py"
  "fetch_text_from_selected_onenote_url.py"
  "llm_provider.py"
  "requirements.txt"
  "requirements-optional.txt"
  "requirements-packaging.txt"
  ".env.example"
  "DEPLOYMENT.md"
  "PACKAGING_ROADMAP.md"
  "packaging"
  "scripts"
  "server"
)

for item in "${ITEMS[@]}"; do
  if [ -e "${item}" ]; then
    cp -R "${item}" "${OUT_ROOT}/"
  else
    echo "[WARN] Missing item (skipped): ${item}"
  fi
done

# Remove transient/generated files from release bundle.
rm -rf "${OUT_ROOT}/server/data"
find "${OUT_ROOT}" -type d -name "__pycache__" -prune -exec rm -rf {} +
find "${OUT_ROOT}" -type f \( -name "*.pyc" -o -name "*.pyo" -o -name ".DS_Store" \) -delete

mkdir -p "${DIST_DIR}"
ZIP_PATH="${DIST_DIR}/${PACKAGE_NAME}.zip"

(
  cd "${STAGE_DIR}"
  zip -qr "${OLDPWD}/${ZIP_PATH}" "${PACKAGE_NAME}"
)

if command -v shasum >/dev/null 2>&1; then
  shasum -a 256 "${ZIP_PATH}" > "${ZIP_PATH}.sha256"
fi

echo "Created release: ${ZIP_PATH}"
if [ -f "${ZIP_PATH}.sha256" ]; then
  echo "Created checksum: ${ZIP_PATH}.sha256"
fi
