#!/bin/bash
# Publish OptraBot to PyPI or Test PyPI
# Usage: ./scripts/publish.sh <version> [--test]
# Example: ./scripts/publish.sh 0.29.3rc6
# Example: ./scripts/publish.sh 0.29.3rc6 --test

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# Load .env file from project root if it exists
ENV_FILE="$PROJECT_DIR/.env"
if [ -f "$ENV_FILE" ]; then
    # Export all variables from .env (skip comments and empty lines)
    set -a
    grep -v '^#' "$ENV_FILE" | grep -v '^$' | while IFS= read -r line; do
        export "$line"
    done
    set +a
    # Source it directly for current shell
    export $(grep -v '^#' "$ENV_FILE" | grep -v '^$' | xargs)
    echo "Loaded tokens from $ENV_FILE"
else
    echo "Warning: No .env file found at $ENV_FILE"
    echo "Create one with PYPI_TOKEN and/or TEST_PYPI_TOKEN"
fi

if [ -z "$1" ]; then
    echo "Usage: $0 <version> [--test]"
    echo "  --test  Publish to test.pypi.org instead of pypi.org"
    exit 1
fi

VERSION="$1"
USE_TEST=false

if [ "$2" = "--test" ]; then
    USE_TEST=true
fi

DIST_DIR="dist"

# Check if matching dist files exist
TARBALL="$DIST_DIR/optrabot-${VERSION}.tar.gz"
WHEEL=$(ls "$DIST_DIR"/optrabot-${VERSION}-*.whl 2>/dev/null | head -1)

if [ ! -f "$TARBALL" ] || [ -z "$WHEEL" ]; then
    echo "Dist files for version $VERSION not found. Building..."
    ./scripts/build.sh
fi

# Re-check after build
TARBALL="$DIST_DIR/optrabot-${VERSION}.tar.gz"
WHEEL=$(ls "$DIST_DIR"/optrabot-${VERSION}-*.whl 2>/dev/null | head -1)

if [ ! -f "$TARBALL" ]; then
    echo "Error: $TARBALL not found"
    exit 1
fi
if [ -z "$WHEEL" ]; then
    echo "Error: No wheel file found for version $VERSION"
    exit 1
fi

echo "Publishing OptraBot $VERSION"
echo "  Tarball: $TARBALL"
echo "  Wheel:   $WHEEL"

if [ "$USE_TEST" = true ]; then
    if [ -z "$TEST_PYPI_TOKEN" ]; then
        echo "Error: TEST_PYPI_TOKEN not set. Add it to .env or export it."
        exit 1
    fi
    echo "  Target:  test.pypi.org"
    uv publish --publish-url https://test.pypi.org/legacy/ --token "$TEST_PYPI_TOKEN" "$TARBALL" "$WHEEL"
else
    if [ -z "$PYPI_TOKEN" ]; then
        echo "Error: PYPI_TOKEN not set. Add it to .env or export it."
        exit 1
    fi
    echo "  Target:  pypi.org"
    uv publish --token "$PYPI_TOKEN" "$TARBALL" "$WHEEL"
fi

echo "Done."
