File size: 12,753 Bytes
12f0507
128f124
 
 
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128f124
12f0507
 
 
 
128f124
 
 
 
 
 
 
12f0507
 
 
 
128f124
12f0507
 
128f124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128f124
12f0507
 
 
 
 
 
 
 
 
128f124
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128f124
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
128f124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128f124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import math
import re
import time
import random
from flask import Blueprint, request, jsonify, g
from auth.middleware import require_auth
from models.database import get_db

questions_bp = Blueprint('questions', __name__, url_prefix='/api')


@questions_bp.route('/topics', methods=['GET'])
@require_auth
def list_topics():
    db = get_db()
    rows = db.execute("""
        SELECT track, track_slug, COUNT(*) as count
        FROM questions
        GROUP BY track_slug
        ORDER BY track
    """).fetchall()

    topics = [{'name': r['track'], 'slug': r['track_slug'], 'count': r['count']} for r in rows]
    return jsonify({'topics': topics})


@questions_bp.route('/topics/<slug>/questions', methods=['GET'])
@require_auth
def get_questions(slug):
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    per_page = min(per_page, 50)
    year = request.args.get('year', '').strip()
    offset = (page - 1) * per_page

    db = get_db()

    params = [slug]
    year_clause = ''
    if year:
        year_clause = ' AND year = ?'
        params.append(year)

    total = db.execute("SELECT COUNT(*) as c FROM questions WHERE track_slug = ?" + year_clause, params).fetchone()['c']

    rows = db.execute("""
        SELECT id, track, track_slug, numero, question_id, year, enunciado, imagens_enunciado, alternativas, media_files
        FROM questions
        WHERE track_slug = ?""" + year_clause + """
        ORDER BY numero
        LIMIT ? OFFSET ?
    """, params + [per_page, offset]).fetchall()

    # Fetch user answers for these questions
    user_id = g.current_user['id']
    question_ids = [r['id'] for r in rows]
    user_answers_map = {}
    if question_ids:
        placeholders = ','.join('?' * len(question_ids))
        ua_rows = db.execute(f"""
            SELECT question_id, selected_answer, is_correct
            FROM user_answers
            WHERE user_id = ? AND question_id IN ({placeholders})
        """, [user_id] + question_ids).fetchall()
        for ua in ua_rows:
            user_answers_map[ua['question_id']] = {
                'user_answer': ua['selected_answer'],
                'user_correct': bool(ua['is_correct'])
            }

    questions = []
    for r in rows:
        raw_alts = json.loads(r['alternativas'] or '[]')
        # Remove correct answer from alternativas sent to client
        for alt in raw_alts:
            alt.pop('correta', None)

        raw_media = json.loads(r['media_files'] or '[]')
        # Separate images from media_files for the enunciado
        enunciado_imgs = []
        for m in raw_media:
            if m.get('type') == 'image':
                enunciado_imgs.append(m.get('filename', ''))

        ua = user_answers_map.get(r['id'], {})
        q = {
            'id': r['id'],
            'numero': r['numero'],
            'question_id': r['question_id'],
            'year': r['year'] or '',
            'enunciado': r['enunciado'],
            'imagens_enunciado': json.loads(r['imagens_enunciado'] or '[]') or enunciado_imgs,
            'alternativas': raw_alts,
            'has_video': any(m.get('type') == 'video' for m in raw_media),
            'user_answer': ua.get('user_answer', None),
            'user_correct': ua.get('user_correct', None),
        }
        questions.append(q)

    return jsonify({
        'questions': questions,
        'total': total,
        'page': page,
        'per_page': per_page,
        'total_pages': (total + per_page - 1) // per_page
    })


@questions_bp.route('/questions/<int:qid>/check', methods=['POST'])
@require_auth
def check_answer(qid):
    data = request.get_json()
    answer = data.get('answer', '').upper() if data else ''

    db = get_db()
    q = db.execute("SELECT gabarito_correta FROM questions WHERE id = ?", (qid,)).fetchone()
    if not q:
        return jsonify({'error': 'Questão não encontrada'}), 404

    correct = q['gabarito_correta'] or ''
    is_correct = 1 if answer == correct else 0

    # Save/update user answer
    user_id = g.current_user['id']
    db.execute("""
        INSERT OR REPLACE INTO user_answers (user_id, question_id, selected_answer, is_correct, answered_at)
        VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
    """, (user_id, qid, answer, is_correct))
    db.commit()

    return jsonify({
        'correct': answer == correct,
        'gabarito_correta': correct
    })


@questions_bp.route('/user/stats', methods=['GET'])
@require_auth
def user_stats():
    user_id = g.current_user['id']
    db = get_db()

    # Overall stats
    overall = db.execute("""
        SELECT COUNT(*) as total_answered,
               SUM(is_correct) as total_correct
        FROM user_answers WHERE user_id = ?
    """, (user_id,)).fetchone()

    total_answered = overall['total_answered'] or 0
    total_correct = overall['total_correct'] or 0
    accuracy = round((total_correct / total_answered * 100), 1) if total_answered > 0 else 0

    # Per-track breakdown
    tracks = db.execute("""
        SELECT q.track, q.track_slug,
               COUNT(*) as total,
               SUM(ua.is_correct) as correct
        FROM user_answers ua
        JOIN questions q ON q.id = ua.question_id
        WHERE ua.user_id = ?
        GROUP BY q.track_slug
        ORDER BY q.track
    """, (user_id,)).fetchall()

    track_stats = []
    for t in tracks:
        t_total = t['total'] or 0
        t_correct = t['correct'] or 0
        track_stats.append({
            'track': t['track'],
            'slug': t['track_slug'],
            'total': t_total,
            'correct': t_correct,
            'percentage': round((t_correct / t_total * 100), 1) if t_total > 0 else 0
        })

    return jsonify({
        'total_answered': total_answered,
        'total_correct': total_correct,
        'accuracy': accuracy,
        'tracks': track_stats
    })


@questions_bp.route('/user/history', methods=['GET'])
@require_auth
def user_history():
    user_id = g.current_user['id']
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    per_page = min(per_page, 50)
    offset = (page - 1) * per_page

    db = get_db()

    total = db.execute("SELECT COUNT(*) as c FROM user_answers WHERE user_id = ?", (user_id,)).fetchone()['c']

    rows = db.execute("""
        SELECT ua.question_id, ua.selected_answer, ua.is_correct, ua.answered_at,
               q.enunciado, q.numero, q.track, q.track_slug, q.gabarito_correta
        FROM user_answers ua
        JOIN questions q ON q.id = ua.question_id
        WHERE ua.user_id = ?
        ORDER BY ua.answered_at DESC
        LIMIT ? OFFSET ?
    """, (user_id, per_page, offset)).fetchall()

    history = []
    for r in rows:
        # Text snippet: strip HTML and truncate
        enunciado = r['enunciado'] or ''
        snippet = re.sub(r'<[^>]+>', '', enunciado)
        snippet = snippet[:120] + '...' if len(snippet) > 120 else snippet

        history.append({
            'question_id': r['question_id'],
            'numero': r['numero'],
            'track': r['track'],
            'track_slug': r['track_slug'],
            'selected_answer': r['selected_answer'],
            'correct_answer': r['gabarito_correta'] or '',
            'is_correct': bool(r['is_correct']),
            'answered_at': r['answered_at'],
            'snippet': snippet
        })

    return jsonify({
        'history': history,
        'total': total,
        'page': page,
        'per_page': per_page,
        'total_pages': math.ceil(total / per_page) if per_page > 0 else 0
    })


@questions_bp.route('/questions/<int:qid>/solution', methods=['GET'])
@require_auth
def get_solution(qid):
    db = get_db()
    q = db.execute("""
        SELECT gabarito_correta, gabarito_texto, imagens_gabarito, media_files, track_slug
        FROM questions WHERE id = ?
    """, (qid,)).fetchone()

    if not q:
        return jsonify({'error': 'Questão não encontrada'}), 404

    # Extract videos from media_files
    raw_media = json.loads(q['media_files'] or '[]')
    videos = []
    for m in raw_media:
        if m.get('type') == 'video' and m.get('filename'):
            videos.append(m['filename'])

    return jsonify({
        'gabarito_correta': q['gabarito_correta'] or '',
        'gabarito_texto': q['gabarito_texto'] or '',
        'imagens_gabarito': json.loads(q['imagens_gabarito'] or '[]'),
        'videos': videos
    })


@questions_bp.route('/years', methods=['GET'])
@require_auth
def list_years():
    """Return distinct years available in the questions table."""
    db = get_db()
    rows = db.execute("""
        SELECT DISTINCT year FROM questions
        WHERE year IS NOT NULL AND year != ''
        ORDER BY year DESC
    """).fetchall()
    years = [r['year'] for r in rows]
    return jsonify({'years': years})


@questions_bp.route('/simulado/generate', methods=['GET'])
@require_auth
def simulado_generate():
    """Generate a simulated exam with random questions."""
    count = request.args.get('count', 50, type=int)
    count = max(1, min(count, 100))
    tracks = request.args.get('tracks', 'all').strip()
    year = request.args.get('year', '').strip()

    db = get_db()

    where_clauses = ["gabarito_correta IS NOT NULL", "gabarito_correta != ''"]
    params = []

    if tracks and tracks != 'all':
        slugs = [s.strip() for s in tracks.split(',') if s.strip()]
        if slugs:
            placeholders = ','.join('?' * len(slugs))
            where_clauses.append(f"track_slug IN ({placeholders})")
            params.extend(slugs)

    if year:
        where_clauses.append("year = ?")
        params.append(year)

    where_sql = ' AND '.join(where_clauses)

    total_available = db.execute(
        f"SELECT COUNT(*) as c FROM questions WHERE {where_sql}", params
    ).fetchone()['c']

    if total_available == 0:
        return jsonify({'error': 'Nenhuma questao encontrada com os filtros selecionados'}), 404

    actual_count = min(count, total_available)

    rows = db.execute(f"""
        SELECT id, track, track_slug, numero, year, enunciado, alternativas
        FROM questions
        WHERE {where_sql}
        ORDER BY RANDOM()
        LIMIT ?
    """, params + [actual_count]).fetchall()

    questions = []
    for r in rows:
        raw_alts = json.loads(r['alternativas'] or '[]')
        for alt in raw_alts:
            alt.pop('correta', None)
        questions.append({
            'id': r['id'],
            'numero': r['numero'],
            'track': r['track'],
            'year': r['year'] or '',
            'enunciado': r['enunciado'],
            'alternativas': raw_alts
        })

    simulado_id = f"sim-{int(time.time())}-{random.randint(1000, 9999)}"
    time_limit = actual_count  # 1 minute per question

    return jsonify({
        'simulado_id': simulado_id,
        'questions': questions,
        'total': actual_count,
        'time_limit_minutes': time_limit
    })


@questions_bp.route('/simulado/submit', methods=['POST'])
@require_auth
def simulado_submit():
    """Submit exam answers and return results."""
    data = request.get_json()
    if not data:
        return jsonify({'error': 'Dados nao fornecidos'}), 400

    simulado_id = data.get('simulado_id', '')
    answers = data.get('answers', {})
    time_spent = data.get('time_spent_seconds', 0)

    if not answers:
        return jsonify({'error': 'Nenhuma resposta enviada'}), 400

    db = get_db()
    question_ids = list(answers.keys())
    placeholders = ','.join('?' * len(question_ids))
    int_ids = [int(qid) for qid in question_ids]

    rows = db.execute(f"""
        SELECT id, gabarito_correta, gabarito_texto
        FROM questions WHERE id IN ({placeholders})
    """, int_ids).fetchall()

    correct_map = {r['id']: r for r in rows}

    details = []
    score = 0
    for qid_str, selected in answers.items():
        qid = int(qid_str)
        q = correct_map.get(qid)
        correct_letter = q['gabarito_correta'] if q else ''
        is_correct = selected.upper() == correct_letter.upper() if correct_letter else False
        if is_correct:
            score += 1
        details.append({
            'question_id': qid,
            'selected': selected,
            'correct': correct_letter,
            'is_correct': is_correct,
            'explanation': (q['gabarito_texto'] or '') if q else ''
        })

    total = len(answers)
    percentage = round((score / total) * 100, 1) if total > 0 else 0

    return jsonify({
        'simulado_id': simulado_id,
        'score': score,
        'total': total,
        'percentage': percentage,
        'time_spent_seconds': time_spent,
        'details': details
    })