#!/bin/bash
# Release script for agentcenter
# Usage: ./scripts/release.sh [version]

set -e

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

# Functions
print_step() {
    echo -e "${BLUE}==>${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

# Banner
echo -e "${GREEN}"
echo "╔═══════════════════════════════════════╗"
echo "║                                       ║"
echo "║   Agent Center Release Script         ║"
echo "║                                       ║"
echo "╚═══════════════════════════════════════╝"
echo -e "${NC}"

# Get current version
CURRENT_VERSION=$(grep '^version = ' pyproject.toml | cut -d'"' -f2)
echo -e "Current version: ${YELLOW}${CURRENT_VERSION}${NC}"

# Get new version from argument or prompt
if [ -n "$1" ]; then
    NEW_VERSION="$1"
else
    read -p "Enter new version (or press Enter to use current): " NEW_VERSION
    if [ -z "$NEW_VERSION" ]; then
        NEW_VERSION="$CURRENT_VERSION"
    fi
fi

echo -e "Release version: ${GREEN}${NEW_VERSION}${NC}"
echo

# Confirm
read -p "Continue with release v${NEW_VERSION}? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    print_error "Release cancelled"
    exit 1
fi

# Step 1: Check working directory
print_step "Checking working directory..."
if [[ -n $(git status -s) ]]; then
    print_warning "Working directory has uncommitted changes:"
    git status -s
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi
print_success "Working directory check complete"

# Step 2: Run tests
print_step "Running tests..."
if uv run pytest --cov=agentcenter --cov-fail-under=80 -q; then
    print_success "All tests passed"
else
    print_error "Tests failed"
    exit 1
fi

# Step 3: Code quality checks
print_step "Running code quality checks..."

# Black
print_step "Checking code formatting with Black..."
if uv run black src/ tests/ --check -q; then
    print_success "Black formatting check passed"
else
    print_warning "Code needs formatting"
    read -p "Run black --format? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        uv run black src/ tests/
        print_success "Code formatted"
    fi
fi

# Ruff
print_step "Checking with Ruff..."
if uv run ruff check src/ tests/ -q; then
    print_success "Ruff check passed"
else
    print_warning "Ruff found issues"
    read -p "Try to fix automatically? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        uv run ruff check src/ tests/ --fix
        print_success "Ruff issues fixed"
    fi
fi

# Step 4: Update version if changed
if [ "$NEW_VERSION" != "$CURRENT_VERSION" ]; then
    print_step "Updating version to ${NEW_VERSION}..."

    # Update pyproject.toml
    sed -i.bak "s/^version = \".*\"/version = \"${NEW_VERSION}\"/" pyproject.toml
    rm pyproject.toml.bak

    print_success "Version updated in pyproject.toml"

    # Prompt to update CHANGELOG
    print_warning "Don't forget to update CHANGELOG.md!"
    read -p "Open CHANGELOG.md for editing? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        ${EDITOR:-vim} CHANGELOG.md
    fi
fi

# Step 5: Git commit and tag
if [ "$NEW_VERSION" != "$CURRENT_VERSION" ] || [[ -n $(git status -s) ]]; then
    print_step "Committing changes..."
    git add pyproject.toml CHANGELOG.md
    git commit -m "Release version ${NEW_VERSION}" || true
    print_success "Changes committed"
fi

print_step "Creating Git tag v${NEW_VERSION}..."
if git tag -a "v${NEW_VERSION}" -m "Release version ${NEW_VERSION}"; then
    print_success "Tag created"
else
    print_warning "Tag already exists"
fi

# Step 6: Clean old builds
print_step "Cleaning old builds..."
rm -rf dist/ build/ *.egg-info
print_success "Old builds cleaned"

# Step 7: Build package
print_step "Building package..."
if uv build; then
    print_success "Package built successfully"
    echo
    echo "Build artifacts:"
    ls -lh dist/
    echo
else
    print_error "Build failed"
    exit 1
fi

# Step 8: Upload to TestPyPI (optional)
echo
read -p "Upload to TestPyPI? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    print_step "Uploading to TestPyPI..."
    if uv run twine upload --repository testpypi dist/*; then
        print_success "Uploaded to TestPyPI"
        echo
        echo "Test installation with:"
        echo "  pip install --index-url https://test.pypi.org/simple/ agentcenter==${NEW_VERSION}"
        echo
        read -p "Press Enter to continue..."
    else
        print_error "Upload to TestPyPI failed"
        exit 1
    fi
fi

# Step 9: Upload to PyPI
echo
read -p "Upload to PyPI? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    print_step "Uploading to PyPI..."
    if uv run twine upload dist/*; then
        print_success "Successfully uploaded to PyPI!"
        echo
        echo -e "${GREEN}╔═══════════════════════════════════════╗${NC}"
        echo -e "${GREEN}║                                       ║${NC}"
        echo -e "${GREEN}║   Release ${NEW_VERSION} Complete! 🎉          ║${NC}"
        echo -e "${GREEN}║                                       ║${NC}"
        echo -e "${GREEN}╚═══════════════════════════════════════╝${NC}"
        echo
        echo "View at: https://pypi.org/project/agentcenter/${NEW_VERSION}/"
        echo
        echo "Install with: pip install agentcenter==${NEW_VERSION}"
        echo
    else
        print_error "Upload to PyPI failed"
        exit 1
    fi
else
    print_warning "PyPI upload skipped"
    echo
    echo "To upload later, run:"
    echo "  uv run twine upload dist/*"
fi

# Step 10: Push to GitHub
echo
read -p "Push to GitHub? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    print_step "Pushing to GitHub..."
    git push origin main
    git push origin "v${NEW_VERSION}"
    print_success "Pushed to GitHub"

    # Optional: Create GitHub release
    if command -v gh &> /dev/null; then
        echo
        read -p "Create GitHub Release? (y/n) " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            print_step "Creating GitHub Release..."
            gh release create "v${NEW_VERSION}" \
                --title "Release v${NEW_VERSION}" \
                --notes-file CHANGELOG.md \
                dist/*
            print_success "GitHub Release created"
        fi
    fi
fi

echo
print_success "Release process complete!"
