File size: 12,088 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import { prisma } from "@/lib/db";
import { claude, parseClaudeJson } from "@/lib/claude";
import { CATEGORIES, CATEGORY_LABELS, type Category } from "@/config/xp";
import { createHash } from "crypto";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface WeekOverWeek {
  currentWeekXp: number;
  previousWeekXp: number;
  xpChange: number;
  xpChangePercent: number;
  currentWeekExercises: number;
  previousWeekExercises: number;
  currentWeekActiveDays: number;
  previousWeekActiveDays: number;
}

export interface CategoryWeekStats {
  category: Category;
  label: string;
  exercises: number;
  avgScore: number;
  totalXp: number;
  previousWeekExercises: number;
  previousWeekAvgScore: number;
}

export interface WeeklyReport {
  report: string;
  highlights: string[];
  areasToFocus: string[];
  weekOverWeek: WeekOverWeek;
  generatedAt: string;
}

interface CacheEntry {
  report: WeeklyReport;
  cachedAt: number;
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/** Cache TTL: 24 hours in milliseconds */
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;

/** Minimum active days in the current week to generate a report */
const MIN_ACTIVE_DAYS = 3;

// ---------------------------------------------------------------------------
// In-memory cache
// ---------------------------------------------------------------------------

const reportCache = new Map<string, CacheEntry>();

// ---------------------------------------------------------------------------
// Cache helpers
// ---------------------------------------------------------------------------

/**
 * Build a cache key from user ID and the current week boundary.
 */
export function buildReportCacheKey(userId: number, now: Date): string {
  const weekStart = getWeekStart(now);
  const payload = `${userId}:${weekStart.toISOString().slice(0, 10)}`;
  return createHash("sha256").update(payload).digest("hex").slice(0, 16);
}

/**
 * Get a cached report if it exists and hasn't expired.
 */
export function getCachedReport(key: string): WeeklyReport | null {
  const entry = reportCache.get(key);
  if (!entry) return null;
  if (Date.now() - entry.cachedAt > CACHE_TTL_MS) {
    reportCache.delete(key);
    return null;
  }
  return entry.report;
}

/**
 * Store a report in cache.
 */
export function cacheReport(key: string, report: WeeklyReport): void {
  reportCache.set(key, { report, cachedAt: Date.now() });
}

// ---------------------------------------------------------------------------
// Date helpers
// ---------------------------------------------------------------------------

/**
 * Get the start of the current week (Monday 00:00 UTC).
 */
export function getWeekStart(now: Date): Date {
  const d = new Date(now);
  const day = d.getUTCDay();
  // day 0 = Sunday, so Monday = 1
  const diff = day === 0 ? 6 : day - 1;
  d.setUTCDate(d.getUTCDate() - diff);
  d.setUTCHours(0, 0, 0, 0);
  return d;
}

/**
 * Get the start of the previous week (Monday 00:00 UTC).
 */
export function getPreviousWeekStart(now: Date): Date {
  const weekStart = getWeekStart(now);
  weekStart.setUTCDate(weekStart.getUTCDate() - 7);
  return weekStart;
}

// ---------------------------------------------------------------------------
// Data aggregation
// ---------------------------------------------------------------------------

/**
 * Gather weekly stats for the current and previous week.
 */
export async function getWeeklyData(
  userId: number,
  now: Date = new Date(),
): Promise<{
  currentWeek: CategoryWeekStats[];
  weekOverWeek: WeekOverWeek;
  streakDays: number;
  longestStreak: number;
  activeDaysThisWeek: number;
}> {
  const weekStart = getWeekStart(now);
  const prevWeekStart = getPreviousWeekStart(now);

  const user = await prisma.user.findUniqueOrThrow({
    where: { id: userId },
  });

  // Fetch activities for current and previous week
  const currentWeekActivities = await prisma.activity.findMany({
    where: {
      userId,
      createdAt: { gte: weekStart },
    },
    orderBy: { createdAt: "asc" },
  });

  const previousWeekActivities = await prisma.activity.findMany({
    where: {
      userId,
      createdAt: { gte: prevWeekStart, lt: weekStart },
    },
    orderBy: { createdAt: "asc" },
  });

  // Count distinct active days (current week)
  const activeDaySet = new Set(
    currentWeekActivities.map((a) => {
      const d = new Date(a.createdAt);
      return `${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`;
    }),
  );
  const activeDaysThisWeek = activeDaySet.size;

  // Count distinct active days (previous week)
  const prevActiveDaySet = new Set(
    previousWeekActivities.map((a) => {
      const d = new Date(a.createdAt);
      return `${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`;
    }),
  );

  // Per-category stats
  const currentWeek: CategoryWeekStats[] = CATEGORIES.map((cat) => {
    const current = currentWeekActivities.filter((a) => a.category === cat);
    const previous = previousWeekActivities.filter((a) => a.category === cat);

    const currentScored = current.filter((a) => a.score !== null);
    const previousScored = previous.filter((a) => a.score !== null);

    const avgScore =
      currentScored.length > 0
        ? currentScored.reduce((s, a) => s + (a.score ?? 0), 0) /
          currentScored.length
        : 0;

    const previousAvgScore =
      previousScored.length > 0
        ? previousScored.reduce((s, a) => s + (a.score ?? 0), 0) /
          previousScored.length
        : 0;

    return {
      category: cat,
      label: CATEGORY_LABELS[cat],
      exercises: current.length,
      avgScore: Math.round(avgScore * 100) / 100,
      totalXp: current.reduce((s, a) => s + a.totalXp, 0),
      previousWeekExercises: previous.length,
      previousWeekAvgScore: Math.round(previousAvgScore * 100) / 100,
    };
  });

  // Week-over-week totals
  const currentWeekXp = currentWeekActivities.reduce(
    (s, a) => s + a.totalXp,
    0,
  );
  const previousWeekXp = previousWeekActivities.reduce(
    (s, a) => s + a.totalXp,
    0,
  );
  const xpChange = currentWeekXp - previousWeekXp;
  const xpChangePercent =
    previousWeekXp > 0
      ? Math.round((xpChange / previousWeekXp) * 1000) / 10
      : currentWeekXp > 0
        ? 100
        : 0;

  const weekOverWeek: WeekOverWeek = {
    currentWeekXp,
    previousWeekXp,
    xpChange,
    xpChangePercent,
    currentWeekExercises: currentWeekActivities.length,
    previousWeekExercises: previousWeekActivities.length,
    currentWeekActiveDays: activeDaysThisWeek,
    previousWeekActiveDays: prevActiveDaySet.size,
  };

  return {
    currentWeek,
    weekOverWeek,
    streakDays: user.streak,
    longestStreak: user.longestStreak,
    activeDaysThisWeek,
  };
}

// ---------------------------------------------------------------------------
// Prompt construction
// ---------------------------------------------------------------------------

/**
 * Build the Claude prompt for weekly report generation.
 */
export function buildWeeklyPrompt(
  currentWeek: CategoryWeekStats[],
  weekOverWeek: WeekOverWeek,
  streakDays: number,
  longestStreak: number,
): string {
  const activeCategories = currentWeek.filter((c) => c.exercises > 0);
  const inactiveCategories = currentWeek.filter((c) => c.exercises === 0);

  const catDetails = activeCategories
    .map((c) => {
      const scoreDiff = c.avgScore - c.previousWeekAvgScore;
      const scoreChange =
        c.previousWeekExercises > 0
          ? ` (${scoreDiff >= 0 ? "+" : ""}${(scoreDiff * 100).toFixed(0)}pp vs last week)`
          : " (new this week)";
      return `- ${c.label}: ${c.exercises} exercises (prev: ${c.previousWeekExercises}), avg score: ${(c.avgScore * 100).toFixed(0)}%${scoreChange}, ${c.totalXp} XP`;
    })
    .join("\n");

  const inactiveList =
    inactiveCategories.length > 0
      ? `\nInactive this week: ${inactiveCategories.map((c) => c.label).join(", ")}`
      : "";

  return `You are the Active Coach for RotNot, a brain training app that combats cognitive atrophy from AI over-reliance. Generate a concise weekly brain health report.

Week-Over-Week Summary:
- XP this week: ${weekOverWeek.currentWeekXp} (last week: ${weekOverWeek.previousWeekXp}, change: ${weekOverWeek.xpChange >= 0 ? "+" : ""}${weekOverWeek.xpChange} / ${weekOverWeek.xpChangePercent >= 0 ? "+" : ""}${weekOverWeek.xpChangePercent}%)
- Exercises this week: ${weekOverWeek.currentWeekExercises} (last week: ${weekOverWeek.previousWeekExercises})
- Active days this week: ${weekOverWeek.currentWeekActiveDays} (last week: ${weekOverWeek.previousWeekActiveDays})
- Current streak: ${streakDays} days (longest ever: ${longestStreak})

Category Breakdown:
${catDetails || "No exercises completed this week."}${inactiveList}

Instructions:
1. "report": 2-3 sentence summary of the week. Be specific — reference numbers, categories, and trends. Do NOT be generic. Keep it direct and motivational without being cheesy.
2. "highlights": Array of 2-4 short bullet strings (~15 words each) — specific things the user did well this week.
3. "areasToFocus": Array of 2-3 short bullet strings (~15 words each) — specific, actionable recommendations for next week.

Respond ONLY in valid JSON (no markdown, no code fences):
{ "report": "...", "highlights": ["...", "..."], "areasToFocus": ["...", "..."] }`;
}

// ---------------------------------------------------------------------------
// Main report generator
// ---------------------------------------------------------------------------

export interface WeeklyReportGate {
  hasReport: false;
  activeDaysThisWeek: number;
  requiredDays: number;
}

/**
 * Generate a weekly brain health report.
 *
 * Returns cached report if available (24h TTL).
 * Returns a WeeklyReportGate object (hasReport: false) with current day
 * count if user has fewer than MIN_ACTIVE_DAYS days of activity this week.
 *
 * Throws if Claude call fails or returns invalid JSON.
 */
export async function generateWeeklyReport(
  userId: number,
  now: Date = new Date(),
): Promise<{ report: WeeklyReport; cached: boolean } | WeeklyReportGate> {
  const cacheKey = buildReportCacheKey(userId, now);

  // Check cache first
  const cached = getCachedReport(cacheKey);
  if (cached) {
    return { report: cached, cached: true };
  }

  // Gather data
  const data = await getWeeklyData(userId, now);

  // Gate: require at least MIN_ACTIVE_DAYS active days
  if (data.activeDaysThisWeek < MIN_ACTIVE_DAYS) {
    return {
      hasReport: false,
      activeDaysThisWeek: data.activeDaysThisWeek,
      requiredDays: MIN_ACTIVE_DAYS,
    };
  }

  // Build prompt and call Claude
  const prompt = buildWeeklyPrompt(
    data.currentWeek,
    data.weekOverWeek,
    data.streakDays,
    data.longestStreak,
  );

  const message = await claude.messages.create({
    model: "claude-haiku-4-5-20251001",
    max_tokens: 1024,
    messages: [{ role: "user", content: prompt }],
  });

  const text =
    message.content[0].type === "text" ? message.content[0].text : "";
  const parsed = parseClaudeJson(text) as {
    report: string;
    highlights: string[];
    areasToFocus: string[];
  };

  // Validate response shape
  if (
    !parsed.report ||
    typeof parsed.report !== "string" ||
    !Array.isArray(parsed.highlights) ||
    !Array.isArray(parsed.areasToFocus) ||
    parsed.highlights.length === 0 ||
    parsed.areasToFocus.length === 0
  ) {
    throw new Error("Claude returned invalid weekly report structure");
  }

  const report: WeeklyReport = {
    report: parsed.report,
    highlights: parsed.highlights,
    areasToFocus: parsed.areasToFocus,
    weekOverWeek: data.weekOverWeek,
    generatedAt: new Date().toISOString(),
  };

  // Cache the result
  cacheReport(cacheKey, report);

  return { report, cached: false };
}