#!/bin/bash
#
# Release script for PyCharter
# Automates: version update, git add, commit, push, tag, and GitHub release
#
# Usage:
#   ./bin/release.sh [version] [--dry-run] [--no-release]
#   ./bin/release.sh 0.0.21
#   ./bin/release.sh 0.0.21 --dry-run
#   ./bin/release.sh 0.0.21 --no-release  # Skip GitHub release creation
#
# If version is not provided, it will be read from pyproject.toml
#

set -e  # Exit on error

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

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

cd "$PROJECT_ROOT"

# Parse arguments
DRY_RUN=false
NO_RELEASE=false
VERSION=""

while [[ $# -gt 0 ]]; do
  case $1 in
    --dry-run)
      DRY_RUN=true
      shift
      ;;
    --no-release)
      NO_RELEASE=true
      shift
      ;;
    *)
      if [[ -z "$VERSION" ]]; then
        VERSION="$1"
      else
        echo -e "${RED}Error: Unknown argument: $1${NC}"
        exit 1
      fi
      shift
      ;;
  esac
done

# Functions
error() {
  echo -e "${RED}❌ Error: $1${NC}" >&2
  exit 1
}

info() {
  echo -e "${BLUE}ℹ️  $1${NC}"
}

success() {
  echo -e "${GREEN}✅ $1${NC}"
}

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

# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
  error "Not in a git repository"
fi

# Check if we're on main/master branch
CURRENT_BRANCH=$(git branch --show-current)
if [[ "$CURRENT_BRANCH" != "main" && "$CURRENT_BRANCH" != "master" ]]; then
  warning "You're on branch '$CURRENT_BRANCH', not main/master"
  read -p "Continue anyway? (y/n) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 1
  fi
fi

# Check for uncommitted changes
if [[ -n $(git status --porcelain) ]]; then
  warning "You have uncommitted changes:"
  git status --short
  read -p "Continue anyway? (y/n) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 1
  fi
fi

# Get current version from pyproject.toml
CURRENT_VERSION=$(grep -E '^version = ' pyproject.toml | sed -E 's/version = "([^"]+)"/\1/')

if [[ -z "$CURRENT_VERSION" ]]; then
  error "Could not find version in pyproject.toml"
fi

info "Current version: $CURRENT_VERSION"

# Get new version
if [[ -z "$VERSION" ]]; then
  echo -e "${BLUE}Enter new version (current: $CURRENT_VERSION):${NC}"
  read -r VERSION
fi

# Validate version format (semantic versioning: x.y.z)
if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  error "Invalid version format. Expected format: x.y.z (e.g., 0.0.21)"
fi

# Check if version is different
if [[ "$VERSION" == "$CURRENT_VERSION" ]]; then
  warning "Version $VERSION is the same as current version"
  read -p "Continue anyway? (y/n) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 1
  fi
fi

# Check if tag already exists
TAG="v$VERSION"
if git rev-parse "$TAG" >/dev/null 2>&1; then
  error "Tag $TAG already exists"
fi

# Summary
echo
echo -e "${BLUE}════════════════════════════════════════${NC}"
echo -e "${BLUE}Release Summary${NC}"
echo -e "${BLUE}════════════════════════════════════════${NC}"
echo "  Current version: $CURRENT_VERSION"
echo "  New version:     $VERSION"
echo "  Tag:             $TAG"
echo "  Branch:          $CURRENT_BRANCH"
echo "  Dry run:         $DRY_RUN"
echo "  Skip release:    $NO_RELEASE"
echo -e "${BLUE}════════════════════════════════════════${NC}"
echo

if [[ "$DRY_RUN" == "true" ]]; then
  warning "DRY RUN MODE - No changes will be made"
  echo
fi

read -p "Continue with release? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  info "Release cancelled"
  exit 0
fi

# Update version in pyproject.toml
info "Updating version in pyproject.toml..."
if [[ "$DRY_RUN" == "false" ]]; then
  # Use sed to update version (works on both Linux and macOS)
  if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    sed -i '' "s/^version = \".*\"/version = \"$VERSION\"/" pyproject.toml
  else
    # Linux
    sed -i "s/^version = \".*\"/version = \"$VERSION\"/" pyproject.toml
  fi
  success "Updated pyproject.toml"
else
  echo "  Would update: version = \"$VERSION\""
fi

# Update version in __init__.py if it exists
if [[ -f "pycharter/__init__.py" ]]; then
  info "Updating version in pycharter/__init__.py..."
  if [[ "$DRY_RUN" == "false" ]]; then
    if [[ "$OSTYPE" == "darwin"* ]]; then
      sed -i '' "s/^__version__ = \".*\"/__version__ = \"$VERSION\"/" pycharter/__init__.py
    else
      sed -i "s/^__version__ = \".*\"/__version__ = \"$VERSION\"/" pycharter/__init__.py
    fi
    success "Updated pycharter/__init__.py"
  else
    echo "  Would update: __version__ = \"$VERSION\""
  fi
fi

# Git add
info "Staging changes..."
if [[ "$DRY_RUN" == "false" ]]; then
  git add pyproject.toml
  [[ -f "pycharter/__init__.py" ]] && git add pycharter/__init__.py
  success "Staged changes"
else
  echo "  Would run: git add pyproject.toml pycharter/__init__.py"
fi

# Git commit
COMMIT_MSG="Bump version to $VERSION"
info "Committing changes..."
if [[ "$DRY_RUN" == "false" ]]; then
  git commit -m "$COMMIT_MSG"
  success "Committed: $COMMIT_MSG"
else
  echo "  Would run: git commit -m \"$COMMIT_MSG\""
fi

# Git push
info "Pushing to remote..."
if [[ "$DRY_RUN" == "false" ]]; then
  git push
  success "Pushed to remote"
else
  echo "  Would run: git push"
fi

# Create git tag
info "Creating git tag $TAG..."
if [[ "$DRY_RUN" == "false" ]]; then
  git tag -a "$TAG" -m "Release $TAG"
  success "Created tag $TAG"
else
  echo "  Would run: git tag -a \"$TAG\" -m \"Release $TAG\""
fi

# Push tag
info "Pushing tag $TAG..."
if [[ "$DRY_RUN" == "false" ]]; then
  git push origin "$TAG"
  success "Pushed tag $TAG"
else
  echo "  Would run: git push origin \"$TAG\""
fi

# Create GitHub release
if [[ "$NO_RELEASE" == "false" ]]; then
  # Check if gh CLI is installed
  if ! command -v gh &> /dev/null; then
    warning "GitHub CLI (gh) not found. Skipping GitHub release creation."
    warning "You can create it manually: gh release create $TAG --title \"$TAG\" --notes \"Release notes\""
  else
    info "Creating GitHub release $TAG..."
    if [[ "$DRY_RUN" == "false" ]]; then
      # Prompt for release notes
      echo
      echo -e "${BLUE}Enter release notes (press Enter for default, or type custom notes):${NC}"
      read -r RELEASE_NOTES
      if [[ -z "$RELEASE_NOTES" ]]; then
        RELEASE_NOTES="Release $TAG"
      fi
      
      if gh release create "$TAG" --title "$TAG" --notes "$RELEASE_NOTES"; then
        success "Created GitHub release $TAG"
        info "GitHub Actions will automatically build and publish to PyPI"
      else
        warning "Failed to create GitHub release. You can create it manually:"
        echo "  gh release create $TAG --title \"$TAG\" --notes \"$RELEASE_NOTES\""
      fi
    else
      echo "  Would run: gh release create $TAG --title \"$TAG\" --notes \"Release notes\""
    fi
  fi
fi

# Final summary
echo
echo -e "${GREEN}════════════════════════════════════════${NC}"
echo -e "${GREEN}Release Complete!${NC}"
echo -e "${GREEN}════════════════════════════════════════${NC}"
echo "  Version: $VERSION"
echo "  Tag:     $TAG"
if [[ "$DRY_RUN" == "true" ]]; then
  echo -e "${YELLOW}  (This was a dry run - no changes were made)${NC}"
else
  echo
  echo "Next steps:"
  echo "  1. Check GitHub Actions: https://github.com/optophi/pycharter/actions"
  echo "  2. Verify PyPI: https://pypi.org/project/pycharter/"
  echo "  3. Test installation: pip install pycharter==$VERSION"
fi
echo
