File size: 29,439 Bytes
664a5eb
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
1993562
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
 
664a5eb
8800c81
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
 
 
664a5eb
8800c81
664a5eb
8800c81
 
 
 
 
664a5eb
 
 
 
8800c81
 
 
 
 
 
664a5eb
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
 
8800c81
 
664a5eb
8800c81
 
 
f0175ec
8800c81
 
f0175ec
 
 
 
 
 
 
 
 
8800c81
 
 
 
664a5eb
 
 
 
 
 
8800c81
 
 
 
 
664a5eb
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664a5eb
 
8800c81
 
 
 
 
 
 
 
664a5eb
8800c81
 
664a5eb
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
1993562
8800c81
1993562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
 
1993562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
 
 
 
f0175ec
aa1fcca
f0175ec
 
 
 
 
 
 
 
 
 
 
8800c81
a42236e
 
 
 
664a5eb
8800c81
 
 
 
a42236e
664a5eb
 
 
a42236e
 
 
 
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
a42236e
 
 
 
 
 
8800c81
 
 
 
 
 
664a5eb
 
8800c81
 
 
664a5eb
8800c81
664a5eb
8800c81
a42236e
664a5eb
 
8800c81
664a5eb
 
 
 
 
8800c81
664a5eb
8800c81
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a42236e
 
 
 
 
 
664a5eb
8800c81
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a42236e
 
 
664a5eb
a42236e
 
664a5eb
 
a42236e
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0175ec
664a5eb
 
f0175ec
 
 
 
 
 
 
 
 
664a5eb
 
 
 
 
 
 
 
 
8800c81
 
 
 
664a5eb
 
 
8800c81
 
a42236e
664a5eb
 
 
 
8800c81
664a5eb
 
 
 
 
8800c81
664a5eb
 
8800c81
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a42236e
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
f0175ec
664a5eb
 
f0175ec
 
 
 
 
 
 
 
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
664a5eb
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
664a5eb
 
8800c81
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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
import asyncio
import csv
import io
import os
import re
import sqlite3
import tempfile
import zipfile
from datetime import UTC, datetime
from typing import Any

from fastapi import APIRouter, Depends, File, Header, HTTPException, Request, UploadFile
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

import cache
import db
import gdoc_writer
import llm_reviewer
from core.auth import Client, get_auth_session
from core.limiter import check_burst_rate_limit

router = APIRouter(tags=["explorer"])


class CreateProblemRequest(BaseModel):
    name: str
    pattern: str
    difficulty: str
    reference_code: str
    description: str = ""
    problem_number: int | None = None
    optimal_time: str | None = "O(N)"
    optimal_space: str | None = "O(N)"
    examples: Any | None = None
    constraints: Any | None = None
    how_to_solve: str | None = ""
    sync_to_gdoc: bool | None = True
    google_doc_id: str | None = None
    solutions: list[dict] | None = None


class UpdateProblemRequest(BaseModel):
    name: str
    pattern: str
    difficulty: str
    reference_code: str
    description: str = ""
    problem_number: int | None = None
    optimal_time: str | None = "O(N)"
    optimal_space: str | None = "O(N)"
    examples: Any | None = None
    constraints: Any | None = None
    how_to_solve: str | None = ""
    solutions: list[dict] | None = None


class FetchLeetCodeRequest(BaseModel):
    query: str


class PrefillProblemRequest(BaseModel):
    name: str = ""
    code: str = ""


class AssistFieldRequest(BaseModel):
    field: str  # 'intuition', 'comments'
    title: str = ""
    code: str = ""
    description: str = ""


@router.post("/api/explorer/problems/fetch-leetcode")
async def fetch_leetcode_endpoint(
    req: FetchLeetCodeRequest,
    request: Request,
    x_ai_provider: str = Header(None),
    x_custom_api_key: str = Header(None),
    x_gemini_api_key: str = Header(None),
):
    if not req.query.strip():
        raise HTTPException(status_code=400, detail="Query cannot be empty")
    api_key = x_custom_api_key or x_gemini_api_key
    check_burst_rate_limit(request, api_key)
    res = await llm_reviewer.fetch_leetcode_problem_async(
        req.query, custom_api_key=api_key, custom_provider=x_ai_provider
    )
    if "error" in res:
        raise HTTPException(status_code=500, detail=res["error"])
    return res


@router.post("/api/explorer/problems/prefill")
async def prefill_problem_endpoint(
    req: PrefillProblemRequest,
    request: Request,
    x_ai_provider: str = Header(None),
    x_custom_api_key: str = Header(None),
    x_gemini_api_key: str = Header(None),
):
    api_key = x_custom_api_key or x_gemini_api_key
    check_burst_rate_limit(request, api_key)
    if req.name.strip().startswith("http") or "leetcode.com" in req.name:
        res = await llm_reviewer.fetch_leetcode_problem_async(
            req.name, custom_api_key=api_key, custom_provider=x_ai_provider
        )
    else:
        res = await llm_reviewer.prefill_problem_details_async(
            req.name, req.code, custom_api_key=api_key, custom_provider=x_ai_provider
        )
    if "error" in res:
        raise HTTPException(status_code=500, detail=res["error"])
    return res


@router.post("/api/explorer/problems/assist-field")
async def assist_field_endpoint(
    req: AssistFieldRequest,
    request: Request,
    x_ai_provider: str = Header(None),
    x_custom_api_key: str = Header(None),
    x_gemini_api_key: str = Header(None),
):
    api_key = x_custom_api_key or x_gemini_api_key
    check_burst_rate_limit(request, api_key)
    if req.field == "intuition":
        res = await llm_reviewer.generate_how_to_solve_intuition_async(
            req.title,
            req.code,
            req.description,
            custom_api_key=api_key,
            custom_provider=x_ai_provider,
        )
    elif req.field == "comments":
        res = await llm_reviewer.format_code_with_emoji_comments_async(
            req.code, req.title, custom_api_key=api_key, custom_provider=x_ai_provider
        )
    else:
        raise HTTPException(status_code=400, detail=f"Unknown field assist type: {req.field}")
    if "error" in res:
        raise HTTPException(status_code=500, detail=res["error"])
    return res


@router.get("/api/explorer/problems")
async def get_explorer_problems(client: Client = Depends(get_auth_session)):
    try:
        return await asyncio.to_thread(db.get_all_problems_with_reviews, client)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/api/explorer/problems/create")
async def create_explorer_problem(
    req: CreateProblemRequest, client: Client = Depends(get_auth_session)
):
    user_id = await asyncio.to_thread(db.get_current_user_id, client)
    if not user_id:
        raise HTTPException(status_code=401, detail="Authentication failed")

    if not req.name.strip():
        raise HTTPException(status_code=400, detail="Problem name cannot be empty")

    def _create_problem_record():
        existing = db.get_problem_by_name(req.name, client)
        if existing:
            raise ValueError(f"A problem named '{req.name}' already exists.")

        prob_data = {
            "name": req.name.strip(),
            "pattern": req.pattern.strip() or "General",
            "difficulty": req.difficulty or "Medium",
            "reference_code": req.reference_code,
            "description": req.description,
            "problem_number": req.problem_number,
            "optimal_time": req.optimal_time or "O(N)",
            "optimal_space": req.optimal_space or "O(N)",
            "examples": req.examples or [],
            "constraints": req.constraints or [],
            "how_to_solve": req.how_to_solve or "",
        }
        if req.solutions is not None:
            prob_data["solutions"] = req.solutions
        res_prob = db.insert_problem(prob_data, client)
        if not res_prob or not res_prob.data:
            raise RuntimeError("Failed to create problem record")

        new_prob_id = res_prob.data[0]["id"]

        now_iso = datetime.now(UTC).isoformat()
        review_data = {
            "problem_id": new_prob_id,
            "fsrs_state": 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": now_iso,
            "last_reviewed": now_iso,
            "times_correct": 0,
            "total_attempts": 0,
        }
        db.insert_review(review_data, client)
        return new_prob_id

    try:
        new_prob_id = await asyncio.to_thread(_create_problem_record)
        await asyncio.to_thread(cache.delete_cache, f"due_reviews:{user_id}")
        await asyncio.to_thread(cache.delete_cache, f"all_problems_reviews:{user_id}")

        # Dual-Write: Append/Update to Google Doc if requested
        gdoc_result = None
        if req.sync_to_gdoc:
            try:
                gdoc_result = await asyncio.to_thread(
                    gdoc_writer.append_or_update_problem_in_doc,
                    doc_id=req.google_doc_id,
                    problem_number=req.problem_number,
                    problem_name=req.name,
                    difficulty=req.difficulty,
                    pattern=req.pattern,
                    description=req.description,
                    examples=req.examples,
                    constraints=req.constraints,
                    optimal_time=req.optimal_time or "O(N)",
                    optimal_space=req.optimal_space or "O(N)",
                    how_to_solve=req.how_to_solve or "",
                    reference_code=req.reference_code,
                    method_name=req.pattern,
                )
                if gdoc_result and gdoc_result.get("doc_url"):
                    await asyncio.to_thread(
                        db.update_problem,
                        new_prob_id,
                        {
                            "google_doc_url": gdoc_result["doc_url"],
                            "google_doc_id": gdoc_result["doc_id"],
                        },
                        client,
                    )
            except Exception as e:
                await asyncio.to_thread(db.log_trace, f"Dual-write Google Doc error: {str(e)}")

        return {"success": True, "problem_id": new_prob_id, "gdoc_result": gdoc_result}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/api/explorer/problems/{problem_id}")
def update_explorer_problem(
    problem_id: str, req: UpdateProblemRequest, client: Client = Depends(get_auth_session)
):
    user_id = db.get_current_user_id(client)
    if not user_id:
        raise HTTPException(status_code=401, detail="Authentication failed")

    try:
        update_data = {
            "name": req.name.strip(),
            "pattern": req.pattern.strip() or "General",
            "difficulty": req.difficulty or "Medium",
            "reference_code": req.reference_code,
            "description": req.description,
            "problem_number": req.problem_number,
            "optimal_time": req.optimal_time or "O(N)",
            "optimal_space": req.optimal_space or "O(N)",
        }
        if req.examples is not None:
            update_data["examples"] = req.examples
        if req.constraints is not None:
            update_data["constraints"] = req.constraints
        if req.how_to_solve is not None:
            update_data["how_to_solve"] = req.how_to_solve
        if req.solutions is not None:
            update_data["solutions"] = req.solutions
            if req.solutions:
                optimal_sol = next(
                    (s for s in req.solutions if s.get("is_optimal")), req.solutions[0]
                )
                if optimal_sol:
                    if optimal_sol.get("pattern"):
                        update_data["pattern"] = optimal_sol["pattern"]
                    if optimal_sol.get("time_complexity"):
                        update_data["optimal_time"] = optimal_sol["time_complexity"]
                    if optimal_sol.get("space_complexity"):
                        update_data["optimal_space"] = optimal_sol["space_complexity"]
                    if optimal_sol.get("code"):
                        update_data["reference_code"] = optimal_sol["code"]

        # 1. First attempt to update directly with problem_id
        res = db.update_problem(problem_id, update_data, client)
        if res and res.data:
            cache.delete_cache(f"due_reviews:{user_id}")
            cache.delete_cache(f"all_problems_reviews:{user_id}")
            return {"success": True, "problem_id": problem_id}

        # 2. Resolve by problem_number or name if exact ID didn't match existing record
        existing = None
        if req.problem_number is not None:
            probs = db.get_problems_by_number(req.problem_number, client)
            user_probs = [p for p in probs if p.get("user_id") == user_id]
            if user_probs:
                existing = user_probs[0]

        if not existing and req.name:
            named_p = db.get_problem_by_name(req.name, client)
            if named_p and (named_p.get("user_id") == user_id or not named_p.get("user_id")):
                existing = named_p

        if existing:
            target_id = existing["id"]
            res = db.update_problem(target_id, update_data, client)
            cache.delete_cache(f"due_reviews:{user_id}")
            cache.delete_cache(f"all_problems_reviews:{user_id}")
            return {"success": True, "problem_id": target_id}

        # 3. If problem is in catalog/queue but not yet in personal table, insert it!
        prob_data = {
            "name": req.name.strip(),
            "problem_number": req.problem_number,
            "pattern": req.pattern.strip() or "General",
            "difficulty": req.difficulty or "Medium",
            "optimal_time": req.optimal_time or "O(N)",
            "optimal_space": req.optimal_space or "O(N)",
            "description": req.description or "",
            "reference_code": req.reference_code or "",
            "examples": req.examples or [],
            "constraints": req.constraints or [],
            "how_to_solve": req.how_to_solve or "",
        }
        if req.solutions is not None:
            prob_data["solutions"] = req.solutions
        res_p = db.insert_problem(prob_data, client)
        if res_p and res_p.data:
            new_id = res_p.data[0]["id"]
            # link any reviews
            revs = db.get_reviews_by_problem_id(problem_id, client)
            for r in revs:
                if (r.get("user_id") == user_id or not r.get("user_id")) and r.get("id"):
                    db.update_review(r["id"], {"problem_id": new_id}, client)
            cache.delete_cache(f"due_reviews:{user_id}")
            cache.delete_cache(f"all_problems_reviews:{user_id}")
            return {"success": True, "problem_id": new_id}

        raise HTTPException(status_code=500, detail="Failed to update or create problem record")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/api/explorer/problems/{problem_id}")
async def delete_explorer_problem(problem_id: str, client: Client = Depends(get_auth_session)):
    user_id = await asyncio.to_thread(db.get_current_user_id, client)
    if not user_id:
        raise HTTPException(status_code=401, detail="Authentication failed")

    success = await asyncio.to_thread(db.delete_problem, problem_id, client)
    if not success:
        raise HTTPException(status_code=404, detail="Problem not found or could not be deleted")

    return {"success": True, "problem_id": problem_id}


@router.get("/api/explorer/export")
async def export_solutions_zip(
    compression: str = "deflate",
    client: Client = Depends(get_auth_session),
):
    user_id = await asyncio.to_thread(db.get_current_user_id, client)
    if not user_id:
        raise HTTPException(status_code=401, detail="Authentication failed")

    try:

        def _generate_zip() -> io.BytesIO:
            problems = db.get_all_problems(client)
            zip_buffer = io.BytesIO()
            is_zstd = compression.lower() in ("zstd", "zstandard") and hasattr(
                zipfile, "ZIP_ZSTANDARD"
            )
            compress_type = zipfile.ZIP_ZSTANDARD if is_zstd else zipfile.ZIP_DEFLATED
            with zipfile.ZipFile(zip_buffer, "w", compress_type) as zip_file:
                for p in problems:
                    name = p.get("name", "Unnamed_Problem")
                    pattern = p.get("pattern", "General")
                    difficulty = p.get("difficulty", "Medium")
                    code = p.get("reference_code", "")
                    description = p.get("description", "")

                    safe_name = re.sub(r"[^\w\-]", "_", name)
                    filename = f"{safe_name}.py"

                    if not code or not code.strip():
                        desc_comment = f"\n# Description: {description}" if description else ""
                        code = f"# Problem: {name}\n# Pattern: {pattern}\n# Difficulty: {difficulty}{desc_comment}\n# Write your solution here!\n\ndef solve():\n    pass\n"
                    else:
                        if description:
                            formatted_desc = "\n".join(
                                [f"# {line}" for line in description.splitlines()]
                            )
                            code = f"# Description:\n{formatted_desc}\n\n" + code

                    zip_file.writestr(filename, code)

            zip_buffer.seek(0)
            return zip_buffer

        zip_buffer = await asyncio.to_thread(_generate_zip)

        filename = (
            "algospaced_solutions_zstd.zip"
            if compression.lower() in ("zstd", "zstandard")
            else "algospaced_solutions.zip"
        )
        headers = {"Content-Disposition": f"attachment; filename={filename}"}
        return StreamingResponse(zip_buffer, media_type="application/zip", headers=headers)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/api/explorer/import")
async def import_problems(file: UploadFile = File(...), client: Client = Depends(get_auth_session)):
    user_id = await asyncio.to_thread(db.get_current_user_id, client)
    if not user_id:
        raise HTTPException(status_code=401, detail="Authentication failed")

    filename = file.filename or ""
    try:
        contents = await file.read()
        if filename.lower().endswith(".csv"):

            def _import_csv() -> int:
                decoded = contents.decode("utf-8-sig", errors="replace")

                # Try to sniff delimiter, fallback to comma
                try:
                    dialect = csv.Sniffer().sniff(decoded[:1024], delimiters=[",", ";", "\t"])
                except Exception:
                    dialect = csv.excel

                reader = csv.DictReader(io.StringIO(decoded), dialect=dialect)

                field_mapping = {}
                for col in reader.fieldnames or []:
                    col_lower = (
                        col.strip().lower().replace("_", " ").replace("&", "").replace("  ", " ")
                    )
                    if col_lower in ("name", "title", "problem name", "problem_name"):
                        field_mapping["name"] = col
                    elif col_lower in (
                        "problem_number",
                        "number",
                        "id",
                        "leetcode_number",
                        "problem number",
                        "leetcode id",
                    ):
                        field_mapping["problem_number"] = col
                    elif col_lower in ("pattern", "category", "topic", "tag"):
                        field_mapping["pattern"] = col
                    elif col_lower in ("difficulty", "level"):
                        field_mapping["difficulty"] = col
                    elif col_lower in (
                        "optimal_time",
                        "time complexity",
                        "time_complexity",
                        "time",
                        "optimal time",
                    ):
                        field_mapping["optimal_time"] = col
                    elif col_lower in (
                        "optimal_space",
                        "space complexity",
                        "space_complexity",
                        "space",
                        "optimal space",
                    ):
                        field_mapping["optimal_space"] = col
                    elif col_lower in (
                        "reference_code",
                        "code",
                        "solution",
                        "reference code",
                        "python solution",
                    ):
                        field_mapping["reference_code"] = col
                    elif col_lower in (
                        "description",
                        "notes",
                        "doc description",
                        "doc_description",
                    ):
                        field_mapping["description"] = col

                imported_count = 0
                for row in reader:
                    name = row.get(field_mapping.get("name", "name"), "").strip()
                    if not name:
                        name = row.get("name", row.get("title", "")).strip()
                    if not name:
                        continue

                    prob_num_str = row.get(
                        field_mapping.get("problem_number", "problem_number"), ""
                    ).strip()
                    if not prob_num_str:
                        prob_num_str = row.get("problem_number", row.get("number", ""))

                    try:
                        problem_number = int(prob_num_str) if prob_num_str else None
                    except ValueError:
                        problem_number = None

                    pattern = (
                        row.get(field_mapping.get("pattern", "pattern"), "").strip() or "General"
                    )
                    difficulty = (
                        row.get(field_mapping.get("difficulty", "difficulty"), "").strip()
                        or "Medium"
                    )
                    optimal_time = (
                        row.get(field_mapping.get("optimal_time", "optimal_time"), "").strip()
                        or "O(N)"
                    )
                    optimal_space = (
                        row.get(field_mapping.get("optimal_space", "optimal_space"), "").strip()
                        or "O(N)"
                    )
                    reference_code = row.get(
                        field_mapping.get("reference_code", "reference_code"), ""
                    ) or row.get("code", "")
                    description = row.get(
                        field_mapping.get("description", "description"), ""
                    ) or row.get("notes", "")

                    existing = db.get_problem_by_name(name, client)
                    if existing:
                        prob_data = {
                            "pattern": pattern,
                            "difficulty": difficulty,
                            "optimal_time": optimal_time,
                            "optimal_space": optimal_space,
                            "reference_code": reference_code,
                            "description": description,
                        }
                        if problem_number is not None:
                            prob_data["problem_number"] = problem_number
                        db.update_problem(existing["id"], prob_data, client)
                    else:
                        prob_data = {
                            "name": name,
                            "pattern": pattern,
                            "difficulty": difficulty,
                            "optimal_time": optimal_time,
                            "optimal_space": optimal_space,
                            "reference_code": reference_code,
                            "description": description,
                        }
                        if problem_number is not None:
                            prob_data["problem_number"] = problem_number

                        res_p = db.insert_problem(prob_data, client)
                        if res_p and res_p.data:
                            new_prob_id = res_p.data[0]["id"]
                            now_iso = datetime.now(UTC).isoformat()
                            review_data = {
                                "problem_id": new_prob_id,
                                "fsrs_state": 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": now_iso,
                                "last_reviewed": now_iso,
                                "times_correct": 0,
                                "total_attempts": 0,
                            }
                            db.insert_review(review_data, client)
                    imported_count += 1
                return imported_count

            count = await asyncio.to_thread(_import_csv)
            if count == 0:
                raise HTTPException(
                    status_code=400,
                    detail="No valid problems found in the CSV. Make sure it has a 'name' or 'title' column.",
                )
            await asyncio.to_thread(cache.delete_cache, f"due_reviews:{user_id}")
            await asyncio.to_thread(cache.delete_cache, f"all_problems_reviews:{user_id}")
            return {"message": f"Successfully imported {count} problems from CSV."}

        elif filename.lower().endswith(".db"):

            def _import_sqlite() -> int:
                with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as tmp:
                    tmp.write(contents)
                    tmp_path = tmp.name

                temp_conn = None
                try:
                    temp_conn = sqlite3.connect(tmp_path)
                    temp_conn.row_factory = sqlite3.Row
                    temp_cursor = temp_conn.cursor()

                    temp_cursor.execute(
                        "SELECT name FROM sqlite_master WHERE type='table' AND name='problems'"
                    )
                    if not temp_cursor.fetchone():
                        raise ValueError("Uploaded DB is missing the 'problems' table.")

                    temp_cursor.execute("SELECT * FROM problems")
                    rows = temp_cursor.fetchall()

                    imported_count = 0
                    for row in rows:
                        p_dict = dict(row)
                        old_id = p_dict.pop("id", None)
                        p_dict.pop("user_id", None)

                        existing = db.get_problem_by_name(p_dict["name"], client)
                        if existing:
                            db.update_problem(existing["id"], p_dict, client)
                        else:
                            res_p = db.insert_problem(p_dict, client)
                            if res_p and res_p.data:
                                new_prob_id = res_p.data[0]["id"]

                                review_copied = False
                                if old_id:
                                    try:
                                        temp_cursor.execute(
                                            "SELECT * FROM user_reviews WHERE problem_id = ?",
                                            (old_id,),
                                        )
                                        rev_row = temp_cursor.fetchone()
                                        if rev_row:
                                            r_dict = dict(rev_row)
                                            r_dict.pop("id", None)
                                            r_dict.pop("user_id", None)
                                            r_dict["problem_id"] = new_prob_id
                                            db.insert_review(r_dict, client)
                                            review_copied = True
                                    except Exception:
                                        pass

                                if not review_copied:
                                    now_iso = datetime.now(UTC).isoformat()
                                    review_data = {
                                        "problem_id": new_prob_id,
                                        "fsrs_state": 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": now_iso,
                                        "last_reviewed": now_iso,
                                        "times_correct": 0,
                                        "total_attempts": 0,
                                    }
                                    db.insert_review(review_data, client)
                        imported_count += 1
                    return imported_count
                finally:
                    if temp_conn is not None:
                        try:
                            temp_conn.close()
                        except Exception:
                            pass
                    try:
                        os.unlink(tmp_path)
                    except Exception:
                        pass

            try:
                count = await asyncio.to_thread(_import_sqlite)
            except ValueError as val_err:
                raise HTTPException(status_code=400, detail=str(val_err))
            await asyncio.to_thread(cache.delete_cache, f"due_reviews:{user_id}")
            await asyncio.to_thread(cache.delete_cache, f"all_problems_reviews:{user_id}")
            return {"message": f"Successfully imported {count} problems from database."}
        else:
            raise HTTPException(
                status_code=400, detail="Unsupported file format. Please upload .csv or .db files."
            )

    except HTTPException:
        raise
    except Exception as e:
        import traceback

        err_trace = f"Import error: {str(e)}\n{traceback.format_exc()}"
        await asyncio.to_thread(db.log_trace, err_trace)
        raise HTTPException(status_code=500, detail=f"Import failed: {str(e)}")