/* The Today brief, written from data already on the screen. A later version will come from the chat model; this one only states facts. */ import { agoTxt, daysAgo, fmtD } from './format'; import type { AdherenceResponse, GoalsResponse } from './life'; export interface Brief { headline: string; lines: string[]; } export interface BriefInput { /** most recent recorded night */ sleep?: { date: string; asleepSec: number } | null; /** most recent workout */ workout?: { title: string; start: string } | null; adherence?: AdherenceResponse | null; goals?: GoalsResponse | null; } const hmText = (sec: number) => { const h = Math.floor(sec / 3600); const m = Math.round((sec % 3600) / 60); return `${h} h ${String(m).padStart(2, '0')}`; }; function greeting(): string { const h = new Date().getHours(); return h < 12 ? 'Good morning' : h < 18 ? 'Good afternoon' : 'Good evening'; } export function buildBrief(i: BriefInput): Brief { const lines: string[] = []; let headline = greeting(); // sleep: only talk about last night if the tracker actually reported it if (i.sleep) { const age = daysAgo(i.sleep.date); if (age <= 1) { headline = `You slept ${hmText(i.sleep.asleepSec)}`; const sleepRule = i.adherence?.protocols .find((p) => p.system === 'sleep')?.rules.find((r) => r.metric === 'sleep.hours'); const target = typeof sleepRule?.value === 'number' ? sleepRule.value * 3600 : null; if (target != null) { const diff = Math.round((i.sleep.asleepSec - target) / 60); lines.push(diff >= 0 ? `That is ${diff} minutes over your ${sleepRule!.value} hour protocol.` : `That is ${-diff} minutes short of your ${sleepRule!.value} hour protocol.`); } } else { lines.push(`No sleep data since ${fmtD(i.sleep.date)}. Eight Sleep has stopped syncing.`); } } // training: last session and this week's count against the weekly rule if (i.workout) { const train = i.adherence?.protocols.find((p) => p.system === 'train'); const weekly = train?.rules.find((r) => r.period === 'week' && r.metric === 'train.workouts'); const weeks = train ? Object.keys(train.weeks).sort() : []; const cur = weekly && weeks.length ? train!.weeks[weeks[weeks.length - 1]]?.[weekly.id] : null; const last = `Your last lift was ${i.workout.title}, ${agoTxt(i.workout.start)}.`; lines.push(cur ? `${last} ${cur.count} of ${cur.need} sessions this week.` : last); } // mind: minutes this week against the goal const med = i.goals?.goals.find((g) => g.metric === 'mind.minutes_7d'); if (med && med.current != null) { lines.push(`Meditation is at ${Math.round(med.current)} of ${med.target} minutes this week.`); } if (!lines.length) lines.push('Pull down to refresh once your trackers have synced.'); return { headline, lines }; }