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

usage() {
    cat <<EOF
Usage: ./release.sh <crate-group> <version> [--execute]

Crate groups: block-explorers, compilers, fork-db, wallets

Without --execute, runs a full dry-run.
With --execute, publishes to crates.io, tags, pushes, and creates a GitHub release.

Requires: cargo login, gh auth login

Examples:
  ./release.sh wallets 0.2.0             # dry-run
  ./release.sh wallets 0.2.0 --execute   # real release
EOF
    exit 1
}

confirm() {
    echo ""
    read -rp "Continue? [y/N] " answer
    [[ "$answer" == "y" || "$answer" == "Y" ]] || { echo "Aborted."; exit 1; }
    echo ""
}

[[ $# -lt 2 ]] && usage

GROUP="$1"
VERSION="$2"
EXECUTE=false
[[ "${3:-}" == "--execute" ]] && EXECUTE=true

# Crate group definitions.
case "$GROUP" in
    compilers)
        TAG="compilers-v${VERSION}"
        PACKAGES=(-p foundry-compilers-core -p foundry-compilers-artifacts-solc -p foundry-compilers-artifacts-vyper -p foundry-compilers-artifacts -p foundry-compilers)
        ;;
    block-explorers)
        TAG="block-explorers-v${VERSION}"
        PACKAGES=(-p foundry-block-explorers)
        ;;
    fork-db)
        TAG="fork-db-v${VERSION}"
        PACKAGES=(-p foundry-fork-db)
        ;;
    wallets)
        TAG="wallets-v${VERSION}"
        PACKAGES=(-p foundry-wallets)
        ;;
    *)
        echo "error: unknown crate group '${GROUP}'"
        usage
        ;;
esac

# 1. Dry-run cargo release (always, as a sanity check)
echo "==> Next: cargo release dry-run"
confirm
cargo release "$VERSION" "${PACKAGES[@]}" --no-push --no-tag

# 2. Semver-checks (advisory, non-blocking)
echo "==> Next: semver-checks"
confirm
if ! cargo +stable semver-checks "${PACKAGES[@]}"; then
    echo ""
    echo "warning: semver-checks reported breaking changes (see above)"
    echo "==> Proceed despite semver-checks failures?"
    confirm
fi

if $EXECUTE; then
    # 3. Publish (changelog is generated by pre-release-hook in release.toml)
    echo "==> Next: publish to crates.io and tag ${TAG}"
    confirm

    cargo release "$VERSION" "${PACKAGES[@]}" --execute

    # 4. Push
    echo "==> Next: push branch and tag to origin"
    confirm

    git push origin HEAD "$TAG"

    # 5. GitHub release
    echo "==> Next: create GitHub release for ${TAG}"
    confirm

    PREV_TAG=$(git tag -l "${GROUP}-v*" --sort=-v:refname | grep -v "^${TAG}$" | head -1)
    if [[ -n "$PREV_TAG" ]]; then
        gh release create "$TAG" --generate-notes --notes-start-tag "$PREV_TAG"
    else
        gh release create "$TAG" --generate-notes
    fi
else
    echo "Dry-run complete. Re-run with --execute to publish."
fi

echo "==> Done"
