#!/bin/bash

# Quantum-Sign Publishing Script
# Publishes all crates to crates.io in dependency order
# Author: Sicarii <sic.tau@pm.me>

set -e

echo "================================================"
echo "Quantum-Sign: The Digital Notary Stamp"
echo "That Even Quantum Computers Can't Forge"
echo "================================================"
echo ""
echo "Publishing to crates.io..."
echo ""

# Check if we're logged in to crates.io
if ! cargo login --help > /dev/null 2>&1; then
    echo "Error: Please login to crates.io first with: cargo login"
    exit 1
fi

# Ensure we're in the workspace root
if [ ! -f "Cargo.toml" ] || [ ! -d "crates" ]; then
    echo "Error: Must be run from workspace root"
    exit 1
fi

# Function to publish a crate with retry logic
publish_crate() {
    local crate_path=$1
    local crate_name=$2

    echo "📦 Publishing $crate_name..."
    cd "$crate_path"

    # Dry run first
    if cargo publish --dry-run; then
        echo "  ✅ Dry run successful"

        # Actual publish
        if cargo publish --no-verify; then
            echo "  ✅ Published $crate_name successfully!"
        else
            echo "  ❌ Failed to publish $crate_name"
            exit 1
        fi
    else
        echo "  ❌ Dry run failed for $crate_name"
        exit 1
    fi

    # Return to workspace root
    cd - > /dev/null

    # Wait for crates.io to index
    echo "  ⏳ Waiting for crates.io to index..."
    sleep 30
    echo ""
}

# Publishing order (respecting dependencies)
echo "Publishing in dependency order..."
echo ""

# Level 1: No internal dependencies
publish_crate "crates/qs-drbg" "qs-drbg"

# Level 2: Depends on qs-drbg
publish_crate "crates/qs-crypto" "qs-crypto"

# Level 3: Independent crates
publish_crate "crates/qs-policy" "qs-policy"
publish_crate "crates/qs-format" "qs-format"

# Level 4: Placeholder crates
publish_crate "crates/qs-verify" "qs-verify"
publish_crate "crates/qs-tsp" "qs-tsp"
publish_crate "crates/qs-transparency" "qs-transparency"

# Level 5: CLI (depends on all others)
echo "Skipping deprecated CLI crate (quantum-sign-cli). Use unified crate 'quantum-sign'."

echo ""
echo "================================================"
echo "🎉 Success! All crates published to crates.io"
echo "================================================"
echo ""
echo "View your crates at:"
echo "  https://crates.io/users/sicarii"
echo ""
echo "Documentation will be available at:"
echo "  https://docs.rs/quantum-sign"
echo ""
echo "Install with:"
echo "  cargo install quantum-sign"
echo ""
echo "For support: sic.tau@pm.me"
echo ""
