#!/bin/bash
set -e

# Change to the directory of the script
cd "$(dirname "$0")"

# Clean up previous builds
echo "Cleaning up dist/, build/, and temporary files..."
rm -rf dist/ build/ *.egg-info dmart info.json

# Install dependencies
# "download and install the deps" as requested
echo "Installing dependencies..."
python3 -m pip install --upgrade pip build twine
python3 -m pip install .
if [ -d "requirements" ]; then
    for req in requirements/*.txt; do
        if [ -f "$req" ] && [[ "$req" != *"test.txt" ]]; then
            python3 -m pip install -r "$req"
        fi
    done
fi

# Create standalone bundle using PyInstaller
# This fulfills the request to "bundle the dmart packages with required pkgs"
# Running it before 'build' ensures info.json is included in the python package
echo "Creating standalone bundle..."
python3 bundler.py

# Build the dmart package (wheel and sdist)
echo "Building dmart wheel and sdist..."
python3 -m build

# Move the bundle to dist/
if [ -f "dmart" ]; then
    mv dmart dist/
fi

# Upload to PyPI
# We only upload the newly built dmart package files (.whl and .tar.gz)
# Twine typically only handles these formats; standalone binaries are not uploaded to PyPI
echo "Uploading to PyPI..."
twine upload --non-interactive dist/*.whl dist/*.tar.gz
