#!/usr/bin/env python3
import os
import time
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)
docs_service = build('docs', 'v1', credentials=creds)
drive_service = build('drive', 'v3', credentials=creds)

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

# Create a new document
doc_metadata = {'title': 'Vấn đáp giới luật - Đã hiệu đính (10 trang đầu)'}
new_doc = docs_service.documents().create(body=doc_metadata).execute()
document_id = new_doc.get('documentId')

print(f"Created Document ID: {document_id}")

# Make it world-readable (anyone with link can view/edit)
try:
    permission = {
        'type': 'anyone',
        'role': 'writer',
    }
    drive_service.permissions().create(fileId=document_id, body=permission).execute()
    print("Permissions updated.")
except Exception as e:
    print(f"Error setting permissions: {e}")

# Insert the text
requests = [
    {
        'insertText': {
            'location': {
                'index': 1,
            },
            'text': edited_text
        }
    }
]

result = docs_service.documents().batchUpdate(documentId=document_id, body={'requests': requests}).execute()
print(f"Text inserted successfully. Link: https://docs.google.com/document/d/{document_id}/edit")