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)}")