#!/usr/bin/env bash
set -euo pipefail

# 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

print_green() { echo -e "${GREEN}$1${NC}"; }
print_blue() { echo -e "${BLUE}$1${NC}"; }
print_yellow() { echo -e "${YELLOW}$1${NC}"; }
print_red() { echo -e "${RED}$1${NC}"; }
print_cyan() { echo -e "${CYAN}$1${NC}"; }

print_banner() {
    echo ""
    print_cyan "╔════════════════════════════════════════════════════════╗"
    print_cyan "║                                                        ║"
    print_cyan "║     ReplyMarketing CLI - Publish to PyPI 🚀           ║"
    print_cyan "║                                                        ║"
    print_cyan "╚════════════════════════════════════════════════════════╝"
    echo ""
}

# Get version from pyproject.toml
get_version() {
    grep -E '^version = ' pyproject.toml | head -1 | sed 's/version = "\(.*\)"/\1/'
}

# Check if uv is installed
check_uv() {
    if ! command -v uv &> /dev/null; then
        print_red "❌ Error: uv is not installed."
        echo ""
        echo "Install uv:"
        echo "  curl -LsSf https://astral.sh/uv/install.sh | sh"
        exit 1
    fi
    print_green "✅ uv is installed"
}

# Check PyPI token
check_token() {
    if [ -z "${PYPI_API_TOKEN:-}" ]; then
        print_red "❌ Error: PYPI_API_TOKEN environment variable is not set!"
        echo ""
        echo "Please set your PyPI API token:"
        echo "  export PYPI_API_TOKEN='your-token-here'"
        echo ""
        echo "Get your token from: https://pypi.org/manage/account/token/"
        exit 1
    fi
    print_green "✅ PyPI token is configured"
}

# Validate version matches git tag
validate_version() {
    local version=$(get_version)
    local tag=$(git describe --tags --exact-match 2>/dev/null || echo "")
    
    if [ -z "$tag" ]; then
        print_yellow "⚠️  Warning: No git tag found on current commit"
        echo "Current version in pyproject.toml: $version"
        echo ""
        read -p "Continue anyway? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    elif [ "$tag" != "$version" ]; then
        print_red "❌ Version mismatch!"
        echo "  Git tag: $tag"
        echo "  pyproject.toml version: $version"
        exit 1
    else
        print_green "✅ Version validated: $version"
    fi
}

# Clean previous builds
clean_builds() {
    print_blue "🧹 Cleaning previous builds..."
    rm -rf dist/ build/ *.egg-info/
    print_green "✅ Cleaned"
}

# Build package
build_package() {
    print_blue "🔨 Building package..."
    uv build
    print_green "✅ Build complete"
}

# Check package with twine
check_package() {
    print_blue "🔍 Checking package with twine..."
    uvx twine check dist/*
    print_green "✅ Package check passed"
}

# Publish to PyPI
publish_package() {
    print_blue "📤 Publishing to PyPI..."
    uv publish --token "$PYPI_API_TOKEN"
    print_green "✅ Published successfully!"
}

# Main
main() {
    print_banner
    
    # Check prerequisites
    check_uv
    check_token
    
    # Validate
    validate_version
    
    # Build and publish
    clean_builds
    build_package
    check_package
    publish_package
    
    local version=$(get_version)
    echo ""
    print_green "═══════════════════════════════════════════════════════════"
    print_green "  🎉 ReplyMarketing CLI v$version published to PyPI!"
    print_green "═══════════════════════════════════════════════════════════"
    echo ""
    print_blue "Install with:"
    echo "  uv tool install replymarketing"
    echo "  # or"
    echo "  pip install replymarketing"
    echo ""
}

main "$@"
