import os
import sys
from google.oauth2 import service_account
from googleapiclient.discovery import build

SERVICE_ACCOUNT_FILE = '/home/openclaw/.openclaw/workspace/google_service_account.json'
DOCUMENT_ID = '1_50QyiXQYy4BEgOObNgPYIZiyoD-yEsOMYasXap-5EQ'
SCOPES = ['https://www.googleapis.com/auth/documents']

def append_to_doc(text):
    creds = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    service = build('docs', 'v1', credentials=creds)

    # Get document to find the end index
    doc = service.documents().get(documentId=DOCUMENT_ID).execute()
    end_index = doc.get('body').get('content')[-1].get('endIndex') - 1

    requests = [
        {
            'insertText': {
                'location': {
                    'index': end_index,
                },
                'text': text
            }
        }
    ]

    service.documents().batchUpdate(
        documentId=DOCUMENT_ID, body={'requests': requests}).execute()

if __name__ == '__main__':
    text_to_append = sys.stdin.read()
    if text_to_append:
        append_to_doc(text_to_append)
        print("Success")
    else:
        print("No text provided")
