File size: 4,827 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
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<PerformanceSummary> {
  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<string, typeof activities>();
  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,
  };
}