File size: 12,581 Bytes
664a5eb
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
 
 
aa1fcca
 
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
aa1fcca
 
8800c81
 
 
 
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
 
664a5eb
8800c81
 
 
 
 
664a5eb
8800c81
 
664a5eb
8800c81
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a42236e
664a5eb
 
 
 
 
 
 
 
8800c81
 
 
 
 
664a5eb
 
 
8800c81
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664a5eb
 
8800c81
 
 
 
664a5eb
 
 
 
 
a42236e
 
 
8800c81
 
 
664a5eb
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
664a5eb
 
 
8800c81
 
 
 
664a5eb
 
8800c81
 
664a5eb
8800c81
 
 
aa1fcca
 
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
aa1fcca
 
8800c81
 
 
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
8800c81
 
 
664a5eb
 
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
import asyncio
from datetime import UTC, datetime

from fastapi import APIRouter, Depends, Header, HTTPException, Request
from pydantic import BaseModel

import ai_cache
import db
import llm_reviewer
import sandbox
import sql_playground
from core.auth import Client, get_auth_session
from core.limiter import check_burst_rate_limit

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

DAILY_PYTHON_CHALLENGE_CACHE = {}  # maps YYYY-MM-DD to challenge dict
ACTIVE_SQL_CHALLENGES = {}  # maps user_id to active challenge dict


class SubmitPythonRequest(BaseModel):
    code: str


@router.get("/api/challenges/python/daily")
async def get_daily_python_challenge(
    request: Request,
    client: Client = Depends(get_auth_session),
    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)
    challenge = await llm_reviewer.generate_daily_python_challenge_async(
        custom_api_key=api_key, custom_provider=x_ai_provider
    )
    if "error" in challenge:
        raise HTTPException(
            status_code=500, detail=f"Failed to generate challenge: {challenge['error']}"
        )

    today_str = datetime.now(UTC).strftime("%Y-%m-%d")
    DAILY_PYTHON_CHALLENGE_CACHE[today_str] = challenge

    user_id = await asyncio.to_thread(db.get_current_user_id, client)
    completed = False
    if user_id:
        try:
            completed = await asyncio.to_thread(
                db.has_completed_challenge, "python", challenge.get("title", ""), client
            )
        except Exception:
            pass

    score_record = await asyncio.to_thread(db.get_user_score, client)
    total_score = score_record["total_score"] if score_record else 0

    return {
        "title": challenge.get("title"),
        "description": challenge.get("description"),
        "difficulty": challenge.get("difficulty"),
        "points": challenge.get("points"),
        "starter_code": challenge.get("starter_code"),
        "completed": completed,
        "total_score": total_score,
    }


@router.post("/api/challenges/python/submit")
async def submit_python_challenge(
    req: SubmitPythonRequest, client: Client = Depends(get_auth_session)
):
    today_str = datetime.now(UTC).strftime("%Y-%m-%d")

    if today_str not in DAILY_PYTHON_CHALLENGE_CACHE:
        challenge = await llm_reviewer.generate_daily_python_challenge_async()
        if "error" in challenge:
            raise HTTPException(
                status_code=500, detail=f"No challenge available: {challenge['error']}"
            )
        DAILY_PYTHON_CHALLENGE_CACHE[today_str] = challenge

    challenge = DAILY_PYTHON_CHALLENGE_CACHE[today_str]
    test_cases = challenge.get("test_cases", [])

    run_res = await sandbox.run_python_sandbox_async(req.code, test_cases)

    if not run_res.get("success", False):
        return {
            "success": False,
            "error": run_res.get("error", "Unknown execution error"),
            "sandbox_type": run_res.get("sandbox_type"),
        }

    results = run_res.get("results", [])
    all_passed = len(results) > 0 and all(r.get("status") == "passed" for r in results)

    points_awarded = 0
    completed_before = False
    total_score = 0

    user_id = await asyncio.to_thread(db.get_current_user_id, client)
    if all_passed and user_id:
        title = challenge.get("title", "Daily Python Challenge")
        points = challenge.get("points", 100)

        try:
            completed_before = await asyncio.to_thread(
                db.has_completed_challenge, "python", title, client
            )
        except Exception:
            pass

        if not completed_before:
            await asyncio.to_thread(db.increment_user_score, points, "python", client)
            await asyncio.to_thread(db.add_challenge_history, "python", title, points, client)
            points_awarded = points

    score_record = await asyncio.to_thread(db.get_user_score, client)
    if score_record:
        total_score = score_record["total_score"]

    if all_passed:
        gold_awarded = 100
        curr = await asyncio.to_thread(db.increment_user_gold, 100, client)
        new_balance = curr.get("gold", 100) if curr else 100
    else:
        gold_awarded = 0
        curr = await asyncio.to_thread(db.get_user_currency, client)
        new_balance = curr.get("gold", 0) if curr else 0

    return {
        "success": True,
        "all_passed": all_passed,
        "results": results,
        "points_awarded": points_awarded,
        "completed_before": completed_before,
        "total_score": total_score,
        "gold_awarded": gold_awarded,
        "new_balance": new_balance,
        "sandbox_type": run_res.get("sandbox_type"),
        "sandbox_warning": run_res.get("sandbox_warning"),
    }


class SQLQueryRequest(BaseModel):
    query: str


@router.post("/api/challenges/mysql/init")
async def init_mysql_challenge(
    request: Request,
    refresh: bool = False,
    client: Client = Depends(get_auth_session),
    x_ai_provider: str = Header(None),
    x_custom_api_key: str = Header(None),
    x_gemini_api_key: str = Header(None),
):
    user_id = await asyncio.to_thread(db.get_current_user_id, client)
    if not user_id:
        raise HTTPException(status_code=401, detail="Authentication failed")

    api_key = x_custom_api_key or x_gemini_api_key
    check_burst_rate_limit(request, api_key)
    challenge = await llm_reviewer.generate_sql_challenge_async(
        custom_api_key=api_key, custom_provider=x_ai_provider, force_refresh=refresh
    )
    if "error" in challenge:
        raise HTTPException(
            status_code=500, detail=f"Failed to generate SQL challenge: {challenge['error']}"
        )

    init_res = await asyncio.to_thread(sql_playground.init_user_db, user_id, challenge)
    if not init_res.get("success", False):
        raise HTTPException(
            status_code=500, detail=f"Failed to initialize database: {init_res.get('error')}"
        )

    ACTIVE_SQL_CHALLENGES[user_id] = challenge

    score_record = await asyncio.to_thread(db.get_user_score, client)
    total_score = score_record["total_score"] if score_record else 0

    return {
        "success": True,
        "title": challenge.get("title"),
        "objective": challenge.get("objective"),
        "points": challenge.get("points"),
        "schema": init_res.get("schema"),
        "challenge_type": challenge.get("challenge_type"),
        "total_score": total_score,
    }


@router.get("/api/challenges/mysql/status")
async def get_mysql_status(
    request: Request,
    client: Client = Depends(get_auth_session),
    x_ai_provider: str = Header(None),
    x_custom_api_key: str = Header(None),
    x_gemini_api_key: str = Header(None),
):
    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 user_id not in ACTIVE_SQL_CHALLENGES:
        today_str = datetime.now(UTC).strftime("%Y-%m-%d")
        challenge = await ai_cache.get_daily_sql_challenge_async(today_str)
        if not challenge or not isinstance(challenge, dict) or "title" not in challenge:
            api_key = x_custom_api_key or x_gemini_api_key
            challenge = await llm_reviewer.generate_sql_challenge_async(
                custom_api_key=api_key, custom_provider=x_ai_provider, force_refresh=False
            )
        if challenge and "title" in challenge:
            init_res = await asyncio.to_thread(sql_playground.init_user_db, user_id, challenge)
            if init_res.get("success", False):
                ACTIVE_SQL_CHALLENGES[user_id] = challenge
            else:
                return {
                    "active": False,
                    "message": "No active SQL session. Please initialize with 'db init'.",
                }
        else:
            return {
                "active": False,
                "message": "No active SQL session. Please initialize with 'db init'.",
            }

    challenge = ACTIVE_SQL_CHALLENGES[user_id]

    schema = {}
    try:

        def _get_schema():
            conn = sql_playground.get_connection(user_id)
            try:
                return sql_playground.get_db_schema(conn)
            finally:
                conn.close()

        schema = await asyncio.to_thread(_get_schema)
    except Exception:
        pass

    completed = False
    try:
        completed = await asyncio.to_thread(
            db.has_completed_challenge, "mysql", challenge.get("title", ""), client
        )
    except Exception:
        pass

    score_record = await asyncio.to_thread(db.get_user_score, client)
    total_score = score_record["total_score"] if score_record else 0

    return {
        "active": True,
        "title": challenge.get("title"),
        "objective": challenge.get("objective"),
        "points": challenge.get("points"),
        "challenge_type": challenge.get("challenge_type"),
        "schema": schema,
        "completed": completed,
        "total_score": total_score,
    }


@router.post("/api/challenges/mysql/query")
async def run_mysql_query(req: SQLQueryRequest, 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 user_id not in ACTIVE_SQL_CHALLENGES:
        today_str = datetime.now(UTC).strftime("%Y-%m-%d")
        cached_challenge = await ai_cache.get_daily_sql_challenge_async(today_str)
        if cached_challenge and isinstance(cached_challenge, dict) and "title" in cached_challenge:
            ACTIVE_SQL_CHALLENGES[user_id] = cached_challenge
        else:
            raise HTTPException(
                status_code=400, detail="No active SQL session. Type 'db init' first."
            )

    challenge = ACTIVE_SQL_CHALLENGES[user_id]

    run_res = await asyncio.to_thread(sql_playground.run_user_query, user_id, req.query, challenge)

    if not run_res.get("success", False):
        return {"success": False, "error": run_res.get("error", "Unknown database error")}

    is_correct = run_res.get("is_correct", False)
    points_awarded = 0
    completed_before = False
    total_score = 0

    if is_correct:
        title = challenge.get("title", "SQL Challenge")
        points = challenge.get("points", 150)

        try:
            completed_before = await asyncio.to_thread(
                db.has_completed_challenge, "mysql", title, client
            )
        except Exception:
            pass

        if not completed_before:
            await asyncio.to_thread(db.increment_user_score, points, "mysql", client)
            await asyncio.to_thread(db.add_challenge_history, "mysql", title, points, client)
            points_awarded = points

    score_record = await asyncio.to_thread(db.get_user_score, client)
    if score_record:
        total_score = score_record["total_score"]

    if is_correct:
        gold_awarded = 100
        curr = await asyncio.to_thread(db.increment_user_gold, 100, client)
        new_balance = curr.get("gold", 100) if curr else 100
    else:
        gold_awarded = 0
        curr = await asyncio.to_thread(db.get_user_currency, client)
        new_balance = curr.get("gold", 0) if curr else 0

    return {
        "success": True,
        "is_correct": is_correct,
        "columns": run_res.get("columns", []),
        "rows": run_res.get("rows", []),
        "rows_affected": run_res.get("rows_affected", 0),
        "schema": run_res.get("schema", {}),
        "points_awarded": points_awarded,
        "completed_before": completed_before,
        "total_score": total_score,
        "gold_awarded": gold_awarded,
        "new_balance": new_balance,
    }


@router.get("/api/scores")
async def get_user_scores(client: Client = Depends(get_auth_session)):
    def _fetch_scores():
        user_id = db.get_current_user_id(client)
        score_data = db.get_user_score(client)
        return score_data or {
            "user_id": user_id,
            "total_score": 0,
            "python_challenges_completed": 0,
            "sql_challenges_completed": 0,
        }

    return await asyncio.to_thread(_fetch_scores)


@router.get("/api/scores/history")
async def get_user_challenge_history(client: Client = Depends(get_auth_session)):
    return await asyncio.to_thread(db.get_challenge_history, client)