#!/bin/bash
# Publish agenai package to PyPI or private registry
#
# Usage:
#   ./scripts/publish.sh              # Publish to PyPI (production)
#   ./scripts/publish.sh --test       # Publish to TestPyPI
#   ./scripts/publish.sh --github     # Publish to GitHub Packages
#   ./scripts/publish.sh --build-only # Build wheel without publishing
#
# Environment variables:
#   PYPI_TOKEN        - PyPI API token (for PyPI)
#   TEST_PYPI_TOKEN   - TestPyPI API token (for --test)
#   GITHUB_TOKEN      - GitHub token (for --github)
#
# Prerequisites:
#   pip install build twine

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

cd "$PROJECT_ROOT"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Parse arguments
TARGET="pypi"
BUILD_ONLY=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --test)
            TARGET="testpypi"
            shift
            ;;
        --github)
            TARGET="github"
            shift
            ;;
        --build-only)
            BUILD_ONLY=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [--test|--github|--build-only]"
            echo ""
            echo "Options:"
            echo "  --test        Publish to TestPyPI"
            echo "  --github      Publish to GitHub Packages"
            echo "  --build-only  Build wheel without publishing"
            echo ""
            echo "Environment variables:"
            echo "  PYPI_TOKEN       PyPI API token"
            echo "  TEST_PYPI_TOKEN  TestPyPI API token"
            echo "  GITHUB_TOKEN     GitHub token (for GitHub Packages)"
            exit 0
            ;;
        *)
            log_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Check prerequisites
log_info "Checking prerequisites..."

if ! command -v python &> /dev/null; then
    log_error "Python is not installed"
    exit 1
fi

# Install build tools if needed
python -m pip install --quiet --upgrade build twine

# Clean previous builds
log_info "Cleaning previous builds..."
rm -rf dist/ build/ *.egg-info

# Get version from pyproject.toml (works with Python 3.10+)
VERSION=$(python -c "
try:
    import tomllib
except ImportError:
    import pip._vendor.tomli as tomllib
print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])
")
log_info "Building version: $VERSION"

# Build the package
log_info "Building package..."
python -m build

if [ "$BUILD_ONLY" = true ]; then
    log_info "Build complete. Wheel files in dist/:"
    ls -la dist/
    exit 0
fi

# Publish based on target
case $TARGET in
    pypi)
        log_info "Publishing to PyPI..."
        if [ -z "$PYPI_TOKEN" ]; then
            log_error "PYPI_TOKEN environment variable is not set"
            log_info "Get your token from: https://pypi.org/manage/account/token/"
            exit 1
        fi
        python -m twine upload dist/* \
            --username __token__ \
            --password "$PYPI_TOKEN"
        log_info "Published to PyPI: https://pypi.org/project/agenai/$VERSION/"
        ;;

    testpypi)
        log_info "Publishing to TestPyPI..."
        if [ -z "$TEST_PYPI_TOKEN" ]; then
            log_error "TEST_PYPI_TOKEN environment variable is not set"
            log_info "Get your token from: https://test.pypi.org/manage/account/token/"
            exit 1
        fi
        python -m twine upload dist/* \
            --repository testpypi \
            --username __token__ \
            --password "$TEST_PYPI_TOKEN"
        log_info "Published to TestPyPI: https://test.pypi.org/project/agenai/$VERSION/"
        log_info "Install with: pip install --index-url https://test.pypi.org/simple/ agenai"
        ;;

    github)
        log_info "Publishing to GitHub Packages..."
        if [ -z "$GITHUB_TOKEN" ]; then
            log_error "GITHUB_TOKEN environment variable is not set"
            exit 1
        fi

        # Get repository info
        REPO_URL=$(git config --get remote.origin.url)
        if [[ "$REPO_URL" =~ github\.com[:/]([^/]+)/([^/.]+) ]]; then
            OWNER="${BASH_REMATCH[1]}"
            REPO="${BASH_REMATCH[2]}"
        else
            log_error "Could not parse GitHub repository from git remote"
            exit 1
        fi

        python -m twine upload dist/* \
            --repository-url https://upload.pypi.org/legacy/ \
            --username __token__ \
            --password "$GITHUB_TOKEN"
        log_info "Published to GitHub Packages"
        log_info "Install with: pip install agenai --index-url https://pypi.pkg.github.com/$OWNER/$REPO/simple/"
        ;;
esac

log_info "Done!"
