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

def append_to_doc(document_id, credentials_path, text):
    creds = service_account.Credentials.from_service_account_file(
        credentials_path, scopes=['https://www.googleapis.com/auth/documents']
    )
    service = build('docs', 'v1', credentials=creds)
    
    requests = [
        {
            'insertText': {
                'endOfSegmentLocation': {
                    'segmentId': ''
                },
                'text': text
            }
        }
    ]
    
    result = service.documents().batchUpdate(
        documentId=document_id, body={'requests': requests}).execute()
    return result

if __name__ == "__main__":
    doc_id = sys.argv[1]
    text_file = sys.argv[2]
    
    with open(text_file, 'r', encoding='utf-8') as f:
        text = f.read()
        
    # Append a newline before if needed, but text probably has it.
    text_to_insert = "\n\n" + text + "\n"
    
    creds_path = "/opt/openclaw/.openclaw/workspace/google_service_account.json"
    try:
        res = append_to_doc(doc_id, creds_path, text_to_insert)
        print("Success")
    except Exception as e:
        print("Error:", str(e))
        sys.exit(1)
