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

# Build Python package (wheel and sdist) with automatic versioning
cd rdst

# Clean old build artifacts
echo "Cleaning old build artifacts..."
rm -rf dist/ build/ *.egg-info

echo "Installing build dependencies..."
# Use PyPI directly to avoid CodeArtifact credential issues for build tools
python -m pip install --upgrade --index-url https://pypi.org/simple build twine

# Read major and minor version from _version.py
# Change to rdst directory if we're in the repo root
if [[ -f "rdst/_version.py" ]]; then
  VERSION_FILE="rdst/_version.py"
elif [[ -f "_version.py" ]]; then
  VERSION_FILE="_version.py"
else
  echo "Error: Cannot find _version.py"
  exit 1
fi

MAJOR=$(grep "^MAJOR = " "$VERSION_FILE" | cut -d '=' -f 2 | tr -d ' ')
MINOR=$(grep "^MINOR = " "$VERSION_FILE" | cut -d '=' -f 2 | tr -d ' ')

if [[ -z "$MAJOR" ]] || [[ -z "$MINOR" ]]; then
  echo "Error: Could not read MAJOR/MINOR from $VERSION_FILE"
  exit 1
fi

echo "Base version from _version.py: $MAJOR.$MINOR"

# Generate full version using semantic versioning (major.minor.patch[.build])
if [[ -n "${BUILDKITE_BUILD_NUMBER:-}" ]]; then
  # Buildkite release: major.minor.patch where patch = build number
  # Format: 0.1.123 (e.g., version 0.1 with build 123)
  export RDST_VERSION="${MAJOR}.${MINOR}.${BUILDKITE_BUILD_NUMBER}"
  echo "Release build version: $RDST_VERSION"
else
  # Local/dev build: major.minor.0.dev<timestamp> (PEP 440 compliant)
  # Format: 0.1.0.dev20251204081653
  TIMESTAMP=$(date +%Y%m%d%H%M%S)
  export RDST_VERSION="${MAJOR}.${MINOR}.0.dev${TIMESTAMP}"
  echo "Local dev build version: $RDST_VERSION"
fi

# Get git hash for metadata (optional but useful for tracing)
GIT_HASH=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
echo "Git commit: $GIT_HASH"

# Write version to _version_build.py for hatchling to read (not tracked in git)
echo "Writing version $RDST_VERSION to _version_build.py..."
cat > _version_build.py <<EOF
"""
RDST Version Information

This file is AUTO-GENERATED by the build system.
Do not edit manually - it will be overwritten on next build.

Current version: $RDST_VERSION
Git commit: $GIT_HASH
"""

# Version constants
MAJOR = ${MAJOR}
MINOR = ${MINOR}

# Full version (set by build system)
__version__ = "${RDST_VERSION}"
__version_info__ = tuple(map(int, "${RDST_VERSION}".split('.')[:2]))
EOF

# Force build tool to use PyPI for isolated environment (fixes 401 error)
export PIP_INDEX_URL=https://pypi.org/simple

echo "Building Python package version $RDST_VERSION..."
python -m build

echo "Build artifacts:"
ls -lh dist/
