diff --git a/agents/weather_briefing.py b/agents/weather_briefing.py index 94abd35..63c8879 100644 --- a/agents/weather_briefing.py +++ b/agents/weather_briefing.py @@ -121,26 +121,76 @@ def format_briefing(weather): return md, f"{condition}, {temp}°F (feels like {feels}°F), wind {wind} mph" -def post_to_wiki(markdown, date_str): - """Create or update a daily briefing doc in Outline.""" - headers = { - "Authorization": f"Bearer {WIKI_TOKEN}", - } +MONTH_NAMES = [ + "", "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December", +] - # Search for existing doc with today's date - title = f"Daily Briefing — {date_str}" - search_result = api_request( + +def find_child_doc(parent_id, title, headers): + """Search for a child doc by title under a given parent.""" + result = api_request( f"{WIKI_API}/documents.search", data={"query": title, "collectionId": WIKI_COLLECTION_ID}, headers=headers, method="POST", ) + for doc in result.get("data", []): + d = doc.get("document", {}) + if d.get("title") == title and d.get("parentDocumentId") == parent_id: + return d["id"] + return None - doc_id = None - for doc in search_result.get("data", []): - if doc.get("document", {}).get("title") == title: - doc_id = doc["document"]["id"] - break + +def ensure_child_doc(parent_id, title, body, headers): + """Find or create a child doc under a parent. Returns doc ID.""" + doc_id = find_child_doc(parent_id, title, headers) + if doc_id: + return doc_id + result = api_request( + f"{WIKI_API}/documents.create", + data={ + "title": title, + "text": body, + "collectionId": WIKI_COLLECTION_ID, + "parentDocumentId": parent_id, + "publish": True, + }, + headers=headers, + method="POST", + ) + print(f"Created wiki doc: {title}") + return result["data"]["id"] + + +def post_to_wiki(markdown, date_str): + """Create or update a daily briefing doc in Outline. + + Hierarchy: Eric's Daily Briefing → {Year} → {Month} → Daily Briefing — {date} + """ + headers = { + "Authorization": f"Bearer {WIKI_TOKEN}", + } + + now = datetime.now(MT) + year_str = str(now.year) + month_str = MONTH_NAMES[now.month] + + # Ensure year doc exists under Eric's Daily Briefing + year_id = ensure_child_doc( + WIKI_PARENT_DOC_ID, year_str, + f"Daily briefings for {year_str}.", headers, + ) + + # Ensure month doc exists under year + month_id = ensure_child_doc( + year_id, month_str, + f"Daily briefings for {month_str} {year_str}.", headers, + ) + + # Search for existing doc with today's date under the month + title = f"Daily Briefing — {date_str}" + doc_id = find_child_doc(month_id, title, headers) if doc_id: api_request( @@ -157,7 +207,7 @@ def post_to_wiki(markdown, date_str): "title": title, "text": markdown, "collectionId": WIKI_COLLECTION_ID, - "parentDocumentId": WIKI_PARENT_DOC_ID, + "parentDocumentId": month_id, "publish": True, }, headers=headers,