#!/bin/zsh
set -e

SCRIPT_DIR=$( cd -- "$( dirname -- "$0 )" &> /dev/null && pwd )
cd $SCRIPT_DIR

# Determine target repository
if [[ "$1" == "test" ]]; then
    REPO="testpypi"
    REPO_URL="--repository testpypi"
    echo "🧪 Publishing to TestPyPI..."
else
    REPO="pypi"
    REPO_URL=""
    echo "🚀 Publishing to PyPI..."
fi

# Check if dist folder exists
if [[ ! -d "dist" ]]; then
    echo "❌ Error: dist/ folder not found. Run build_package.sh first."
    exit 1
fi

# Check if there are files to upload
if [[ -z "$(ls -A dist)" ]]; then
    echo "❌ Error: dist/ folder is empty. Run build_package.sh first."
    exit 1
fi

# Show what we're about to upload
echo "📦 Files to upload:"
ls -la dist/

# Extract version from built files for confirmation
wheel_file=$(ls dist/*.whl | head -1)
if [[ -n "$wheel_file" ]]; then
    version=$(echo "$wheel_file" | sed 's/.*-\([0-9][^-]*\)-.*/\1/')
    echo "📋 Version: $version"
    
    # Check if it's a beta/pre-release
    if [[ $version =~ (b|rc|a|dev) ]]; then
        echo "⚠️  This is a pre-release version."
    fi
fi

# Confirmation prompt for PyPI (not TestPyPI)
if [[ "$REPO" == "pypi" ]]; then
    echo ""
    echo "⚠️  You are about to publish to the LIVE PyPI repository!"
    echo "   This action cannot be undone."
    echo "   Make sure you've tested on TestPyPI first."
    echo ""
    echo "Continue? (y/N)"
    read -r response
    if [[ ! $response =~ ^[Yy]$ ]]; then
        echo "❌ Aborted."
        exit 1
    fi
fi

# Final validation
echo "🔍 Final validation..."
uv run twine check dist/*

# Upload to repository
echo "📤 Uploading to $REPO..."
if [[ "$REPO" == "testpypi" ]]; then
    uv run twine upload --repository testpypi --verbose dist/*
else
    uv run twine upload --verbose dist/*
fi

echo ""
echo "✅ Done! Package uploaded successfully to $REPO."

if [[ "$REPO" == "testpypi" ]]; then
    echo ""
    echo "🧪 To test installation from TestPyPI:"
    echo "   pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ radiens-core"
    echo ""
    echo "📝 Note: --extra-index-url ensures dependencies are found on regular PyPI"
    echo ""
    echo "🚀 When ready for production, run: ./publish_to_pypi.sh"
else
    echo ""
    echo "🎉 Your package is now live on PyPI!"
    echo "   Install with: pip install radiens-core"
fi