File size: 12,893 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
"""Problem-set search, filtering, sorting and paging.

The catalogue lives in ``leetcode_questions`` and every list the site renders
is produced by one SQL query against it, joined with the signed-in member's
``leetcode_progress`` rows when there is one. Filter state is expressed
entirely in the URL so a filtered list can be linked, refreshed and shared.
"""

from __future__ import annotations

import json
from contextlib import closing
from dataclasses import dataclass, field
from typing import Any, Iterable, Sequence
from urllib.parse import urlencode

from . import content, store


# The captured problem-set page rendered the pinned daily question plus
# questions 1-100 in one uninterrupted list, so one page is exactly that many
# rows. Paging then continues into the rest of the local catalogue.
PER_PAGE = 101
MAX_PAGE = 999

# Every key the query layer accepts. ``frequency`` and ``contest-point`` are
# deliberately absent from the visible sort menu (``content.SORT_OPTIONS``):
# the source prints both behind a Premium lock and captured no values, so the
# clone will not offer them as if they were source facts. They stay orderable
# here because the stored figures are deterministic and the JSON surface is
# expected to sort by any stored column.
SORT_COLUMNS: dict[str, str] = {
    "custom": "q.number",
    "difficulty": "CASE q.difficulty WHEN 'Easy' THEN 1 WHEN 'Medium' THEN 2"
    " ELSE 3 END",
    "acceptance": "q.acceptance",
    "question-id": "q.number",
    "title": "LOWER(q.title)",
    "last-submitted": "COALESCE(p.last_submitted_at, '')",
    "frequency": "q.frequency",
    "contest-point": "q.contest_point",
}

DEFAULT_ORDER: dict[str, str] = {
    "custom": "asc",
    "difficulty": "asc",
    "acceptance": "asc",
    "question-id": "asc",
    "title": "asc",
    "last-submitted": "desc",
    "frequency": "desc",
    "contest-point": "desc",
}


@dataclass
class ProblemQuery:
    category: str = "all"
    search: str = ""
    difficulty: str = ""
    status: str = ""
    topics: tuple[str, ...] = ()
    language: str = ""
    sort: str = "custom"
    order: str = ""
    page: int = 1

    @property
    def effective_order(self) -> str:
        if self.order in {"asc", "desc"}:
            return self.order
        return DEFAULT_ORDER.get(self.sort, "asc")

    @property
    def is_filtered(self) -> bool:
        return bool(
            self.search
            or self.difficulty
            or self.status
            or self.topics
            or self.language
            or self.sort != "custom"
            or self.order
        )

    def path(self) -> str:
        if self.category and self.category != "all":
            return f"/problemset/{self.category}"
        return "/problemset/"

    def as_params(self, **overrides: Any) -> list[tuple[str, str]]:
        values: list[tuple[str, str]] = []
        search = overrides.get("search", self.search)
        difficulty = overrides.get("difficulty", self.difficulty)
        status = overrides.get("status", self.status)
        topics = overrides.get("topics", self.topics)
        language = overrides.get("language", self.language)
        sort = overrides.get("sort", self.sort)
        order = overrides.get("order", self.order)
        page = overrides.get("page", self.page)
        if search:
            values.append(("search", search))
        if difficulty:
            values.append(("difficulty", difficulty))
        if status:
            values.append(("status", status))
        for topic in topics:
            values.append(("topic", topic))
        if language:
            values.append(("language", language))
        if sort and sort != "custom":
            values.append(("sort", sort))
        if order:
            values.append(("order", order))
        if page and int(page) > 1:
            values.append(("page", str(page)))
        return values

    def url(self, **overrides: Any) -> str:
        category = overrides.pop("category", self.category)
        base = (
            f"/problemset/{category}"
            if category and category != "all"
            else "/problemset/"
        )
        params = self.as_params(**overrides)
        return f"{base}?{urlencode(params)}" if params else base


def _first(values: Sequence[str]) -> str:
    for value in values:
        text = str(value).strip()
        if text:
            return text
    return ""


def parse_query(params: Any, category: str = "all") -> ProblemQuery:
    """Build the query state from the request's own URL parameters."""

    getlist = getattr(params, "getlist", None)
    def values(name: str) -> list[str]:
        if getlist is not None:
            return [str(item) for item in getlist(name)]
        raw = params.get(name)
        return [] if raw is None else [str(raw)]

    difficulty = _first(values("difficulty"))
    if difficulty not in {"", "Easy", "Medium", "Hard"}:
        difficulty = ""
    status = _first(values("status")).casefold()
    if status not in {"", "todo", "solved", "attempted"}:
        status = ""
    topics = tuple(
        topic
        for topic in dict.fromkeys(
            item.strip() for item in values("topic") if item.strip()
        )
        if topic in content.ALL_TOPICS
    )
    language = _first(values("language"))
    if language not in content.LANGUAGE_LABELS:
        language = ""
    sort = _first(values("sort")) or "custom"
    if sort not in SORT_COLUMNS:
        sort = "custom"
    order = _first(values("order")).casefold()
    if order not in {"asc", "desc"}:
        order = ""
    try:
        page = int(_first(values("page")) or "1")
    except ValueError:
        page = 1
    page = max(1, min(page, MAX_PAGE))
    valid_categories = {slug for slug, _ in content.CATEGORIES}
    return ProblemQuery(
        category=category if category in valid_categories else "all",
        search=_first(values("search"))[:120],
        difficulty=difficulty,
        status=status,
        topics=topics,
        language=language,
        sort=sort,
        order=order,
        page=page,
    )


@dataclass
class ProblemPage:
    rows: list[dict[str, Any]] = field(default_factory=list)
    total: int = 0
    page: int = 1
    per_page: int = PER_PAGE
    solved: int = 0
    catalogue_total: int = 0

    @property
    def pages(self) -> int:
        return max(1, -(-self.total // self.per_page))

    @property
    def start_index(self) -> int:
        return 0 if not self.total else (self.page - 1) * self.per_page + 1

    @property
    def end_index(self) -> int:
        return min(self.total, self.page * self.per_page)

    @property
    def is_empty(self) -> bool:
        return self.total == 0


def _where(query: ProblemQuery, subject_id: str | None) -> tuple[str, list[Any]]:
    clauses: list[str] = []
    parameters: list[Any] = []
    if query.category != "all":
        clauses.append("q.category = ?")
        parameters.append(query.category)
    if query.search:
        clauses.append("(LOWER(q.title) LIKE ? OR CAST(q.number AS TEXT) LIKE ?)")
        needle = f"%{query.search.casefold()}%"
        parameters.extend([needle, f"%{query.search.strip()}%"])
    if query.difficulty:
        clauses.append("q.difficulty = ?")
        parameters.append(query.difficulty)
    for topic in query.topics:
        clauses.append("q.topics_json LIKE ?")
        parameters.append(f'%"{topic}"%')
    if query.language:
        clauses.append("q.languages_json LIKE ?")
        parameters.append(f'%"{query.language}"%')
    if query.status and subject_id:
        if query.status == "todo":
            clauses.append("p.status IS NULL")
        else:
            clauses.append("p.status = ?")
            parameters.append(query.status)
    elif query.status == "solved" and not subject_id:
        clauses.append("1 = 0")
    return (" AND ".join(clauses) if clauses else "1 = 1"), parameters


def run_query(query: ProblemQuery, subject_id: str | None) -> ProblemPage:
    where, parameters = _where(query, subject_id)
    column = SORT_COLUMNS.get(query.sort, "q.number")
    direction = "ASC" if query.effective_order == "asc" else "DESC"
    join_subject = subject_id or ""
    # The daily question sits above the list, as the captured page rendered it,
    # but only while the visitor has not chosen their own ordering.
    pinning = query.sort in {"custom", "question-id"} and not query.order
    pin = "CASE WHEN q.slug = ? THEN 0 ELSE 1 END, " if pinning else ""
    pin_parameters: list[Any] = [content.DAILY_SLUG] if pinning else []
    with closing(store.connect()) as connection:
        total_row = connection.execute(
            "SELECT COUNT(*) FROM leetcode_questions q"
            " LEFT JOIN leetcode_progress p"
            " ON p.question_slug = q.slug AND p.subject_id = ?"
            f" WHERE {where}",
            [join_subject, *parameters],
        ).fetchone()
        total = int(total_row[0]) if total_row is not None else 0
        pages = max(1, -(-total // PER_PAGE))
        page = min(max(1, query.page), pages)
        rows = connection.execute(
            "SELECT q.*, p.status AS member_status,"
            " p.last_submitted_at AS member_last_submitted"
            " FROM leetcode_questions q"
            " LEFT JOIN leetcode_progress p"
            " ON p.question_slug = q.slug AND p.subject_id = ?"
            f" WHERE {where}"
            f" ORDER BY {pin}{column} {direction}, q.number ASC"
            " LIMIT ? OFFSET ?",
            [
                join_subject,
                *parameters,
                *pin_parameters,
                PER_PAGE,
                (page - 1) * PER_PAGE,
            ],
        ).fetchall()
        catalogue_row = connection.execute(
            "SELECT COUNT(*) FROM leetcode_questions"
        ).fetchone()
        catalogue_total = int(catalogue_row[0]) if catalogue_row is not None else 0
        solved = 0
        if subject_id:
            solved_row = connection.execute(
                "SELECT COUNT(*) FROM leetcode_progress"
                " WHERE subject_id = ? AND status = 'solved'",
                (subject_id,),
            ).fetchone()
            solved = int(solved_row[0]) if solved_row is not None else 0
    return ProblemPage(
        rows=[_public_row(row) for row in rows],
        total=total,
        page=page,
        solved=solved,
        catalogue_total=catalogue_total,
    )


def _public_row(row: Any) -> dict[str, Any]:
    slug = str(row["slug"])
    item = content.question(slug)
    return {
        "slug": slug,
        "number": int(row["number"]),
        "title": row["title"],
        "difficulty": row["difficulty"],
        "difficulty_label": content.difficulty_label(str(row["difficulty"])),
        "category": row["category"],
        "topics": json.loads(row["topics_json"]),
        "languages": json.loads(row["languages_json"]),
        "acceptance": float(row["acceptance"]),
        "frequency": int(row["frequency"]),
        "contest_point": int(row["contest_point"]),
        "status": row["member_status"],
        "last_submitted": row["member_last_submitted"],
        "is_daily": slug == content.DAILY_SLUG,
        "workspace_ready": bool(item and item.workspace_ready),
    }


def random_slug(query: ProblemQuery, subject_id: str | None, seed: str = "") -> str | None:
    """Pick one question from the active filter for the shuffle control."""

    import random

    where, parameters = _where(query, subject_id)
    with closing(store.connect()) as connection:
        slugs = [
            str(row["slug"])
            for row in connection.execute(
                "SELECT q.slug FROM leetcode_questions q"
                " LEFT JOIN leetcode_progress p"
                " ON p.question_slug = q.slug AND p.subject_id = ?"
                f" WHERE {where} ORDER BY q.number",
                [subject_id or "", *parameters],
            )
        ]
    if not slugs:
        return None
    chooser = random.Random(seed) if seed else random.Random()
    return chooser.choice(slugs)


def topic_counts(category: str = "all") -> list[tuple[str, int]]:
    counts: dict[str, int] = {}
    for question in content.iter_questions():
        if category != "all" and question.category != category:
            continue
        for topic in question.topics:
            counts[topic] = counts.get(topic, 0) + 1
    return sorted(counts.items(), key=lambda item: (-item[1], item[0]))


def category_counts() -> dict[str, int]:
    counts: dict[str, int] = {"all": 0}
    for question in content.iter_questions():
        counts["all"] += 1
        counts[question.category] = counts.get(question.category, 0) + 1
    return counts


def iter_pages(page: int, pages: int) -> Iterable[int]:
    window = {1, pages, page, page - 1, page + 1}
    return sorted(number for number in window if 1 <= number <= pages)