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

USAGE="Usage: ./scripts/release.sh [--dry-run] <patch|minor|major>"

DRY_RUN=false
BUMP=""

# Parse args
while [[ $# -gt 0 ]]; do
    case "$1" in
        --dry-run) DRY_RUN=true; shift ;;
        patch|minor|major) BUMP="$1"; shift ;;
        -h|--help) echo "$USAGE"; exit 0 ;;
        *) echo "Unknown arg: $1"; echo "$USAGE"; exit 1 ;;
    esac
done

if [[ -z "$BUMP" ]]; then
    echo "Error: bump type required (patch, minor, major)"
    echo "$USAGE"
    exit 1
fi

# Ensure clean working tree
if ! git diff --quiet || ! git diff --cached --quiet; then
    echo "Error: working tree has uncommitted changes"
    echo "Commit or stash changes before releasing."
    exit 1
fi

# Check Unreleased section has content
UNRELEASED_CONTENT=$(awk '/^## \[Unreleased\]/{found=1; next} /^## \[/{exit} found{print}' CHANGELOG.md | sed '/^$/d')
if [[ -z "$UNRELEASED_CONTENT" ]]; then
    echo "Error: ## [Unreleased] section in CHANGELOG.md is empty"
    echo "Add changelog entries before releasing."
    exit 1
fi

# Preview version bump
CURRENT=$(uv version | grep -oP '\d+\.\d+\.\d+')
echo "Current version: $CURRENT"
uv version --bump "$BUMP" --dry-run
NEW=$(uv version --bump "$BUMP" --dry-run 2>&1 | grep -oP '\d+\.\d+\.\d+' | tail -1)

if [[ "$DRY_RUN" == "true" ]]; then
    echo ""
    echo "[dry-run] Would bump $CURRENT → $NEW"
    echo "[dry-run] Would update CHANGELOG.md, commit, tag v$NEW, and push"
    exit 0
fi

# Confirm
echo ""
read -p "Release v$NEW? [y/N] " -n 1 -r
echo
[[ $REPLY =~ ^[Yy]$ ]] || { echo "Aborted."; exit 0; }

# Bump version in pyproject.toml
uv version --bump "$BUMP"
NEW=$(uv version | grep -oP '\d+\.\d+\.\d+')

# Update CHANGELOG.md: insert versioned header below Unreleased
DATE=$(date +%Y-%m-%d)
sed -i "s/^## \[Unreleased\]$/## [Unreleased]\n\n## [$NEW] - $DATE/" CHANGELOG.md

# Stage and commit
git add pyproject.toml uv.lock CHANGELOG.md
git commit -m "release: v$NEW"
git tag -a "v$NEW" -m "v$NEW"

# Push
git push
git push --tags

echo ""
echo "Released v$NEW"
echo "GitHub Actions will handle PyPI publish + GitHub Release."
