#!/bin/bash
# ESP Viewer Release Script

set -e

# --- Configuration ---
PROJECT_ROOT=$(pwd)
WEB_DIR="$PROJECT_ROOT/esp_viewer/web"
DIST_DIR="$PROJECT_ROOT/dist"
VENV_BIN="$PROJECT_ROOT/.venv/bin"

# Ensure we are in the project root
if [ ! -f "pyproject.toml" ]; then
    echo "Error: pyproject.toml not found. Please run this script from the project root."
    exit 1
fi

echo "🚀 Starting release process..."

# 1. Check Python environment
if [ -d ".venv" ]; then
    echo "Using virtual environment dependencies..."
    export PATH="$VENV_BIN:$PATH"
fi

# 2. Build Tools Check
# Use python -m pip to ensure it goes into the right place
python3 -m pip install --upgrade hatch twine

# 3. Version Check
VERSION=$(grep -m 1 "version =" pyproject.toml | cut -d '"' -f 2)
echo "📦 Current version: $VERSION"

# 4. Frontend Build
echo "🏗️ Building Frontend..."
cd "$WEB_DIR"
npm install
npm run build
cd "$PROJECT_ROOT"

# 5. Clean Previous Builds
echo "🧹 Cleaning old artifacts..."
rm -rf "$DIST_DIR"
rm -rf *.egg-info

# 6. Build Package
echo "📦 Building Wheel and SDist..."
hatch build

# 7. Verification
echo "🔍 Verifying build contents..."
WHEEL_FILE=$(ls "$DIST_DIR"/*.whl)
echo "Built: $WHEEL_FILE"

# 8. Upload (Manual Trigger)
echo ""
echo "---------------------------------------------------"
echo "Build Successful!"
echo "To publish to PyPI, run:"
echo "  twine upload dist/*"
echo "To publish to TestPyPI, run:"
echo "  twine upload --repository testpypi dist/*"
echo "---------------------------------------------------"
