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