File size: 23,664 Bytes
7f8e190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
"""Site-owned SQLite business schema for the LeetCode offline clone.

The vendored ``websitebench.site_backend`` runtime owns the shared library
tables (site binding, mail jobs, payment ledger) and
``websitebench.local_clone_auth`` owns accounts, sessions and verification
flows. Everything below is this site's own business state, held in the same
site-bound database file:

* ``leetcode_questions``   — the seeded local question catalogue
* ``leetcode_profiles``    — username/account binding created during signup
* ``leetcode_drafts``      — the editor buffer per (member, question, language)
* ``leetcode_submissions`` — every graded submission, server-side
* ``leetcode_progress``    — solved / attempted status per member

Migrations are forward-only, recorded in ``leetcode_schema_migrations`` and
safe to re-run. Seeding is deterministic: the catalogue is rewritten from
:mod:`leetcode_app.content` on every boot, and every generated timestamp comes
from a fixed base clock plus a row counter, never from the wall clock.
"""

from __future__ import annotations

import json
import sqlite3
import threading
from contextlib import closing
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any

from backend.site_backend_integration import open_site_services
from websitebench.local_clone_auth import LocalAuthStore
from websitebench.site_backend import SiteBackend

from . import content
from .content import Question


SITE_ID = "leetcode"

# One fixed base clock for the whole clone, so an identical operation sequence
# always produces identical stored state.
BASE_CLOCK = datetime(2026, 8, 20, 9, 0, 0, tzinfo=UTC)
STEP_SECONDS = 61

SOLVED = "solved"
ATTEMPTED = "attempted"

_MIGRATIONS: dict[str, str] = {
    "0001_catalogue": """
        CREATE TABLE IF NOT EXISTS leetcode_questions (
            slug TEXT PRIMARY KEY,
            number INTEGER NOT NULL UNIQUE,
            title TEXT NOT NULL,
            difficulty TEXT NOT NULL
                CHECK (difficulty IN ('Easy', 'Medium', 'Hard')),
            category TEXT NOT NULL,
            topics_json TEXT NOT NULL,
            companies_json TEXT NOT NULL,
            languages_json TEXT NOT NULL,
            acceptance REAL NOT NULL CHECK (acceptance >= 0),
            frequency INTEGER NOT NULL CHECK (frequency BETWEEN 0 AND 100),
            contest_point INTEGER NOT NULL CHECK (contest_point >= 0),
            detail_json TEXT NOT NULL
        );
        CREATE INDEX IF NOT EXISTS idx_leetcode_questions_category
            ON leetcode_questions (category, number);
    """,
    "0002_members": """
        CREATE TABLE IF NOT EXISTS leetcode_profiles (
            subject_id TEXT PRIMARY KEY,
            account_id TEXT NOT NULL UNIQUE,
            username TEXT NOT NULL,
            username_normalized TEXT NOT NULL UNIQUE,
            email_normalized TEXT NOT NULL UNIQUE,
            created_at TEXT NOT NULL
        );
    """,
    "0003_work": """
        CREATE TABLE IF NOT EXISTS leetcode_drafts (
            subject_id TEXT NOT NULL,
            question_slug TEXT NOT NULL,
            language TEXT NOT NULL,
            source TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            PRIMARY KEY (subject_id, question_slug, language)
        );
        CREATE TABLE IF NOT EXISTS leetcode_submissions (
            id INTEGER PRIMARY KEY,
            subject_id TEXT NOT NULL,
            question_slug TEXT NOT NULL,
            language TEXT NOT NULL,
            status TEXT NOT NULL,
            message TEXT NOT NULL DEFAULT '',
            passed INTEGER NOT NULL CHECK (passed >= 0),
            total INTEGER NOT NULL CHECK (total >= 0),
            runtime_ms INTEGER,
            memory_mb REAL,
            runtime_percentile REAL,
            memory_percentile REAL,
            failing_input TEXT,
            failing_output TEXT,
            failing_expected TEXT,
            source TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        CREATE INDEX IF NOT EXISTS idx_leetcode_submissions_member
            ON leetcode_submissions (subject_id, id DESC);
        CREATE INDEX IF NOT EXISTS idx_leetcode_submissions_question
            ON leetcode_submissions (subject_id, question_slug, id DESC);
        CREATE TABLE IF NOT EXISTS leetcode_progress (
            subject_id TEXT NOT NULL,
            question_slug TEXT NOT NULL,
            status TEXT NOT NULL CHECK (status IN ('solved', 'attempted')),
            first_solved_at TEXT,
            last_submitted_at TEXT NOT NULL,
            attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
            PRIMARY KEY (subject_id, question_slug)
        );
    """,
}

_BUSINESS_TABLES = (
    "leetcode_progress",
    "leetcode_submissions",
    "leetcode_drafts",
    "leetcode_profiles",
)

_SERVICES_LOCK = threading.Lock()
_SERVICES: tuple[SiteBackend, LocalAuthStore] | None = None


# ---------------------------------------------------------------------------
# lifecycle
# ---------------------------------------------------------------------------


def services() -> tuple[SiteBackend, LocalAuthStore]:
    """Process-wide bound backend + auth pair with the business schema ready."""

    global _SERVICES
    with _SERVICES_LOCK:
        if _SERVICES is None:
            backend, auth = open_site_services()
            migrate(backend.lifecycle.database_path)
            seed_catalogue(backend.lifecycle.database_path)
            _SERVICES = (backend, auth)
        return _SERVICES


def close_services() -> None:
    global _SERVICES
    with _SERVICES_LOCK:
        _SERVICES = None


def database_path() -> Path:
    return services()[0].lifecycle.database_path


def _connect(path: Path) -> sqlite3.Connection:
    connection = sqlite3.connect(str(path), timeout=15)
    connection.row_factory = sqlite3.Row
    connection.execute("PRAGMA foreign_keys = ON")
    connection.execute("PRAGMA busy_timeout = 5000")
    return connection


def connect() -> sqlite3.Connection:
    return _connect(database_path())


def migrate(path: Path) -> list[str]:
    """Apply every pending forward migration. Safe to run repeatedly."""

    applied_now: list[str] = []
    with closing(_connect(path)) as connection, connection:
        connection.execute(
            """
            CREATE TABLE IF NOT EXISTS leetcode_schema_migrations (
                migration_id TEXT PRIMARY KEY,
                applied_at TEXT NOT NULL
            )
            """
        )
        applied = {
            str(row["migration_id"])
            for row in connection.execute(
                "SELECT migration_id FROM leetcode_schema_migrations"
            )
        }
        for migration_id, ddl in _MIGRATIONS.items():
            if migration_id in applied:
                continue
            connection.executescript(ddl)
            connection.execute(
                "INSERT INTO leetcode_schema_migrations (migration_id, applied_at)"
                " VALUES (?, ?)",
                (migration_id, BASE_CLOCK.isoformat().replace("+00:00", "Z")),
            )
            applied_now.append(migration_id)
    return applied_now


def applied_migrations(path: Path | None = None) -> list[str]:
    target = path or database_path()
    with closing(_connect(target)) as connection:
        return [
            str(row["migration_id"])
            for row in connection.execute(
                "SELECT migration_id FROM leetcode_schema_migrations"
                " ORDER BY migration_id"
            )
        ]


def seed_catalogue(path: Path) -> int:
    """Write the deterministic question catalogue. Idempotent by slug."""

    rows = [
        (
            item.slug,
            item.number,
            item.title,
            item.difficulty,
            item.category,
            json.dumps(list(item.topics), separators=(",", ":")),
            json.dumps(list(item.companies), separators=(",", ":")),
            json.dumps(list(item.languages), separators=(",", ":")),
            item.acceptance,
            item.frequency,
            item.contest_point,
            json.dumps(
                content.detail_payload(item), separators=(",", ":"), sort_keys=True
            ),
        )
        for item in content.iter_questions()
    ]
    with closing(_connect(path)) as connection, connection:
        connection.executemany(
            """
            INSERT INTO leetcode_questions (
                slug, number, title, difficulty, category, topics_json,
                companies_json, languages_json, acceptance, frequency,
                contest_point, detail_json
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(slug) DO UPDATE SET
                number = excluded.number,
                title = excluded.title,
                difficulty = excluded.difficulty,
                category = excluded.category,
                topics_json = excluded.topics_json,
                companies_json = excluded.companies_json,
                languages_json = excluded.languages_json,
                acceptance = excluded.acceptance,
                frequency = excluded.frequency,
                contest_point = excluded.contest_point,
                detail_json = excluded.detail_json
            """,
            rows,
        )
    return len(rows)


def reset() -> None:
    """Clear member state and re-seed. Used by tests and the reset endpoint."""

    backend, auth = services()

    def _site_reset(connection: sqlite3.Connection) -> None:
        for table in _BUSINESS_TABLES:
            connection.execute(f"DELETE FROM {table}")
        backend.lifecycle.reset_embedded(connection, confirm_site_id=SITE_ID)

    auth.reset_site_state(site_reset=_site_reset, seed_accounts=[])
    seed_catalogue(backend.lifecycle.database_path)


# ---------------------------------------------------------------------------
# deterministic clock
# ---------------------------------------------------------------------------


def _stamp(connection: sqlite3.Connection) -> str:
    row = connection.execute("SELECT COUNT(*) FROM leetcode_submissions").fetchone()
    sequence = int(row[0]) if row is not None else 0
    moment = BASE_CLOCK + timedelta(seconds=STEP_SECONDS * sequence)
    return moment.isoformat().replace("+00:00", "Z")


def profile_stamp(connection: sqlite3.Connection) -> str:
    row = connection.execute("SELECT COUNT(*) FROM leetcode_profiles").fetchone()
    sequence = int(row[0]) if row is not None else 0
    moment = BASE_CLOCK + timedelta(seconds=STEP_SECONDS * sequence)
    return moment.isoformat().replace("+00:00", "Z")


# ---------------------------------------------------------------------------
# catalogue reads
# ---------------------------------------------------------------------------


def _question_row(row: sqlite3.Row) -> dict[str, Any]:
    return {
        "slug": row["slug"],
        "number": int(row["number"]),
        "title": row["title"],
        "difficulty": row["difficulty"],
        "category": row["category"],
        "topics": json.loads(row["topics_json"]),
        "companies": json.loads(row["companies_json"]),
        "languages": json.loads(row["languages_json"]),
        "acceptance": float(row["acceptance"]),
        "frequency": int(row["frequency"]),
        "contest_point": int(row["contest_point"]),
        "detail": json.loads(row["detail_json"]),
    }


def question_count() -> int:
    with closing(connect()) as connection:
        row = connection.execute("SELECT COUNT(*) FROM leetcode_questions").fetchone()
        return int(row[0]) if row is not None else 0


def load_question(slug: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM leetcode_questions WHERE slug = ?", (slug,)
        ).fetchone()
    return _question_row(row) if row is not None else None


def catalogue_question(slug: str) -> Question | None:
    """The in-process question object used by the verdict model."""

    return content.question(slug)


# ---------------------------------------------------------------------------
# member profiles
# ---------------------------------------------------------------------------


def normalize_username(username: str) -> str:
    return " ".join(username.split()).casefold()


def username_taken(username: str) -> bool:
    with closing(connect()) as connection:
        return (
            connection.execute(
                "SELECT 1 FROM leetcode_profiles WHERE username_normalized = ?",
                (normalize_username(username),),
            ).fetchone()
            is not None
        )


def create_profile(
    connection: sqlite3.Connection,
    *,
    account_id: str,
    username: str,
    email: str,
) -> str:
    """Create the business member row inside the auth store's transaction."""

    subject_id = f"member_{normalize_username(username)}"
    connection.execute(
        """
        INSERT INTO leetcode_profiles (
            subject_id, account_id, username, username_normalized,
            email_normalized, created_at
        ) VALUES (?, ?, ?, ?, ?, ?)
        """,
        (
            subject_id,
            account_id,
            username,
            normalize_username(username),
            email,
            profile_stamp(connection),
        ),
    )
    return subject_id


def profile_for_email(email: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM leetcode_profiles WHERE email_normalized = ?",
            (email.strip().casefold(),),
        ).fetchone()
    return dict(row) if row is not None else None


def profile_for_username(username: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM leetcode_profiles WHERE username_normalized = ?",
            (normalize_username(username),),
        ).fetchone()
    return dict(row) if row is not None else None


def profile_for_subject(subject_id: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM leetcode_profiles WHERE subject_id = ?", (subject_id,)
        ).fetchone()
    return dict(row) if row is not None else None


def resolve_login_email(identifier: str) -> str:
    """Map a username-or-email login identifier onto the account email."""

    candidate = identifier.strip()
    if "@" in candidate:
        return candidate.casefold()
    profile = profile_for_username(candidate)
    if profile is None:
        # Keep the failure path indistinguishable: hand the auth store a
        # syntactically valid address that owns no account.
        return "unknown-member@leetcode.invalid"
    return str(profile["email_normalized"])


# ---------------------------------------------------------------------------
# drafts
# ---------------------------------------------------------------------------


def save_draft(subject_id: str, slug: str, language: str, source: str) -> str:
    with closing(connect()) as connection, connection:
        updated_at = profile_stamp(connection)
        connection.execute(
            """
            INSERT INTO leetcode_drafts (
                subject_id, question_slug, language, source, updated_at
            ) VALUES (?, ?, ?, ?, ?)
            ON CONFLICT(subject_id, question_slug, language) DO UPDATE SET
                source = excluded.source,
                updated_at = excluded.updated_at
            """,
            (subject_id, slug, language, source, updated_at),
        )
    return updated_at


def load_draft(subject_id: str, slug: str, language: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT source, updated_at FROM leetcode_drafts"
            " WHERE subject_id = ? AND question_slug = ? AND language = ?",
            (subject_id, slug, language),
        ).fetchone()
    return dict(row) if row is not None else None


# ---------------------------------------------------------------------------
# submissions and progress
# ---------------------------------------------------------------------------


def record_submission(
    subject_id: str,
    slug: str,
    language: str,
    source: str,
    verdict: Any,
) -> dict[str, Any]:
    """Persist one graded submission and update the member's progress."""

    failing = verdict.failing
    with closing(connect()) as connection, connection:
        connection.execute("BEGIN IMMEDIATE")
        created_at = _stamp(connection)
        cursor = connection.execute(
            """
            INSERT INTO leetcode_submissions (
                subject_id, question_slug, language, status, message, passed,
                total, runtime_ms, memory_mb, runtime_percentile,
                memory_percentile, failing_input, failing_output,
                failing_expected, source, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                subject_id,
                slug,
                language,
                verdict.status,
                verdict.message,
                verdict.passed,
                verdict.total,
                verdict.runtime_ms,
                verdict.memory_mb,
                verdict.runtime_percentile,
                verdict.memory_percentile,
                failing.input if failing is not None else None,
                failing.output if failing is not None else None,
                failing.expected if failing is not None else None,
                source,
                created_at,
            ),
        )
        submission_id = int(cursor.lastrowid or 0)
        solved = verdict.status == "Accepted"
        existing = connection.execute(
            "SELECT status, first_solved_at, attempts FROM leetcode_progress"
            " WHERE subject_id = ? AND question_slug = ?",
            (subject_id, slug),
        ).fetchone()
        attempts = (int(existing["attempts"]) if existing is not None else 0) + 1
        first_solved_at = existing["first_solved_at"] if existing is not None else None
        if solved and first_solved_at is None:
            first_solved_at = created_at
        status = SOLVED if (solved or first_solved_at is not None) else ATTEMPTED
        connection.execute(
            """
            INSERT INTO leetcode_progress (
                subject_id, question_slug, status, first_solved_at,
                last_submitted_at, attempts
            ) VALUES (?, ?, ?, ?, ?, ?)
            ON CONFLICT(subject_id, question_slug) DO UPDATE SET
                status = excluded.status,
                first_solved_at = excluded.first_solved_at,
                last_submitted_at = excluded.last_submitted_at,
                attempts = excluded.attempts
            """,
            (subject_id, slug, status, first_solved_at, created_at, attempts),
        )
    return {"submission_id": submission_id, "created_at": created_at}


def submission(subject_id: str, submission_id: int) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM leetcode_submissions WHERE id = ? AND subject_id = ?",
            (submission_id, subject_id),
        ).fetchone()
    return dict(row) if row is not None else None


def submissions(
    subject_id: str,
    *,
    slug: str | None = None,
    limit: int = 20,
    offset: int = 0,
) -> list[dict[str, Any]]:
    query = (
        "SELECT s.*, q.title, q.number FROM leetcode_submissions s"
        " JOIN leetcode_questions q ON q.slug = s.question_slug"
        " WHERE s.subject_id = ?"
    )
    parameters: list[Any] = [subject_id]
    if slug is not None:
        query += " AND s.question_slug = ?"
        parameters.append(slug)
    query += " ORDER BY s.id DESC LIMIT ? OFFSET ?"
    parameters.extend([limit, offset])
    with closing(connect()) as connection:
        return [dict(row) for row in connection.execute(query, parameters)]


def submission_count(subject_id: str, *, slug: str | None = None) -> int:
    query = "SELECT COUNT(*) FROM leetcode_submissions WHERE subject_id = ?"
    parameters: list[Any] = [subject_id]
    if slug is not None:
        query += " AND question_slug = ?"
        parameters.append(slug)
    with closing(connect()) as connection:
        row = connection.execute(query, parameters).fetchone()
    return int(row[0]) if row is not None else 0


def progress_map(subject_id: str | None) -> dict[str, str]:
    if not subject_id:
        return {}
    with closing(connect()) as connection:
        return {
            str(row["question_slug"]): str(row["status"])
            for row in connection.execute(
                "SELECT question_slug, status FROM leetcode_progress"
                " WHERE subject_id = ?",
                (subject_id,),
            )
        }


def progress_summary(subject_id: str | None) -> dict[str, Any]:
    """Solved/attempted counts by difficulty, plus the totals shown on /progress/."""

    totals = {"Easy": 0, "Medium": 0, "Hard": 0}
    solved = {"Easy": 0, "Medium": 0, "Hard": 0}
    attempted = {"Easy": 0, "Medium": 0, "Hard": 0}
    with closing(connect()) as connection:
        for row in connection.execute(
            "SELECT difficulty, COUNT(*) AS total FROM leetcode_questions"
            " GROUP BY difficulty"
        ):
            totals[str(row["difficulty"])] = int(row["total"])
        if subject_id:
            for row in connection.execute(
                """
                SELECT q.difficulty AS difficulty, p.status AS status,
                       COUNT(*) AS total
                FROM leetcode_progress p
                JOIN leetcode_questions q ON q.slug = p.question_slug
                WHERE p.subject_id = ?
                GROUP BY q.difficulty, p.status
                """,
                (subject_id,),
            ):
                bucket = solved if str(row["status"]) == SOLVED else attempted
                bucket[str(row["difficulty"])] = int(row["total"])
        submissions_total = (
            submission_count(subject_id) if subject_id else 0
        )
        accepted_total = 0
        if subject_id:
            row = connection.execute(
                "SELECT COUNT(*) FROM leetcode_submissions"
                " WHERE subject_id = ? AND status = 'Accepted'",
                (subject_id,),
            ).fetchone()
            accepted_total = int(row[0]) if row is not None else 0
    return {
        "totals": totals,
        "solved": solved,
        "attempted": attempted,
        "total_questions": sum(totals.values()),
        "total_solved": sum(solved.values()),
        "total_attempted": sum(attempted.values()),
        "submissions": submissions_total,
        "accepted": accepted_total,
        "acceptance_rate": (
            round(accepted_total * 100 / submissions_total, 1)
            if submissions_total
            else 0.0
        ),
    }


def last_submitted_map(subject_id: str | None) -> dict[str, str]:
    if not subject_id:
        return {}
    with closing(connect()) as connection:
        return {
            str(row["question_slug"]): str(row["last_submitted_at"])
            for row in connection.execute(
                "SELECT question_slug, last_submitted_at FROM leetcode_progress"
                " WHERE subject_id = ?",
                (subject_id,),
            )
        }