import sys
import io
import socket

old_getaddrinfo = socket.getaddrinfo
def new_getaddrinfo(*args, **kwargs):
    responses = old_getaddrinfo(*args, **kwargs)
    return [response for response in responses if response[0] == socket.AF_INET]
socket.getaddrinfo = new_getaddrinfo

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

SERVICE_ACCOUNT_FILE = 'google_service_account.json'
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/documents']

creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
drive_service = build('drive', 'v3', credentials=creds)
docs_service = build('docs', 'v1', credentials=creds)

folder_id = '1EaS10C6-ozNN0iyZC_pJ_28-SG8EWetG'
query = f"'{folder_id}' in parents and name = 'Dieu gi that su co gia tri - trich xuat' and mimeType = 'application/vnd.google-apps.document' and trashed = false"

results = drive_service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
items = results.get('files', [])

if not items:
    print("Document not found.")
    sys.exit(1)

document_id = items[0]['id']
print(f"Found document: {items[0]['name']} (ID: {document_id})")

with open('extracted_myanmar.txt', 'r', encoding='utf-8') as f:
    text_to_append = f.read()

# Make sure we add a leading newline to separate from existing content
text_to_append = "\n\n" + text_to_append.strip() + "\n\n"

requests = [
    {
        'insertText': {
            'location': {
                'index': 1 # We'll append at the end by fetching the document length first
            },
            'text': text_to_append
        }
    }
]

doc = docs_service.documents().get(documentId=document_id).execute()
content = doc.get('body').get('content')
end_index = content[-1]['endIndex'] - 1

requests[0]['insertText']['location']['index'] = end_index

result = docs_service.documents().batchUpdate(documentId=document_id, body={'requests': requests}).execute()
print("Successfully appended text to document.")
