#!/usr/bin/env python3
import os
import json
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io

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

url = 'https://docs.google.com/document/d/1OU4qFFbLCXybdyhTXOdh1Kuy4JBXpjDv/edit?usp=sharing&ouid=103789065343444502410&rtpof=true&sd=true'
doc_id = url.split('/d/')[1].split('/')[0]
print(f"Document ID: {doc_id}")

creds = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=creds)

# Try to export as plain text
try:
    request = service.files().export_media(fileId=doc_id, mimeType='text/plain')
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print(f"Download {int(status.progress() * 100)}%.")
    text = fh.getvalue().decode('utf-8')
    print("\nExported text (first 2000 chars):")
    print(text[:2000])
except Exception as e:
    print(f"Export as plain text failed: {e}")
    # Try to download the raw .docx file
    try:
        request = service.files().get_media(fileId=doc_id)
        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(f"Download raw .docx {int(status.progress() * 100)}%.")
        # Save to local file
        with open('temp_doc.docx', 'wb') as f:
            f.write(fh.getvalue())
        print("Downloaded .docx file as 'temp_doc.docx'")
        # Try to parse with python-docx if installed
        try:
            import docx
            doc = docx.Document('temp_doc.docx')
            full_text = []
            for para in doc.paragraphs:
                full_text.append(para.text)
            text = '\n'.join(full_text)
            print("\nParsed .docx content (first 2000 chars):")
            print(text[:2000])
        except ImportError:
            print("python-docx not installed. Cannot parse .docx content.")
    except Exception as e2:
        print(f"Download raw .docx also failed: {e2}")