# backend/app/worker/jobs/digest.py — 능동 다이제스트/브리핑 (집계만, 새 사실 없음) (phase-14)
from sqlmodel import Session, select

from ...automation.event_bus import bus
from ...models import Approval, CalEvent, Task, TaskStatus

DIGEST_TIMES = ["09:00", "13:00", "18:30"]


def run_digest(session: Session, slot: str = "09:00") -> dict:
    """예약 시각 다이제스트 → 알림 벨 + 능동 브리핑. 작업/일정/결재 요약(집계)."""
    open_tasks = sum(1 for t in session.exec(select(Task)).all() if t.status != TaskStatus.done)
    events = len(session.exec(select(CalEvent)).all())
    pending = sum(1 for a in session.exec(select(Approval)).all() if a.status == "pending")
    count = open_tasks + pending
    summary = {
        "slot": slot,
        "open_tasks": open_tasks,
        "events": events,
        "pending_approvals": pending,
        "count": count,
    }
    bus.publish("digest.generated", {"time": slot, "count": count})
    return summary
