#!/bin/bash
SERVICE_ACCOUNT_KEY_FILE="/opt/openclaw/.openclaw/workspace/google_service_account.json"
DOCUMENT_ID="1xiB5pmqTOSch_VJh735mYHLWzCdBKWNNBFo0VCynBV8"
SCOPE="https://www.googleapis.com/auth/documents"

HEADER=$(echo -n '{"alg":"RS256","typ":"JWT"}' | base64 | tr -d '\n=' | tr '/+' '_-')
IAT=$(date +%s)
EXP=$((IAT + 3600))
CLIENT_EMAIL=$(jq -r .client_email "$SERVICE_ACCOUNT_KEY_FILE")
CLAIM_SET=$(jq -n -c --arg email "$CLIENT_EMAIL" --arg scope "$SCOPE" --argjson iat $IAT --argjson exp $EXP '{iss: $email, scope: $scope, aud: "https://www.googleapis.com/oauth2/v4/token", iat: $iat, exp: $exp}')
CLAIM_SET_ENCODED=$(echo -n "$CLAIM_SET" | base64 | tr -d '\n=' | tr '/+' '_-')
SIGNED_CONTENT="$HEADER.$CLAIM_SET_ENCODED"
PRIVATE_KEY=$(jq -r .private_key "$SERVICE_ACCOUNT_KEY_FILE")
echo "$PRIVATE_KEY" > /tmp/private_key.pem
SIGNATURE=$(echo -n "$SIGNED_CONTENT" | openssl dgst -sha256 -sign /tmp/private_key.pem | base64 | tr -d '\n=' | tr '/+' '_-')
rm /tmp/private_key.pem
JWT="$SIGNED_CONTENT.$SIGNATURE"
TOKEN_RESPONSE=$(curl -s -X POST "https://www.googleapis.com/oauth2/v4/token" -H "Content-Type: application/x-www-form-urlencoded" --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" --data-urlencode "assertion=$JWT")
ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r .access_token)

# Read the extracted text and escape it for JSON
TEXT_TO_APPEND=$(cat /opt/openclaw/.openclaw/workspace/pages_41_50_extracted.txt)
# Use jq to create the JSON body with the escaped text
BATCH_UPDATE_BODY=$(jq -n --arg text "$TEXT_TO_APPEND\n" '{
  "requests": [
    {
      "insertText": {
        "endOfSegmentLocation": {},
        "text": $text
      }
    }
  ]
}')

DOCS_API_ENDPOINT="https://docs.googleapis.com/v1/documents/$DOCUMENT_ID:batchUpdate"

curl -s -X POST "$DOCS_API_ENDPOINT" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d "$BATCH_UPDATE_BODY" | jq .
