#!/usr/bin/env python3
"""The week ahead on BlueRune's desktop: a card with your next events, from khal when it is
installed, or else from calendar files (.ics).

BlueRune keeps the card (it is made with `bluerunectl ext set`), so it stays across restarts;
run this every few minutes to bring it up to date, for example with a systemd user timer.
`BLUERUNE_AGENDA_ICS` names the calendar files, separated by colons; without it,
~/.local/share/bluerune/agenda.ics. Only Python's own library is needed. A press on the card
opens your calendar app, and Refresh in its menu reads the calendars again.
See docs/extensions.md.

Calendar files: each event's start and title are read, with simple repeats (daily, weekly on
given days, monthly, yearly, with an interval, a count or an end); other rules are shown once.
"""

import datetime as dt
import json
import os
import shlex
import shutil
import subprocess
import sys
from pathlib import Path

try:
    from zoneinfo import ZoneInfo
except ImportError:  # Python before 3.9: times in a named zone are read as local.
    ZoneInfo = None

ID = "agenda"
DAYS = 7
# The most events the card lists, as BlueRune allows.
ROWS = 8
TEXT, DETAIL = 64, 120
CALENDARS = ("gnome-calendar", "merkuro-calendar", "kalendar", "evolution")
WEEKDAYS = {"MO": 0, "TU": 1, "WE": 2, "TH": 3, "FR": 4, "SA": 5, "SU": 6}


def short(words, most):
    words = " ".join(str(words).split())
    return words if len(words) <= most else words[: most - 1] + "…"


# --- Calendar files -----------------------------------------------------------------------


def lines(text):
    """The file's lines with folded ones joined back up."""
    out = []
    for line in text.splitlines():
        if line[:1] in (" ", "\t") and out:
            out[-1] += line[1:]
        elif line:
            out.append(line)
    return out


def moment(params, value):
    """A start as a date (all day) or a local datetime."""
    value = value.strip()
    if "VALUE=DATE" in params or len(value) == 8:
        return dt.datetime.strptime(value[:8], "%Y%m%d").date()
    when = dt.datetime.strptime(value[:15], "%Y%m%dT%H%M%S")
    if value.endswith("Z"):
        return when.replace(tzinfo=dt.timezone.utc).astimezone().replace(tzinfo=None)
    zone = next((param[5:] for param in params if param.startswith("TZID=")), None)
    if zone and ZoneInfo:
        try:
            return when.replace(tzinfo=ZoneInfo(zone)).astimezone().replace(tzinfo=None)
        except (KeyError, ValueError):
            pass
    return when


def day_of(when):
    return when if not isinstance(when, dt.datetime) else when.date()


def candidates(start, freq, step, days):
    """Every start `freq` makes from `start` on, in order and without end: `None` for one
    that falls on a day the month doesn't have."""
    if freq == "WEEKLY" and days:
        monday = day_of(start) - dt.timedelta(days=day_of(start).weekday())
        for week in range(sys.maxsize):
            for weekday in sorted(days):
                one = monday + dt.timedelta(weeks=week * step, days=weekday)
                if one >= day_of(start):
                    yield dt.datetime.combine(one, start.time()) if isinstance(start, dt.datetime) else one
    for n in range(sys.maxsize):
        if freq == "DAILY":
            yield start + dt.timedelta(days=n * step)
        elif freq == "WEEKLY":
            yield start + dt.timedelta(weeks=n * step)
        elif freq in ("MONTHLY", "YEARLY"):
            year, month = divmod(start.month - 1 + n * step * (12 if freq == "YEARLY" else 1), 12)
            try:
                yield start.replace(year=start.year + year, month=month + 1)
            except ValueError:  # The 31st, or 29 February, in a month without it.
                yield None
        else:
            yield start
            return


def repeats(start, rule, until_day):
    """Each start of an event from `start` on, following `rule`, up to `until_day`."""
    parts = dict(part.split("=", 1) for part in rule.split(";") if "=" in part)
    freq, step = parts.get("FREQ"), max(1, int(parts.get("INTERVAL", "1")))
    count = int(parts["COUNT"]) if "COUNT" in parts else None
    end = day_of(moment([], parts["UNTIL"])) if "UNTIL" in parts else None
    days = [WEEKDAYS[day[-2:]] for day in parts.get("BYDAY", "").split(",") if day[-2:] in WEEKDAYS]
    made = 0
    for at in candidates(start, freq, step, days):
        if at is None:
            continue
        if day_of(at) > until_day or (end is not None and day_of(at) > end) or (count is not None and made >= count):
            return
        made += 1
        yield at


def from_files(paths, today):
    events = []
    last = today + dt.timedelta(days=DAYS)
    for path in paths:
        try:
            text = Path(path).expanduser().read_text(encoding="utf-8", errors="replace")
        except OSError as error:
            print(f"bluerune-agenda: {error}", file=sys.stderr)
            continue
        event = None
        for line in lines(text):
            name, _, value = line.partition(":")
            key, *params = name.split(";")
            key = key.upper()
            if key == "BEGIN" and value.strip().upper() == "VEVENT":
                event = {}
            elif key == "END" and value.strip().upper() == "VEVENT" and event is not None:
                if "start" in event:
                    starts = repeats(event["start"], event["rule"], last) if "rule" in event else [event["start"]]
                    try:
                        events.extend((start, event.get("title", "Untitled")) for start in starts if today <= day_of(start) <= last)
                    except ValueError:  # A repeat rule with a count or an end that isn't one.
                        events.extend((start, event.get("title", "Untitled")) for start in [event["start"]] if today <= day_of(start) <= last)
                event = None
            elif event is not None:
                if key == "DTSTART":
                    try:
                        event["start"] = moment(params, value)
                    except ValueError:
                        pass
                elif key == "SUMMARY":
                    event["title"] = value.replace("\\,", ",").replace("\\;", ";").replace("\\n", " ")
                elif key == "RRULE":
                    event["rule"] = value.strip().upper()
    return events


# --- khal ---------------------------------------------------------------------------------


def from_khal(today):
    """The next week's events as khal lists them: its own words for when."""
    shown = subprocess.run(
        ["khal", "list", "--day-format", "", "--format", "{start-date}\t{start-time}\t{title}", today.isoformat(), f"{DAYS}d"],
        capture_output=True, text=True, timeout=30, check=False,
    )
    events = []
    for line in shown.stdout.splitlines():
        parts = line.split("\t")
        if len(parts) == 3 and parts[2].strip():
            date, time, title = parts
            events.append(((date + " " + time).strip(), title))
    return events


# --- The card -----------------------------------------------------------------------------


def when(start, today):
    """When an event is, as short as it can be said."""
    day = day_of(start)
    if day == today:
        name = ""
    elif day == today + dt.timedelta(days=1):
        name = "Tomorrow"
    else:
        name = day.strftime("%a")
    if isinstance(start, dt.datetime):
        return f"{name} {start.strftime('%H:%M')}".strip()
    return name or "All day"


def card(today):
    if shutil.which("khal"):
        rows = [{"text": short(title, TEXT), "detail": short(at, DETAIL), "icon": "event"} for at, title in from_khal(today)]
    else:
        paths = os.environ.get("BLUERUNE_AGENDA_ICS", "~/.local/share/bluerune/agenda.ics").split(":")
        events = sorted(from_files(paths, today), key=lambda event: (day_of(event[0]), event[0].time() if isinstance(event[0], dt.datetime) else dt.time()))
        now = dt.datetime.now()
        events = [event for event in events if not isinstance(event[0], dt.datetime) or event[0] >= now - dt.timedelta(hours=1)]
        rows = [{"text": short(title, TEXT), "detail": when(start, today), "icon": "event" if isinstance(start, dt.datetime) else "today"} for start, title in events]
    content = {
        "title": short(today.strftime("Today, %A %-d %B"), TEXT),
        "icon": "calendar_month",
        "hue": "blue",
        "list": rows[:ROWS] or [{"text": "Nothing in the next week"}],
        "menu": [{"label": "Refresh", "action": "refresh"}],
    }
    if len(rows) > ROWS:
        content["detail"] = f"{len(rows) - ROWS} more this week"
    return content


def publish():
    script = os.path.realpath(sys.argv[0])
    # The card's command runs in BlueRune's environment, so it carries the calendar files.
    files = os.environ.get("BLUERUNE_AGENDA_ICS")
    command = (f"BLUERUNE_AGENDA_ICS={shlex.quote(files)} " if files else "") + f"{shlex.quote(script)} --clicked"
    content = json.dumps(card(dt.date.today()))
    subprocess.run(["bluerunectl", "ext", "set", ID, "--slot", "desktop", "--name", "Agenda", "--content", content, "--on-click", command], check=True)


def clicked():
    action, value = os.environ.get("BLUERUNE_ACTION"), os.environ.get("BLUERUNE_VALUE")
    if action == "menu" and value == "refresh":
        publish()
    elif action == "activate":
        program = next((program for program in CALENDARS if shutil.which(program)), None)
        if program:
            subprocess.Popen([program], start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


if __name__ == "__main__":
    clicked() if sys.argv[1:] == ["--clicked"] else publish()
