"""The append-only audit trail, which is also the notification seam.

Every state change in caddie writes one row here. `notified_at` is reserved so
a future notifier needs no migration; nothing reads it yet.
"""

from sqlalchemy import select

from app.models import Activity


def record(session, project_id: str, verb: str, *, actor: str = "",
           actor_type: str = "agency", stage_id: str | None = None,
           payload: dict | None = None, client_visible: bool = True) -> Activity:
    row = Activity(project_id=project_id, verb=verb, actor=actor,
                   actor_type=actor_type, stage_id=stage_id,
                   payload=payload or None, client_visible=client_visible)
    session.add(row)
    session.flush()
    return row


def feed(session, project_id: str, *, for_client: bool, limit: int = 50) -> list[Activity]:
    q = select(Activity).where(Activity.project_id == project_id)
    if for_client:
        q = q.where(Activity.client_visible.is_(True))
    return list(session.execute(
        q.order_by(Activity.at.desc()).limit(limit)).scalars())
