#!/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__ = """Turn runner `work projection` JSON on stdin into read-only day/week facts."""
import datetime
import json
import sys

sys.dont_write_bytecode = True

LABELS = {
    "asked": "Getting ready", "planning": "Getting ready", "starting": "Getting ready",
    "waiting for you": "Waiting for your OK", "working": "Working",
    "needs you": "Needs you", "paused": "Paused", "unknown": "Not sure",
    "lost": "Can't find", "reported": "Ready to read",
    "ready to review": "Ready to read", "seen reported": "Ready to read",
    "kept apart": "Done. Not in your project yet.", "recorded": "Done",
    "answered": "Done", "not accepted": "Waiting for your OK",
    "cancelled": "Put away", "put away": "Put away", "failed": "Didn't work",
    "seen working": "Working", "seen ended": "Put away", "seen read": "Done",
}
WAITING = {"waiting for you", "needs you", "ready to review", "seen reported", "not accepted", "unknown", "lost"}
EVENTS = {"started", "finished", "accepted", "stopped", "recovered"}
MAX_PIECES = 20


def clean(value, limit=100):
    """One line of untrusted data, never a command or a new display line."""
    return " ".join(str(value or "").split())[:limit]


def date_of(value):
    try:
        return datetime.date.fromisoformat(str(value)[:10])
    except ValueError:
        return None


def pieces(doc):
    raw = doc.get("items", {}) if isinstance(doc, dict) else {}
    rows = raw.values() if isinstance(raw, dict) else raw if isinstance(raw, list) else []
    out = []
    for row in rows:
        if not isinstance(row, dict):
            continue
        state = row.get("state")
        if not isinstance(state, str) or state not in LABELS:
            continue
        name = clean(row.get("title") or row.get("item"), 100)
        if not name:
            continue
        label = LABELS[state]
        if state == "paused":
            reason = clean(row.get("reason"), 80)
            if reason in ("time", "deadline"):
                label = "Stopped at its time"
            elif reason:
                label += ": " + reason
        out.append({"id": clean(row.get("item"), 100), "title": name,
                    "state": state, "label": label, "at": clean(row.get("at"), 40),
                    "waiting": state in WAITING})
    return sorted(out, key=lambda x: (not x["waiting"], x["title"].casefold()))


def view(doc, mode, today=None):
    today = today or datetime.date.today()
    rows = pieces(doc)
    if mode == "letter":
        since = today - datetime.timedelta(days=1)
        changed = [r for r in rows if date_of(r["at"]) and date_of(r["at"]) >= since]
        shown = changed[:MAX_PIECES]
        return {"lines": [r["label"] + ": " + r["title"] for r in shown],
                "pieces": shown, "more": len(changed) - len(shown)}
    if mode == "needs":
        waiting = [r for r in rows if r["waiting"]]
        return {"pieces": waiting[:MAX_PIECES], "more": max(0, len(waiting) - MAX_PIECES)}
    if mode == "today":
        return {"pieces": rows[:MAX_PIECES], "more": max(0, len(rows) - MAX_PIECES)}
    # A snapshot cannot prove transitions during a week. The runner may add
    # projected, bounded event facts; counts are then exact for that window.
    start = today - datetime.timedelta(days=today.weekday())
    raw = doc.get("events") if isinstance(doc, dict) else None
    counts = {event: 0 for event in sorted(EVENTS)}
    if isinstance(raw, list):
        for event in raw:
            if not isinstance(event, dict):
                continue
            kind = event.get("kind")
            if isinstance(kind, str) and kind in counts and start <= (date_of(event.get("at")) or datetime.date.min) <= today:
                counts[kind] += 1
    waiting = [r for r in rows if r["waiting"]]
    return {"counts": counts if isinstance(raw, list) else None,
            "counts_complete": isinstance(raw, list),
            "waiting": waiting[:MAX_PIECES], "more": max(0, len(waiting) - MAX_PIECES),
            "week_start": start.isoformat()}


def main(argv):
    if len(argv) != 1 or argv[0] not in ("letter", "weekly", "today", "needs"):
        return 2
    try:
        doc = json.load(sys.stdin)
    except (ValueError, UnicodeError):
        return 2
    print(json.dumps(view(doc, argv[0]), ensure_ascii=False))
    return 0


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