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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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/**
 * Tests for generateWeeklyReport β€” the top-level weekly brain health report generator.
 *
 * Covers:
 *   - cache hit: returns cached report without calling Claude or DB
 *   - cache miss, < MIN_ACTIVE_DAYS: returns null (gate)
 *   - cache miss, >= MIN_ACTIVE_DAYS: calls Claude, parses response, caches result
 *   - cache miss: returns { report, cached: false }
 *   - cache hit:  returns { report, cached: true }
 *   - Claude response is parsed and stored in WeeklyReport shape
 *   - weekOverWeek data from getWeeklyData is included in the returned report
 *   - generatedAt is a valid ISO timestamp
 *   - throws when Claude returns invalid JSON
 *   - throws when Claude returns missing required fields
 *   - throws when highlights is empty array
 *   - throws when areasToFocus is empty array
 *   - throws when Claude network call fails
 *   - caches the result after successful generation
 *   - different userId + same week β†’ different cache key (independent reports)
 *   - same userId + different week β†’ different cache key
 *   - correct haiku model used
 *   - prompt content contains category and XP data
 *
 * Strategy: because reportCache is module-level in-memory state, each test
 * that exercises "cache miss" paths uses a distinct userId (incremented via a
 * counter) so prior test runs can never produce a spurious cache hit.
 */

import { describe, it, expect, vi, beforeEach } from "vitest";

// ---------------------------------------------------------------------------
// Mock: Prisma (via getWeeklyData which calls prisma internally)
// ---------------------------------------------------------------------------

const mockUserFindUniqueOrThrow = vi.fn();
const mockActivityFindMany = vi.fn();

vi.mock("@/lib/db", () => ({
  prisma: {
    user: {
      findUniqueOrThrow: (...args: unknown[]) =>
        mockUserFindUniqueOrThrow(...args),
    },
    activity: {
      findMany: (...args: unknown[]) => mockActivityFindMany(...args),
    },
  },
}));

// ---------------------------------------------------------------------------
// Mock: Claude
// ---------------------------------------------------------------------------

const mockMessagesCreate = vi.fn();

vi.mock("@/lib/claude", () => ({
  claude: {
    messages: {
      create: (...args: unknown[]) => mockMessagesCreate(...args),
    },
  },
  parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()),
}));

// ---------------------------------------------------------------------------
// Import under test (after mocks are wired)
// ---------------------------------------------------------------------------

import { generateWeeklyReport, type WeeklyReport } from "../weekly-report";

/** Convenience alias for the non-gate branch of the generateWeeklyReport return type */
type ReportResult = { report: WeeklyReport; cached: boolean };

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/** Build a Date at UTC noon for a given YYYY-MM-DD */
function utcDay(iso: string): Date {
  return new Date(`${iso}T12:00:00Z`);
}

/** Wednesday 2026-03-18 β€” stable reference date; week starts Monday 2026-03-16 */
const NOW = utcDay("2026-03-18");

/** Counter to generate unique userIds so the in-memory cache never leaks across tests. */
let nextUserId = 100;
function freshUserId(): number {
  return nextUserId++;
}

/** Base user object returned by DB mock */
const BASE_USER = { streak: 7, longestStreak: 30 };

/** Build a valid Claude response JSON string */
function claudeReport(overrides: Record<string, unknown> = {}): string {
  return JSON.stringify({
    report: "Great week overall, strong performance in Chess.",
    highlights: ["Completed 10 chess puzzles", "Maintained 7-day streak"],
    areasToFocus: ["Try Feynman challenges", "Aim for 3 logic sessions next week"],
    ...overrides,
  });
}

/** Wrap Claude response text in the SDK response shape */
function claudeResponse(text: string) {
  return {
    content: [{ type: "text", text }],
  };
}

/** 3 activities on distinct days (Mon/Tue/Wed) β€” always passes the MIN_ACTIVE_DAYS gate */
function threeDistinctDays() {
  return [
    { category: "chess", createdAt: new Date("2026-03-16T10:00:00Z"), score: 0.8, totalXp: 50 },
    { category: "chess", createdAt: new Date("2026-03-17T10:00:00Z"), score: 0.8, totalXp: 50 },
    { category: "chess", createdAt: new Date("2026-03-18T10:00:00Z"), score: 0.8, totalXp: 50 },
  ];
}

/**
 * Set up mockActivityFindMany to return `currentWeekActivities` for current-week
 * queries and an empty array for previous-week queries.
 *
 * getWeeklyData calls prisma.activity.findMany twice:
 *   1. { createdAt: { gte: weekStart } }              β†’ current week
 *   2. { createdAt: { gte: prevWeekStart, lt: weekStart } } β†’ previous week (has `lt`)
 */
function setupActivityMock(currentWeekActivities: object[]) {
  mockActivityFindMany.mockImplementation(
    ({ where }: { where: { createdAt?: { lt?: Date; gte: Date } } }) => {
      if (where?.createdAt?.lt) return Promise.resolve([]); // previous week query
      return Promise.resolve(currentWeekActivities);
    },
  );
}

// ---------------------------------------------------------------------------
// Reset common mocks before each test
// ---------------------------------------------------------------------------

beforeEach(() => {
  vi.clearAllMocks();
  mockUserFindUniqueOrThrow.mockResolvedValue(BASE_USER);
  setupActivityMock(threeDistinctDays());
  mockMessagesCreate.mockResolvedValue(claudeResponse(claudeReport()));
});

// ---------------------------------------------------------------------------
// Cache hit
// ---------------------------------------------------------------------------

describe("cache hit", () => {
  it("returns cached report without calling Claude or DB a second time", async () => {
    const uid = freshUserId();

    // First call β€” populates cache
    await generateWeeklyReport(uid, NOW);
    const priorDbCalls = mockUserFindUniqueOrThrow.mock.calls.length;
    const priorClaudeCalls = mockMessagesCreate.mock.calls.length;

    // Second call β€” should use cache
    const result = await generateWeeklyReport(uid, NOW) as ReportResult;

    expect(result).not.toBeNull();
    expect(result.cached).toBe(true);
    expect(mockUserFindUniqueOrThrow).toHaveBeenCalledTimes(priorDbCalls);
    expect(mockMessagesCreate).toHaveBeenCalledTimes(priorClaudeCalls);
  });

  it("cached result preserves all original report fields", async () => {
    const uid = freshUserId();

    await generateWeeklyReport(uid, NOW);
    const result = await generateWeeklyReport(uid, NOW) as ReportResult;

    expect(result.cached).toBe(true);
    expect(result.report.report).toBe(
      "Great week overall, strong performance in Chess.",
    );
    expect(result.report.highlights).toEqual([
      "Completed 10 chess puzzles",
      "Maintained 7-day streak",
    ]);
    expect(result.report.areasToFocus).toEqual([
      "Try Feynman challenges",
      "Aim for 3 logic sessions next week",
    ]);
  });
});

// ---------------------------------------------------------------------------
// MIN_ACTIVE_DAYS gate (< 3 active days β†’ null)
// ---------------------------------------------------------------------------

describe("MIN_ACTIVE_DAYS gate", () => {
  it("returns gate object (hasReport: false) when activeDaysThisWeek is 2 (< 3)", async () => {
    setupActivityMock([
      { category: "chess", createdAt: new Date("2026-03-16T10:00:00Z"), score: 0.8, totalXp: 50 },
      { category: "chess", createdAt: new Date("2026-03-17T10:00:00Z"), score: 0.8, totalXp: 50 },
      // only 2 distinct days
    ]);

    const result = await generateWeeklyReport(freshUserId(), NOW);
    expect(result).not.toBeNull();
    expect("hasReport" in result).toBe(true);
    const gate = result as { hasReport: false; activeDaysThisWeek: number; requiredDays: number };
    expect(gate.hasReport).toBe(false);
    expect(gate.activeDaysThisWeek).toBe(2);
    expect(gate.requiredDays).toBe(3);
    expect(mockMessagesCreate).not.toHaveBeenCalled();
  });

  it("returns gate with activeDaysThisWeek=0 when there are no activities this week", async () => {
    setupActivityMock([]);

    const result = await generateWeeklyReport(freshUserId(), NOW);
    expect("hasReport" in result).toBe(true);
    const gate = result as { hasReport: false; activeDaysThisWeek: number; requiredDays: number };
    expect(gate.hasReport).toBe(false);
    expect(gate.activeDaysThisWeek).toBe(0);
    expect(mockMessagesCreate).not.toHaveBeenCalled();
  });

  it("counts only distinct active days (same-day duplicates don't inflate count)", async () => {
    // 5 activities all on Monday β†’ 1 active day < 3
    setupActivityMock([
      { category: "chess", createdAt: new Date("2026-03-16T09:00:00Z"), score: 0.9, totalXp: 50 },
      { category: "chess", createdAt: new Date("2026-03-16T10:00:00Z"), score: 0.8, totalXp: 50 },
      { category: "chess", createdAt: new Date("2026-03-16T11:00:00Z"), score: 0.7, totalXp: 50 },
      { category: "chess", createdAt: new Date("2026-03-16T12:00:00Z"), score: 0.8, totalXp: 50 },
      { category: "chess", createdAt: new Date("2026-03-16T14:00:00Z"), score: 0.9, totalXp: 50 },
    ]);

    const result = await generateWeeklyReport(freshUserId(), NOW);
    expect("hasReport" in result).toBe(true);
    const gate = result as { hasReport: false; activeDaysThisWeek: number; requiredDays: number };
    expect(gate.activeDaysThisWeek).toBe(1);
  });

  it("passes the gate with exactly 3 distinct active days", async () => {
    // Default mock already sets up 3 distinct days
    const result = await generateWeeklyReport(freshUserId(), NOW);
    expect(result).not.toBeNull();
    expect(mockMessagesCreate).toHaveBeenCalledTimes(1);
  });
});

// ---------------------------------------------------------------------------
// Successful generation
// ---------------------------------------------------------------------------

describe("successful report generation", () => {
  it("returns { cached: false } on first generation", async () => {
    const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult;
    expect(result).not.toBeNull();
    expect(result.cached).toBe(false);
  });

  it("report object includes the text from Claude", async () => {
    const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult;
    expect(result.report.report).toBe(
      "Great week overall, strong performance in Chess.",
    );
    expect(result.report.highlights).toEqual([
      "Completed 10 chess puzzles",
      "Maintained 7-day streak",
    ]);
    expect(result.report.areasToFocus).toEqual([
      "Try Feynman challenges",
      "Aim for 3 logic sessions next week",
    ]);
  });

  it("report includes weekOverWeek data from getWeeklyData", async () => {
    const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult;
    const wow = result.report.weekOverWeek;
    expect(wow).toBeDefined();
    expect(typeof wow.currentWeekXp).toBe("number");
    expect(typeof wow.previousWeekXp).toBe("number");
    expect(typeof wow.xpChange).toBe("number");
    expect(typeof wow.xpChangePercent).toBe("number");
    expect(typeof wow.currentWeekActiveDays).toBe("number");
    expect(wow.currentWeekActiveDays).toBe(3); // our 3 distinct test days
  });

  it("currentWeekXp in weekOverWeek matches the sum of activity XP", async () => {
    // Each of 3 test activities has totalXp = 50 β†’ sum = 150
    const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult;
    expect(result.report.weekOverWeek.currentWeekXp).toBe(150);
  });

  it("report includes a generatedAt ISO timestamp", async () => {
    const before = Date.now();
    const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult;
    const after = Date.now();

    const ts = new Date(result.report.generatedAt).getTime();
    expect(ts).toBeGreaterThanOrEqual(before);
    expect(ts).toBeLessThanOrEqual(after);
  });

  it("uses the haiku model for cost efficiency", async () => {
    await generateWeeklyReport(freshUserId(), NOW);
    const call = mockMessagesCreate.mock.calls[0][0];
    expect(call.model).toBe("claude-haiku-4-5-20251001");
  });

  it("prompt contains total XP data", async () => {
    setupActivityMock([
      { category: "chess", createdAt: new Date("2026-03-16T10:00:00Z"), score: 0.9, totalXp: 200 },
      { category: "chess", createdAt: new Date("2026-03-17T10:00:00Z"), score: 0.8, totalXp: 150 },
      { category: "chess", createdAt: new Date("2026-03-18T10:00:00Z"), score: 0.7, totalXp: 100 },
    ]);

    await generateWeeklyReport(freshUserId(), NOW);
    const call = mockMessagesCreate.mock.calls[0][0];
    const prompt: string = call.messages[0].content;

    // Total = 450 XP
    expect(prompt).toContain("450");
  });

  it("prompt contains streak data from DB user", async () => {
    mockUserFindUniqueOrThrow.mockResolvedValue({ streak: 14, longestStreak: 42 });

    await generateWeeklyReport(freshUserId(), NOW);
    const call = mockMessagesCreate.mock.calls[0][0];
    const prompt: string = call.messages[0].content;

    expect(prompt).toContain("14 days");
    expect(prompt).toContain("42");
  });

  it("caches the result so second call doesn't hit Claude", async () => {
    const uid = freshUserId();
    await generateWeeklyReport(uid, NOW);
    expect(mockMessagesCreate).toHaveBeenCalledTimes(1);

    await generateWeeklyReport(uid, NOW);
    expect(mockMessagesCreate).toHaveBeenCalledTimes(1); // no additional call
  });
});

// ---------------------------------------------------------------------------
// Error handling
// ---------------------------------------------------------------------------

describe("error handling", () => {
  it("throws when Claude returns invalid JSON", async () => {
    mockMessagesCreate.mockResolvedValue(
      claudeResponse("this is not valid JSON {{{"),
    );

    await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow();
  });

  it("throws when Claude returns empty report string", async () => {
    mockMessagesCreate.mockResolvedValue(
      claudeResponse(claudeReport({ report: "" })),
    );

    await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow(
      "invalid weekly report structure",
    );
  });

  it("throws when highlights array is missing", async () => {
    mockMessagesCreate.mockResolvedValue(
      claudeResponse(JSON.stringify({
        report: "A report",
        areasToFocus: ["something"],
        // highlights intentionally absent
      })),
    );

    await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow();
  });

  it("throws when highlights array is empty", async () => {
    mockMessagesCreate.mockResolvedValue(
      claudeResponse(claudeReport({ highlights: [] })),
    );

    await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow(
      "invalid weekly report structure",
    );
  });

  it("throws when areasToFocus array is empty", async () => {
    mockMessagesCreate.mockResolvedValue(
      claudeResponse(claudeReport({ areasToFocus: [] })),
    );

    await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow(
      "invalid weekly report structure",
    );
  });

  it("throws when areasToFocus is not an array", async () => {
    mockMessagesCreate.mockResolvedValue(
      claudeResponse(claudeReport({ areasToFocus: "not an array" })),
    );

    await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow();
  });

  it("throws when Claude network call fails", async () => {
    mockMessagesCreate.mockRejectedValue(new Error("Network error"));

    await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow(
      "Network error",
    );
  });

  it("does NOT cache on error β€” next call retries Claude", async () => {
    const uid = freshUserId();
    mockMessagesCreate.mockRejectedValueOnce(new Error("Transient failure"));

    // First call fails
    await expect(generateWeeklyReport(uid, NOW)).rejects.toThrow();

    // Reset to success
    mockMessagesCreate.mockResolvedValue(claudeResponse(claudeReport()));

    // Second call should succeed (no stale error cached)
    const result = await generateWeeklyReport(uid, NOW) as ReportResult;
    expect(result).not.toBeNull();
    expect(result.cached).toBe(false);
    expect(mockMessagesCreate).toHaveBeenCalledTimes(2); // first failed + second ok
  });
});

// ---------------------------------------------------------------------------
// Cache key isolation
// ---------------------------------------------------------------------------

describe("cache key isolation", () => {
  it("different userIds in the same week use separate cache entries", async () => {
    const uid1 = freshUserId();
    const uid2 = freshUserId();

    await generateWeeklyReport(uid1, NOW);
    expect(mockMessagesCreate).toHaveBeenCalledTimes(1);

    await generateWeeklyReport(uid2, NOW); // different user β€” different key
    expect(mockMessagesCreate).toHaveBeenCalledTimes(2);
  });

  it("same userId in a different week generates a fresh report", async () => {
    const uid = freshUserId();

    await generateWeeklyReport(uid, NOW); // week of 2026-03-16
    expect(mockMessagesCreate).toHaveBeenCalledTimes(1);

    const nextWeek = utcDay("2026-03-25"); // week of 2026-03-23
    await generateWeeklyReport(uid, nextWeek);
    expect(mockMessagesCreate).toHaveBeenCalledTimes(2);
  });

  it("same userId, different days within the same week share a cache key", async () => {
    const uid = freshUserId();

    await generateWeeklyReport(uid, utcDay("2026-03-16")); // Monday
    expect(mockMessagesCreate).toHaveBeenCalledTimes(1);

    await generateWeeklyReport(uid, utcDay("2026-03-18")); // Wednesday (same ISO week)
    expect(mockMessagesCreate).toHaveBeenCalledTimes(1); // cache hit β€” no extra Claude call
  });
});