#!/bin/sh
""":"
case "$0" in
    # Inside the app: always this bundle's Python, never a home inherited from another one.
    *.app/Contents/Resources/*) bundle=${0%%.app/Contents/Resources/*}.app
                                export PYTHONHOME="$bundle/Contents/Resources/python" ;;
esac
exec "$PYTHONHOME/bin/python3" -I -S -B "$0" "$@"
": """
__doc__ = """Propose: a change to what steers later runs, for the user's click (brief 0117).

    bin/propose manual|profile|preferences|directives < lines   lines to add to me/<kind>.md
    bin/propose job < job.json                                    a job for the list, off
    bin/propose reminder < reminder.json                          a reminder, set only if the user's message asked

A run Argoni started never changes me/ or the job list itself: it proposes, the app shows
the lines, and only the user's click applies them (design nothing-destroyed §3.1). The
proposal goes into the run's own folder (ARGONI_PROPOSALS, given by the runner) in the
runner's shape; outside such a run it is refused. A job proposal is checked here as
`bin/scheduled propose` checks it; the scheduled-job skill uses that. A reminder is
{"text", "at" | "in_minutes" | "calendar" | "interval", "when"?}: in a chat turn the runner sets it at
once, but only if the user's own recorded message asked to be reminded and holds the text; else it is dropped.

Exit status: 0 proposed (one line: what, and that the user decides); 2 usage; 3 refused.
Standard library only.
"""
import json
import os
import sys

sys.dont_write_bytecode = True  # no __pycache__ beside the engine's scripts
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import boxes  # noqa: E402


def main(argv):
    if len(argv) != 2 or argv[1] not in boxes.TEXT_KINDS + ("job", "reminder"):
        print("usage: bin/propose manual|profile|preferences|directives|job|reminder < text", file=sys.stderr)
        return 2
    raw = sys.stdin.buffer.read(boxes.PROPOSAL_MAX + 1)
    try:
        if len(raw) > boxes.PROPOSAL_MAX:
            raise boxes.Refused("at most %d bytes" % boxes.PROPOSAL_MAX)
        try:
            text = raw.decode("utf-8")
        except UnicodeDecodeError:
            raise boxes.Refused("not UTF-8 text")
        if argv[1] in ("job", "reminder"):
            try:
                doc = {"kind": argv[1], argv[1]: json.loads(text)}
            except ValueError:
                raise boxes.Refused("a %s is one JSON object" % argv[1])
        else:
            doc = {"kind": argv[1], "text": text.strip("\n")}
        name = boxes.propose(doc)
    except boxes.Refused as e:
        print("propose: REFUSED, %s; nothing written" % e, file=sys.stderr)
        return 3
    except OSError as e:
        print("propose: REFUSED, %s; nothing written" % e, file=sys.stderr)
        return 3
    if argv[1] == "reminder":
        print("proposed (%s): Argoni sets the reminder only if the user's own message asked for one" % name)
        return 0
    print("proposed (%s): the user sees it in Argoni and decides; nothing in me/ or the job list changed" % name)
    return 0


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