#!/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__ = """Day: what today and this evening really hold, from the user's calendar and reminders.

    bin/day                 the day file as plain lines (for Today and morning)
    bin/day --json          the same facts as JSON
    bin/day --refresh       first rewrite .summary/day.json from EventKit
                            (swift bin/day-eventkit.swift), then print
    bin/day --file F        read F instead of .summary/day.json (tests)

The day file is .summary/day.json. Two writers can fill it, both offline:
    1. bin/day-eventkit.swift, run by --refresh. Works once this Mac grants
       calendar access to the app the runner runs in; it never asks unless
       run by hand with --ask.
    2. The app, which asks macOS for the calendar itself (brief 0406) and
       writes today's file once the user switched the calendar on.
With `read_calendar` on, --refresh tries the engine's own read first; when it
is refused or fails, it uses today's file the app wrote, and says in one line
which it used. With it off, the calendar is never read (brief 0106).
ARGONI_DAY_READER names another program to run in place of the Swift reader
(tests: never this Mac's real calendar).
The shape is the one bin/day-eventkit.swift prints: events with title,
start, end, all_day, calendar, side; reminders with title, list, due,
has_time. Nothing else is ever in it: no notes, location, attendees, links.
A work event (side: work, an Exchange calendar) is its title and time only.

The lines are facts, not advice: "Evening: free after 19:00." The skill that
shows them (today, morning) may add what follows from them ("so the side
project tomorrow") in its own words, from the project pages.

In a demo folder (`demo: true` in config.json) nothing on this Mac is read:
the day comes from demo-day.json in the life folder, whose events carry
times only ("10:00") and are always read as today. --refresh is refused.

Exit status: 0 printed; 2 no day file, or it is not today's (one line says
which and what would fill it).
"""
import datetime
import json
import os
import subprocess
import sys

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

LIFE = lifecfg.root()
DAY = os.path.join(LIFE, ".summary", "day.json")
DEMO = lifecfg.demo(LIFE)
DEMO_DAY = os.path.join(LIFE, "demo-day.json")
EVENING = (18, 0)   # the evening starts here
NIGHT = (23, 30)    # "free after" is only said before this
MIN_GAP = 60        # minutes; a shorter gap is not "free"


def hm(t):
    return t.strftime("%H:%M")


def parse(s):
    return datetime.datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone()


def refresh():
    reader = os.environ.get("ARGONI_DAY_READER")
    cmd = [reader] if reader else ["swift", os.path.join(BIN, "day-eventkit.swift")]
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    except (OSError, subprocess.TimeoutExpired) as e:
        return "the calendar reader did not run: %s" % e
    if p.returncode != 0:
        return (p.stderr.strip().splitlines() or ["day-eventkit failed"])[-1]
    os.makedirs(os.path.dirname(DAY), exist_ok=True)
    try:
        lifecfg.write_atomic(DAY, p.stdout)
    except OSError as e:
        return "the day was read but not saved: %s" % e
    return None


def demo_day(path, now):
    """The demo's day, its HH:MM times put on today's date."""
    data = json.load(open(path, encoding="utf-8"))

    def at(hhmm):
        h, m = (int(x) for x in hhmm.split(":"))
        return now.replace(hour=h, minute=m, second=0, microsecond=0).isoformat()
    for e in data.get("events", []):
        e["start"], e["end"] = at(e.get("start", "00:00")), at(e.get("end", "23:59"))
    for r in data.get("reminders", []):
        if r.get("due"):
            r["due"] = at(r["due"])
    data["date"] = now.date().isoformat()
    return data


def facts(data, now):
    day = now.date()
    timed, all_day = [], []
    for e in data.get("events", []):
        if not isinstance(e, dict):
            continue
        try:
            start, end = parse(e["start"]), parse(e["end"])
            str(e["title"])
        except (KeyError, TypeError, ValueError, AttributeError):
            continue  # an event the reader did not write whole: left out, never a crash
        if e.get("all_day"):
            all_day.append({"title": e["title"], "side": e.get("side")})
        elif start.date() <= day <= end.date():
            timed.append({"title": e["title"], "side": e.get("side"), "start": start, "end": end})
    timed.sort(key=lambda e: e["start"])
    evening_at = now.replace(hour=EVENING[0], minute=EVENING[1], second=0, microsecond=0)
    night_at = now.replace(hour=NIGHT[0], minute=NIGHT[1], second=0, microsecond=0)
    evening = [e for e in timed if e["end"] > evening_at]
    # Free windows in the evening (from now, if the evening has begun).
    free, cursor = [], max(evening_at, now)
    for e in evening:
        if (e["start"] - cursor).total_seconds() >= MIN_GAP * 60:
            free.append((cursor, e["start"]))
        cursor = max(cursor, e["end"])
    if cursor < night_at:
        free.append((cursor, None))
    due, overdue, later = [], [], []
    for r in data.get("reminders", []):
        if not isinstance(r, dict):
            continue
        if not r.get("due"):
            later.append(r)
            continue
        try:
            d = parse(r["due"])
            r["title"]
        except (KeyError, TypeError, ValueError, AttributeError):
            continue
        row = {"title": r["title"], "list": r.get("list"), "at": hm(d) if r.get("has_time") else None}
        if d.date() < day or (r.get("has_time") and d < now):
            overdue.append(row)
        else:
            due.append(row)
    return {"date": day.isoformat(), "generated_at": data.get("generated_at"),
            "calendar_allowed": data.get("calendar_allowed", "events" in data),
            "reminders_allowed": data.get("reminders_allowed", "reminders" in data),
            "events": [dict(e, start=hm(e["start"]), end=hm(e["end"])) for e in timed],
            "all_day": all_day, "evening": [dict(e, start=hm(e["start"]), end=hm(e["end"])) for e in evening],
            "evening_free": [[hm(a), hm(b) if b else None] for a, b in free],
            "reminders_due": due, "reminders_overdue": overdue}


def label(e):
    return "%s %s%s" % (e["start"], e["title"], " (work)" if e.get("side") == "work" else "")


def lines(f):
    out = []
    if f["calendar_allowed"]:
        n = len(f["events"])
        out.append("Day: %s." % ("; ".join(label(e) for e in f["events"]) if n else "nothing on the calendar"))
        if f["all_day"]:
            out.append("All day: %s." % ", ".join(e["title"] for e in f["all_day"]))
        free = f["evening_free"]
        if not f["evening"]:
            out.append("Evening: free.")
        elif free and free[-1][1] is None and len(free) == 1:
            out.append("Evening: %s; free after %s." % ("; ".join(label(e) for e in f["evening"]), free[0][0]))
        else:
            gaps = ", ".join("%s to %s" % (a, b) if b else "after %s" % a for a, b in free)
            out.append("Evening: %s; %s." % ("; ".join(label(e) for e in f["evening"]),
                                             "free " + gaps if gaps else "no free hour"))
    else:
        out.append("Day: NOT ESTABLISHED, no calendar permission.")
    if f["reminders_allowed"]:
        r = f["reminders_due"]
        out.append("Reminders: %s." % ("; ".join((x["at"] + " " if x["at"] else "") + x["title"] for x in r)
                                       if r else "none due today"))
        if f["reminders_overdue"]:
            out.append("Overdue: %s." % "; ".join(x["title"] for x in f["reminders_overdue"]))
    return out


def app_day_today(path, now):
    """True when the day file holds today (written by the app, or an earlier read)."""
    try:
        return json.load(open(path, encoding="utf-8")).get("date") == now.date().isoformat()
    except (OSError, ValueError, AttributeError):
        return False


def main(argv):
    path = argv[argv.index("--file") + 1] if "--file" in argv else DAY
    now = datetime.datetime.now().astimezone()
    if DEMO and "--file" not in argv:
        if "--refresh" in argv:
            print("day: demo folder, this Mac's calendar is never read; showing the demo's day")
        try:
            data = demo_day(DEMO_DAY, now)
        except (OSError, ValueError):
            print("day: NOT ESTABLISHED, demo folder with no demo-day.json; this Mac is not read.")
            return 2
        f = facts(data, now)
        print(json.dumps(f, indent=1, ensure_ascii=False) if "--json" in argv else "\n".join(lines(f)))
        return 0
    note = sys.stderr if "--json" in argv else sys.stdout  # --json keeps stdout pure JSON
    if "--refresh" in argv and not lifecfg.config(LIFE).get("read_calendar"):
        # Off until the user switches it on (config.json read_calendar, or the settings window).
        print("day: the calendar is off, not read (switch it on in settings: read_calendar)", file=note)
    elif "--refresh" in argv:
        err = refresh()
        if not err:
            print("day: read from this Mac's calendar", file=note)
        elif app_day_today(path, now):
            print("day: this Mac's calendar read failed (%s); using the day the app wrote" % err, file=note)
        else:
            print("day: %s; and no day from the app for today" % err, file=note)
            return 2
    try:
        data = json.load(open(path, encoding="utf-8"))
        if not isinstance(data, dict) or not all(isinstance(data.get(k, []), list) for k in ("events", "reminders")):
            raise ValueError("not the shape a day file has")
    except (OSError, ValueError):
        print("day: NOT ESTABLISHED, no day file (%s). It is filled by bin/day --refresh once "
              "calendar access is granted, or by the app once it writes it." % os.path.relpath(path, LIFE))
        return 2
    if data.get("date") != now.date().isoformat():
        print("day: NOT ESTABLISHED, the day file is for %s, not today." % data.get("date"))
        return 2
    f = facts(data, now)
    if "--json" in argv:
        print(json.dumps(f, indent=1, ensure_ascii=False))
    else:
        print("\n".join(lines(f)))
    return 0


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