#!/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__ = """Care: the engine's half of the care reminders and of the interrupt rule (brief 0113).

    bin/care list [--json]               every reminder: on or off, its rule in words, its settings
    bin/care on|off NAME                 switch one (water, stand, eyes, break, walk, lunch, prayer, wind-down)
    bin/care set NAME KEY VALUE          change one setting: care set prayer city Cairo, care set stand after_minutes 45
    bin/care tick [--json] < signals     the app, about once a minute: what it sees; the one nudge to show, or none
    bin/care gate [--json] < nudge       any other nudge (needs action, a job's result): show now, or hold
    bin/care done NAME                   the user did it (drank, stood up): its clock starts again
    bin/care snooze NAME MINUTES|today   not before then
    bin/care prayer [--date YYYY-MM-DD] [--json]   the day's prayer times for the place set
    bin/care cities QUERY                cities the prayer times know, for a picker
    bin/care week [--json]               this week's counts, for the This week card

Settings live in data/config.json under `care` (the user's, from the screen or
by hand); every missing key is the default below. On by default: water, stand
and posture, eye rest, a break after long focus. Off: walk, lunch, prayer
times, winding down (docs/vision.md).

The rules are about the user being at the Mac, never a fixed timer:
    stand    after `after_minutes` (60) at the Mac without being away
    break    after `after_minutes` (120) at the Mac without being away
    eyes     every `every_minutes` (45) at the Mac without being away
    water    every `every_minutes` (90) of time at the Mac, counted across the day
The defaults are on the calm side: a user who never pauses gets about two
nudges an hour (a made-up day, 09:00 to 16:00, in brief 0113's report).
    lunch    once, between `from` and `to`, while at the Mac
    walk     once, between `from` and `to`, after `after_minutes_today` at the Mac today
    wind-down  once, from `at`, while at the Mac
    prayer   at each prayer's time (plus `minutes_after`), within `window_minutes`, while at the Mac
"Away" is no key, click or mouse move for `away_minutes` (5): coming back starts
stand, break and eyes again, so a user who just moved is not told to move. A
break also counts as standing and resting the eyes; standing counts as resting them.

The interrupt rule (decided, docs/vision.md): never while the app sees a call, a
meeting, a full-screen app, a shared screen or a Focus (`hold_in`, the user's to
change); at most one nudge every `gap_minutes` (20); a nudge that needs action
(Claude Code asks, a meeting starts) always goes through, quietly when the user
is in a call, meeting or sharing the screen; every nudge says why and offers a
snooze. A held reminder stays due and comes when the user is free.

The app sends the signals (`tick`): {"idle_seconds": N, "busy": ["call", ...]}.
The engine keeps the time at the Mac itself in .summary/care.json (rebuilt,
never authority). Counts for the This week card go to log/care.log, one line
per nudge and per answer; prayer is never written there while health, money
and family are off (sensitive_domains): which prayers someone keeps is theirs.
ARGONI_NOW (an ISO time) stands in for the clock, for tests.

Exit status: 0; 2 usage; 3 refused. Standard library only; the Mac's own python3 (3.9).
"""
import copy
import datetime
import json
import os
import sys

BIN = os.path.dirname(os.path.abspath(__file__))
sys.dont_write_bytecode = True
sys.path.insert(0, BIN)
import lifecfg  # noqa: E402
import prayer  # noqa: E402

LIFE = lifecfg.root()
CONFIG = os.path.join(LIFE, "config.json")
STATE = os.path.join(LIFE, ".summary", "care.json")
LOG = os.path.join(LIFE, "log", "care.log")

ORDER = ["prayer", "break", "stand", "eyes", "water", "lunch", "walk", "wind-down"]
DEFAULTS = {
    "water": {"on": True, "every_minutes": 90},
    "stand": {"on": True, "after_minutes": 60},
    "eyes": {"on": True, "every_minutes": 45},
    "break": {"on": True, "after_minutes": 120},
    "walk": {"on": False, "from": "15:00", "to": "18:00", "after_minutes_today": 180},
    "lunch": {"on": False, "from": "12:30", "to": "14:30"},
    "prayer": {"on": False, "city": None, "place": None, "method": None, "asr": "standard",
               "prayers": list(prayer.PRAYERS), "minutes_after": 0, "window_minutes": 45},
    "wind-down": {"on": False, "at": "22:00"},
    "gap_minutes": 20,
    "away_minutes": 5,
    "hold_in": ["call", "meeting", "fullscreen", "screen-share", "focus"],
}
QUIET_IN = ("call", "meeting", "screen-share")   # needs action still shows, but with no sound or bubble
BUSY_WORDS = {"call": "a call", "meeting": "a meeting", "fullscreen": "a full-screen app",
              "screen-share": "sharing the screen", "focus": "a Focus"}
SNOOZE = [10, 30, 60, "today"]
NOT_HERE = 120   # idle seconds after which nobody is there to see a nudge
# The character's state for each (v5.1's daily moments). Prayer has none: a gentle line only.
STATE_OF = {"water": "water", "stand": "posture", "eyes": "eye-break", "break": "take-a-break",
            "walk": "walk", "lunch": "lunch", "wind-down": "evening", "prayer": None}
WORDS = {
    "water": "Time for some water.",
    "stand": "Stand up and stretch for a minute.",
    "eyes": "Look at something far away for twenty seconds.",
    "break": "A short break would help. Step away for a few minutes.",
    "walk": "A short walk would do you good.",
    "lunch": "Lunch time, if you have not eaten yet.",
    "wind-down": "It is getting late. Time to start winding down.",
}
RULES = {
    "water": lambda c: "every %d minutes at the Mac" % c["every_minutes"],
    "stand": lambda c: "after %d minutes at the Mac without a pause" % c["after_minutes"],
    "eyes": lambda c: "every %d minutes on the screen without a pause" % c["every_minutes"],
    "break": lambda c: "after %d minutes of focus without a pause" % c["after_minutes"],
    "walk": lambda c: "once between %s and %s, after %d hours at the Mac" % (
        c["from"], c["to"], c["after_minutes_today"] // 60),
    "lunch": lambda c: "once between %s and %s" % (c["from"], c["to"]),
    "wind-down": lambda c: "once from %s" % c["at"],
    "prayer": lambda c: "at each prayer time%s" % (", for %s" % c["city"] if c.get("city") else
                                                    ", for the place set" if c.get("place") else
                                                    "; set a city first"),
}


# ---------------------------------------------------------------- settings and state

def now():
    fake = os.environ.get("ARGONI_NOW")  # tests only: a fixed clock
    return datetime.datetime.fromisoformat(fake).astimezone() if fake else datetime.datetime.now().astimezone()


def read_json(path, default):
    try:
        with open(path, encoding="utf-8") as fh:
            return json.load(fh)
    except (OSError, ValueError):
        return default


def write_json(path, data):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    lifecfg.write_atomic(path, json.dumps(data, indent=2, ensure_ascii=False) + "\n")


def settings():
    """config.json `care` over the defaults, key by key."""
    mine = lifecfg.config(LIFE).get("care") or {}
    out = copy.deepcopy(DEFAULTS)
    for k, v in mine.items():
        if isinstance(out.get(k), dict) and isinstance(v, dict):
            out[k].update(v)
        elif k in out:
            out[k] = v
    return out


def save_setting(name, key, value):
    """One key in config.json `care`, the rest of the file as it was. A config.json that
    exists but does not parse is never written over (it holds the user's name, folders and
    switches): SystemExit 3 with one line instead."""
    cfg = read_json(CONFIG, None) if os.path.exists(CONFIG) else {}
    if not isinstance(cfg, dict):
        print("care: REFUSED config.json cannot be read; fix it first, so nothing in it is lost")
        sys.exit(3)
    care = cfg.get("care") if isinstance(cfg.get("care"), dict) else {}
    cfg["care"] = care
    if key is None:
        care[name] = value
    else:
        if not isinstance(care.get(name), dict):
            care[name] = {}
        care[name][key] = value
    write_json(CONFIG, cfg)


def load_state(t):
    s = read_json(STATE, {})
    if not isinstance(s, dict) or not isinstance(s.get("reminders", {}), dict) \
            or not all(isinstance(v, dict) for v in s.get("reminders", {}).values()):
        s = {}  # a damaged state is a new day's: the reminders start again
    if s.get("day") != t.date().isoformat():
        # A new day: the time at the Mac today and the once-a-day reminders start again.
        s = {"day": t.date().isoformat(), "present_today": 0.0, "stretch_from": None,
             "last_tick": s.get("last_tick"), "last_nudge": s.get("last_nudge"),
             "reminders": {k: {kk: vv for kk, vv in v.items() if kk in ("last", "water_at")}
                           for k, v in (s.get("reminders") or {}).items()}}
        for r in s["reminders"].values():
            r["water_at"] = 0.0
    s.setdefault("reminders", {})
    return s


def iso(t):
    return t.isoformat(timespec="seconds")


def parse(v):
    return datetime.datetime.fromisoformat(v) if v else None


def minutes(a, b):
    return (a - b).total_seconds() / 60.0


def hhmm(t, text):
    h, m = [int(x) for x in str(text).split(":")]
    return t.replace(hour=h, minute=m, second=0, microsecond=0)


def log(t, name, what):
    """One line per nudge and answer, for the week's counts. Prayer only when the user keeps
    health, money and family on this Mac."""
    if name == "prayer" and not lifecfg.sensitive_allowed(lifecfg.config(LIFE)):
        return
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    try:
        lifecfg.append_text(LOG, "%s\t%s\t%s\n" % (iso(t), name, what), header="# time\treminder\twhat\n")
    except OSError as e:
        print("care: log/care.log not written (%s)" % e, file=sys.stderr)


# ---------------------------------------------------------------- prayer

def prayer_place(c):
    if c.get("place"):
        p = c["place"]
        return {"name": p.get("name", "your place"), "country": p.get("country"),
                "lat": float(p["lat"]), "lon": float(p["lon"]), "tz": p["tz"]}
    return prayer.find_place(c["city"]) if c.get("city") else None


def prayer_today(c, day):
    place = prayer_place(c)
    if not place:
        return None, None, {}
    method = c.get("method") or prayer.default_method(place)
    return place, method, prayer.times(place, day, method, c.get("asr") or "standard")


# ---------------------------------------------------------------- what is due

def due(cfg, s, t):
    """[(name, text, reason)] in ORDER, every reminder due now, before the interrupt rule."""
    out = []
    stretch_from = parse(s.get("stretch_from"))
    stretch = minutes(t, stretch_from) if stretch_from else 0
    R = s["reminders"]

    def since_last(name):
        last = parse(R.get(name, {}).get("last"))
        start = max(x for x in (last, stretch_from) if x) if (last or stretch_from) else t
        return minutes(t, start)

    def snoozed(name):
        until = parse(R.get(name, {}).get("snoozed_until"))
        return until and t < until

    def once_today(name):
        last = parse(R.get(name, {}).get("last"))
        return last and last.date() == t.date()

    for name in ORDER:
        c = cfg[name]
        if not c.get("on") or snoozed(name):
            continue
        if name == "prayer":
            place, method, times = prayer_today(c, t.date())
            shown = R.get("prayer", {}).get("shown") or {}
            for p in c.get("prayers") or prayer.PRAYERS:
                at = times.get(p)
                if not at:
                    continue
                start = at + datetime.timedelta(minutes=c.get("minutes_after", 0))
                if start <= t < start + datetime.timedelta(minutes=c.get("window_minutes", 45)) \
                        and shown.get(p) != t.date().isoformat():
                    title = "jumuah" if p == "dhuhr" and t.weekday() == 4 else p
                    out.append((name, "It is time for %s (%s)." % (prayer.TITLES[title], at.strftime("%H:%M")),
                                "%s began at %s in %s." % (prayer.TITLES[title], at.strftime("%H:%M"), place["name"]),
                                p))
                    break
            continue
        if not stretch_from:
            continue  # not at the Mac
        if name in ("stand", "break"):
            n = since_last(name)
            if n >= c["after_minutes"]:
                out.append((name, WORDS[name], "You have been at the Mac for %d minutes without a pause." % n, None))
        elif name == "eyes":
            n = since_last(name)
            if n >= c["every_minutes"]:
                out.append((name, WORDS[name], "%d minutes on the screen since your eyes last rested." % n, None))
        elif name == "water":
            n = s["present_today"] - R.get("water", {}).get("water_at", 0.0)
            if n >= c["every_minutes"]:
                out.append((name, WORDS[name], "%d minutes at the Mac since the last water reminder." % n, None))
        elif name == "lunch":
            if hhmm(t, c["from"]) <= t < hhmm(t, c["to"]) and not once_today(name):
                out.append((name, WORDS[name], "It is between %s and %s." % (c["from"], c["to"]), None))
        elif name == "walk":
            if hhmm(t, c["from"]) <= t < hhmm(t, c["to"]) and not once_today(name) \
                    and s["present_today"] >= c["after_minutes_today"] and stretch >= 30:
                out.append((name, WORDS[name], "%.1f hours at the Mac today." % (s["present_today"] / 60), None))
        elif name == "wind-down":
            if t >= hhmm(t, c["at"]) and not once_today(name):
                out.append((name, WORDS[name], "It is past %s." % c["at"], None))
    return out


def held_by(cfg, busy):
    return [b for b in busy if b in cfg["hold_in"]]


def gap_left(cfg, s, t):
    last = parse(s.get("last_nudge"))
    if not last:
        return 0
    return max(0.0, cfg["gap_minutes"] - minutes(t, last))


def mark_shown(s, name, t, which=None):
    R = s["reminders"].setdefault(name, {})
    R["last"] = iso(t)
    R.pop("snoozed_until", None)
    if name == "water":
        R["water_at"] = s["present_today"]
    if name == "prayer" and which:
        R.setdefault("shown", {})[which] = t.date().isoformat()
    # A break rests the legs and eyes too; standing rests the eyes.
    for also in {"break": ("stand", "eyes"), "stand": ("eyes",)}.get(name, ()):
        s["reminders"].setdefault(also, {})["last"] = iso(t)


# ---------------------------------------------------------------- verbs

def read_stdin_json():
    try:
        data = json.loads(sys.stdin.read() or "{}")
    except ValueError as e:
        raise SystemExit(print("care: the input is not JSON: %s" % e, file=sys.stderr) or 2)
    if not isinstance(data, dict):
        raise SystemExit(print("care: the input must be a JSON object", file=sys.stderr) or 2)
    return data


def cmd_tick(as_json):
    """What the app sees now; the one care nudge to show, or why none."""
    sig = read_stdin_json()
    t = now()
    cfg = settings()
    s = load_state(t)
    idle = float(sig.get("idle_seconds") or 0)
    busy = [str(b) for b in (sig.get("busy") or [])]
    last_tick = parse(s.get("last_tick"))
    gap = minutes(t, last_tick) if last_tick else None
    away = cfg["away_minutes"]
    # Away: idle long enough, or the app saw nothing for that long (the Mac slept, the app was shut).
    if idle >= away * 60 or gap is None or gap > away:
        if idle >= away * 60:
            s["stretch_from"] = None
        else:
            s["stretch_from"] = iso(t - datetime.timedelta(seconds=idle))
    elif not s.get("stretch_from"):
        s["stretch_from"] = iso(t - datetime.timedelta(seconds=idle))
    if gap is not None and gap <= away and idle < away * 60:
        s["present_today"] = round(s["present_today"] + min(gap, 2.0), 2)
    s["last_tick"] = iso(t)

    result = {"nudge": None}
    waiting = due(cfg, s, t)
    if not waiting:
        result["why"] = "nothing due"
    elif idle >= NOT_HERE:
        result["why"] = "nobody at the Mac; %s waits" % waiting[0][0]
    elif held_by(cfg, busy):
        result["why"] = "held: you are in %s; %s waits" % (BUSY_WORDS.get(held_by(cfg, busy)[0], held_by(cfg, busy)[0]),
                                                           waiting[0][0])
    elif gap_left(cfg, s, t) > 0:
        nxt = parse(s["last_nudge"]) + datetime.timedelta(minutes=cfg["gap_minutes"])
        result["why"] = "held: one nudge every %d minutes; next from %s; %s waits" % (
            cfg["gap_minutes"], nxt.strftime("%H:%M"), waiting[0][0])
        result["next_from"] = iso(nxt)
    else:
        name, text, reason, which = waiting[0]
        mark_shown(s, name, t, which)
        s["last_nudge"] = iso(t)
        result["nudge"] = {"kind": "care", "reminder": name, "text": text, "reason": reason,
                           "state": STATE_OF[name], "snooze": SNOOZE, "quiet": False}
        log(t, name, "shown")
    write_json(STATE, s)
    if as_json:
        print(json.dumps(result, ensure_ascii=False))
    else:
        n = result["nudge"]
        print("%s (%s)" % (n["text"], n["reason"]) if n else result["why"])
    return 0


def cmd_gate(as_json):
    """Any nudge that is not a care reminder: {"kind": "needs-action" | "note", "text", "reason", "busy"}."""
    n = read_stdin_json()
    t = now()
    cfg = settings()
    s = load_state(t)
    busy = [str(b) for b in (n.get("busy") or [])]
    kind = n.get("kind") or "note"
    if not str(n.get("reason") or "").strip():
        print("care: REFUSED every nudge says why: give a reason")
        return 3
    if kind == "needs-action":
        out = {"show": True, "quiet": any(b in QUIET_IN for b in busy),
               "why": "needs action: always shown" + ("; quietly, no sound or bubble, while in %s"
                                                        % BUSY_WORDS[next(b for b in busy if b in QUIET_IN)]
                                                        if any(b in QUIET_IN for b in busy) else "")}
    elif held_by(cfg, busy):
        out = {"show": False, "why": "held: you are in %s" % BUSY_WORDS.get(held_by(cfg, busy)[0], held_by(cfg, busy)[0])}
    elif gap_left(cfg, s, t) > 0:
        nxt = parse(s["last_nudge"]) + datetime.timedelta(minutes=cfg["gap_minutes"])
        out = {"show": False, "why": "held: one nudge every %d minutes" % cfg["gap_minutes"], "next_from": iso(nxt)}
    else:
        out = {"show": True, "quiet": False, "why": "free"}
        s["last_nudge"] = iso(t)
        write_json(STATE, s)
    if out["show"]:
        out["snooze"] = SNOOZE
    if as_json:
        print(json.dumps(out, ensure_ascii=False))
    else:
        print(("show" + (" quietly" if out.get("quiet") else "") if out["show"] else "hold") + ": " + out["why"])
    return 0


def known(name):
    if name not in ORDER:
        print("care: no reminder named %s (%s)" % (name, ", ".join(ORDER)), file=sys.stderr)
        return False
    return True


def cmd_switch(name, on):
    if not known(name):
        return 2
    if on and name == "prayer" and not prayer_place(settings()["prayer"]):
        save_setting(name, "on", True)
        print("prayer switched on; set a city first: care set prayer city CITY (care cities QUERY lists them)")
        return 0
    save_setting(name, "on", on)
    print("%s switched %s" % (name, "on" if on else "off"))
    return 0


def cmd_set(name, key, value):
    """One setting, checked: numbers stay numbers, times stay HH:MM, the city must be known."""
    if name in ("gap_minutes", "away_minutes"):
        if not value.isdigit() or int(value) < 1:
            print("care: REFUSED %s must be whole minutes, 1 or more" % name)
            return 3
        save_setting(name, None, int(value))
        print("%s set to %s" % (name, value))
        return 0
    if name == "hold_in":
        kinds = [k.strip() for k in value.split(",") if k.strip()]
        bad = [k for k in kinds if k not in BUSY_WORDS]
        if bad:
            print("care: REFUSED hold_in takes %s" % ", ".join(BUSY_WORDS))
            return 3
        save_setting(name, None, kinds)
        print("hold_in set to %s" % (", ".join(kinds) or "nothing"))
        return 0
    if not known(name):
        return 2
    default = DEFAULTS[name]
    if key not in default or key == "on":
        print("care: REFUSED %s has no setting %r (%s)" % (name, key, ", ".join(k for k in default if k != "on")))
        return 3
    if name == "prayer" and key == "city":
        place = prayer.find_place(value)
        if not place:
            hits = prayer.search(value, 5)
            print("care: REFUSED no city %r%s" % (value, "; did you mean: " + ", ".join(
                "%s, %s" % (h["name"], h["country"]) for h in hits) if hits else
                "; give the place by hand in config.json care.prayer.place {name, lat, lon, tz}"))
            return 3
        save_setting(name, "city", "%s, %s" % (place["name"], place["country"]))
        method = settings()["prayer"].get("method") or prayer.default_method(place)
        print("prayer city set to %s, %s; method %s (%s)%s" % (
            place["name"], place["country"], method, prayer.METHODS[method]["label"],
            "" if settings()["prayer"].get("method") else ", the one most used there; change it with: care set prayer method NAME"))
        return 0
    if name == "prayer" and key == "method":
        if value not in prayer.METHODS:
            print("care: REFUSED methods: %s" % ", ".join(prayer.METHODS))
            return 3
        save_setting(name, key, value)
        print("prayer method set to %s (%s)" % (value, prayer.METHODS[value]["label"]))
        return 0
    if name == "prayer" and key == "asr":
        if value not in prayer.ASR:
            print("care: REFUSED asr is standard or hanafi")
            return 3
    elif name == "prayer" and key == "prayers":
        ps = [p.strip() for p in value.split(",") if p.strip()]
        if not ps or any(p not in prayer.PRAYERS for p in ps):
            print("care: REFUSED prayers: a comma list of %s" % ", ".join(prayer.PRAYERS))
            return 3
        value = ps
    elif name == "prayer" and key == "place":
        print("care: REFUSED give the place in config.json care.prayer.place {name, lat, lon, tz} by hand")
        return 3
    elif isinstance(default[key], int):
        if not value.isdigit() or int(value) < 1:
            print("care: REFUSED %s must be whole minutes, 1 or more" % key)
            return 3
        value = int(value)
    elif isinstance(default[key], str):
        try:
            hhmm(now(), value)
        except (ValueError, TypeError):
            print("care: REFUSED %s must be a time like 15:00" % key)
            return 3
    save_setting(name, key, value)
    print("%s %s set to %s" % (name, key, value if not isinstance(value, list) else ", ".join(value)))
    return 0


def cmd_done(name):
    if not known(name):
        return 2
    t = now()
    s = load_state(t)
    mark_shown(s, name, t)
    write_json(STATE, s)
    log(t, name, "done")
    print("%s: done, its clock starts again" % name)
    return 0


def cmd_snooze(name, how):
    if not known(name):
        return 2
    t = now()
    if how == "today":
        until = (t + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
    elif how.isdigit() and int(how) > 0:
        until = t + datetime.timedelta(minutes=int(how))
    else:
        print("care: snooze takes minutes or today", file=sys.stderr)
        return 2
    s = load_state(t)
    s["reminders"].setdefault(name, {})["snoozed_until"] = iso(until)
    write_json(STATE, s)
    log(t, name, "snoozed %s" % how)
    print("%s snoozed until %s" % (name, until.strftime("%H:%M" if how != "today" else "tomorrow")))
    return 0


def cmd_prayer(day, as_json):
    c = settings()["prayer"]
    place, method, times = prayer_today(c, day)
    if not place:
        msg = "No place set for prayer times: care set prayer city CITY."
        print(json.dumps({"place": None, "line": msg}) if as_json else msg)
        return 0
    if as_json:
        print(json.dumps({"place": place, "method": method, "method_label": prayer.METHODS[method]["label"],
                          "asr": c.get("asr") or "standard", "date": day.isoformat(),
                          "times": {k: v.strftime("%H:%M") for k, v in times.items()}}, ensure_ascii=False))
    else:
        print("%s, %s, %s (%s)" % (place["name"], day.isoformat(), method, prayer.METHODS[method]["label"]))
        for k, v in times.items():
            print("  %-8s %s" % (prayer.TITLES[k], v.strftime("%H:%M")))
    return 0


def cmd_list(as_json):
    cfg = settings()
    rows = []
    for name in ORDER:
        c = cfg[name]
        rows.append({"name": name, "on": bool(c.get("on")), "rule": RULES[name](c),
                     "state": STATE_OF[name], "settings": {k: v for k, v in c.items() if k != "on"},
                     "default_on": DEFAULTS[name]["on"]})
    if as_json:
        print(json.dumps({"reminders": rows, "gap_minutes": cfg["gap_minutes"], "away_minutes": cfg["away_minutes"],
                          "hold_in": cfg["hold_in"], "methods": {k: v["label"] for k, v in prayer.METHODS.items()}},
                         indent=2, ensure_ascii=False))
        return 0
    for r in rows:
        print("%-10s %-3s %s" % (r["name"], "on" if r["on"] else "off", r["rule"]))
    print("At most one nudge every %d minutes; held in: %s." % (
        cfg["gap_minutes"], ", ".join(BUSY_WORDS.get(b, b) for b in cfg["hold_in"]) or "nothing"))
    return 0


def cmd_week(as_json):
    t = now()
    # The user's week: it starts the day after `week_ends` (Thursday unless set), as the weekly review.
    ends = {"monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3, "friday": 4, "saturday": 5,
            "sunday": 6}.get(str(lifecfg.config(LIFE).get("week_ends") or "thursday").lower(), 3)
    start = (t - datetime.timedelta(days=(t.weekday() - (ends + 1)) % 7)).date()
    counts = {}
    try:
        lines = open(LOG, encoding="utf-8").read().splitlines()
    except OSError:
        lines = []
    for l in lines:
        parts = l.split("\t")
        if l.startswith("#") or len(parts) < 3 or parts[0][:10] < start.isoformat():
            continue
        what = parts[2].split()[0]
        counts.setdefault(parts[1], {}).setdefault(what, 0)
        counts[parts[1]][what] += 1
    if as_json:
        print(json.dumps({"since": start.isoformat(), "counts": counts}, ensure_ascii=False))
    elif not counts:
        print("No reminders this week.")
    else:
        for name, c in counts.items():
            print("%-10s %s" % (name, ", ".join("%s %d" % kv for kv in sorted(c.items()))))
    return 0


def main(argv):
    a = argv[1:]
    usage = __doc__.split("\n\n")[1]
    as_json = "--json" in a
    a = [x for x in a if x != "--json"]
    if a == ["list"]:
        return cmd_list(as_json)
    if a == ["tick"]:
        return cmd_tick(as_json)
    if a == ["gate"]:
        return cmd_gate(as_json)
    if a == ["week"]:
        return cmd_week(as_json)
    if len(a) == 2 and a[0] in ("on", "off"):
        return cmd_switch(a[1], a[0] == "on")
    if len(a) == 2 and a[0] == "done":
        return cmd_done(a[1])
    if len(a) == 3 and a[0] == "snooze":
        return cmd_snooze(a[1], a[2])
    if len(a) == 3 and a[0] == "set" and a[1] in ("gap_minutes", "away_minutes", "hold_in"):
        return cmd_set(a[1], None, a[2])
    if len(a) >= 4 and a[0] == "set":
        return cmd_set(a[1], a[2], " ".join(a[3:]))
    if a[:1] == ["prayer"]:
        day = now().date()
        if len(a) == 3 and a[1] == "--date":
            try:
                day = datetime.date.fromisoformat(a[2])
            except ValueError:
                print("care: --date takes YYYY-MM-DD", file=sys.stderr)
                return 2
        elif len(a) != 1:
            print(usage, file=sys.stderr)
            return 2
        return cmd_prayer(day, as_json)
    if len(a) >= 2 and a[0] == "cities":
        hits = prayer.search(" ".join(a[1:]))
        if as_json:
            print(json.dumps(hits, ensure_ascii=False))
        else:
            print("\n".join("%s, %s" % (h["name"], h["country"]) for h in hits) or "no city by that name")
        return 0
    print(usage, file=sys.stderr)
    return 2


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