File size: 2,863 Bytes
6ba35d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import logging
from datetime import datetime
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from auth import get_creds

# ---------------- LOGGING SETUP ---------------- #
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logger = logging.getLogger(__name__)


# ---------------- MAIN FUNCTION ---------------- #
def append_to_doc(doc_id: str, content: str):
    """
    Appends timestamped content to a Google Doc.

    Args:
        doc_id (str): Google Doc ID
        content (str): Text to append

    Returns:
        dict: status + message
    """

    try:
        logger.info(f"Starting append_to_doc for doc_id={doc_id}")

        # -------- INPUT VALIDATION -------- #
        if not doc_id or not content:
            logger.error("Missing doc_id or content")
            return {
                "status": "error",
                "message": "doc_id and content are required"
            }

        # -------- AUTH -------- #
        creds = get_creds()
        logger.info("Credentials loaded")

        # -------- INIT SERVICE -------- #
        service = build("docs", "v1", credentials=creds)
        logger.info("Google Docs service initialized")

        # -------- FORMAT CONTENT -------- #
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        formatted_content = f"\n[{timestamp}]\n{content}\n"

        # -------- PREPARE REQUEST -------- #
        requests = [
            {
                "insertText": {
                    "endOfSegmentLocation": {},
                    "text": formatted_content
                }
            }
        ]

        # -------- EXECUTE API CALL -------- #
        try:
            service.documents().batchUpdate(
                documentId=doc_id,
                body={"requests": requests}
            ).execute()

            logger.info("Content appended successfully")

            return {
                "status": "success",
                "message": "Content appended to document",
                "document_id": doc_id
            }

        except HttpError as e:
            logger.error(f"Google Docs API error: {e}")

            return {
                "status": "error",
                "message": "Google Docs API error",
                "details": str(e)
            }

        except Exception as e:
            logger.error(f"Execution error: {e}")

            return {
                "status": "error",
                "message": "Failed during API execution",
                "details": str(e)
            }

    # -------- FALLBACK ERROR -------- #
    except Exception as e:
        logger.error(f"Unexpected error: {e}")

        return {
            "status": "error",
            "message": "Unexpected error occurred",
            "details": str(e)
        }