#!/usr/bin/env bash
# Package the backend Python source for distribution.
#
# Environment variables:
#   OUTPUT_DIR  - where to write the tarball (default: ./dist)
#   VERSION     - version string (default: read from VERSION file)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WORKSPACE="${SCRIPT_DIR}/.."
OUTPUT_DIR="${OUTPUT_DIR:-${WORKSPACE}/dist}"
VERSION="${VERSION:-$(cat "${WORKSPACE}/VERSION" 2>/dev/null || echo "0.1.0")}"

echo "=== Dangerous Pi Backend Package ==="
echo "Version: ${VERSION}"

STAGING="/tmp/backend-staging/backend"
rm -rf /tmp/backend-staging
mkdir -p "$STAGING"

# Copy backend source
cp -r "${WORKSPACE}/app/backend" "${STAGING}/app/backend"

# Copy requirements
cp "${WORKSPACE}/requirements.txt" "${STAGING}/"

cat > "${STAGING}/COMPONENT_VERSION" << EOF
{
  "component_id": "backend",
  "version": "${VERSION}",
  "build_date": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
}
EOF

mkdir -p "$OUTPUT_DIR"
TARBALL="backend-${VERSION}.tar.gz"
cd /tmp/backend-staging
tar -czf "${OUTPUT_DIR}/${TARBALL}" backend/
echo "✅ Built: ${OUTPUT_DIR}/${TARBALL}"

rm -rf /tmp/backend-staging
