#!/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__ = """Words: file the user's words, from stdin, into a report or a decision, byte for byte.

    bin/words [--from app|chat] <verb> <id>   --from: where their words came
                                       from, written in the label (default app)
    bin/words readback <report-id>     append them under ## Read-back; brief -> done
    bin/words accept   <decision-id>   status accepted; "What we chose, and why" = them
    bin/words reject   <decision-id>   status rejected; "What we chose, and why" = them
    bin/words still-right <decision-id>  "- DATE still right: <them>" under ## Revisits;
                                          revisit: moves forward by the record's own gap
    bin/words change-it   <decision-id>  "- DATE change it: <them>" under ## Revisits;
                                          status unchanged (the decide skill drafts the new one)

The id is the four-digit number (0027) or the file's stem (0027-app-...).
A report may carry a part letter (0033A, 0033A-app-...); its brief (0033)
turns done only when every part's report has a read-back.
Their text comes on stdin and is written exactly as it came: no trimming inside,
no quoting, no rewording. Only the trailing newlines are dropped, so the file
keeps one blank line between blocks. The model never retypes their words: the
read-back and accept skills hand their text to this script and do the bookkeeping
around it (project page, now.md, log, check, commit).

Refuses (exit 3, nothing written) when the text is empty, the id does not match
exactly one file, or the decision is not proposed (accept, reject) or not
accepted (still-right, change-it). still-right alone takes empty text: then its
line carries only the date.
Prints one line on success: what it wrote, where.
"""
import datetime
import os
import re
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 lifecfg  # noqa: E402

LIFE = lifecfg.root()


def refuse(msg):
    print("words: REFUSED %s" % msg)
    sys.exit(3)


def matches(folder, ident):
    """The files in folder/ that id names (the number, or the file's whole stem)."""
    num = ident.split("-", 1)[0]
    d = os.path.join(LIFE, folder)
    hits = sorted(f for f in os.listdir(d) if f.startswith(num + "-") and f.endswith(".md")) if os.path.isdir(d) else []
    if len(ident) > len(num):
        hits = [f for f in hits if f == ident + ".md"]
    return [os.path.join(d, f) for f in hits]


def find(folder, ident, parts=False):
    """The one file id names, or a refusal. parts: the id may carry a part letter after
    the number (reports only)."""
    pat = r"[0-9]{4}[A-Z]?(-[a-z0-9-]{1,80})?" if parts else r"[0-9]{4}(-[a-z0-9-]{1,80})?"
    if not re.fullmatch(pat, ident or ""):
        refuse("bad id %r" % ident)
    hits = matches(folder, ident)
    if len(hits) != 1:
        refuse("%d files match %s/%s" % (len(hits), folder, ident))
    return hits[0]


def set_field(text, key, value):
    """Set `key: value` in the frontmatter, adding the line before the closing --- if missing."""
    m = re.match(r"---\n(.*?\n)---\n", text, re.S)
    if not m:
        refuse("no frontmatter")
    front = m.group(1)
    line = "%s: %s\n" % (key, value)
    if re.search(r"(?m)^%s:.*\n" % re.escape(key), front):
        front = re.sub(r"(?m)^%s:.*\n" % re.escape(key), lambda _: line, front, count=1)
    else:
        front += line
    return "---\n" + front + "---\n" + text[m.end():]


def field(text, key):
    m = re.search(r"(?m)^%s:\s*(.*)$" % re.escape(key), text.split("\n---", 1)[0])
    return m.group(1).strip() if m else ""


def section_bounds(text, heading):
    """(start of body, end of body) of `## heading...`, or None."""
    # "Read-back" also finds "Read back" and "Readback": one section, however it is spelled.
    m = re.search(r"(?mi)^## %s.*\n" % re.escape(heading).replace("\\-", "[- ]?"), text)
    if not m:
        return None
    nxt = re.search(r"(?m)^#{1,2} ", text[m.end():])
    return m.end(), (m.end() + nxt.start()) if nxt else len(text)


def write(path, text):
    """The whole file or nothing, never through a link (lifecfg.write_atomic)."""
    try:
        lifecfg.write_atomic(path, text)
    except OSError as e:
        refuse("%s not written: %s" % (os.path.relpath(path, LIFE), e))


def has_readback(path):
    text = open(path, encoding="utf-8").read()
    b = section_bounds(text, "Read-back")
    return bool(b) and bool(text[b[0]:b[1]].strip())


def readback(ident, words, now, source):
    report = find("reports", ident, parts=True)
    text = open(report, encoding="utf-8").read()
    block = "Their words, %s, from %s:\n\n%s\n" % (now.strftime("%Y-%m-%d %H:%M"), source, words)
    b = section_bounds(text, "Read-back")
    if b:
        body = text[b[0]:b[1]].rstrip("\n")
        text = text[:b[0]] + (body + "\n\n" if body.strip() else "\n") + block + ("\n" + text[b[1]:] if text[b[1]:] else "")
    else:
        text = text.rstrip("\n") + "\n\n## Read-back\n\n" + block
    write(report, text)

    # A brief with parts (0033A..0033D) turns done only when every part is read back.
    d = os.path.join(LIFE, "reports")
    siblings = sorted(f for f in os.listdir(d) if re.fullmatch(r"%s[A-Z]?-.*\.md" % ident[:4], f))
    waiting = [f.split("-", 1)[0] for f in siblings if not has_readback(os.path.join(d, f))]
    # No brief at that number (or two) is not a refusal: the read-back is filed.
    briefs = matches("briefs", ident[:4])
    brief = briefs[0] if len(briefs) == 1 else None
    if brief and waiting:
        rel = os.path.relpath(report, LIFE)
        print("words: read-back filed in %s; %s stays open, waiting for %s" % (rel, os.path.relpath(brief, LIFE), ", ".join(waiting)))
        return
    if brief:
        bt = open(brief, encoding="utf-8").read()
        bt = set_field(bt, "status", "done (read back %s)" % now.strftime("%Y-%m-%d"))
        bt = set_field(bt, "updated", now.strftime("%Y-%m-%d"))
        write(brief, bt)
    rel = os.path.relpath(report, LIFE)
    print("words: read-back filed in %s%s" % (rel, "; %s status done" % os.path.relpath(brief, LIFE) if brief else "; no brief at that number"))


def decide(verb, ident, words, now, source):
    path = find("decisions", ident)
    text = open(path, encoding="utf-8").read()
    status = field(text, "status")
    if status != "proposed":
        refuse("decision %s is '%s', not proposed" % (ident, status or "?"))
    b = section_bounds(text, "What we chose")
    if not b:
        refuse("no '## What we chose, and why' section")
    day = now.strftime("%Y-%m-%d")
    lead = "Accepted" if verb == "accept" else "Rejected"
    who = lifecfg.config(LIFE)["user_name"] or "the user"
    body = "\n%s by %s, %s. Their words, from %s:\n\n%s\n\n" % (lead, who, day, source, words)
    text = text[:b[0]] + body + text[b[1]:]
    if verb == "accept":
        text = set_field(text, "status", "accepted")
        text = set_field(text, "accepted", who)
        text = set_field(text, "date", day)
        text = set_field(text, "author", "user")
        text = set_field(text, "confidence", "stated")
    else:
        text = set_field(text, "status", "rejected")
    text = set_field(text, "updated", day)
    write(path, text)
    print("words: decision %s %s in %s" % (ident, "accepted" if verb == "accept" else "rejected", os.path.relpath(path, LIFE)))


def revisit(verb, ident, words, now):
    """The user's answer at a decision's revisit, one dated line under ## Revisits."""
    path = find("decisions", ident)
    text = open(path, encoding="utf-8").read()
    status = field(text, "status")
    if status != "accepted":
        refuse("decision %s is '%s', not accepted" % (ident, status or "?"))
    if verb == "change-it" and not words.strip():
        refuse("empty text: their words are required for change it")
    today = now.date()
    day = today.isoformat()
    new_revisit = None
    if verb == "still-right":
        # The gap is the record's own, date: to its first revisit:, kept in
        # revisit_gap_days the first time so a second "still right" does not double it.
        try:
            old = datetime.date.fromisoformat(field(text, "revisit"))
            kept = field(text, "revisit_gap_days")
            days = int(kept) if kept else (old - datetime.date.fromisoformat(field(text, "date"))).days
        except ValueError:
            refuse("decision %s has no readable date:, revisit: or revisit_gap_days:" % ident)
        if days <= 0:
            refuse("decision %s: revisit %s is not after its date" % (ident, old))
        gap = datetime.timedelta(days=days)
        new_revisit = old + gap
        while new_revisit <= today:  # answered long after the revisit: the next one is still ahead
            new_revisit += gap
    label = "still right" if verb == "still-right" else "change it"
    line = "- %s %s:%s\n" % (day, label, (" " + words) if words.strip() else "")
    b = section_bounds(text, "Revisits")
    if b:
        body = text[b[0]:b[1]].rstrip("\n")
        rest = text[b[1]:]
        text = text[:b[0]] + (body + "\n" if body.strip() else "\n") + line + ("\n" + rest if rest else "")
    else:
        text = text.rstrip("\n") + "\n\n## Revisits\n\n" + line
    if new_revisit:
        text = set_field(text, "revisit", new_revisit.isoformat())
        text = set_field(text, "revisit_gap_days", str(gap.days))
    text = set_field(text, "updated", day)
    write(path, text)
    rel = os.path.relpath(path, LIFE)
    if new_revisit:
        print("words: decision %s still right, filed in %s; revisit now %s" % (ident, rel, new_revisit))
    else:
        print("words: decision %s change it, filed in %s; status stays %s, a new decision is drafted next" % (ident, rel, status))


def main(argv):
    verbs = ("readback", "accept", "reject", "still-right", "change-it")
    source = "the app"
    if "--from" in argv:
        i = argv.index("--from")
        val = argv[i + 1] if i + 1 < len(argv) else ""
        if val not in ("app", "chat"):
            refuse("--from must be app or chat, not %r" % val)
        source = "the app" if val == "app" else "chat"
        argv = argv[:i] + argv[i + 2:]
    if len(argv) != 3 or argv[1] not in verbs:
        print(__doc__.strip().split("\n\n")[1], file=sys.stderr)
        return 2
    raw = sys.stdin.buffer.read().decode("utf-8")
    words = raw.rstrip("\n")
    if not words.strip() and argv[1] != "still-right":
        refuse("empty text: their words are required")
    now = datetime.datetime.now()
    if argv[1] == "readback":
        readback(argv[2], words, now, source)
    elif argv[1] in ("still-right", "change-it"):
        revisit(argv[1], argv[2], words, now)
    else:
        decide(argv[1], argv[2], words, now, source)
    return 0


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