# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """Which days still owe the group a report, and posting them. The event log already survives an outage: a message carries Signal's own send timestamp, signal-cli keeps receiving while the bot is down, and the replay on reconnect is absorbed by the primary key. So the *counts* come back on their own, filed under the day they were actually sent. The *report* did not. A bot that was down at 21:37 simply never posted that day, and nothing ever went back for it -- the old counter merged the day into the next one instead, which is the bug this release exists to remove. So the last day reported is written down per group, and every day since then gets posted when the bot comes back. Bounded, because coming back from a fortnight offline should not open with a fortnight of back-posts. """ from __future__ import annotations import logging from typing import TYPE_CHECKING, Final from signal_bot.stats.periods import shift if TYPE_CHECKING: from signal_bot.store import Store logger = logging.getLogger(__name__) LAST_REPORTED_KEY: Final = "last_reported_day" # At most a week of catch-up in one go. Long enough to cover a weekend # outage nobody noticed, short enough that a month offline is not a wall. CATCHUP_LIMIT: Final = 7 def days_to_report(store: Store, group_id: str, latest: str) -> list[str]: """Every day up to ``latest`` that has not been reported yet, oldest first. Args: store: The open database, which holds the per-group marker. group_id: The group being reported on. latest: The most recent day eligible for a report, normally yesterday. Returns: The days to post, oldest first. A group with no marker gets only ``latest``: the marker is absent on a brand-new group and on the first run after this release, and neither should trigger a backlog. """ last = store.meta(group_id, LAST_REPORTED_KEY) if last is None: return [latest] if last >= latest: return [] days = [] day = shift(last, 1) while day <= latest: days.append(day) day = shift(day, 1) return days[-CATCHUP_LIMIT:] def mark_reported(store: Store, group_id: str, day: str) -> None: """Record that a day no longer owes this group a report. Called for a day that was posted *and* for a day nobody spoke on -- an empty day is settled, not pending, and leaving it unmarked would make the bot reconsider it every night forever. """ store.set_meta(group_id, LAST_REPORTED_KEY, day)