Spaces:
Running
Running
File size: 11,610 Bytes
f0175ec | 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 | import { supabase } from '../firebaseClient';
import { getAllCatalogProblems, type CatalogProblem } from './catalogService';
import { batchActivateProblems } from './reviewService';
import type { ProblemSolution } from '../types/reviewTypes';
export interface ManagedCard {
id: string;
problem_number?: number;
name: string;
pattern: string;
difficulty: 'Easy' | 'Medium' | 'Hard';
description?: string;
reference_code?: string;
starter_code?: string;
optimal_time?: string;
optimal_space?: string;
how_to_solve?: string;
examples?: Array<{ input?: string; output?: string; explanation?: string } | string>;
constraints?: string[] | string;
solutions?: ProblemSolution[];
leetcode_url?: string;
// SRS Review details
is_enrolled: boolean;
is_custom: boolean;
fsrs_state: number | null; // 0=New, 1=Learning, 2=Review, 3=Relearning, null if not enrolled
fsrs_step?: number;
fsrs_stability?: number;
fsrs_difficulty?: number;
fsrs_elapsed_days?: number;
fsrs_scheduled_days?: number;
fsrs_reps?: number;
fsrs_lapses?: number;
next_review: string | null;
last_reviewed: string | null;
times_correct: number;
total_attempts: number;
is_due: boolean;
catalogProblem?: CatalogProblem;
}
interface RawExplorerProblem {
id: string;
name: string;
problem_number?: number;
pattern: string;
difficulty: 'Easy' | 'Medium' | 'Hard';
description?: string | null;
reference_code?: string | null;
starter_code?: string | null;
optimal_time?: string | null;
optimal_space?: string | null;
how_to_solve?: string | null;
examples?: Array<{ input?: string; output?: string; explanation?: string } | string> | null;
constraints?: string[] | string | null;
solutions?: ProblemSolution[] | string | null;
fsrs_state?: number | null;
fsrs_step?: number | null;
fsrs_stability?: number | null;
fsrs_difficulty?: number | null;
fsrs_elapsed_days?: number | null;
fsrs_scheduled_days?: number | null;
fsrs_reps?: number | null;
fsrs_lapses?: number | null;
next_review?: string | null;
last_reviewed?: string | null;
times_correct?: number | null;
total_attempts?: number | null;
}
async function getAuthToken(): Promise<string> {
try {
const { data: { session } } = await supabase.auth.getSession();
return session ? session.access_token : 'sandbox';
} catch {
return 'sandbox';
}
}
/**
* Normalizes title for consistent cross-database matching.
*/
function normalizeName(name: string): string {
return name.toLowerCase().replace(/\s*-\s*method.*$/i, '').replace(/[^a-z0-9]+/g, '');
}
function parseJsonSafe<T>(val: unknown): T | undefined {
if (typeof val === 'string') {
try {
return JSON.parse(val) as T;
} catch {
return undefined;
}
}
return (val as T) ?? undefined;
}
/**
* Loads all cards (catalog + custom problems) merged with user SRS review statistics.
*/
export async function fetchManagedCards(): Promise<ManagedCard[]> {
const token = await getAuthToken();
const catalog = getAllCatalogProblems();
let explorerProblems: RawExplorerProblem[] = [];
try {
const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (res.ok) {
explorerProblems = await res.json();
}
} catch {
// Graceful offline fallback
explorerProblems = [];
}
// Maps for efficient matching
const explorerByNum = new Map<number, RawExplorerProblem>();
const explorerByName = new Map<string, RawExplorerProblem>();
const matchedExplorerIds = new Set<string>();
for (const p of explorerProblems) {
if (p.problem_number !== undefined && p.problem_number !== null) {
explorerByNum.set(p.problem_number, p);
}
explorerByName.set(normalizeName(p.name), p);
}
const now = new Date();
const managedCards: ManagedCard[] = [];
// 1. Process curated catalog problems
for (const cat of catalog) {
const matched = explorerByNum.get(cat.problem_number) || explorerByName.get(normalizeName(cat.name));
if (matched) {
matchedExplorerIds.add(matched.id);
const isEnrolled = matched.next_review !== null && matched.next_review !== undefined || (matched.fsrs_state !== null && matched.fsrs_state !== undefined);
const nextReviewDate = matched.next_review ? new Date(matched.next_review) : null;
const isDue = isEnrolled && nextReviewDate !== null ? nextReviewDate <= now : false;
const parsedSolutions = parseJsonSafe<ProblemSolution[]>(matched.solutions);
const parsedExamples = parseJsonSafe<Array<{ input?: string; output?: string; explanation?: string } | string>>(matched.examples);
const parsedConstraints = parseJsonSafe<string[] | string>(matched.constraints);
managedCards.push({
id: matched.id,
problem_number: cat.problem_number,
name: cat.name,
pattern: cat.pattern,
difficulty: cat.difficulty,
description: matched.description || cat.description,
reference_code: matched.reference_code || cat.reference_solution,
starter_code: matched.starter_code || cat.starter_code,
optimal_time: matched.optimal_time || cat.time_complexity,
optimal_space: matched.optimal_space || cat.space_complexity,
how_to_solve: matched.how_to_solve || '',
examples: (parsedExamples && (Array.isArray(parsedExamples) ? parsedExamples.length > 0 : true))
? parsedExamples
: cat.examples,
constraints: (parsedConstraints && (Array.isArray(parsedConstraints) ? parsedConstraints.length > 0 : true))
? parsedConstraints
: cat.constraints,
solutions: parsedSolutions,
leetcode_url: cat.leetcode_url,
is_enrolled: isEnrolled,
is_custom: false,
fsrs_state: matched.fsrs_state ?? (isEnrolled ? 0 : null),
fsrs_step: matched.fsrs_step ?? 0,
fsrs_stability: matched.fsrs_stability ?? 0.0,
fsrs_difficulty: matched.fsrs_difficulty ?? 0.0,
fsrs_elapsed_days: matched.fsrs_elapsed_days ?? 0,
fsrs_scheduled_days: matched.fsrs_scheduled_days ?? 0,
fsrs_reps: matched.fsrs_reps ?? 0,
fsrs_lapses: matched.fsrs_lapses ?? 0,
next_review: matched.next_review ?? null,
last_reviewed: matched.last_reviewed ?? null,
times_correct: matched.times_correct ?? 0,
total_attempts: matched.total_attempts ?? 0,
is_due: isDue,
catalogProblem: cat
});
} else {
// Unenrolled catalog card
managedCards.push({
id: cat.id,
problem_number: cat.problem_number,
name: cat.name,
pattern: cat.pattern,
difficulty: cat.difficulty,
description: cat.description,
reference_code: cat.reference_solution,
starter_code: cat.starter_code,
optimal_time: cat.time_complexity,
optimal_space: cat.space_complexity,
how_to_solve: '',
examples: cat.examples,
constraints: cat.constraints,
leetcode_url: cat.leetcode_url,
is_enrolled: false,
is_custom: false,
fsrs_state: null,
fsrs_step: 0,
fsrs_stability: 0.0,
fsrs_difficulty: 0.0,
fsrs_elapsed_days: 0,
fsrs_scheduled_days: 0,
fsrs_reps: 0,
fsrs_lapses: 0,
next_review: null,
last_reviewed: null,
times_correct: 0,
total_attempts: 0,
is_due: false,
catalogProblem: cat
});
}
}
// 2. Add custom problems created by user not in curated catalog
for (const exp of explorerProblems) {
if (!matchedExplorerIds.has(exp.id)) {
const isEnrolled = exp.next_review !== null && exp.next_review !== undefined || (exp.fsrs_state !== null && exp.fsrs_state !== undefined);
const nextReviewDate = exp.next_review ? new Date(exp.next_review) : null;
const isDue = isEnrolled && nextReviewDate !== null ? nextReviewDate <= now : false;
const parsedSolutions = parseJsonSafe<ProblemSolution[]>(exp.solutions);
const parsedExamples = parseJsonSafe<Array<{ input?: string; output?: string; explanation?: string } | string>>(exp.examples) || [];
const parsedConstraints = parseJsonSafe<string[] | string>(exp.constraints) || [];
managedCards.push({
id: exp.id,
problem_number: exp.problem_number,
name: exp.name,
pattern: exp.pattern || 'General',
difficulty: exp.difficulty || 'Medium',
description: exp.description || '',
reference_code: exp.reference_code || '',
starter_code: exp.starter_code || '',
optimal_time: exp.optimal_time || 'O(N)',
optimal_space: exp.optimal_space || 'O(1)',
how_to_solve: exp.how_to_solve || '',
examples: parsedExamples,
constraints: parsedConstraints,
solutions: parsedSolutions,
is_enrolled: isEnrolled,
is_custom: true,
fsrs_state: exp.fsrs_state ?? (isEnrolled ? 0 : null),
fsrs_step: exp.fsrs_step ?? 0,
fsrs_stability: exp.fsrs_stability ?? 0.0,
fsrs_difficulty: exp.fsrs_difficulty ?? 0.0,
fsrs_elapsed_days: exp.fsrs_elapsed_days ?? 0,
fsrs_scheduled_days: exp.fsrs_scheduled_days ?? 0,
fsrs_reps: exp.fsrs_reps ?? 0,
fsrs_lapses: exp.fsrs_lapses ?? 0,
next_review: exp.next_review ?? null,
last_reviewed: exp.last_reviewed ?? null,
times_correct: exp.times_correct ?? 0,
total_attempts: exp.total_attempts ?? 0,
is_due: isDue
});
}
}
return managedCards;
}
/**
* Resets SRS review progress for one or more cards back to initial FSRS state due immediately.
*/
export async function resetCardReviews(problemIds: string[]): Promise<boolean> {
if (problemIds.length === 0) return true;
const token = await getAuthToken();
const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/reviews/reset`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ problem_ids: problemIds })
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: 'Failed to reset reviews' }));
throw new Error(err.detail || 'Failed to reset reviews');
}
return true;
}
/**
* Deletes a custom problem card from the database.
*/
export async function deleteCustomCard(problemId: string): Promise<boolean> {
const token = await getAuthToken();
const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/${problemId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: 'Failed to delete problem' }));
throw new Error(err.detail || 'Failed to delete problem');
}
return true;
}
/**
* Batch deletes multiple custom cards by ID.
*/
export async function deleteCustomCards(problemIds: string[]): Promise<number> {
let count = 0;
for (const id of problemIds) {
try {
await deleteCustomCard(id);
count++;
} catch {
// Continue deleting remaining cards
}
}
return count;
}
/**
* Enrolls catalog problems into the SRS review queue.
*/
export async function enrollCatalogCards(catalogProblems: CatalogProblem[]): Promise<number> {
if (catalogProblems.length === 0) return 0;
const result = await batchActivateProblems(catalogProblems);
return result.enrolled_count;
}
|