# Print every chat title in a ChatGPT conversations.json, grouped by month,
# newest month first. Usage: python month_index.py conversations.json > index.md
import collections
import datetime
import json
import sys

with open(sys.argv[1], encoding="utf-8") as f:
    data = json.load(f)
if isinstance(data, dict):
    data = data.get("conversations", [])

months = collections.defaultdict(list)
for conv in data:
    when = datetime.datetime.fromtimestamp(conv.get("create_time") or 0)
    months[when.strftime("%Y-%m")].append((when, (conv.get("title") or "").strip() or "Untitled chat"))

for month in sorted(months, reverse=True):
    chats = sorted(months[month], reverse=True)
    print(f"## {datetime.datetime.strptime(month, '%Y-%m').strftime('%B %Y')} ({len(chats)})")
    for when, title in chats:
        print(f"- {when:%Y-%m-%d} {title}")
    print()
