File size: 12,336 Bytes
65d68f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
// ─── Chapter progress β€” saved on this device ──────────────────────────────────
// Lightweight, on-device progress for curriculum chapters. Powers the
// progress-aware behaviour of the intelligent teach engine and /teach UI.
//
// SSR-safe: every accessor guards `window`. Corruption-safe: reads never throw,
// they fall back to an empty store. Follows the app's existing local-store
// conventions (docdoe_* key, docdoe:*-updated event).

import { getSubject, getChapter } from "./curriculum/index";
import type { ChapterMeta } from "./curriculum/types";

// ─── Public types ───────────────────────────────────────────────────────────

export type ChapterStatus =
  | "not_started"
  | "started"
  | "completed"
  | "revised"
  | "weak";

export type ConfidenceLevel = "low" | "medium" | "high";

export type ChapterProgressEntry = {
  key: string; // `${level}::${subjectSlug}::${chapterSlug}`
  level: string;
  subjectSlug: string;
  chapterSlug: string;
  status: ChapterStatus;
  studyCount: number;
  quizScore: number | null; // most recent quiz %, 0–100
  quizAttempts: number;
  weakTopics: string[];
  confidence: ConfidenceLevel | null;
  startedAt: string | null; // ISO
  lastStudied: string | null; // ISO
  completedAt: string | null; // ISO
};

export type RecommendationType = "revision" | "next" | "easy_win";

export type Recommendation = {
  level: string;
  subjectSlug: string;
  subjectName: string;
  chapter: ChapterMeta;
  reason: string;
  type: RecommendationType;
};

// ─── Storage plumbing ─────────────────────────────────────────────────────────

const STORAGE_KEY = "docdoe_chapter_progress";
export const PROGRESS_EVENT = "docdoe:chapter-progress-updated";

type ProgressStore = Record<string, ChapterProgressEntry>;

function canUseStorage(): boolean {
  return typeof window !== "undefined" && Boolean(window.localStorage);
}

function keyOf(level: string, subjectSlug: string, chapterSlug: string): string {
  return `${level}::${subjectSlug}::${chapterSlug}`;
}

function nowIso(): string {
  return new Date().toISOString();
}

function readStore(): ProgressStore {
  if (!canUseStorage()) return {};
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (!raw) return {};
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
    return parsed as ProgressStore;
  } catch {
    return {};
  }
}

function writeStore(store: ProgressStore): void {
  if (!canUseStorage()) return;
  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(store));
    window.dispatchEvent(new Event(PROGRESS_EVENT));
  } catch {
    // storage full / blocked β€” progress is best-effort, never crash the UI
  }
}

function emptyEntry(level: string, subjectSlug: string, chapterSlug: string): ChapterProgressEntry {
  return {
    key: keyOf(level, subjectSlug, chapterSlug),
    level,
    subjectSlug,
    chapterSlug,
    status: "not_started",
    studyCount: 0,
    quizScore: null,
    quizAttempts: 0,
    weakTopics: [],
    confidence: null,
    startedAt: null,
    lastStudied: null,
    completedAt: null,
  };
}

function mutate(
  level: string,
  subjectSlug: string,
  chapterSlug: string,
  apply: (entry: ChapterProgressEntry) => void,
): ChapterProgressEntry {
  const store = readStore();
  const key = keyOf(level, subjectSlug, chapterSlug);
  const entry = store[key] ?? emptyEntry(level, subjectSlug, chapterSlug);
  apply(entry);
  store[key] = entry;
  writeStore(store);
  return entry;
}

// ─── Reads ────────────────────────────────────────────────────────────────────

export function getChapterEntry(
  level: string,
  subjectSlug: string,
  chapterSlug: string,
): ChapterProgressEntry | null {
  const store = readStore();
  return store[keyOf(level, subjectSlug, chapterSlug)] ?? null;
}

export function getProgress(): ChapterProgressEntry[] {
  return Object.values(readStore());
}

export function statusLabel(status: ChapterStatus): string {
  switch (status) {
    case "not_started": return "Not started";
    case "started": return "In progress";
    case "completed": return "Completed";
    case "revised": return "Revised";
    case "weak": return "Needs revision";
  }
}

// ─── Writes ───────────────────────────────────────────────────────────────────

export function markChapterStarted(
  level: string,
  subjectSlug: string,
  chapterSlug: string,
): ChapterProgressEntry {
  return mutate(level, subjectSlug, chapterSlug, (e) => {
    e.studyCount += 1;
    e.lastStudied = nowIso();
    if (!e.startedAt) e.startedAt = nowIso();
    // Don't downgrade a completed/revised chapter just because it was reopened.
    if (e.status === "not_started") e.status = "started";
  });
}

export function markChapterCompleted(
  level: string,
  subjectSlug: string,
  chapterSlug: string,
): ChapterProgressEntry {
  return mutate(level, subjectSlug, chapterSlug, (e) => {
    e.status = "completed";
    e.completedAt = nowIso();
    e.lastStudied = nowIso();
    if (!e.startedAt) e.startedAt = nowIso();
  });
}

export function markChapterRevised(
  level: string,
  subjectSlug: string,
  chapterSlug: string,
): ChapterProgressEntry {
  return mutate(level, subjectSlug, chapterSlug, (e) => {
    e.status = "revised";
    e.lastStudied = nowIso();
    if (!e.startedAt) e.startedAt = nowIso();
  });
}

export function markChapterWeak(
  level: string,
  subjectSlug: string,
  chapterSlug: string,
  weakTopics?: string[],
): ChapterProgressEntry {
  return mutate(level, subjectSlug, chapterSlug, (e) => {
    e.status = "weak";
    e.lastStudied = nowIso();
    if (!e.startedAt) e.startedAt = nowIso();
    if (weakTopics && weakTopics.length > 0) {
      const merged = new Set([...e.weakTopics, ...weakTopics]);
      e.weakTopics = Array.from(merged).slice(0, 8);
    }
  });
}

export function saveQuizScore(
  level: string,
  subjectSlug: string,
  chapterSlug: string,
  score: number,
): ChapterProgressEntry {
  const clamped = Math.max(0, Math.min(100, Math.round(score)));
  return mutate(level, subjectSlug, chapterSlug, (e) => {
    e.quizScore = clamped;
    e.quizAttempts += 1;
    e.lastStudied = nowIso();
    if (!e.startedAt) e.startedAt = nowIso();
    if (clamped < 50) {
      e.status = "weak";
    } else if (e.status === "not_started" || e.status === "started") {
      // A solid score on an unfinished chapter counts as a pass-through revise.
      e.status = clamped >= 80 ? "revised" : "started";
    }
    e.confidence = clamped >= 80 ? "high" : clamped >= 50 ? "medium" : "low";
  });
}

export function resetChapter(
  level: string,
  subjectSlug: string,
  chapterSlug: string,
): void {
  const store = readStore();
  delete store[keyOf(level, subjectSlug, chapterSlug)];
  writeStore(store);
}

// ─── Subscriptions ──────────────────────────────────────────────────────────

/** Subscribe to progress changes on this device. Returns an unsubscribe fn. */
export function subscribeToProgress(listener: () => void): () => void {
  if (typeof window === "undefined") return () => {};
  const handler = () => listener();
  window.addEventListener(PROGRESS_EVENT, handler);
  window.addEventListener("storage", handler);
  return () => {
    window.removeEventListener(PROGRESS_EVENT, handler);
    window.removeEventListener("storage", handler);
  };
}

// ─── Recommendations ──────────────────────────────────────────────────────────

function isUnfinished(status: ChapterStatus): boolean {
  return status === "not_started" || status === "started";
}

/**
 * Suggest what to study next, blending three signals:
 *   - revision: chapters marked weak or with a low last quiz
 *   - next:     the next unfinished chapter in the preferred subject's sequence
 *   - easy_win: exam-relevant, easy chapters not yet completed
 *
 * When a subject is given, lead with the next chapter in that subject; otherwise
 * lead with revision. Deduped by chapter, capped at `n`.
 */
export function getRecommendedNextChapters(
  preferLevel?: string | null,
  preferSubject?: string | null,
  n = 3,
): Recommendation[] {
  const store = readStore();
  const entries = Object.values(store);

  const revisionRecs: Recommendation[] = [];
  for (const e of entries) {
    const isWeak = e.status === "weak";
    const lowQuiz = e.quizScore !== null && e.quizScore < 50;
    if (!isWeak && !lowQuiz) continue;
    const subject = getSubject(e.level, e.subjectSlug);
    const chapter = getChapter(e.level, e.subjectSlug, e.chapterSlug);
    if (!subject || !chapter) continue;
    const reason = isWeak
      ? "You marked this weak β€” revise it before moving on"
      : `Last quiz was ${e.quizScore}% β€” a revision will help`;
    revisionRecs.push({
      level: e.level,
      subjectSlug: e.subjectSlug,
      subjectName: subject.name,
      chapter,
      reason,
      type: "revision",
    });
  }

  const nextRecs: Recommendation[] = [];
  if (preferLevel && preferSubject) {
    const subject = getSubject(preferLevel, preferSubject);
    if (subject) {
      for (const chapter of subject.chapters) {
        const entry = store[keyOf(preferLevel, preferSubject, chapter.slug)];
        const status: ChapterStatus = entry?.status ?? "not_started";
        if (!isUnfinished(status)) continue;
        nextRecs.push({
          level: preferLevel,
          subjectSlug: preferSubject,
          subjectName: subject.name,
          chapter,
          reason:
            status === "started"
              ? `Continue your ${subject.name} sequence`
              : `Next up in ${subject.name}`,
          type: "next",
        });
        break; // only the single next chapter in sequence
      }
    }
  }

  const easyWinRecs: Recommendation[] = [];
  {
    const level = preferLevel ?? null;
    const subjectSlug = preferSubject ?? null;
    const subjects = subjectsToScan(level, subjectSlug);
    for (const ctx of subjects) {
      for (const chapter of ctx.subject.chapters) {
        const entry = store[keyOf(ctx.level, ctx.subjectSlug, chapter.slug)];
        const status: ChapterStatus = entry?.status ?? "not_started";
        if (status === "completed" || status === "revised") continue;
        const highYield = chapter.pyqFrequency === "very_high" || chapter.pyqFrequency === "high";
        if (highYield && chapter.difficulty === "easy") {
          easyWinRecs.push({
            level: ctx.level,
            subjectSlug: ctx.subjectSlug,
            subjectName: ctx.subject.name,
            chapter,
            reason: "Quick to learn β€” exam-relevant",
            type: "easy_win",
          });
        }
      }
    }
  }

  const ordered = preferSubject
    ? [...nextRecs, ...revisionRecs, ...easyWinRecs]
    : [...revisionRecs, ...nextRecs, ...easyWinRecs];

  const seen = new Set<string>();
  const deduped: Recommendation[] = [];
  for (const rec of ordered) {
    const id = keyOf(rec.level, rec.subjectSlug, rec.chapter.slug);
    if (seen.has(id)) continue;
    seen.add(id);
    deduped.push(rec);
    if (deduped.length >= n) break;
  }
  return deduped;
}

type SubjectScanContext = { level: string; subjectSlug: string; subject: { name: string; chapters: ChapterMeta[] } };

function subjectsToScan(level: string | null, subjectSlug: string | null): SubjectScanContext[] {
  if (level && subjectSlug) {
    const subject = getSubject(level, subjectSlug);
    return subject ? [{ level, subjectSlug, subject }] : [];
  }
  return [];
}