import { prisma } from "@/lib/db"; import { CATEGORIES, Category, CATEGORY_LABELS } from "@/config/xp"; /** * Trend direction based on comparing recent vs older performance. */ export type Trend = "improving" | "declining" | "stable" | "new"; export interface CategoryPerformance { category: Category; label: string; successRate: number; // 0-100 attempts: number; avgScore: number; // 0-1 avgDurationSecs: number | null; totalXp: number; level: number; trend: Trend; } export interface PerformanceSummary { categories: CategoryPerformance[]; overallScore: number; // 0-100 weighted average streakDays: number; longestStreak: number; totalExercises: number; activeDays: number; lastActivityAt: string | null; } /** * Minimum attempts required for a meaningful trend calculation. */ const MIN_TREND_ATTEMPTS = 3; /** * Threshold for trend detection. ±5pp is considered stable. */ const TREND_THRESHOLD = 0.05; /** * Determine trend by comparing the average score of recent activities * (last N/2) to older activities (first N/2). */ export function computeTrend(scores: number[]): Trend { if (scores.length < MIN_TREND_ATTEMPTS) return "new"; const midpoint = Math.floor(scores.length / 2); const older = scores.slice(0, midpoint); const recent = scores.slice(midpoint); const olderAvg = older.reduce((s, v) => s + v, 0) / older.length; const recentAvg = recent.reduce((s, v) => s + v, 0) / recent.length; const diff = recentAvg - olderAvg; if (diff > TREND_THRESHOLD) return "improving"; if (diff < -TREND_THRESHOLD) return "declining"; return "stable"; } /** * Calculate success rate: percentage of activities with score >= 0.6 (passing). */ export function calcSuccessRate( activities: { score: number | null }[], ): number { const scored = activities.filter((a) => a.score !== null); if (scored.length === 0) return 0; const passed = scored.filter((a) => (a.score ?? 0) >= 0.6).length; return Math.round((passed / scored.length) * 1000) / 10; } /** * Build a full performance summary for a user. */ export async function getPerformanceSummary( userId: number, ): Promise { const user = await prisma.user.findUniqueOrThrow({ where: { id: userId }, include: { categorySkills: true }, }); // Fetch all activities ordered chronologically (oldest first for trend calc) const activities = await prisma.activity.findMany({ where: { userId }, orderBy: { createdAt: "asc" }, }); // Group by category const byCat = new Map(); for (const a of activities) { const arr = byCat.get(a.category) ?? []; arr.push(a); byCat.set(a.category, arr); } // Build category performance array const categories: CategoryPerformance[] = CATEGORIES.map((cat) => { const catActivities = byCat.get(cat) ?? []; const skill = user.categorySkills.find( (cs: { category: string }) => cs.category === cat, ); const scored = catActivities.filter((a) => a.score !== null); const scores = scored.map((a) => a.score ?? 0); const avgScore = scores.length > 0 ? Math.round((scores.reduce((s, v) => s + v, 0) / scores.length) * 100) / 100 : 0; const durActivities = catActivities.filter((a) => a.durationSecs !== null); const avgDurationSecs = durActivities.length > 0 ? Math.round( durActivities.reduce((s, a) => s + (a.durationSecs ?? 0), 0) / durActivities.length, ) : null; const totalXp = catActivities.reduce((s, a) => s + a.totalXp, 0); return { category: cat, label: CATEGORY_LABELS[cat], successRate: calcSuccessRate(catActivities), attempts: catActivities.length, avgScore, avgDurationSecs, totalXp, level: skill?.level ?? 1, trend: computeTrend(scores), }; }); // Overall weighted score (weighted by attempt count) const totalAttempts = categories.reduce((s, c) => s + c.attempts, 0); const overallScore = totalAttempts > 0 ? Math.round( (categories.reduce((s, c) => s + c.successRate * c.attempts, 0) / totalAttempts) * 10, ) / 10 : 0; // Count distinct active days const activeDaySet = new Set( activities.map((a) => { const d = new Date(a.createdAt); return `${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`; }), ); const lastActivity = activities.length > 0 ? activities[activities.length - 1].createdAt.toISOString() : null; return { categories, overallScore, streakDays: user.streak, longestStreak: user.longestStreak, totalExercises: totalAttempts, activeDays: activeDaySet.size, lastActivityAt: lastActivity, }; }