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(); // --------------------------------------------------------------------------- // 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 }; }