# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """Turning one parsed message into one row of history.""" from __future__ import annotations from typing import TYPE_CHECKING from signal_bot.counting import media_kind from signal_bot.stats.events import MessageEvent from signal_bot.stats.periods import MS_PER_SECOND, day_of, hour_of if TYPE_CHECKING: import datetime as dt from signal_bot.models import IncomingMessage from signal_bot.stats.events import EventStore def to_event( group_id: str, message: IncomingMessage, now: dt.datetime, *, is_command: bool, ) -> MessageEvent: """Reduce a message to the metadata the statistics keep. The timestamp falls back to the clock because ``models._timestamp`` returns 0 when neither the payload nor the envelope carried one. Zero is not merely inaccurate: it is part of the primary key, so every zero-timestamp frame from one sender would collide and the whole run would be recorded as a single message. """ sent_at_ms = message.timestamp or int(now.timestamp() * MS_PER_SECOND) return MessageEvent( group_id=group_id, uuid=message.source_uuid, display_name=message.source_name or message.source_uuid, sent_at_ms=sent_at_ms, day=day_of(sent_at_ms), local_hour=hour_of(sent_at_ms), media_kind=media_kind(message), media_count=len(message.attachment_types) or int(message.has_sticker), char_len=len(message.text or ""), is_command=is_command, is_reply=message.is_reply, ) def record_message( events: EventStore, group_id: str, message: IncomingMessage, now: dt.datetime, *, is_command: bool, ) -> None: """Append a message to the history and refresh who its sender is.""" event = to_event(group_id, message, now, is_command=is_command) events.record(event) events.note_person( group_id, event.uuid, event.display_name, message.source_number, event.day, )