#!/bin/bash
set -e

# Navigate to the script's directory
cd "$(dirname "$0")"

# Extract version from Cargo.toml
VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')

echo "=== Zinit Build & Publish ==="
echo "Version: $VERSION"
echo ""

# Clean previous build artifacts
echo "Cleaning previous build artifacts..."
cargo clean
echo "Done."
echo ""

# Check formatting
echo "Checking code formatting..."
cargo fmt --check || {
    echo "Code is not formatted. Running cargo fmt..."
    cargo fmt
}
echo "Done."
echo ""

# Run clippy for linting
echo "Running clippy..."
cargo clippy --all-targets --all-features -- -D warnings
echo "Done."
echo ""

# Build the library
echo "Building with full features..."
cargo build --release --features full
echo "Done."
echo ""

# Run tests
echo "Running tests..."
cargo test --lib --features full -- --test-threads=1 || true
echo "Done."
echo ""

# Generate documentation
echo "Generating documentation..."
cargo doc --no-deps --features full
echo "Done."
echo ""

# Verify package can be published
echo "Verifying package..."
cargo publish --dry-run
echo "Done."
echo ""

# Ask for confirmation before publishing
echo "=== Pre-publish checks complete ==="
echo ""
echo "Package:  zinit v$VERSION"
echo "Binaries: zinit, zinit-server, zinit-pid1"
echo ""
read -p "Do you want to publish to crates.io? (y/N) " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Publishing to crates.io..."
    cargo publish --allow-dirty
    echo ""
    echo "=== Successfully published to crates.io! ==="
else
    echo "Publish cancelled."
fi
