#!/bin/bash
set -eu

# Ada release script — builds locally and publishes to homebrew-tap
# Usage: ./scripts/release.sh [version]
# Example: ./scripts/release.sh 0.1.3
#          ./scripts/release.sh  (uses version from package.json)

REPO="saikrishnabolla/ada"
TAP_REPO="saikrishnabolla/homebrew-tap"

# Get version
if [ -n "${1:-}" ]; then
  VERSION="$1"
else
  VERSION=$(node -p "require('./package.json').version")
fi

TAG="v${VERSION}"
echo ""
echo "  Releasing Ada $TAG"
echo ""

# 1. Build
echo "  [1/5] Building TypeScript..."
npm run build

echo "  [2/5] Building native bundle..."
npm run build:native-bundle

BUNDLE="dist/release/ada-${VERSION}-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m | sed 's/x86_64/x64/' | sed 's/aarch64/arm64/').tar.gz"

if [ ! -f "$BUNDLE" ]; then
  echo "  Error: Bundle not found at $BUNDLE"
  exit 1
fi

# 2. Get SHA
SHA=$(shasum -a 256 "$BUNDLE" | cut -d' ' -f1)
PLATFORM=$(echo "$BUNDLE" | grep -o '[a-z]*-[a-z0-9]*\.tar\.gz' | sed 's/\.tar\.gz//')

echo "  [3/5] Uploading to homebrew-tap..."

# 3. Upload to homebrew-tap release
if gh release view "$TAG" --repo "$TAP_REPO" >/dev/null 2>&1; then
  gh release delete-asset "$TAG" "ada-${VERSION}-${PLATFORM}.tar.gz" --repo "$TAP_REPO" --yes 2>/dev/null || true
  gh release upload "$TAG" "$BUNDLE" --repo "$TAP_REPO"
else
  gh release create "$TAG" "$BUNDLE" \
    --repo "$TAP_REPO" \
    --title "Ada $TAG" \
    --notes "Ada ${VERSION} native bundles"
fi

echo "  [4/5] Updating Homebrew formula..."

# 4. Get current formula and update SHA for this platform
BASE_URL="https://github.com/${TAP_REPO}/releases/download/${TAG}"

# Build formula — only include platforms we have bundles for
# For a full release, run this script on each platform or use the CI workflow
FORMULA_SHA=$(gh api "repos/${TAP_REPO}/contents/Formula/ada.rb" --jq '.sha')
CURRENT_FORMULA=$(gh api "repos/${TAP_REPO}/contents/Formula/ada.rb" --jq '.content' | base64 -d)

# Generate new formula
cat > /tmp/ada-formula.rb << RUBY
class Ada < Formula
  desc "The AI research agent for the terminal"
  homepage "https://thinkwithada.com"
  version "${VERSION}"
  license "Apache-2.0"

  on_macos do
    on_arm do
      url "${BASE_URL}/ada-${VERSION}-darwin-arm64.tar.gz"
      sha256 "PLACEHOLDER_DARWIN_ARM64"
    end
    on_intel do
      url "${BASE_URL}/ada-${VERSION}-darwin-x64.tar.gz"
      sha256 "PLACEHOLDER_DARWIN_X64"
    end
  end

  on_linux do
    on_intel do
      url "${BASE_URL}/ada-${VERSION}-linux-x64.tar.gz"
      sha256 "PLACEHOLDER_LINUX_X64"
    end
  end

  def install
    libexec.install Dir["*"]

    (bin/"ada").write <<~EOS
      #!/bin/bash
      exec "#{libexec}/node/bin/node" "#{libexec}/app/bin/ada.js" "\$@"
    EOS
  end

  test do
    assert_match version.to_s, shell_output("#{bin}/ada --version")
  end
end
RUBY

# Fill in SHAs — use current formula's SHAs for platforms we didn't build, new SHA for current platform
for p in darwin-arm64 darwin-x64 linux-x64; do
  if [ "$p" = "$PLATFORM" ]; then
    PLATFORM_SHA="$SHA"
  else
    # Try to get from existing release
    PLATFORM_SHA=$(curl -fsSL "${BASE_URL}/ada-${VERSION}-${p}.tar.gz" -o /tmp/ada-check-${p}.tar.gz 2>/dev/null && shasum -a 256 /tmp/ada-check-${p}.tar.gz | cut -d' ' -f1 || echo "")
    rm -f /tmp/ada-check-${p}.tar.gz
    if [ -z "$PLATFORM_SHA" ]; then
      # Extract from current formula
      PLATFORM_SHA=$(echo "$CURRENT_FORMULA" | grep -A1 "ada-.*-${p}" | grep sha256 | sed 's/.*"\(.*\)".*/\1/' || echo "MISSING")
    fi
  fi
  PLACEHOLDER="PLACEHOLDER_$(echo "$p" | tr '-' '_' | tr '[:lower:]' '[:upper:]')"
  sed -i.bak "s/${PLACEHOLDER}/${PLATFORM_SHA}/" /tmp/ada-formula.rb
done
rm -f /tmp/ada-formula.rb.bak

# Upload formula
CONTENT=$(base64 < /tmp/ada-formula.rb | tr -d '\n')
gh api "repos/${TAP_REPO}/contents/Formula/ada.rb" \
  --method PUT \
  --field message="Update Ada to ${TAG}" \
  --field branch="main" \
  --field sha="$FORMULA_SHA" \
  --field content="$CONTENT" \
  --silent

rm -f /tmp/ada-formula.rb

echo "  [5/5] Updating ada repo release..."

# 5. Also update ada repo release
if gh release view "$TAG" --repo "$REPO" >/dev/null 2>&1; then
  gh release delete-asset "$TAG" "ada-${VERSION}-${PLATFORM}.tar.gz" --repo "$REPO" --yes 2>/dev/null || true
  gh release upload "$TAG" "$BUNDLE" --repo "$REPO" --clobber
else
  gh release create "$TAG" "$BUNDLE" \
    --repo "$REPO" \
    --title "$TAG" \
    --notes "Ada ${VERSION} native bundles"
fi

echo ""
echo "  Done! Released Ada $TAG (${PLATFORM})"
echo "  Users can update with: ada update"
echo ""
