#!/bin/bash
#
# Zexus Deployment Script
# Handles version updates and package installation for production deployment.
#
# Usage:
#     ./zx-deploy           # Deploy current version
#     ./zx-deploy --patch   # Bump patch version and deploy
#     ./zx-deploy --minor   # Bump minor version and deploy
#     ./zx-deploy --major   # Bump major version and deploy
#

set -e  # Exit on error

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

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

echo -e "${BLUE}🚀 Zexus Deployment Script${NC}"
echo "================================"

# Parse arguments
BUMP_VERSION=""
SKIP_TESTS=false
FORCE=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --patch)
            BUMP_VERSION="patch"
            shift
            ;;
        --minor)
            BUMP_VERSION="minor"
            shift
            ;;
        --major)
            BUMP_VERSION="major"
            shift
            ;;
        --skip-tests)
            SKIP_TESTS=true
            shift
            ;;
        --force)
            FORCE=true
            shift
            ;;
        --help)
            echo "Usage: ./zx-deploy [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --patch       Bump patch version (0.0.X)"
            echo "  --minor       Bump minor version (0.X.0)"
            echo "  --major       Bump major version (X.0.0)"
            echo "  --skip-tests  Skip running tests"
            echo "  --force       Force deployment even if tests fail"
            echo "  --help        Show this help message"
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            exit 1
            ;;
    esac
done

# Function to bump version in setup.py
bump_version() {
    local bump_type=$1
    echo -e "${BLUE}📦 Bumping $bump_type version...${NC}"
    
    # Read current version from setup.py
    current_version=$(grep -oP "version=['\"]([0-9]+\.[0-9]+\.[0-9]+)" setup.py | grep -oP "[0-9]+\.[0-9]+\.[0-9]+")
    
    if [ -z "$current_version" ]; then
        echo -e "${RED}❌ Could not find version in setup.py${NC}"
        exit 1
    fi
    
    echo "   Current version: $current_version"
    
    # Split version into components
    IFS='.' read -r major minor patch <<< "$current_version"
    
    # Bump the appropriate component
    case $bump_type in
        patch)
            patch=$((patch + 1))
            ;;
        minor)
            minor=$((minor + 1))
            patch=0
            ;;
        major)
            major=$((major + 1))
            minor=0
            patch=0
            ;;
    esac
    
    new_version="$major.$minor.$patch"
    echo "   New version: $new_version"
    
    # Update setup.py
    sed -i "s/version=['\"][0-9]\+\.[0-9]\+\.[0-9]\+['\"]/version='$new_version'/" setup.py
    
    # Update pyproject.toml if it exists
    if [ -f "pyproject.toml" ]; then
        sed -i "s/version = \"[0-9]\+\.[0-9]\+\.[0-9]\+\"/version = \"$new_version\"/" pyproject.toml
    fi
    
    echo -e "${GREEN}✅ Version bumped to $new_version${NC}"
}

# Bump version if requested
if [ -n "$BUMP_VERSION" ]; then
    bump_version "$BUMP_VERSION"
fi

# Run tests unless skipped
if [ "$SKIP_TESTS" = false ]; then
    echo -e "${BLUE}🧪 Running tests...${NC}"
    
    if [ -f "pytest.ini" ] || [ -d "tests" ]; then
        if command -v pytest &> /dev/null; then
            if pytest -v; then
                echo -e "${GREEN}✅ All tests passed${NC}"
            else
                if [ "$FORCE" = false ]; then
                    echo -e "${RED}❌ Tests failed. Use --force to deploy anyway${NC}"
                    exit 1
                else
                    echo -e "${YELLOW}⚠️  Tests failed but continuing due to --force${NC}"
                fi
            fi
        else
            echo -e "${YELLOW}⚠️  pytest not installed, skipping tests${NC}"
        fi
    else
        echo -e "${YELLOW}⚠️  No tests found, skipping${NC}"
    fi
fi

# Uninstall old version
echo -e "${BLUE}🗑️  Uninstalling old version...${NC}"
pip uninstall -y zexus 2>/dev/null || true

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

# Install in editable mode for development, or regular install for production
echo -e "${BLUE}📦 Installing Zexus...${NC}"
if [ -f "setup.py" ]; then
    pip install -e . --no-cache-dir
else
    echo -e "${RED}❌ setup.py not found${NC}"
    exit 1
fi

# Verify installation
echo -e "${BLUE}🔍 Verifying installation...${NC}"
if command -v zx &> /dev/null; then
    installed_version=$(zx --version 2>&1 | grep -oP "[0-9]+\.[0-9]+\.[0-9]+" | head -1 || echo "unknown")
    echo -e "${GREEN}✅ Zexus installed successfully${NC}"
    echo "   Version: $installed_version"
    echo "   Location: $(which zx)"
else
    echo -e "${RED}❌ Installation failed - zx command not found${NC}"
    exit 1
fi

# Print success message
echo ""
echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}🎉 Deployment Complete!${NC}"
echo -e "${GREEN}================================${NC}"
echo ""
echo "You can now use the 'zx' command to run the updated interpreter."
echo ""
echo "Quick test:"
echo "  zx --version"
echo "  zx run your_script.zx"
