#!/usr/bin/env bash
#
# Publish the flowlines SDK to PyPI.
#
# Usage:
#   ./scripts/publish.sh [patch|minor|major]   (default: patch)
#
# Prerequisites:
#   - uv installed
#   - A PyPI API token configured (via UV_PUBLISH_TOKEN env var, or ~/.pypirc)
#   - Clean git working tree on the main branch
#
set -euo pipefail

BUMP_TYPE="${1:-patch}"

if [[ "$BUMP_TYPE" != "patch" && "$BUMP_TYPE" != "minor" && "$BUMP_TYPE" != "major" ]]; then
    echo "Error: version bump type must be one of: patch, minor, major"
    exit 1
fi

# --- Ensure clean working tree ---
if [[ -n "$(git status --porcelain)" ]]; then
    echo "Error: working tree is not clean. Commit or stash your changes first."
    exit 1
fi

# --- Read current version ---
CURRENT_VERSION=$(grep '^version = ' pyproject.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
echo "Current version: $CURRENT_VERSION"

IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_VERSION"

case "$BUMP_TYPE" in
    major) MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;;
    minor) MINOR=$((MINOR + 1)); PATCH=0 ;;
    patch) PATCH=$((PATCH + 1)) ;;
esac

NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}"
echo "New version:     $NEW_VERSION"

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

# --- Run unit tests ---
echo ""
echo "==> Running unit tests..."
uv run pytest tests/

# --- Run lint & type checks ---
echo ""
echo "==> Running lint..."
uv run ruff check flowlines/ tests/

echo ""
echo "==> Running type checks..."
uv run mypy flowlines/

# --- Bump version in pyproject.toml ---
echo ""
echo "==> Bumping version to $NEW_VERSION..."
sed -i '' "s/^version = \"$CURRENT_VERSION\"/version = \"$NEW_VERSION\"/" pyproject.toml

# --- Build ---
echo ""
echo "==> Building..."
uv build

# --- Commit, tag, and push ---
echo ""
echo "==> Committing version bump and tagging v$NEW_VERSION..."
git add pyproject.toml
git commit -m "Release v$NEW_VERSION"
git tag -a "v$NEW_VERSION" -m "Release v$NEW_VERSION"

# --- Publish to PyPI ---
echo ""
echo "==> Publishing to PyPI..."
uvx twine upload dist/*

# --- Push commit and tag ---
echo ""
echo "==> Pushing to remote..."
git push
git push --tags

echo ""
echo "Done! Published flowlines v$NEW_VERSION to PyPI."
