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

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

usage() {
    echo "Usage: script/release-tag <version>"
    echo ""
    echo "Creates a git tag, GitHub release, and publishes to crates.io."
    echo "Run this after the release PR has been merged."
    echo ""
    echo "Example:"
    echo "  script/release-tag 0.2.0"
    exit 1
}

log() { echo -e "${GREEN}==>${NC} $1"; }
warn() { echo -e "${YELLOW}warning:${NC} $1"; }
error() { echo -e "${RED}error:${NC} $1" >&2; exit 1; }

[[ $# -ne 1 ]] && usage
VERSION="$1"

# Validate version format
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    error "Invalid version format: $VERSION (expected x.y.z)"
fi

[[ ! -f "Cargo.toml" ]] && error "Must run from repository root"

# Ensure we're on main and up to date
CURRENT_BRANCH=$(git branch --show-current)
[[ "$CURRENT_BRANCH" != "main" ]] && error "Must be on main branch (currently on $CURRENT_BRANCH)"

git fetch origin main
git reset --hard origin/main

# Verify version in Cargo.toml matches
CARGO_VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
if [[ "$CARGO_VERSION" != "$VERSION" ]]; then
    error "Version mismatch: Cargo.toml has $CARGO_VERSION, expected $VERSION"
fi

log "Creating tag v$VERSION..."
git tag -a "v$VERSION" -m "Release v$VERSION"

log "Pushing tag..."
git push origin "v$VERSION"

log "Creating GitHub release..."
gh release create "v$VERSION" \
    --title "v$VERSION" \
    --generate-notes

log "Publishing to crates.io..."
echo ""
warn "About to publish to crates.io. This cannot be undone."
read -p "Continue? [y/N] " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    cargo publish
    log "Published to crates.io!"
else
    warn "Skipped crates.io publish. Run 'cargo publish' manually when ready."
fi

echo ""
log "Release v$VERSION complete!"
echo ""
echo "  GitHub: https://github.com/iamnbutler/spool/releases/tag/v$VERSION"
echo "  crates.io: https://crates.io/crates/spool"
