#!/bin/bash
# Publish script for ReplyMarketing CLI to PyPI using uv only

set -e

echo "🚀 Publishing ReplyMarketing CLI to PyPI..."

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Check if uv is installed
if ! command -v uv &> /dev/null; then
    echo -e "${RED}Error: uv is not installed${NC}"
    echo "Install uv: curl -LsSf https://astral.sh/uv/install.sh | sh"
    exit 1
fi

echo -e "${BLUE}Using uv version:${NC} $(uv --version)"

# Check for PyPI credentials
if [ -z "$UV_PUBLISH_TOKEN" ] && [ -z "$PYPI_TOKEN" ]; then
    echo -e "${YELLOW}Warning: UV_PUBLISH_TOKEN or PYPI_TOKEN environment variable not set${NC}"
    echo "Set it with: export UV_PUBLISH_TOKEN=pypi-xxx"
    echo ""
fi

# Clean previous builds
echo -e "${BLUE}Cleaning previous builds...${NC}"
rm -rf dist/ build/ *.egg-info

# Build the package using uv
echo -e "${BLUE}Building package with uv...${NC}"
uv build

# Show package info
echo ""
echo -e "${GREEN}✓ Package built successfully!${NC}"
echo ""
ls -lh dist/
echo ""

# Validate the package
echo -e "${BLUE}Validating package...${NC}"
uvx twine check dist/* || echo -e "${YELLOW}⚠️  Validation warnings (non-fatal)${NC}"

echo ""

# Ask for confirmation before publishing
read -p "Publish to PyPI? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${BLUE}Publishing to PyPI using uv...${NC}"
    
    # Use uv publish with token
    if [ -n "$UV_PUBLISH_TOKEN" ]; then
        uv publish --token "$UV_PUBLISH_TOKEN"
    elif [ -n "$PYPI_TOKEN" ]; then
        uv publish --token "$PYPI_TOKEN"
    else
        uv publish
    fi
    
    echo ""
    echo -e "${GREEN}✅ Published successfully!${NC}"
    echo ""
    echo -e "${CYAN}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${CYAN}  Install with:${NC}"
    echo -e "${CYAN}    uv tool install replymarketing${NC}"
    echo -e "${CYAN}    or${NC}"
    echo -e "${CYAN}    pip install replymarketing${NC}"
    echo -e "${CYAN}═══════════════════════════════════════════════════════════${NC}"
    echo ""
    echo -e "${BLUE}View at: https://pypi.org/project/replymarketing/${NC}"
else
    echo -e "${YELLOW}Publish cancelled${NC}"
    echo "Package is available in dist/ directory"
fi
