File size: 11,134 Bytes
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5deec3c
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Import data from Supabase SQL migration files into SQLite.

Reads:
  - supabase_migration/02_data_tracks.sql (track definitions)
  - supabase_migration/03_data_questions.sql (questions + answers)

Produces: data/medmembers.db (SQLite)
"""

import os
import re
import json
import sqlite3
import unicodedata
from werkzeug.security import generate_password_hash

# Paths
BASE_DIR = os.path.dirname(__file__)
MIGRATION_DIR = os.path.join(os.path.dirname(BASE_DIR), 'supabase_migration')
# In Docker, migration files are inside /app/supabase_migration/
if not os.path.exists(MIGRATION_DIR):
    MIGRATION_DIR = os.path.join(BASE_DIR, 'supabase_migration')
DB_PATH = os.environ.get('DB_PATH', os.path.join(BASE_DIR, 'data', 'medmembers.db'))

ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL', 'admin@medmembers.com')
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin123')


def slugify(text):
    """Convert track name to URL-friendly slug."""
    text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('ascii')
    text = text.lower().strip()
    text = re.sub(r'[^\w\s-]', '', text)
    text = re.sub(r'[-\s]+', '_', text)
    return text


def parse_tracks(sql_path):
    """Parse tracks from 02_data_tracks.sql."""
    tracks = {}
    with open(sql_path, 'r', encoding='utf-8') as f:
        for line in f:
            # INSERT INTO tracks (id, name, question_count) VALUES (1, 'CATARATA', 538)
            m = re.search(r"VALUES\s*\(\s*(\d+)\s*,\s*'([^']+)'\s*,\s*(\d+)\s*\)", line)
            if m:
                tid = int(m.group(1))
                name = m.group(2)
                count = int(m.group(3))
                tracks[tid] = {'name': name, 'slug': slugify(name), 'count': count}
    return tracks


def parse_pg_jsonb(raw):
    """Parse PostgreSQL JSONB literal from SQL."""
    # Remove ::jsonb cast
    raw = re.sub(r"'::jsonb\s*$", "", raw.strip())
    if raw.startswith("'"):
        raw = raw[1:]
    # Unescape PostgreSQL single-quote escaping
    raw = raw.replace("''", "'")
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return []


def extract_questions_and_answers(sql_path, tracks):
    """Parse questions and answers from 03_data_questions.sql."""
    questions = []
    answers = {}

    with open(sql_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # Parse questions
    # Pattern: INSERT INTO questions (id, track_id, year, question_html, options_json, media_files) VALUES (...)
    q_pattern = re.compile(
        r"INSERT\s+INTO\s+questions\s*\([^)]+\)\s*VALUES\s*\("
        r"'(\d+)'\s*,\s*"           # id
        r"(\d+)\s*,\s*"              # track_id
        r"'([^']*)'\s*,\s*"          # year
        r"'((?:[^']|'')*?)'\s*,\s*"  # question_html (escaped single quotes)
        r"('(?:[^']|'')*?'::jsonb)\s*,\s*"  # options_json
        r"('(?:[^']|'')*?'::jsonb)\s*"       # media_files
        r"\)",
        re.DOTALL
    )

    for m in q_pattern.finditer(content):
        qid = m.group(1)
        track_id = int(m.group(2))
        year = m.group(3)
        question_html = m.group(4).replace("''", "'")
        options_raw = m.group(5)
        media_raw = m.group(6)

        track_info = tracks.get(track_id, {'name': 'OUTROS', 'slug': 'outros'})

        options = parse_pg_jsonb(options_raw)
        media_files = parse_pg_jsonb(media_raw)

        # Convert options format: [{letter, text}] -> [{letra, texto}]
        alternativas = []
        for opt in options:
            alternativas.append({
                'letra': opt.get('letter', ''),
                'texto': opt.get('text', ''),
            })

        questions.append({
            'id': int(qid),
            'track': track_info['name'],
            'track_slug': track_info['slug'],
            'year': year,
            'enunciado': question_html,
            'alternativas': json.dumps(alternativas, ensure_ascii=False),
            'media_files': json.dumps(media_files, ensure_ascii=False),
            'imagens_enunciado': '[]',
            'imagens_gabarito': '[]',
        })

    # Parse answers
    # Pattern: INSERT INTO answers (question_id, correct_letter, correct_answer, explanation_html) VALUES (...)
    a_pattern = re.compile(
        r"INSERT\s+INTO\s+answers\s*\([^)]+\)\s*VALUES\s*\("
        r"'(\d+)'\s*,\s*"           # question_id
        r"'([^']*)'\s*,\s*"         # correct_letter
        r"'((?:[^']|'')*?)'\s*,\s*" # correct_answer
        r"'((?:[^']|'')*?)'\s*"     # explanation_html
        r"\)",
        re.DOTALL
    )

    for m in a_pattern.finditer(content):
        qid = m.group(1)
        correct_letter = m.group(2)
        explanation = m.group(4).replace("''", "'")
        answers[qid] = {
            'correct_letter': correct_letter,
            'explanation': explanation
        }

    return questions, answers


def build_database():
    """Build the SQLite database from migration files."""
    os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)

    # Remove existing DB
    if os.path.exists(DB_PATH):
        os.remove(DB_PATH)

    print(f"Creating database at: {DB_PATH}")

    db = sqlite3.connect(DB_PATH)
    db.execute("PRAGMA journal_mode=WAL")
    db.execute("PRAGMA foreign_keys=ON")

    # Create schema
    db.executescript("""
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            email TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL,
            display_name TEXT,
            role TEXT DEFAULT 'user',
            is_active INTEGER DEFAULT 1,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );

        CREATE TABLE IF NOT EXISTS sessions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            token TEXT UNIQUE NOT NULL,
            user_id INTEGER NOT NULL,
            ip_address TEXT,
            user_agent TEXT,
            device_info TEXT,
            login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            last_heartbeat TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            is_active INTEGER DEFAULT 1,
            logout_time TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id)
        );

        CREATE TABLE IF NOT EXISTS session_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            email TEXT,
            ip_address TEXT,
            user_agent TEXT,
            device_info TEXT,
            login_time TIMESTAMP,
            logout_time TIMESTAMP,
            duration_seconds INTEGER,
            kicked_by TEXT
        );

        CREATE TABLE IF NOT EXISTS questions (
            id INTEGER PRIMARY KEY,
            track TEXT NOT NULL,
            track_slug TEXT NOT NULL,
            numero INTEGER NOT NULL DEFAULT 0,
            question_id TEXT UNIQUE,
            year TEXT DEFAULT '',
            enunciado TEXT NOT NULL,
            imagens_enunciado TEXT DEFAULT '[]',
            alternativas TEXT NOT NULL DEFAULT '[]',
            gabarito_correta TEXT DEFAULT '',
            gabarito_texto TEXT DEFAULT '',
            imagens_gabarito TEXT DEFAULT '[]',
            media_files TEXT DEFAULT '[]'
        );

        CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
        CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
        CREATE INDEX IF NOT EXISTS idx_sessions_active ON sessions(is_active);
        CREATE INDEX IF NOT EXISTS idx_questions_track ON questions(track_slug);
        CREATE INDEX IF NOT EXISTS idx_questions_qid ON questions(question_id);
        CREATE INDEX IF NOT EXISTS idx_session_log_user ON session_log(user_id);

        CREATE TABLE IF NOT EXISTS password_reset_codes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            email TEXT NOT NULL,
            code TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            expires_at TIMESTAMP NOT NULL,
            used INTEGER DEFAULT 0
        );

        CREATE INDEX IF NOT EXISTS idx_reset_codes_email ON password_reset_codes(email);
        CREATE INDEX IF NOT EXISTS idx_reset_codes_code ON password_reset_codes(code);
    """)

    # Parse data files
    tracks_file = os.path.join(MIGRATION_DIR, '02_data_tracks.sql')
    questions_file = os.path.join(MIGRATION_DIR, '03_data_questions.sql')

    print(f"Parsing tracks from: {tracks_file}")
    tracks = parse_tracks(tracks_file)
    print(f"  Found {len(tracks)} tracks")

    print(f"Parsing questions from: {questions_file}")
    questions, answers = extract_questions_and_answers(questions_file, tracks)
    print(f"  Found {len(questions)} questions, {len(answers)} answers")

    # Assign numero (sequential per track)
    track_counters = {}
    for q in questions:
        slug = q['track_slug']
        track_counters[slug] = track_counters.get(slug, 0) + 1
        q['numero'] = track_counters[slug]

    # Insert questions
    print("Inserting questions...")
    for q in questions:
        qid_str = str(q['id'])
        answer = answers.get(qid_str, {})
        gabarito_correta = answer.get('correct_letter', '')
        gabarito_texto = answer.get('explanation', '')

        db.execute("""
            INSERT OR IGNORE INTO questions
            (id, track, track_slug, numero, question_id, year, enunciado, imagens_enunciado,
             alternativas, gabarito_correta, gabarito_texto, imagens_gabarito, media_files)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            q['id'], q['track'], q['track_slug'], q['numero'],
            f"Q_{q['id']}", q['year'], q['enunciado'],
            q['imagens_enunciado'], q['alternativas'],
            gabarito_correta, gabarito_texto, q['imagens_gabarito'],
            q['media_files']
        ))

    # Create admin user
    print(f"Creating admin user: {ADMIN_EMAIL}")
    db.execute(
        "INSERT OR IGNORE INTO users (email, password_hash, display_name, role) VALUES (?, ?, ?, ?)",
        (ADMIN_EMAIL, generate_password_hash(ADMIN_PASSWORD), 'Administrador', 'admin')
    )

    db.commit()

    # Print summary
    total_q = db.execute("SELECT COUNT(*) FROM questions").fetchone()[0]
    total_tracks = db.execute("SELECT COUNT(DISTINCT track_slug) FROM questions").fetchone()[0]
    total_with_answer = db.execute("SELECT COUNT(*) FROM questions WHERE gabarito_correta != ''").fetchone()[0]

    print("\n" + "=" * 50)
    print("DATABASE BUILD COMPLETE")
    print("=" * 50)
    print(f"  Total questions: {total_q}")
    print(f"  Total tracks: {total_tracks}")
    print(f"  Questions with answers: {total_with_answer}")
    print(f"  Database size: {os.path.getsize(DB_PATH) / 1024 / 1024:.1f} MB")

    # Track breakdown
    tracks_q = db.execute("""
        SELECT track, track_slug, COUNT(*) as cnt
        FROM questions GROUP BY track_slug ORDER BY track
    """).fetchall()
    print("\n  Track breakdown:")
    for row in tracks_q:
        print(f"    {row[0]}: {row[2]} questions (slug: {row[1]})")

    db.close()
    print(f"\nDatabase saved to: {DB_PATH}")


if __name__ == '__main__':
    build_database()