File size: 13,289 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
"""Local route families derived from the Playwright evidence.

``data/families.json`` is written by ``tools/build_local_data.py`` from the
captured page instances. This module turns it into the view models the family
templates render, and it owns two rules that keep the clone honest:

* every list this module hands a template is either a real local route or an
  explicit boundary row — never a ``#`` link and never a remote origin;
* every source-side figure (question counts, chapter counts, contest dates) is
  labelled as a *source* figure, because the local seeded body below it is a
  deterministic sample of this clone's own 1,000-problem catalogue.

Company↔problem and tag↔problem mappings were not capturable: LeetCode renders
company tags behind Premium, and the tag list pages render their rows from an
authenticated API. Each collection page therefore seeds a deterministic local
sample from this clone's catalogue and says so on the page.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Iterable

from . import content


DATA_DIR = Path(__file__).resolve().parent / "data"
FAMILIES: dict[str, Any] = json.loads(
    (DATA_DIR / "families.json").read_text(encoding="utf-8")
)

COMPANY_ROWS: tuple[dict[str, Any], ...] = tuple(FAMILIES["company"]["rows"])
COMPANY_BY_SLUG: dict[str, dict[str, Any]] = {row["slug"]: row for row in COMPANY_ROWS}
COMPANY_POPULATION: int = int(FAMILIES["company"]["population"])
COMPANY_SAMPLE: int = int(FAMILIES["company"]["sample"])

TAG_ROWS: tuple[dict[str, Any], ...] = tuple(FAMILIES["tag"]["rows"])
TAG_BY_SLUG: dict[str, dict[str, Any]] = {row["slug"]: row for row in TAG_ROWS}

EXPLORE_SECTIONS: tuple[dict[str, Any], ...] = tuple(FAMILIES["explore"]["sections"])
EXPLORE_SECTION_BY_PATH: dict[str, dict[str, Any]] = {
    row["path"]: row for row in EXPLORE_SECTIONS
}
EXPLORE_CARDS: tuple[dict[str, Any], ...] = tuple(FAMILIES["explore"]["cards"])
EXPLORE_CARD_BY_PATH: dict[str, dict[str, Any]] = {
    row["path"]: row for row in EXPLORE_CARDS
}

STUDYPLANS: tuple[dict[str, Any], ...] = tuple(FAMILIES["studyplan"]["plans"])
STUDYPLAN_BY_SLUG: dict[str, dict[str, Any]] = {row["slug"]: row for row in STUDYPLANS}
STUDYPLAN_DETAIL: dict[str, dict[str, Any]] = {
    row["slug"]: row for row in FAMILIES["studyplan"]["details"]
}

CONTEST: dict[str, Any] = FAMILIES["contest"]
CONTEST_BY_SLUG: dict[str, dict[str, Any]] = {
    row["slug"]: row for row in (*CONTEST["upcoming"], *CONTEST["past"])
}

DISCUSS: dict[str, Any] = FAMILIES["discuss"]
DISCUSS_BY_ID: dict[str, dict[str, Any]] = {row["id"]: row for row in DISCUSS["posts"]}

PROFILES: tuple[dict[str, Any], ...] = tuple(FAMILIES["profile"])
PROFILE_BY_HANDLE: dict[str, dict[str, Any]] = {
    row["handle"]: row for row in PROFILES
}

PREMIUM: dict[str, Any] = FAMILIES["premium"]
STORE: dict[str, Any] = FAMILIES["store"]
INTERVIEW: dict[str, Any] = FAMILIES["interview"]
ASSESSMENT: dict[str, Any] = FAMILIES["assessment"]
BUSINESS: dict[str, Any] = FAMILIES["business"]
SUPPORT: dict[str, Any] = FAMILIES["support"]
LEGAL: dict[str, Any] = FAMILIES["legal"]
STATIC_PAGES: dict[str, dict[str, Any]] = {
    row["path"]: row for row in FAMILIES["static_pages"]
}
PROBLEMSET_CATEGORIES: tuple[dict[str, Any], ...] = tuple(
    FAMILIES["problemset_categories"]
)

#: Shown wherever a page seeds local rows in place of a source collection the
#: anonymous capture could not enumerate.
SEEDED_NOTE = (
    "The membership list below is a deterministic local sample of this clone's "
    "own 1,000-problem catalogue. The source renders this collection from an "
    "authenticated or Premium-gated API, so no membership was captured and none "
    "is invented here."
)
PREMIUM_BOUNDARY = (
    "This clone implements no payment. LeetCode Premium is presented from the "
    "captured marketing copy only; every subscribe control answers locally and "
    "no card, price or account is ever charged."
)


# ---------------------------------------------------------------------------
# deterministic local sampling
# ---------------------------------------------------------------------------


def _rotate(seed: str) -> int:
    """A stable non-cryptographic offset derived from a slug.

    ``hash()`` is salted per process, so a hand-rolled sum keeps the seeded
    sample identical across restarts, which the site tests depend on.
    """

    total = 0
    for position, character in enumerate(seed):
        total = (total * 131 + ord(character) + position) % 1_000_003
    return total


def sample_questions(seed: str, size: int) -> list[content.Question]:
    """A stable, evenly spread slice of the catalogue for one collection."""

    catalogue = content.LISTING_ORDER
    if not catalogue or size <= 0:
        return []
    size = min(size, len(catalogue))
    offset = _rotate(seed) % len(catalogue)
    stride = max(1, len(catalogue) // size)
    picked: list[content.Question] = []
    seen: set[str] = set()
    index = offset
    while len(picked) < size:
        item = catalogue[index % len(catalogue)]
        if item.slug not in seen:
            seen.add(item.slug)
            picked.append(item)
        index += stride
        if len(seen) >= len(catalogue):
            break
    picked.sort(key=lambda item: item.number)
    return picked


def question_rows(items: Iterable[content.Question]) -> list[dict[str, Any]]:
    return [
        {
            "slug": item.slug,
            "number": item.number,
            "title": item.title,
            "difficulty": item.difficulty,
            "difficulty_label": content.difficulty_label(item.difficulty),
            "acceptance": item.acceptance,
            "href": f"/problems/{item.slug}/description/",
            "premium_locked": item.premium_locked,
        }
        for item in items
    ]


# ---------------------------------------------------------------------------
# collections (company + tag/problem-list)
# ---------------------------------------------------------------------------


def company(slug: str) -> dict[str, Any] | None:
    row = COMPANY_BY_SLUG.get(slug)
    if row is None:
        return None
    size = min(25, max(5, int(row.get("source_question_count") or 0) or 5))
    return {
        "kind": "company",
        "slug": slug,
        "name": row.get("name") or slug,
        "source_question_count": row.get("source_question_count"),
        "source_saved_count": row.get("source_saved_count"),
        "source_updated_label": row.get("source_updated_label"),
        "rows": question_rows(sample_questions(f"company:{slug}", size)),
        "seeded_note": SEEDED_NOTE,
        "discuss_href": "/discuss/",
        "premium_href": "/subscribe/",
    }


def tag(slug: str) -> dict[str, Any] | None:
    row = TAG_BY_SLUG.get(slug)
    if row is None:
        return None
    label = row.get("label") or slug
    local = [item for item in content.LISTING_ORDER if label in item.topics]
    return {
        "kind": "tag",
        "slug": slug,
        "name": label,
        "source_question_count": row.get("source_question_count"),
        "source_saved_count": row.get("source_saved_count"),
        "source_updated_label": row.get("source_updated_label"),
        "list_available": bool(row.get("list_available", True)),
        "label_source": row.get("label_source", "tag-page"),
        "rows": question_rows(local),
        "filter_href": f"/problemset/?topic={label.replace(' ', '+')}",
        "seeded_note": (
            "The rows below are this clone's own 1,000-problem catalogue "
            "filtered by the captured per-problem topic chips. The source "
            "figure beside the heading counts the full 4,029-problem bank."
        ),
        "discuss_href": "/discuss/",
        "premium_href": "/subscribe/",
    }


# ---------------------------------------------------------------------------
# study plans
# ---------------------------------------------------------------------------


def studyplan(slug: str) -> dict[str, Any] | None:
    row = STUDYPLAN_BY_SLUG.get(slug)
    if row is None:
        return None
    detail = STUDYPLAN_DETAIL.get(slug)
    groups: list[dict[str, Any]] = []
    if detail is not None:
        for group in detail["groups"]:
            problems = []
            for entry in group["problems"]:
                local = content.question(entry["slug"])
                problems.append(
                    {
                        "slug": entry["slug"],
                        "title": entry.get("title") or entry["slug"],
                        "difficulty": entry.get("difficulty") or "",
                        "href": (
                            f"/problems/{entry['slug']}/description/"
                            if local is not None
                            else None
                        ),
                    }
                )
            groups.append({"name": group["name"], "problems": problems})
    return {
        "slug": slug,
        "label": row.get("label") or slug,
        "premium": bool(row.get("premium")),
        "detail": detail is not None,
        "title": (detail or {}).get("title") or row.get("label") or slug,
        "groups": groups,
        "problem_total": sum(len(group["problems"]) for group in groups),
        "local_total": sum(
            1
            for group in groups
            for problem in group["problems"]
            if problem["href"] is not None
        ),
    }


# ---------------------------------------------------------------------------
# explore
# ---------------------------------------------------------------------------


def explore_section(path: str) -> dict[str, Any] | None:
    row = EXPLORE_SECTION_BY_PATH.get(path)
    if row is None:
        return None
    cards = []
    for card in row["cards"]:
        target = card.get("path")
        cards.append(
            {
                **card,
                "href": target if target in EXPLORE_CARD_BY_PATH else None,
                "locked": card.get("state") == "Locked" or card.get("premium"),
            }
        )
    return {"path": path, "title": row["title"], "cards": cards}


def explore_card(path: str) -> dict[str, Any] | None:
    row = EXPLORE_CARD_BY_PATH.get(path)
    if row is None:
        return None
    card = row.get("card") or {}
    seed = path.strip("/").rsplit("/", 1)[-1]
    return {
        "path": path,
        "caption": card.get("caption") or "Explore card",
        "chapters": card.get("chapters"),
        "items": card.get("items"),
        "locked": card.get("state") == "Locked" or card.get("premium"),
        "rows": question_rows(sample_questions(f"explore:{seed}", 8)),
        "captured_text": row.get("captured_text", ""),
    }


# ---------------------------------------------------------------------------
# contest
# ---------------------------------------------------------------------------


def contest(slug: str) -> dict[str, Any] | None:
    row = CONTEST_BY_SLUG.get(slug)
    if row is None:
        return None
    upcoming = any(entry["slug"] == slug for entry in CONTEST["upcoming"])
    return {
        "slug": slug,
        "name": row.get("name") or slug,
        "starts": row.get("starts") or "",
        "upcoming": upcoming,
        "rows": question_rows(sample_questions(f"contest:{slug}", 4)),
    }


# ---------------------------------------------------------------------------
# discuss
# ---------------------------------------------------------------------------


def discuss_post(identifier: str) -> dict[str, Any] | None:
    row = DISCUSS_BY_ID.get(identifier)
    if row is None:
        return None
    featured = DISCUSS.get("featured_post") or {}
    body = featured.get("captured_text", "") if featured.get("path") == row["path"] else ""
    return {
        "id": identifier,
        "path": row["path"],
        "title": row.get("label") or featured.get("title") or "Discuss post",
        "captured_body": body,
        "has_body": bool(body),
    }


# ---------------------------------------------------------------------------
# public profiles
# ---------------------------------------------------------------------------


def profile(handle: str) -> dict[str, Any]:
    row = PROFILE_BY_HANDLE.get(handle)
    return {
        "handle": handle,
        "captured": row is not None,
        "title": (row or {}).get("title") or handle,
        "captured_text": (row or {}).get("captured_text", ""),
    }


__all__ = [
    "ASSESSMENT",
    "BUSINESS",
    "COMPANY_BY_SLUG",
    "COMPANY_POPULATION",
    "COMPANY_ROWS",
    "COMPANY_SAMPLE",
    "CONTEST",
    "CONTEST_BY_SLUG",
    "DISCUSS",
    "DISCUSS_BY_ID",
    "EXPLORE_CARDS",
    "EXPLORE_CARD_BY_PATH",
    "EXPLORE_SECTIONS",
    "EXPLORE_SECTION_BY_PATH",
    "INTERVIEW",
    "LEGAL",
    "PREMIUM",
    "PREMIUM_BOUNDARY",
    "PROBLEMSET_CATEGORIES",
    "PROFILES",
    "SEEDED_NOTE",
    "STATIC_PAGES",
    "STORE",
    "STUDYPLANS",
    "STUDYPLAN_BY_SLUG",
    "STUDYPLAN_DETAIL",
    "SUPPORT",
    "TAG_BY_SLUG",
    "TAG_ROWS",
    "company",
    "contest",
    "discuss_post",
    "explore_card",
    "explore_section",
    "profile",
    "question_rows",
    "sample_questions",
    "studyplan",
    "tag",
]