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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
import { describe, it, expect } from "vitest";
import {
  parseActivityMetadata,
  buildDomainProfiles,
  recommendDifficulty,
  getCalibratedTopics,
  type TopicAttempt,
  type KnowledgeProfile,
} from "@/lib/feynman/knowledge-profile";
import { FEYNMAN_TOPICS } from "@/lib/feynman/topics";

// ---------------------------------------------------------------------------
// parseActivityMetadata
// ---------------------------------------------------------------------------

describe("parseActivityMetadata", () => {
  it("parses valid metadata with a known topic", () => {
    const result = parseActivityMetadata({
      metadata: JSON.stringify({
        topic: "How a hash table works",
        wasTaught: false,
        accuracy: 8,
        completeness: 7,
        clarity: 9,
      }),
      score: 0.8,
      createdAt: new Date("2026-03-20T10:00:00Z"),
    });

    expect(result).not.toBeNull();
    expect(result!.topicId).toBe("cs-01");
    expect(result!.domain).toBe("CS");
    expect(result!.difficulty).toBe("beginner");
    expect(result!.score).toBe(0.8);
    expect(result!.wasTaught).toBe(false);
  });

  it("returns null for null metadata", () => {
    expect(
      parseActivityMetadata({
        metadata: null,
        score: 0.5,
        createdAt: new Date(),
      }),
    ).toBeNull();
  });

  it("returns null for malformed JSON", () => {
    expect(
      parseActivityMetadata({
        metadata: "not-json",
        score: 0.5,
        createdAt: new Date(),
      }),
    ).toBeNull();
  });

  it("returns null for metadata missing topic field", () => {
    expect(
      parseActivityMetadata({
        metadata: JSON.stringify({ accuracy: 8 }),
        score: 0.5,
        createdAt: new Date(),
      }),
    ).toBeNull();
  });

  it("handles wasTaught flag correctly", () => {
    const result = parseActivityMetadata({
      metadata: JSON.stringify({
        topic: "Newton's three laws of motion",
        wasTaught: true,
      }),
      score: 0.6,
      createdAt: new Date(),
    });

    expect(result).not.toBeNull();
    expect(result!.wasTaught).toBe(true);
    expect(result!.domain).toBe("Physics");
  });

  it("handles unknown topics with fallback IDs", () => {
    const result = parseActivityMetadata({
      metadata: JSON.stringify({ topic: "Quantum entanglement deep dive" }),
      score: 0.4,
      createdAt: new Date(),
    });

    expect(result).not.toBeNull();
    expect(result!.topicId).toContain("unknown-");
    expect(result!.domain).toBe("Unknown");
  });
});

// ---------------------------------------------------------------------------
// buildDomainProfiles
// ---------------------------------------------------------------------------

describe("buildDomainProfiles", () => {
  const mockAttempts: TopicAttempt[] = [
    {
      topicId: "cs-01",
      topic: "How a hash table works",
      domain: "CS",
      difficulty: "beginner",
      score: 0.8,
      wasTaught: false,
      attemptedAt: new Date("2026-03-18"),
    },
    {
      topicId: "cs-02",
      topic: "Big O notation and time complexity",
      domain: "CS",
      difficulty: "beginner",
      score: 0.6,
      wasTaught: true,
      attemptedAt: new Date("2026-03-19"),
    },
    {
      topicId: "ph-01",
      topic: "Newton's three laws of motion",
      domain: "Physics",
      difficulty: "beginner",
      score: 0.9,
      wasTaught: false,
      attemptedAt: new Date("2026-03-20"),
    },
  ];

  it("groups attempts by domain", () => {
    const profiles = buildDomainProfiles(mockAttempts);
    expect(profiles.size).toBe(2);
    expect(profiles.has("CS")).toBe(true);
    expect(profiles.has("Physics")).toBe(true);
  });

  it("calculates correct attempt counts", () => {
    const profiles = buildDomainProfiles(mockAttempts);
    expect(profiles.get("CS")!.attempts).toBe(2);
    expect(profiles.get("Physics")!.attempts).toBe(1);
  });

  it("calculates average scores", () => {
    const profiles = buildDomainProfiles(mockAttempts);
    expect(profiles.get("CS")!.avgScore).toBe(0.7); // (0.8 + 0.6) / 2
    expect(profiles.get("Physics")!.avgScore).toBe(0.9);
  });

  it("tracks taught count", () => {
    const profiles = buildDomainProfiles(mockAttempts);
    expect(profiles.get("CS")!.taughtCount).toBe(1);
    expect(profiles.get("Physics")!.taughtCount).toBe(0);
  });

  it("identifies mastered topics (avg score >= 0.7)", () => {
    const profiles = buildDomainProfiles(mockAttempts);
    expect(profiles.get("CS")!.masteredTopics).toContain("cs-01");
    expect(profiles.get("Physics")!.masteredTopics).toContain("ph-01");
  });

  it("tracks attempted topic IDs", () => {
    const profiles = buildDomainProfiles(mockAttempts);
    const cs = profiles.get("CS")!;
    expect(cs.attemptedTopicIds.has("cs-01")).toBe(true);
    expect(cs.attemptedTopicIds.has("cs-02")).toBe(true);
    expect(cs.attemptedTopicIds.has("cs-03")).toBe(false);
  });

  it("returns empty map for no attempts", () => {
    const profiles = buildDomainProfiles([]);
    expect(profiles.size).toBe(0);
  });
});

// ---------------------------------------------------------------------------
// recommendDifficulty
// ---------------------------------------------------------------------------

describe("recommendDifficulty", () => {
  it("recommends beginner for new users (< 3 attempts)", () => {
    expect(recommendDifficulty(0, 0)).toBe("beginner");
    expect(recommendDifficulty(1, 0.9)).toBe("beginner");
    expect(recommendDifficulty(2, 0.8)).toBe("beginner");
  });

  it("recommends intermediate for moderate experience", () => {
    expect(recommendDifficulty(5, 0.5)).toBe("intermediate");
    expect(recommendDifficulty(7, 0.6)).toBe("intermediate");
  });

  it("recommends expert for experienced users with strong scores", () => {
    expect(recommendDifficulty(10, 0.75)).toBe("expert");
    expect(recommendDifficulty(8, 0.65)).toBe("expert");
  });

  it("stays intermediate for experienced users with low scores", () => {
    expect(recommendDifficulty(15, 0.4)).toBe("intermediate");
  });
});

// ---------------------------------------------------------------------------
// getCalibratedTopics
// ---------------------------------------------------------------------------

describe("getCalibratedTopics", () => {
  function makeProfile(overrides: Partial<KnowledgeProfile> = {}): KnowledgeProfile {
    return {
      userId: 1,
      totalAttempts: 0,
      domains: new Map(),
      recentTopicIds: [],
      recommendedDifficulty: "beginner",
      ...overrides,
    };
  }

  it("returns 3 topics by default", () => {
    const topics = getCalibratedTopics(makeProfile());
    expect(topics).toHaveLength(3);
  });

  it("returns topics from the topic pool", () => {
    const topics = getCalibratedTopics(makeProfile());
    const allIds = new Set(FEYNMAN_TOPICS.map((t) => t.id));
    for (const t of topics) {
      expect(allIds.has(t.id)).toBe(true);
    }
  });

  it("returns unique topics", () => {
    const topics = getCalibratedTopics(makeProfile());
    const ids = topics.map((t) => t.id);
    expect(new Set(ids).size).toBe(ids.length);
  });

  it("avoids recently attempted topics when possible", () => {
    // Mark most beginner topics as recent
    const recentIds = FEYNMAN_TOPICS.filter((t) => t.difficulty === "beginner")
      .slice(0, 8)
      .map((t) => t.id);

    const profile = makeProfile({ recentTopicIds: recentIds });
    const topics = getCalibratedTopics(profile);

    // At least some topics should not be in the recent list
    const freshCount = topics.filter((t) => !recentIds.includes(t.id)).length;
    expect(freshCount).toBeGreaterThan(0);
  });

  it("filters by domain when specified", () => {
    const topics = getCalibratedTopics(makeProfile(), "CS");
    for (const t of topics) {
      expect(t.domain).toBe("CS");
    }
  });

  it("returns empty array for nonexistent domain", () => {
    const topics = getCalibratedTopics(makeProfile(), "Nonexistent");
    expect(topics).toHaveLength(0);
  });

  it("respects custom count", () => {
    const topics = getCalibratedTopics(makeProfile(), undefined, 2);
    expect(topics).toHaveLength(2);
  });

  it("prefers recommended difficulty level", () => {
    // Run 20 times to account for shuffle randomness
    let matchCount = 0;
    const profile = makeProfile({ recommendedDifficulty: "beginner", totalAttempts: 0 });
    for (let i = 0; i < 20; i++) {
      const topics = getCalibratedTopics(profile);
      const beginnerCount = topics.filter((t) => t.difficulty === "beginner").length;
      if (beginnerCount >= 1) matchCount++;
    }
    // Should include at least one beginner topic most of the time
    expect(matchCount).toBeGreaterThanOrEqual(15);
  });

  it("returns all available topics when pool is small", () => {
    // Philosophy has 6 topics; asking for 100
    const topics = getCalibratedTopics(makeProfile(), "Philosophy", 100);
    const philTopics = FEYNMAN_TOPICS.filter((t) => t.domain === "Philosophy");
    expect(topics).toHaveLength(philTopics.length);
  });

  // -------------------------------------------------------------------------
  // Prerequisite-aware selection (readyPool vs lockedPool logic)
  // -------------------------------------------------------------------------

  it("always includes topics with no prerequisites (beginners are always ready)", () => {
    // With an empty mastered set, topics with no prereqs should be available
    const profile = makeProfile({ recommendedDifficulty: "beginner" });
    // Run 20 times to account for shuffling
    let hasBeginnerCount = 0;
    for (let i = 0; i < 20; i++) {
      const topics = getCalibratedTopics(profile);
      const hasNoPrerequireds = topics.some((t) => !t.prerequisites?.length);
      if (hasNoPrerequireds) hasBeginnerCount++;
    }
    expect(hasBeginnerCount).toBeGreaterThanOrEqual(18);
  });

  it("preferentially returns ready topics when mastered set satisfies prerequisites", () => {
    // cs-05 requires cs-02. If we have mastered cs-02, cs-05 should become available.
    // cs-09 requires cs-01 AND cs-02 — both mastered here.
    const profile = makeProfile({
      recommendedDifficulty: "intermediate",
      totalAttempts: 5,
      domains: new Map([
        [
          "CS",
          {
            domain: "CS",
            attempts: 5,
            avgScore: 0.8,
            taughtCount: 0,
            masteredTopics: ["cs-01", "cs-02"],
            attemptedTopicIds: new Set(["cs-01", "cs-02"]),
          },
        ],
      ]),
    });

    // Run multiple times and assert that cs-05 (or another ready topic) can appear
    let readyTopicFound = false;
    for (let i = 0; i < 30; i++) {
      const topics = getCalibratedTopics(profile, "CS");
      // cs-05 requires cs-02 (mastered) — should be ready
      if (topics.some((t) => t.id === "cs-05")) {
        readyTopicFound = true;
        break;
      }
    }
    expect(readyTopicFound).toBe(true);
  });

  it("does not include locked topics when enough ready topics exist", () => {
    // For CS domain filtered to beginner, there are several topics with no prereqs.
    // With mastered = {} (nothing mastered), only topics with no prereqs are ready.
    // cs-03, cs-01, cs-02, cs-04, cs-06, cs-10 are beginner CS topics with no prereqs.
    // Asking for 3 should fill entirely from the ready pool.
    const profile = makeProfile({ recommendedDifficulty: "beginner" });
    const csTopicsNoPrereqs = FEYNMAN_TOPICS.filter(
      (t) => t.domain === "CS" && !t.prerequisites?.length,
    );

    // Sanity: should have at least 3 beginner no-prereq CS topics
    expect(csTopicsNoPrereqs.length).toBeGreaterThanOrEqual(3);

    // Run 20 times; verify returned topics are all from the no-prereq set
    let allReadyCount = 0;
    for (let i = 0; i < 20; i++) {
      const topics = getCalibratedTopics(profile, "CS", 3);
      const allReady = topics.every(
        (t) => !t.prerequisites?.length || t.prerequisites.length === 0,
      );
      if (allReady) allReadyCount++;
    }
    // Should almost always return ready-only topics when enough exist
    expect(allReadyCount).toBeGreaterThanOrEqual(15);
  });

  it("may include a locked topic when the ready pool is small (step 5 fallback)", () => {
    // cs-08 requires cs-06 (no prereqs itself), so mastering cs-06 is not satisfied here.
    // We ask for enough topics that the locked pool must be used.
    // In CS domain: mark almost all no-prereq topics as recent to shrink the fresh pool,
    // but keep mastered empty so topics with prereqs are locked.
    const noPrereqCsIds = FEYNMAN_TOPICS.filter(
      (t) => t.domain === "CS" && !t.prerequisites?.length,
    ).map((t) => t.id);

    const profile = makeProfile({
      recentTopicIds: noPrereqCsIds, // all no-prereq CS topics are recent
      recommendedDifficulty: "intermediate",
      totalAttempts: 6,
    });

    // Requesting 5 topics from CS with no prereqs marked as recent.
    // Since fresh pool is small, the fallback paths must draw from locked pool.
    let lockedTopicSeen = false;
    for (let i = 0; i < 30; i++) {
      const topics = getCalibratedTopics(profile, "CS", 5);
      if (topics.some((t) => t.prerequisites && t.prerequisites.length > 0)) {
        lockedTopicSeen = true;
        break;
      }
    }
    expect(lockedTopicSeen).toBe(true);
  });

  it("returned topics are always unique even when mixing ready and locked pools", () => {
    // Stress test: run 50 iterations, assert no duplicates regardless of path taken
    const profile = makeProfile({ recommendedDifficulty: "intermediate", totalAttempts: 4 });
    for (let i = 0; i < 50; i++) {
      const topics = getCalibratedTopics(profile, "CS", 4);
      const ids = topics.map((t) => t.id);
      expect(new Set(ids).size).toBe(ids.length);
    }
  });

  it("topics with all prerequisites mastered appear before topics with unmet prerequisites", () => {
    // ph-04 requires ph-01 + ph-02. We master ph-01 and ph-02, making ph-04 ready.
    // ph-07 requires ph-04 (not yet mastered here) — ph-07 remains locked.
    const profile = makeProfile({
      recommendedDifficulty: "expert",
      totalAttempts: 10,
      domains: new Map([
        [
          "Physics",
          {
            domain: "Physics",
            attempts: 10,
            avgScore: 0.75,
            taughtCount: 0,
            masteredTopics: ["ph-01", "ph-02"],
            attemptedTopicIds: new Set(["ph-01", "ph-02"]),
          },
        ],
      ]),
    });

    // ph-04 (prereqs: ph-01, ph-02 — both mastered) should be reachable
    let ph04Found = false;
    // ph-07 (prereq: ph-04 — not mastered) should also be reachable (Step 5 locked path)
    // but ph-04 should appear before ph-07 across multiple runs
    for (let i = 0; i < 30; i++) {
      const topics = getCalibratedTopics(profile, "Physics", 3);
      if (topics.some((t) => t.id === "ph-04")) {
        ph04Found = true;
        break;
      }
    }
    expect(ph04Found).toBe(true);
  });
});