#!/usr/bin/env python3
"""Add one reminder to the family Remindo.

    python add_reminder.py "Call the dentist" 2026-12-02 15:00
    python add_reminder.py "Water the plants" 2026-12-02           # a to-do of that day, no ring
    python add_reminder.py "Milk" --list                            # a shopping list line

Needs REMINDO_KEY in the environment (rmd_..., from the phone web: Settings > AI and apps > Connect a computer).
Python 3.8+, standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.request

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


def call(method, path, body=None):
    key = os.environ.get("REMINDO_KEY")
    if not key:
        sys.exit("Set REMINDO_KEY to your rmd_... key first.")
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(BASE + path, data=data, method=method, headers={
        "Authorization": f"Bearer {key}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        err = json.load(e) if e.headers.get("Content-Type", "").startswith("application/json") else {}
        sys.exit(f"{e.code} {err.get('error', e.reason)}" + (f" ({err['field']})" if err.get("field") else ""))


def main(argv):
    if len(argv) < 2:
        sys.exit(__doc__)
    what = argv[1]
    if "--list" in argv:
        body = {"what": what, "kind": "list"}
    else:
        body = {"what": what}
        if len(argv) > 2:
            body["date"] = argv[2]
        if len(argv) > 3:
            body["time"] = argv[3]
    answer = call("POST", "/api/v1/reminders", body)
    for r in answer["result"]["reminders"]:
        when = " ".join(x for x in (r.get("date"), r.get("time")) if x) or "no date"
        print(f"added {r['kind']} {r['id']}: {r['what']} ({when})")


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