#!/usr/bin/env bash
set -euo pipefail

# Specwright GitHub App Setup
# Run this after creating the app at:
#   https://github.com/organizations/Gerner-Ventures/settings/apps/new
#
# Use the settings from github-app-manifest.json when filling in the form.
#
# After creating the app:
#   1. Note the App ID from the app settings page
#   2. Generate a private key (.pem file) from the app settings page
#   3. Note the webhook secret you configured
#   4. Install the app on the gv-exp-specwright repo
#   5. Run this script to set Vercel environment variables

echo "=== Specwright GitHub App Setup ==="
echo ""

read -rp "GitHub App ID: " APP_ID
read -rp "Path to private key .pem file: " PEM_PATH
read -rp "Webhook secret: " WEBHOOK_SECRET

if [[ ! -f "$PEM_PATH" ]]; then
  echo "Error: PEM file not found at $PEM_PATH"
  exit 1
fi

PRIVATE_KEY=$(cat "$PEM_PATH")

echo ""
echo "Setting Vercel environment variables..."

echo "$APP_ID" | npx vercel env add APP_ID production preview development
echo "$PRIVATE_KEY" | npx vercel env add PRIVATE_KEY production preview development
echo "$WEBHOOK_SECRET" | npx vercel env add WEBHOOK_SECRET production preview development

echo ""
echo "Done! Redeploying to pick up new env vars..."
npx vercel --prod

echo ""
echo "Verify the webhook endpoint:"
echo "  curl -s -o /dev/null -w '%{http_code}' https://gv-exp-specwright.vercel.app/api/webhook"
echo "  (Should return 400 or 405, not 500)"
