#!/usr/bin/env python3
"""Send an AI-made summary to the Remindo's Discover page as a text card.

    python discover_card.py "Morning brief" "3 meetings today. Report due 4 PM. Rain after 6."

Typical use: your assistant writes the summary, this script posts it. Needs REMINDO_KEY (rmd_...).
Python 3.8+, standard library only. The card replaces the last one of the same id and expires after 24 hours.
"""
import json
import os
import sys
import urllib.error
import urllib.request

BASE = "https://server-us.remindo-api.workers.dev"


def main(argv):
    if len(argv) < 3:
        sys.exit(__doc__)
    key = os.environ.get("REMINDO_KEY") or sys.exit("Set REMINDO_KEY first.")
    card = {"id": "brief", "kind": "text", "title": argv[1][:40], "text": " ".join(argv[2:])[:300], "expires_in_s": 24 * 3600}
    req = urllib.request.Request(BASE + "/api/v1/cards", data=json.dumps(card).encode(), method="POST", headers={
        "Authorization": f"Bearer {key}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            print(json.load(r))
    except urllib.error.HTTPError as e:
        sys.exit(f"{e.code} {e.read().decode()[:200]}")
    print("Open the Discover page on the Remindo to see it.")


if __name__ == "__main__":
    main(sys.argv)
