#!/bin/bash
# Comprehensive release script for clod
# Combines man page generation, Hackage release, Homebrew formula update, and bottle creation

set -e  # Exit on any error

cd "$(dirname "$0")/.."
PROJECT_ROOT=$(pwd)

# Extract current version from cabal file
CURRENT_VERSION=$(grep "^version:" clod.cabal | sed 's/version: *//')
echo "Current version: $CURRENT_VERSION"

# Calculate default new version (increment last number)
if [[ $CURRENT_VERSION =~ ([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
  MAJOR="${BASH_REMATCH[1]}"
  MINOR="${BASH_REMATCH[2]}"
  PATCH="${BASH_REMATCH[3]}"
  DEFAULT_VERSION="$MAJOR.$MINOR.$((PATCH + 1))"
else
  # Fall back to simple increment if version format is unexpected
  DEFAULT_VERSION="$CURRENT_VERSION+1"
fi

# Ask user for new version
read -r -p "Enter new version [$DEFAULT_VERSION]: " VERSION
VERSION=${VERSION:-$DEFAULT_VERSION}

echo "=== Starting comprehensive release process for clod $VERSION ==="

# Step 1: Verify tests pass before proceeding
echo "=== Running tests ==="
echo "Verifying all tests pass before making any changes..."
if ! cabal test; then
  echo "ERROR: Tests failed. Aborting release process."
  exit 1
fi
echo "All tests passed. Proceeding with release..."

# Update version in cabal file
echo "Updating version in clod.cabal..."
sed -i '' "s/^version:[ ]*$CURRENT_VERSION/version:             $VERSION/" clod.cabal

# Update CHANGELOG.md with new version entry
echo "Updating CHANGELOG.md..."
TODAY=$(date +"%Y-%m-%d")

# Check if a changelog entry for this version already exists
if ! grep -q "^## \[$VERSION\]" CHANGELOG.md; then
  # Insert new version entry at the top of the changelog (after the header)
  sed -i '' "1,/^# Changelog/ s/^# Changelog/# Changelog\n\n## [$VERSION] - $TODAY\n\n- Add your changes here\n\nThis release was created through human-AI pair programming, with Claude as the primary code author and Fuzz Leonard providing guidance, architectural decisions, and final review.\n/" CHANGELOG.md
  
  # Open CHANGELOG.md for editing
  echo "Opening CHANGELOG.md for editing. Please add your release notes."
  echo "Press Enter to continue once you've saved the changes."
  ${EDITOR:-nano} CHANGELOG.md
  read -r -p "Press Enter to continue with the release process..."
fi

# Step 1: Generate man pages
echo "=== Generating man pages ==="

# Inline implementation of generate-man-pages.sh
# Ensure pandoc is available
if ! command -v pandoc &> /dev/null; then
    echo "Error: pandoc is required to generate man pages"
    echo "Please install pandoc: https://pandoc.org/installing.html"
    exit 1
fi

# Make sure the source man directory exists
mkdir -p "$PROJECT_ROOT/man"

# Generate clod(1) - Command reference
echo "Generating clod(1).md source file..."
cat > "$PROJECT_ROOT/man/clod.1.md" << EOF
% CLOD(1) Clod $VERSION
% Fuzz Leonard & Claude <ink@fuzz.ink>
% March 2025

# NAME

clod - Claude Loader for preparing files for Claude AI's Project Knowledge

# SYNOPSIS

**clod** [*OPTIONS*]

# DESCRIPTION

Clod is a utility for preparing and uploading files to Claude AI's Project Knowledge feature. 
It tracks file changes, respects .gitignore and .clodignore patterns, and optimizes filenames 
for Claude's UI.

# OPTIONS

**--all**, **-a**
: Process all files (respecting .gitignore and .clodignore)

**--test**, **-t**
: Run in test mode (no prompts, useful for CI)

**--staging-dir** *DIR*, **-d** *DIR*
: Specify a directory for test mode (only used with --test)

**--verbose**, **-v**
: Enable verbose output

**--flush**, **-f**
: Remove missing entries from the database

**--last**, **-l**
: Reuse the previous staging directory

**--help**
: Show help information

**--version**
: Show version information

# EXAMPLES

Run clod (first run processes all files, subsequent runs process only modified files):
    clod

Force processing of all files:
    clod --all

Run in test mode with an optional test directory:
    clod --test --staging-dir /path/to/test/dir
    
Reuse the previous staging directory:
    clod --last
    
Remove missing entries from the database:
    clod --flush

# ENVIRONMENT VARIABLES

**CLOD_DIR**
: Override the default .clod directory name

**CLODIGNORE**
: Override the default .clodignore filename

# FILES

**.clodignore**
: Pattern file similar to .gitignore for excluding files

**.clod/database.dhall**
: Database of file checksums and metadata

# SEE ALSO

**clod(7)** for information about project instructions and safeguards.
**clod(8)** for a complete workflow guide to using clod with Claude AI.
EOF

# Generate clod(7) - Project instructions and safeguards
if [ -f "$PROJECT_ROOT/project-instructions.md" ] && [ -f "$PROJECT_ROOT/guardrails.md" ]; then
  echo "Generating clod(7).md source file..."
  
  # Create the header section
  cat > "$PROJECT_ROOT/man/clod.7.md" << EOF
% CLOD(7) Clod $VERSION
% Fuzz Leonard & Claude <ink@fuzz.ink>
% March 2025

# NAME

clod - project instructions and safeguards for Claude AI integration

# DESCRIPTION

This man page contains guidance on how to structure project instructions for Claude AI
and implement safeguards when using clod with Claude AI's Project Knowledge feature.
# PROJECT INSTRUCTIONS
EOF

  # Append project-instructions.md and guardrails.md content with a single redirection
  {
    # Append project-instructions.md content
    cat "$PROJECT_ROOT/project-instructions.md"
    # Add safeguards section
    echo ""
    echo "# SAFEGUARDS" 
    cat "$PROJECT_ROOT/guardrails.md"
  } >> "$PROJECT_ROOT/man/clod.7.md"
else
  echo "Warning: Cannot generate clod(7).md, source files missing"
fi

# Generate clod(8) - Complete workflow guide
if [ -f "$PROJECT_ROOT/HUMAN.md" ]; then
  echo "Generating clod(8).md source file..."
  
  # Create the header section
  cat > "$PROJECT_ROOT/man/clod.8.md" << EOF
% CLOD(8) Clod $VERSION
% Fuzz Leonard & Claude <ink@fuzz.ink>
% March 2025

# NAME

clod - complete workflow guide for using clod with Claude AI

# DESCRIPTION

This man page contains a comprehensive guide to using clod with Claude AI,
including best practices, workflow details, and integration tips.

# ABOUT CLAUDE'S INVOLVEMENT

This project represents a novel approach to software development, where Claude
(the AI assistant from Anthropic) served as the primary programmer, implementing 
nearly 100% of the codebase based on guidance from Fuzz Leonard. This
human-AI collaboration model leverages each collaborator's strengths, with
the human providing vision, requirements and architectural decisions, and the
AI handling implementation details, testing, and most documentation.
EOF

  # Append HUMAN.md content
  cat "$PROJECT_ROOT/HUMAN.md" >> "$PROJECT_ROOT/man/clod.8.md"
else
  echo "Warning: Cannot generate clod(8).md, HUMAN.md missing"
fi

echo "Man page markdown generation completed"

# Commit version bump changes and man pages together
echo "=== Committing version bump and man page changes ==="
echo "Do you want to commit these changes? [y/N]"
read -r version_response
if [[ "$version_response" =~ ^[Yy] ]]; then
  git add clod.cabal CHANGELOG.md man/
  git commit -m "Bump version to $VERSION and update man pages"
  
  echo "Do you want to push the commit to origin? [y/N]"
  read -r push_version_response
  if [[ "$push_version_response" =~ ^[Yy] ]]; then
    git push origin
  fi
fi

# Step 2: Generate documentation
echo "=== Building documentation for Hackage ==="
cabal haddock --haddock-for-hackage

# Step 3: Create source distribution
echo "=== Creating source distribution ==="
cabal sdist

# Step 4: Check package
echo "=== Checking package ==="
cabal check

# Step 5: Test build
echo "=== Testing build ==="
cabal build --disable-documentation

# Step 6: Build man pages for verification
echo "=== Building man pages for verification ==="
# Clean temp directory first to ensure we're testing with fresh files
rm -rf /tmp/clod-man-test
mkdir -p /tmp/clod-man-test
"$PROJECT_ROOT/bin/install-man-pages.sh" /tmp/clod-man-test

# Step 7: Verify man pages were generated correctly
echo "=== Verifying man pages ==="
echo "Source markdown files:"
find "$PROJECT_ROOT/man/" -name "*.md" -type f -exec ls -la {} \;
echo "Generated man pages in test directory:"
find /tmp/clod-man-test -maxdepth 1 -not -name "." -not -name ".." -exec ls -la {} \;
# Clean up after verification
rm -rf /tmp/clod-man-test

# Step 8: Create tag
echo "=== Creating Git tag ==="
echo "Do you want to create git tag v$VERSION? [y/N]"
read -r response
if [[ "$response" =~ ^[Yy] ]]; then
  # Check if tag already exists
  if git rev-parse "v$VERSION" >/dev/null 2>&1; then
    echo "Tag v$VERSION already exists!"
    echo "Do you want to force update it? [y/N]"
    read -r force_tag
    if [[ "$force_tag" =~ ^[Yy] ]]; then
      git tag -fa "v$VERSION" -m "Release version $VERSION"
      echo "Tag v$VERSION updated."
    else
      echo "Skipping tag creation."
    fi
  else
    git tag -a "v$VERSION" -m "Release version $VERSION"
    echo "Tag v$VERSION created."
  fi
  
  echo "Do you want to push the tag to origin? [y/N]"
  read -r push_response
  if [[ "$push_response" =~ ^[Yy] ]]; then
    git push origin "v$VERSION"
  fi
fi

# Step 9: Generate documentation package for Hackage
echo "=== Generating Hackage documentation package ==="
echo "Generating documentation package for Hackage..."
cabal haddock --haddock-for-hackage --enable-documentation

# Step 10: Upload to Hackage (manual step)
echo "=== Ready to upload to Hackage ==="
echo "The following commands will upload the package and documentation to Hackage:"
echo
echo "  cabal upload --publish dist-newstyle/sdist/clod-$VERSION.tar.gz"
echo "  curl --http1.1 for documentation (using HTTP 1.1 to work around Hackage networking issues)"
echo

echo "Do you want to upload to Hackage now? [y/N]"
read -r upload_response
if [[ "$upload_response" =~ ^[Yy] ]]; then
  echo "Uploading package to Hackage..."
  cabal upload --publish "dist-newstyle/sdist/clod-$VERSION.tar.gz"
  
  echo "Please enter your Hackage username for documentation upload:"
  read -r username
  
  echo "Uploading documentation for clod-$VERSION"
  echo "You will be prompted for your Hackage password."
  # Must force HTTP 1.1 to get around networking issues
  curl --http1.1 -X PUT --data-binary "@dist-newstyle/clod-$VERSION-docs.tar.gz" \
    -H 'Content-Type: application/x-tar' \
    -H 'Content-Encoding: gzip' \
    --user "$username" \
    "https://hackage.haskell.org/package/clod-$VERSION/docs"
else
  echo "Skipping Hackage upload. Run the commands manually when ready."
  # Don't exit here as we still want to update the Homebrew formula
fi

# Step 11: Wait for Hackage to process the package
echo "=== Waiting for Hackage to process the package ==="
echo "Waiting for Hackage to process the package (10 seconds)..."
sleep 10

# Step 12: Calculate SHA256 for Homebrew formula
echo "=== Updating Homebrew formula ==="
echo "Calculating SHA256 for Hackage package..."
HACKAGE_URL="https://hackage.haskell.org/package/clod-$VERSION/clod-$VERSION.tar.gz"

# Try to download and calculate SHA up to 3 times with increasing delays
MAX_ATTEMPTS=3
ATTEMPT=1
SHA256=""

while [ $ATTEMPT -le $MAX_ATTEMPTS ] && [ -z "$SHA256" ]; do
  echo "Attempt $ATTEMPT of $MAX_ATTEMPTS to calculate SHA256..."
  
  # Download the package and calculate SHA256
  SHA256=$(curl -sL "$HACKAGE_URL" | shasum -a 256 | cut -d ' ' -f 1)
  
  if [ -z "$SHA256" ] || [ "$SHA256" = "da39a3ee5e6b4b0d3255bfef95601890afd80709" ]; then
    # Empty SHA or SHA of empty file (package not available yet)
    WAIT_TIME=$((ATTEMPT * 10))
    echo "Package not available yet. Waiting $WAIT_TIME seconds before retry..."
    sleep $WAIT_TIME
    ATTEMPT=$((ATTEMPT + 1))
  else
    # Validate that the SHA256 looks legitimate (64 hex chars)
    if [[ "$SHA256" =~ ^[0-9a-f]{64}$ ]]; then
      echo "Valid SHA256 obtained: $SHA256"
      break
    else
      echo "Invalid SHA256 obtained. Retrying..."
      SHA256=""
      sleep 5
      ATTEMPT=$((ATTEMPT + 1))
    fi
  fi
done

if [ -z "$SHA256" ]; then
  echo "Error: Failed to calculate SHA256 after $MAX_ATTEMPTS attempts."
  echo "The package might not be available on Hackage yet."
  echo "You will need to update the formula manually with:"
  echo "  curl -sL $HACKAGE_URL | shasum -a 256"
  exit 1
fi

# Verify the package is accessible with expected size
PACKAGE_SIZE=$(curl -sI "$HACKAGE_URL" | grep -i "Content-Length" | awk '{print $2}' | tr -d '\r')
if [ -z "$PACKAGE_SIZE" ] || [ "$PACKAGE_SIZE" -lt 1000 ]; then
  echo "Warning: Package seems too small or inaccessible ($PACKAGE_SIZE bytes)."
  echo "SHA256 might be incorrect. Proceed with caution."
  echo "Press Enter to continue or Ctrl+C to abort and fix manually."
  read -r
fi

# Step 13: Update Homebrew formula
FORMULA_PATH="../homebrew-tap/Formula/clod.rb"
if [ ! -f "$FORMULA_PATH" ]; then
  echo "Error: Homebrew formula not found at $FORMULA_PATH"
  exit 1
fi

echo "Updating Homebrew formula with new version $VERSION and SHA256 $SHA256..."

# First verify that all required marker comments exist
if ! grep -q "TARBALL_URL_MARKER" "$FORMULA_PATH"; then
  echo "ERROR: TARBALL_URL_MARKER not found in formula. Cannot update safely."
  exit 1
fi

if ! grep -q "TARBALL_SHA256_MARKER" "$FORMULA_PATH"; then
  echo "ERROR: TARBALL_SHA256_MARKER not found in formula. Cannot update safely."
  exit 1
fi

# Remember we're in the clod directory for this part
# Save current directory to return to it for homebrew operations
CLOD_DIR="$(pwd)"

# Always update the bottle root_url to match the current version
# even if we're not building a bottle - this prevents version mismatches
ROOT_URL_TEMPLATE="    root_url \"https://github.com/fuzz/clod/releases/download/v$VERSION\" # BOTTLE_ROOT_URL_MARKER"
sed -i '' "s|.*BOTTLE_ROOT_URL_MARKER.*|$ROOT_URL_TEMPLATE|" "$FORMULA_PATH"

# Use simple templates for the complete lines
URL_TEMPLATE="  url \"https://hackage.haskell.org/package/clod-$VERSION/clod-$VERSION.tar.gz\" # TARBALL_URL_MARKER"
SHA_TEMPLATE="  sha256 \"$SHA256\" # TARBALL_SHA256_MARKER"

# Replace the entire lines with the markers
sed -i '' "s|.*TARBALL_URL_MARKER.*|$URL_TEMPLATE|" "$FORMULA_PATH"
sed -i '' "s|.*TARBALL_SHA256_MARKER.*|$SHA_TEMPLATE|" "$FORMULA_PATH"

# Verify the changes were made correctly
if ! grep -q "clod-$VERSION.*\.tar\.gz.*TARBALL_URL_MARKER" "$FORMULA_PATH"; then
  echo "ERROR: Formula URL update failed. Please check $FORMULA_PATH manually."
  grep -A 2 "url" "$FORMULA_PATH"
  exit 1
fi

if ! grep -q "$SHA256.*TARBALL_SHA256_MARKER" "$FORMULA_PATH"; then
  echo "ERROR: Formula SHA256 update failed. Please check $FORMULA_PATH manually."
  grep -A 2 "sha256" "$FORMULA_PATH"
  exit 1
fi

echo "Formula updated successfully with new version and SHA256."

# Step 14: Create and update bottle
echo "=== Building Homebrew bottle ==="
echo "Do you want to build a Homebrew bottle for this release? [y/N]"

# Debug input behavior
echo "Debug: TTY status: $([ -t 0 ] && echo 'Input is from terminal' || echo 'Input is NOT from terminal')" >&2
echo "Debug: Input source: $(tty 2>/dev/null || echo 'unknown')" >&2

# For debugging, force a delay and make prompt more visible
echo -e "\033[1;31mWAITING FOR INPUT (y/N):\033[0m" >&2
sleep 1

read -r bottle_response
echo "Debug: User entered: '$bottle_response'" >&2

if [[ "$bottle_response" =~ ^[Yy] ]]; then
  # Build bottle directly, no subshell so errors propagate
  echo "Building bottle for clod formula..."
  
  # Change to homebrew-tap directory, with error handling
  if ! cd "../homebrew-tap"; then
    echo "ERROR: Failed to change to homebrew-tap directory"
    exit 1
  fi
  
  # Clean environment and create the bottle
  echo "Creating bottle for this formula..."
  
  # Ensure we have a clean state - uninstall any version of clod
  brew uninstall --force clod 2>/dev/null || true
  
  # Make sure our tap is properly set up
  echo "Ensuring tap is properly set up..."
  # Commit any changes to ensure the tap repo is clean
  git add Formula/clod.rb
  git commit -m "Update formula for version $VERSION" || true
  
  # Point the tap to our local repo
  brew untap fuzz/tap 2>/dev/null || true
  brew tap fuzz/tap "$(pwd)"
  
  # Now install using the tap reference, not the file path
  echo "Installing formula with --build-bottle flag..."
  brew install --build-bottle fuzz/tap/clod
  
  echo "Creating bottle file..."
  # Now we can reference the formula by its tap name
  echo "Creating bottle with JSON output..."
  
  # Check if jq is available - we need it to parse the JSON
  if ! command -v jq &> /dev/null; then
    echo "ERROR: jq is required but not installed. Please install jq."
    exit 1
  fi
  
  # Add explicit flushing to make sure output is visible
  echo "About to run bottle command with JSON output" >&2
  set -x  # Turn on command tracing for debugging
  
  # Run brew bottle with JSON output to get both filename and local_filename
  if ! brew bottle --json --root-url="https://github.com/fuzz/clod/releases/download/v$VERSION" fuzz/tap/clod; then
    echo "ERROR: Failed to create bottle" >&2
    exit 1
  fi
  
  set +x  # Turn off command tracing
  echo "Bottle command completed successfully" >&2
  
  # Find the JSON file created by brew bottle
  bottle_json=$(find . -name "*.json" -newer "$(pwd)/.git/index" -print | head -1)
  echo "Found JSON file: $bottle_json"
  
  if [ -z "$bottle_json" ] || [ ! -f "$bottle_json" ]; then
    echo "ERROR: Could not find bottle JSON file" >&2
    exit 1
  fi
  
  # Extract both filenames from the JSON
  # The JSON structure has the filenames under the "tags" key for the specific platform
  expected_filename=$(jq -r '.[] | .bottle.tags | to_entries[0].value.filename' "$bottle_json")
  local_filename=$(jq -r '.[] | .bottle.tags | to_entries[0].value.local_filename' "$bottle_json")
  
  # Fail if we couldn't extract the filenames
  if [ -z "$expected_filename" ] || [ -z "$local_filename" ]; then
    echo "ERROR: Failed to extract expected_filename or local_filename from JSON" >&2
    echo "JSON content:" >&2
    cat "$bottle_json" >&2
    exit 1
  fi
  
  echo "Expected filename (for Homebrew): $expected_filename"
  echo "Local filename (generated): $local_filename"
  
  # Use the local_filename as our bottle_file
  bottle_file=$local_filename
  
  # Verify the bottle file exists
  if [ ! -f "$bottle_file" ]; then
    echo "ERROR: Bottle file not found: $bottle_file" >&2
    exit 1
  fi
  
  echo "Bottle file: $bottle_file"
  
  # Extract the SHA256 from the JSON
  echo "Extracting SHA256 from JSON..." >&2
  bottle_sha=$(jq -r '.[] | .bottle.tags | to_entries[0].value.sha256' "$bottle_json")
  
  if [ -z "$bottle_sha" ]; then
    echo "ERROR: Failed to extract SHA256 from JSON" >&2
    echo "JSON content:" >&2
    cat "$bottle_json" >&2
    exit 1
  fi
  
  echo "Bottle SHA256: $bottle_sha"
  
  # Extract the macOS version from the JSON
  macos_version=$(jq -r '.[] | .bottle.tags | keys[0]' "$bottle_json" | cut -d'_' -f2)
  echo "macOS version: $macos_version"
  
  # Fail if we can't extract the macOS version
  if [ -z "$macos_version" ]; then
    echo "ERROR: Failed to extract macOS version from JSON"
    echo "JSON content:" >&2
    cat "$bottle_json" >&2
    exit 1
  fi
  
  # Note: We already checked each variable individually with better error messages
  
  # Make sure the bottle file exists
  echo "Checking if bottle file exists: $bottle_file" >&2
  ls -la "$bottle_file" >&2 || echo "Bottle file not found" >&2
  
  if [ ! -f "$bottle_file" ]; then
    echo "ERROR: Bottle file not found: $bottle_file"
    echo "Contents of current directory:" >&2
    ls -la >&2
    exit 1
  fi
  
  # Move the bottle to a directory for release
  mkdir -p bottles
  mv "$bottle_file" bottles/
  
  echo "Bottle created successfully: bottles/$bottle_file"
  
  # Check for GitHub CLI and upload bottle
  echo "===== BEGIN GITHUB UPLOAD SECTION =====" >&2
  echo "Checking for GitHub CLI (gh)..."
  if ! command -v gh &> /dev/null; then
    echo "ERROR: GitHub CLI (gh) not found. Please install it to automate bottle uploads."
    echo "See: https://cli.github.com/"
    exit 1
  fi
  
  echo "==> INTERACTIVE PROMPT: GitHub Upload" >&2
  echo "Do you want to upload bottle to GitHub? [y/N]"
  read -r upload_bottle
  echo "User response to upload prompt: $upload_bottle" >&2
  
  if [[ "$upload_bottle" =~ ^[Yy] ]]; then
    # Change directory to the clod repository for GitHub operations
    cd "$CLOD_DIR"
    
    echo "Checking if release for v$VERSION exists..."
    if ! gh release view "v$VERSION" &>/dev/null; then
      echo "Release v$VERSION doesn't exist. Creating it now..."
      gh release create "v$VERSION" --title "Release v$VERSION" --notes "Release v$VERSION with Homebrew bottle support."
    fi
    
    # Go back to homebrew-tap directory to access the bottle file
    cd "../homebrew-tap"
    
    echo "Renaming bottle file to match Homebrew's expected filename..."
    # Use the exact filename from the JSON file
    if ! mv "bottles/$bottle_file" "bottles/$expected_filename"; then
      echo "ERROR: Failed to rename bottle file to match Homebrew's expected filename." >&2
      exit 1
    fi
    
    echo "Successfully renamed bottle file to: $expected_filename"
    
    # Go back to clod directory for GitHub operations
    cd "$CLOD_DIR"
    
    echo "Uploading bottle to GitHub release v$VERSION in fuzz/clod repository..."
    if ! gh release upload "v$VERSION" "../homebrew-tap/bottles/$expected_filename" --clobber; then
      echo "ERROR: Failed to upload bottle to GitHub." >&2 
      exit 1
    fi
    
    echo "Bottle uploaded successfully to GitHub release!"
    echo "URL: https://github.com/fuzz/clod/releases/download/v$VERSION/$expected_filename"
    
    # Change back to homebrew-tap directory
    cd "../homebrew-tap"
  else
    echo "Skipping GitHub upload as requested."
  fi
  echo "===== END GITHUB UPLOAD SECTION =====" >&2
  
  # Update the formula with bottle information
  echo "Updating formula with bottle information..."
  
  # Extract rebuild number directly from the bottle filename
  # Using bash regex with BASH_REMATCH
  if [[ "$bottle_file" =~ bottle\.([0-9]+) ]]; then
    rebuild_num="${BASH_REMATCH[1]}"
    echo "Found rebuild number $rebuild_num in bottle filename: $bottle_file"
    
    # Check if rebuild directive already exists
    if grep -q "^[[:space:]]*rebuild" Formula/clod.rb; then
      # Update the rebuild directive in the formula
      echo "Setting rebuild to $rebuild_num based on bottle filename"
      # Use awk to properly match and replace the rebuild line
      awk -v num="$rebuild_num" '{if ($1 == "rebuild") {print "    rebuild " num;} else {print $0;}}' Formula/clod.rb > Formula/clod.rb.new
      mv Formula/clod.rb.new Formula/clod.rb
      
      # Verify the rebuild was updated correctly
      echo "Verifying rebuild number in formula:"
      grep "rebuild" Formula/clod.rb
    else
      # Add rebuild directive if it doesn't exist
      echo "Adding rebuild directive with value $rebuild_num"
      sed -i '' "/root_url/a\\
    rebuild $rebuild_num" Formula/clod.rb
    fi
  else
    echo "No rebuild number found in filename, removing rebuild directive if present"
    # Remove rebuild directive if it exists
    sed -i '' '/^[[:space:]]*rebuild [0-9]\+$/d' Formula/clod.rb
  fi
  
  # Update the bottle SHA - use :any for cellar since we link against libmagic
  BOTTLE_SHA_TEMPLATE="    sha256 cellar: :any, arm64_${macos_version}: \"$bottle_sha\" # BOTTLE_SHA256_MARKER"
  
  # Replace the SHA line with the marker
  sed -i '' "s|.*BOTTLE_SHA256_MARKER.*|$BOTTLE_SHA_TEMPLATE|" Formula/clod.rb
  if ! grep -q "v$VERSION.*BOTTLE_ROOT_URL_MARKER" Formula/clod.rb; then
    echo "ERROR: Bottle root_url update failed. Please check Formula/clod.rb manually."
    grep -A 2 "root_url" Formula/clod.rb
    exit 1
  fi
  
  if ! grep -q "arm64_${macos_version}.*$bottle_sha.*BOTTLE_SHA256_MARKER" Formula/clod.rb; then
    echo "ERROR: Bottle SHA update failed. Please check Formula/clod.rb manually."
    grep -A 2 "sha256 cellar" Formula/clod.rb
    exit 1
  fi
  
  # Ask if the user wants to PUSH and then test the bottle installation
  echo "IMPORTANT: You must push formula changes to GitHub before testing bottle installation."
  echo "Do you want to push changes to GitHub and then test the bottle? [y/N]"
  read -r test_bottle
  if [[ "$test_bottle" =~ ^[Yy] ]]; then
    echo "Preparing to push formula changes to GitHub..."
    
    # Show the formula's bottle section for reference
    echo "Current formula bottle section:"
    grep -A 5 "bottle do" Formula/clod.rb
    
    # Show the bottle filename for reference
    echo "Bottle filename: $bottle_file"
    
    # Commit changes 
    git add Formula/clod.rb
    git commit -m "Update bottle references for version $VERSION" || true
    
    # Push changes to GitHub
    echo "Pushing formula changes to GitHub..."
    if ! git push origin main; then
      echo "ERROR: Failed to push changes to GitHub. Test installation will fail."
      echo "Please push changes manually and then test installation."
      exit 1
    fi
    
    echo "Changes pushed to GitHub. Waiting 10 seconds for changes to propagate..."
    sleep 10
    
    # Uninstall any existing version
    brew uninstall --force clod 2>/dev/null || true
    
    # Untap and retap to get the latest formula from GitHub
    brew untap fuzz/tap 2>/dev/null || true
    brew tap fuzz/tap
    
    # Install with debugging
    echo "Installing from GitHub formula..."
    brew install --verbose fuzz/tap/clod 
    
    # Show what was installed
    echo "Verifying installation..."
    clod --version
    brew info clod
    
    echo "Bottle test complete."
  fi
  
  # Return to original directory
  cd "$CLOD_DIR" || exit 1
fi

# Return to clod directory no matter what
cd "$CLOD_DIR" || exit 1

echo "=== Release process complete! ==="
echo "Version $VERSION has been released to Hackage and the Homebrew formula has been updated."
echo "Remember to test the Homebrew installation with: brew install fuzz/tap/clod"
