File size: 7,319 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
import type { PerformanceSummary, CategoryPerformance } from "./performance";
import type { Category } from "@/config/xp";
import { CATEGORIES } from "@/config/xp";

export type DifficultyLevel = "easy" | "medium" | "hard";

// ---------------------------------------------------------------------------
// Thresholds
// ---------------------------------------------------------------------------

/** Success rate (0–100) below which we recommend easy difficulty */
const EASY_THRESHOLD = 40;

/** Success rate (0–100) at or above which we recommend hard difficulty */
const HARD_THRESHOLD = 70;

/** Streak days at or above which we boost difficulty one level */
const HOT_STREAK_DAYS = 5;

// ---------------------------------------------------------------------------
// Core selectors
// ---------------------------------------------------------------------------

/**
 * Select a base difficulty level from a success rate (0–100).
 *
 *   < 40%  β†’ easy   (user is struggling)
 *   40–69% β†’ medium (building consistency)
 *   β‰₯ 70%  β†’ hard   (ready for a challenge)
 */
export function selectDifficulty(successRate: number): DifficultyLevel {
  if (successRate < EASY_THRESHOLD) return "easy";
  if (successRate < HARD_THRESHOLD) return "medium";
  return "hard";
}

/**
 * Shift a difficulty one step up or down, clamped to valid values.
 */
function bumpDifficulty(
  level: DifficultyLevel,
  direction: "up" | "down",
): DifficultyLevel {
  const order: DifficultyLevel[] = ["easy", "medium", "hard"];
  const idx = order.indexOf(level);
  const next = direction === "up" ? idx + 1 : idx - 1;
  return order[Math.max(0, Math.min(2, next))];
}

// ---------------------------------------------------------------------------
// Next-skill labels per category and level band
// ---------------------------------------------------------------------------

const NEXT_SKILL_MAP: Record<Category, [string, string, string]> = {
  chess: [
    "basic tactics",
    "pattern recognition",
    "complex combinations",
  ],
  reading: [
    "active recall",
    "inference & analysis",
    "critical evaluation",
  ],
  feynman: [
    "concept fundamentals",
    "simplified explanation",
    "teaching mastery",
  ],
  logic: [
    "basic deduction",
    "multi-step reasoning",
    "complex problem solving",
  ],
  "critical-thinking": [
    "identifying fallacies",
    "argument reconstruction",
    "steelman & synthesis",
  ],
  quests: [
    "foundational concepts",
    "applied knowledge",
    "expert application",
  ],
  coding: [
    "core implementation",
    "debugging & review",
    "system architecture",
  ],
};

function getNextSkill(category: Category, level: number): string {
  const [beginner, intermediate, advanced] = NEXT_SKILL_MAP[category];
  if (level <= 2) return beginner;
  if (level <= 5) return intermediate;
  return advanced;
}

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

export interface DifficultyRecommendation {
  difficulty: DifficultyLevel;
  nextSkill: string;
  adjustmentReason: string;
  /** False when the category has no activity history (brand-new user). */
  hasHistory: boolean;
}

export interface DifficultyRecommendations {
  recommendations: Record<Category, DifficultyRecommendation>;
  updatedAt: string;
}

// ---------------------------------------------------------------------------
// Main recommendation builder
// ---------------------------------------------------------------------------

/**
 * Compute per-category difficulty recommendations from a performance summary.
 *
 * Adjustment rules (applied in order):
 *  1. Base difficulty from success rate bands.
 *  2. Hot streak (β‰₯ 5 days): bump up one level.
 *  3. Cold streak (0 days, but user has some history): bump down one level.
 *  4. Improving trend: bump up one level (capped at hard).
 *  5. Declining trend: bump down one level (capped at easy).
 *
 * Edge cases:
 *  - Category with 0 attempts: returns medium with hasHistory = false.
 *  - Brand-new user (totalExercises = 0): all categories get hasHistory = false.
 */
export function getRecommendedSettings(
  summary: PerformanceSummary,
): DifficultyRecommendations {
  const recommendations = {} as Record<Category, DifficultyRecommendation>;

  for (const cat of summary.categories as CategoryPerformance[]) {
    const category = cat.category;

    // No history for this category yet
    if (cat.attempts === 0) {
      recommendations[category] = {
        difficulty: "medium",
        nextSkill: getNextSkill(category, cat.level),
        adjustmentReason: "No activity yet β€” starting at medium difficulty",
        hasHistory: false,
      };
      continue;
    }

    // --- Step 1: base difficulty from success rate ---
    let adjusted = selectDifficulty(cat.successRate);
    const reasons: string[] = [buildBaseReason(adjusted, cat.successRate)];

    // --- Step 2: hot streak boost ---
    if (summary.streakDays >= HOT_STREAK_DAYS) {
      const bumped = bumpDifficulty(adjusted, "up");
      if (bumped !== adjusted) {
        adjusted = bumped;
        reasons.push(`hot streak (${summary.streakDays} days) boosted difficulty`);
      }
    }

    // --- Step 3: cold/broken streak reduction ---
    if (summary.streakDays === 0 && summary.totalExercises > 0) {
      const bumped = bumpDifficulty(adjusted, "down");
      if (bumped !== adjusted) {
        adjusted = bumped;
        reasons.push("easing back in after a break");
      }
    }

    // --- Step 4 & 5: trend adjustment ---
    if (cat.trend === "improving") {
      const bumped = bumpDifficulty(adjusted, "up");
      if (bumped !== adjusted) {
        adjusted = bumped;
        reasons.push("upward trend detected");
      }
    } else if (cat.trend === "declining") {
      const bumped = bumpDifficulty(adjusted, "down");
      if (bumped !== adjusted) {
        adjusted = bumped;
        reasons.push("declining trend detected");
      }
    }

    recommendations[category] = {
      difficulty: adjusted,
      nextSkill: getNextSkill(category, cat.level),
      adjustmentReason: reasons.join(" β€” "),
      hasHistory: true,
    };
  }

  // Ensure all categories are present even if missing from summary.categories
  for (const cat of CATEGORIES) {
    if (!recommendations[cat]) {
      recommendations[cat] = {
        difficulty: "medium",
        nextSkill: getNextSkill(cat, 1),
        adjustmentReason: "No activity yet β€” starting at medium difficulty",
        hasHistory: false,
      };
    }
  }

  return {
    recommendations,
    updatedAt: new Date().toISOString(),
  };
}

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

function buildBaseReason(
  difficulty: DifficultyLevel,
  successRate: number,
): string {
  const pct = successRate.toFixed(1);
  switch (difficulty) {
    case "easy":
      return `Low success rate (${pct}%) β€” focusing on fundamentals`;
    case "medium":
      return `Moderate success rate (${pct}%) β€” building consistency`;
    case "hard":
      return `High success rate (${pct}%) β€” ready for a challenge`;
  }
}