#!/usr/bin/env python3
"""Embed photos inline in a Google Doc using the Docs API."""
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from googleapiclient.http import MediaFileUpload
from pathlib import Path

creds = Credentials.from_authorized_user_file('google_token.json', [
    'https://www.googleapis.com/auth/drive.file',
    'https://www.googleapis.com/auth/documents',
])
drive = build('drive', 'v3', credentials=creds)
docs = build('docs', 'v1', credentials=creds)

DOC_ID = '127h73CMkVlC3wv2-ZZYQ_oBWkhW4MWWRv4Te57umwt0'
PHOTO_DIR = Path('/home/ccuser/opsman-work/daily')

photo_files = sorted(PHOTO_DIR.glob('*.jpg'))
print(f"Found {len(photo_files)} photos")

# Get current doc content length so we append at the end
doc = docs.documents().get(documentId=DOC_ID).execute()
content = doc.get('body', {}).get('content', [])
# Find the last index
end_index = 1
for el in content:
    end_index = el.get('endIndex', end_index)

requests = []
current_index = end_index

for photo_path in photo_files:
    fname = photo_path.name
    print(f"Uploading {fname}...")

    # Upload to Drive
    media = MediaFileUpload(str(photo_path), mimetype='image/jpeg')
    uploaded = drive.files().create(
        body={'name': fname, 'mimeType': 'image/jpeg'},
        media_body=media,
        fields='id, webContentLink, thumbnailLink'
    ).execute()
    file_id = uploaded['id']
    print(f"  File ID: {file_id}")

    # Make publicly readable
    drive.permissions().create(
        fileId=file_id,
        body={'type': 'anyone', 'role': 'reader'}
    ).execute()

    # Use the direct image URL from Drive
    image_url = f"https://drive.google.com/uc?export=view&id={file_id}"

    # Add a caption paragraph
    requests.append({
        'insertText': {
            'location': {'index': current_index},
            'text': f"\n{fname}\n"
        }
    })
    current_index += len(fname) + 2

    # Insert inline image after caption
    requests.append({
        'insertInlineImage': {
            'location': {'index': current_index},
            'uri': image_url,
            'objectSize': {
                'width': {'magnitude': 600, 'unit': 'PT'},
                'height': {'magnitude': 450, 'unit': 'PT'}
            }
        }
    })
    current_index += 1

    print(f"  Embedded at index {current_index}")

print(f"\nInserting at index {end_index}, {len(requests)} requests...")
docs.documents().batchUpdate(
    documentId=DOC_ID,
    body={'requests': requests}
).execute()

print("Done!")