#!/bin/bash
# Quick Publish Script for Irene Cipher
# This script automates the publishing process

set -e  # Exit on error

echo "╔════════════════════════════════════════════════════════════╗"
echo "║        Irene Cipher - PyPI Publishing Script              ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

# Check if maturin is installed
if ! command -v maturin &> /dev/null; then
    echo "❌ maturin not found. Installing..."
    pip install maturin
fi

# Check if PyPI token is set
if [ -z "$MATURIN_PYPI_TOKEN" ]; then
    echo "⚠️  MATURIN_PYPI_TOKEN environment variable not set"
    echo ""
    echo "Please set your PyPI token:"
    echo "  export MATURIN_PYPI_TOKEN='pypi-YOUR_TOKEN'"
    echo ""
    echo "Get your token from: https://pypi.org/manage/account/token/"
    exit 1
fi

echo "✓ maturin found"
echo "✓ PyPI token configured"
echo ""

# Run tests
echo "Running tests..."
echo "─────────────────────────────────────────────────────────────"

if cargo test --quiet; then
    echo "✓ Rust tests passed"
else
    echo "❌ Rust tests failed"
    exit 1
fi

if python test_irene_cipher.py > /dev/null 2>&1; then
    echo "✓ Python tests passed"
else
    echo "❌ Python tests failed"
    exit 1
fi

echo ""

# Format check
echo "Checking code formatting..."
echo "─────────────────────────────────────────────────────────────"

if cargo fmt --check --quiet; then
    echo "✓ Code formatting OK"
else
    echo "⚠️  Code needs formatting. Run: cargo fmt"
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo ""

# Version info
echo "Package Information:"
echo "─────────────────────────────────────────────────────────────"
VERSION=$(grep "^version" Cargo.toml | head -1 | cut -d'"' -f2)
echo "Name: irene-cipher"
echo "Version: $VERSION"
echo ""

# Ask for confirmation
read -p "Ready to publish version $VERSION to PyPI? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    exit 1
fi

echo ""

# Build and publish
echo "Building and publishing..."
echo "─────────────────────────────────────────────────────────────"

if maturin publish; then
    echo ""
    echo "╔════════════════════════════════════════════════════════════╗"
    echo "║                    SUCCESS! 🎉                             ║"
    echo "╚════════════════════════════════════════════════════════════╝"
    echo ""
    echo "Package published to PyPI!"
    echo ""
    echo "View at: https://pypi.org/project/irene-cipher/$VERSION/"
    echo ""
    echo "Install with: pip install irene-cipher"
    echo ""
else
    echo ""
    echo "❌ Publishing failed"
    echo ""
    echo "Common issues:"
    echo "  - Version already exists (bump version in Cargo.toml and pyproject.toml)"
    echo "  - Invalid token (check MATURIN_PYPI_TOKEN)"
    echo "  - Network issues (check internet connection)"
    exit 1
fi
