#!/bin/bash

# Simple Vadalog Extension Deployment Script
set -e

echo "=========================================="
echo "  Vadalog Extension Deployment"
echo "=========================================="
echo ""

# Check if we're in the right directory
if [ ! -f "pyproject.toml" ]; then
    echo "Error: Run this from the extension directory"
    exit 1
fi

# Get current version
CURRENT_VERSION=$(grep '^version = ' pyproject.toml | sed 's/version = "\(.*\)"/\1/')
echo "Current version: $CURRENT_VERSION"

# Parse and increment patch version
IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_VERSION"
NEW_PATCH=$((PATCH + 1))
NEW_VERSION="${MAJOR}.${MINOR}.${NEW_PATCH}"

echo "New version: $NEW_VERSION"
echo ""

read -p "Continue with version $NEW_VERSION? [y/N]: " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 0
fi

# Update versions
echo "Updating versions..."
sed -i "s/^version = \".*\"/version = \"${NEW_VERSION}\"/" pyproject.toml
sed -i "s/\"version\": \".*\"/\"version\": \"${NEW_VERSION}\"/" package.json

# Clean and build
echo "Building package..."
rm -rf dist/ build/ *.egg-info
python -m build

# Validate
echo "Validating..."
twine check dist/*

if [ $? -ne 0 ]; then
    echo "Validation failed!"
    exit 1
fi

echo ""
echo "Package ready to upload:"
ls -lh dist/
echo ""

read -p "Upload to PyPI? [y/N]: " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Build complete but not uploaded."
    exit 0
fi

# Ask for PyPI token
echo ""
echo "Enter your PyPI token:"
echo "(Get it from: https://pypi.org/manage/account/token/)"
echo ""
read -s PYPI_TOKEN

# Upload
echo ""
echo "Uploading to PyPI..."
twine upload dist/* -u __token__ -p "$PYPI_TOKEN"

if [ $? -eq 0 ]; then
    echo ""
    echo "=========================================="
    echo "  ✅ Successfully deployed v${NEW_VERSION}!"
    echo "=========================================="
    echo ""
    echo "Package: https://pypi.org/project/vadalog-extension/${NEW_VERSION}/"
    echo ""
    echo "Don't forget to commit:"
    echo "  git add pyproject.toml package.json"
    echo "  git commit -m 'Release v${NEW_VERSION}'"
    echo "  git tag v${NEW_VERSION}"
    echo "  git push && git push --tags"
else
    echo "Upload failed!"
    exit 1
fi
