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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
"""LeetCode offline clone — FastAPI composition root.

Every route below is served from this process with no remote dependency. The
layering is described in :mod:`leetcode_app`:

* ``leetcode_app.content``  — the seeded local question catalogue.
* ``leetcode_app.store``    — this site's SQLite business schema, opened through
  the generated ``backend/site_backend_integration.py`` seam.
* ``leetcode_app.accounts`` — account/session/recovery flows on top of the
  vendored ``websitebench.local_clone_auth`` store.
* ``leetcode_app.judge``    — the deterministic offline verdict model. Guest
  source code is never executed.
* ``leetcode_app.query``    — problem-set search, filter, sort and paging.
* ``leetcode_app.render``   — the Jinja2 environment.

Runtime contracts this file owns:

* ``GET  /healthz``               -> ``{"ok":true,"site_id":"leetcode"}``
* ``GET  /__websitebench/health`` -> ``{"status":"ok"}`` (Harbor deployment ABI)
* ``POST /__admin/reset``         -> deterministic reset, admin-token guarded
* ``GET  /__admin/mail/latest``   -> session-scoped verification-code inspection
  through ``LocalAuthStore.local_mail_for_session``; admin-token guarded
* ``GET  /api/session``           -> the caller's own session state
* ``GET  /api/questions``         -> the problem-set query as JSON

``/api/*`` is a JSON surface: an unknown path under it answers
``{"error":"not-found"}`` with 404 rather than the HTML 404 page. Every other
unknown path renders the HTML 404 page. The ``/api`` routes exist for
deterministic evaluation and for the page scripts; they are not part of the
captured source and are never rendered as if they were.

Every response carries a same-origin Content-Security-Policy, so no remote
origin is reachable from a rendered page.
"""

from __future__ import annotations

import hmac
import json
import os
import sys
from pathlib import Path
from typing import Any
from urllib.parse import quote, urlencode

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from starlette.staticfiles import StaticFiles

ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:  # vendored websitebench + backend imports
    sys.path.insert(0, str(ROOT))

from leetcode_app import (  # noqa: E402
    DISPLAY_NAME,
    SITE_ID,
    accounts,
    content,
    families,
    judge,
    query as problem_query,
    sidebar,
    store,
)
from leetcode_app.render import render  # noqa: E402

STATIC_DIR = ROOT / "static"

_HEALTH_BODY = json.dumps({"ok": True, "site_id": SITE_ID}, separators=(",", ":"))
_HARBOR_HEALTH_BODY = '{"status":"ok"}'

# Admin token for the two ``/__admin`` control endpoints. A non-secret local
# default keeps `pytest` and the shared diagnostics runnable; a deployment
# injects the real value through the environment. It is never logged.
ADMIN_TOKEN = os.environ.get("WEBSITEBENCH_LEETCODE_ADMIN_TOKEN", "leetcode-local-admin")
ADMIN_HEADER = "X-WebsiteBench-Admin-Token"

BUILD_ID = os.environ.get("DEPLOYMENT_BUILD_ID") or os.environ.get(
    "WEBSITEBENCH_BUILD_ID"
)

CONTENT_SECURITY_POLICY = (
    "default-src 'self'; "
    "img-src 'self' data:; "
    "style-src 'self' 'unsafe-inline'; "
    "script-src 'self'; "
    "font-src 'self' data:; "
    "connect-src 'self'; "
    "frame-ancestors 'none'; "
    "base-uri 'self'; "
    "form-action 'self'"
)

SESSION_STATE_KEY = "leetcode_session"

#: Liveness probes must answer before, and independently of, the business
#: database. The deployment ABI waits on them, so a storage fault has to show
#: up as a failing page rather than as a process that never reports at all.
LIVENESS_PATHS = frozenset({"/healthz", "/__websitebench/health"})

WORKBENCH_TABS: tuple[tuple[str, str], ...] = (
    ("description", "Description"),
    ("editorial", "Editorial"),
    ("solutions", "Solutions"),
    ("submissions", "Submissions"),
)

# The few captured destinations with no local reconstruction of their own.
# Everything else in the chrome now has a real family page below.
BOUNDARY_PAGES: dict[str, tuple[str, str]] = {
    "/developer/": ("Developer", "The developer tools the home page describes"),
}

app = FastAPI(title=DISPLAY_NAME, docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")


# ---------------------------------------------------------------------------
# session plumbing
# ---------------------------------------------------------------------------


def _cookie_name() -> str:
    return str(accounts.session_cookie_settings()["name"])


def _apply_session_cookie(response: Response, token: str) -> Response:
    settings = accounts.session_cookie_settings()
    response.set_cookie(
        settings["name"],
        token,
        max_age=60 * 60 * 24 * 30,
        path=str(settings.get("path", "/")),
        secure=bool(settings.get("secure", True)),
        httponly=bool(settings.get("httponly", True)),
        samesite=str(settings.get("samesite", "Lax")).lower(),
    )
    return response


@app.middleware("http")
async def session_and_headers(request: Request, call_next):
    """Attach one durable browser session, then stamp the runtime headers."""

    token: str | None = None
    info: dict[str, Any] = {}
    if request.url.path not in LIVENESS_PATHS:
        try:
            token, info = accounts.ensure_session(request.cookies.get(_cookie_name()))
        except Exception:  # noqa: BLE001 - a broken session must not 500 the page
            try:
                token, info = accounts.ensure_session(None)
            except Exception:  # noqa: BLE001 - storage is down; stay anonymous
                token, info = None, {}
    setattr(request.state, SESSION_STATE_KEY, (token or "", info))
    response = await call_next(request)
    rotated = getattr(request.state, "rotated_session", None)
    if rotated is not None:
        _apply_session_cookie(response, rotated)
    elif getattr(request.state, "cleared_session", False):
        response.delete_cookie(_cookie_name(), path="/")
    elif token:
        _apply_session_cookie(response, token)
    response.headers["Content-Security-Policy"] = CONTENT_SECURITY_POLICY
    response.headers["Referrer-Policy"] = "no-referrer"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    if BUILD_ID:
        response.headers["X-WebsiteBench-Build-Id"] = BUILD_ID
    return response


def _session(request: Request) -> tuple[str, dict[str, Any]]:
    return getattr(request.state, SESSION_STATE_KEY)


def _member(request: Request) -> dict[str, Any] | None:
    _, info = _session(request)
    return accounts.current_member(info)


def _subject(request: Request) -> str | None:
    member = _member(request)
    return None if member is None else str(member["subject_id"])


def _html(body: str, status_code: int = 200) -> HTMLResponse:
    return HTMLResponse(body, status_code=status_code)


def _redirect(request: Request, location: str, token: str | None = None) -> Response:
    response = RedirectResponse(location, status_code=303)
    if token is not None:
        request.state.rotated_session = token
    return response


def _safe_next(value: str | None, fallback: str = "/") -> str:
    """Only same-origin absolute paths may come back from a form field."""

    if not value or not value.startswith("/") or value.startswith("//"):
        return fallback
    return value


# ---------------------------------------------------------------------------
# runtime + control endpoints
# ---------------------------------------------------------------------------


@app.get("/healthz", include_in_schema=False)
async def healthz() -> Response:
    return Response(content=_HEALTH_BODY, media_type="application/json")


@app.get("/__websitebench/health", include_in_schema=False)
async def harbor_health() -> Response:
    return Response(content=_HARBOR_HEALTH_BODY, media_type="application/json")


def _admin_authorized(request: Request) -> bool:
    return hmac.compare_digest(request.headers.get(ADMIN_HEADER, ""), ADMIN_TOKEN)


@app.post("/__admin/reset", include_in_schema=False)
async def admin_reset(request: Request) -> JSONResponse:
    """Deterministic reset: clear member state and re-seed the catalogue."""

    if not _admin_authorized(request):
        return JSONResponse({"error": "forbidden"}, status_code=403)
    store.reset()
    request.state.cleared_session = True
    return JSONResponse(
        {"reset": True, "site_id": SITE_ID, "questions": store.question_count()}
    )


@app.get("/__admin/mail/latest", include_in_schema=False)
async def admin_mail_latest(request: Request) -> JSONResponse:
    """Session-scoped verification-code inspection for a deterministic evaluator.

    This is the vendored store's own control surface
    (``LocalAuthStore.local_mail_for_session``): it returns only the message the
    *calling session* is waiting on, so it can never read another visitor's
    code. The site adds nothing to it beyond the admin-token guard.
    """

    if not _admin_authorized(request):
        return JSONResponse({"error": "forbidden"}, status_code=403)
    purpose = request.query_params.get("purpose", "registration")
    if purpose not in {"registration", "password-reset"}:
        return JSONResponse({"error": "unknown-purpose"}, status_code=400)
    token, _ = _session(request)
    message = accounts.pending_message(token, purpose)
    status = accounts.flow_status(token, purpose)
    if message is None:
        return JSONResponse(
            {"purpose": purpose, "pending": False, "flow": status}, status_code=404
        )
    return JSONResponse(
        {
            "purpose": purpose,
            "pending": True,
            "flow": status,
            "recipient": message["recipient"],
            "subject": message["subject"],
            "verification_code": message["code"],
        }
    )


# ---------------------------------------------------------------------------
# JSON surface
#
# These two routes are this clone's own read API. Nothing under ``/api`` was
# captured from the source; they exist so the page scripts and a deterministic
# evaluator can read the same state the templates render, without scraping
# HTML. Both are read-only, session-scoped and same-origin.
# ---------------------------------------------------------------------------


@app.get("/api/session", include_in_schema=False)
async def api_session(request: Request) -> JSONResponse:
    """The calling session's own identity. Never another visitor's."""

    member = _member(request)
    return JSONResponse(
        {
            "site_id": SITE_ID,
            "authenticated": member is not None,
            "member": (
                None
                if member is None
                else {"username": member["username"], "email": member["email"]}
            ),
        }
    )


@app.get("/api/questions", include_in_schema=False)
async def api_questions(request: Request) -> JSONResponse:
    """The problem-set query, with the same filters the HTML list accepts."""

    subject_id = _subject(request)
    requested = str(request.query_params.get("category", "all"))
    state = problem_query.parse_query(request.query_params, requested)
    page = problem_query.run_query(state, subject_id)
    return JSONResponse(
        {
            "questions": page.rows,
            "total": page.total,
            "page": page.page,
            "pages": page.pages,
            "per_page": page.per_page,
            "catalogue_total": page.catalogue_total,
            "solved": page.solved,
            "daily_slug": content.DAILY_SLUG,
            "query": {
                "category": state.category,
                "search": state.search,
                "difficulty": state.difficulty,
                "status": state.status,
                "topics": list(state.topics),
                "language": state.language,
                "sort": state.sort,
                "order": state.effective_order,
            },
        }
    )


# ---------------------------------------------------------------------------
# marketing home
# ---------------------------------------------------------------------------


@app.get("/", include_in_schema=False)
async def home(request: Request) -> HTMLResponse:
    return _html(
        render(
            "home.html",
            member=_member(request),
            body_class="marketing",
            catalogue_total=store.question_count(),
            playground_snippets=content.PLAYGROUND_SNIPPETS,
        )
    )


# ---------------------------------------------------------------------------
# problem set
# ---------------------------------------------------------------------------


def _problemset(request: Request, category: str) -> HTMLResponse:
    subject_id = _subject(request)
    state = problem_query.parse_query(request.query_params, category)
    page = problem_query.run_query(state, subject_id)
    return _html(
        render(
            "problemset.html",
            member=_member(request),
            body_class="app",
            query=state,
            page=page,
            topics=problem_query.topic_counts(state.category),
            page_numbers=list(problem_query.iter_pages(page.page, page.pages)),
            random_url=_random_url(state),
            solved_percent=(
                round(page.solved * 100 / page.catalogue_total, 1)
                if page.catalogue_total
                else 0
            ),
            daily_slug=content.DAILY_SLUG,
            source_total=content.SOURCE_TOTAL,
            calendar=sidebar.daily_panel(),
            companies=sidebar.companies(),
        )
    )


def _random_url(state: problem_query.ProblemQuery) -> str:
    """The "Pick one" control keeps whatever filter the list is showing."""

    params = state.as_params(page=1)
    if state.category != "all":
        params = [("category", state.category), *params]
    suffix = f"?{urlencode(params)}" if params else ""
    return f"/problemset/random/{suffix}"


@app.get("/problemset", include_in_schema=False)
@app.get("/problemset/", include_in_schema=False)
async def problemset_all(request: Request) -> HTMLResponse:
    return _problemset(request, "all")


def _shuffle(request: Request) -> Response:
    """Send the visitor to one question drawn from the active filter.

    The draw is uniform over the filtered set. ``?seed=`` makes one draw
    repeatable, which is what a deterministic evaluator needs. When nothing
    matches there is nothing to draw, so the control returns to the list it
    came from instead of dead-ending on a 404.
    """

    category = str(request.query_params.get("category", "all"))
    state = problem_query.parse_query(request.query_params, category)
    seed = str(request.query_params.get("seed", "")).strip()
    slug = problem_query.random_slug(state, _subject(request), seed)
    if slug is None:
        return RedirectResponse(state.path(), status_code=303)
    return RedirectResponse(f"/problems/{slug}/description/", status_code=303)


@app.get("/problemset/random", include_in_schema=False)
@app.get("/problemset/random/", include_in_schema=False)
async def problemset_random(request: Request) -> Response:
    return _shuffle(request)


# Both spellings render directly. The source links its category tabs with a
# trailing slash (``/problemset/database/``, ``/problemset/all-code-essentials/``)
# and the local nav links them without one, so neither form may bounce through a
# redirect on the way to the list.
@app.get("/problemset/{category}", include_in_schema=False)
@app.get("/problemset/{category}/", include_in_schema=False)
async def problemset_category(request: Request, category: str) -> Response:
    known = {slug for slug, _ in content.CATEGORIES}
    # The source serves the "All Topics" tab at /problemset/all-code-essentials.
    alias = {"all-code-essentials": "all"}.get(category, category)
    if alias not in known:
        return _not_found(request)
    return _problemset(request, alias)


@app.get("/problems/random", include_in_schema=False)
@app.get("/problems/random/", include_in_schema=False)
async def problems_random(request: Request) -> Response:
    """The workspace header's shuffle. Same draw as /problemset/random/."""

    return _shuffle(request)


# ---------------------------------------------------------------------------
# problem workspace
# ---------------------------------------------------------------------------


def _workbench_context(
    request: Request,
    item: content.Question,
    tab: str,
    *,
    result: dict[str, Any] | None = None,
    console_tab: str = "testcase",
    cases: list[str] | None = None,
    source: str | None = None,
    language: str | None = None,
) -> dict[str, Any]:
    member = _member(request)
    subject_id = None if member is None else str(member["subject_id"])
    chosen = content.normalize_language(item, language or request.query_params.get("lang"))
    draft = (
        store.load_draft(subject_id, item.slug, chosen) if subject_id is not None else None
    )
    editor_source = source
    if editor_source is None:
        editor_source = draft["source"] if draft else item.starter.get(chosen, "")
    next_path = f"/problems/{item.slug}/{tab}/"
    return {
        "member": member,
        "body_class": "workbench",
        "question": item,
        "tab": tab,
        "tabs": WORKBENCH_TABS,
        "language": chosen,
        "language_query": f"?lang={chosen}" if chosen != item.default_language else "",
        "source": editor_source,
        "cases": cases if cases is not None else list(item.cases),
        "supports_custom_input": item.supports_custom_input,
        "console_tab": console_tab,
        "result": result,
        "auth_notice": None if member else content.ANONYMOUS_JUDGE_NOTICE,
        "next_path": next_path,
        "saved_label": "Saved" if draft else "Auto",
        "neighbours": content.neighbours(item.slug),
        "similar": content.similar_questions(item),
        "no_workspace_notice": content.NO_WORKSPACE_NOTICE,
        "question_submissions": (
            store.submissions(subject_id, slug=item.slug, limit=20)
            if subject_id is not None
            else []
        ),
        "progress_status": (
            store.progress_map(subject_id).get(item.slug) if subject_id else None
        ),
    }


@app.get("/problems/{slug}", include_in_schema=False)
@app.get("/problems/{slug}/", include_in_schema=False)
async def problem_root(slug: str) -> Response:
    """The source links questions without a tab; the tab is always Description."""

    if content.question(slug) is None:
        return RedirectResponse("/problemset/", status_code=307)
    return RedirectResponse(f"/problems/{slug}/description/", status_code=307)


@app.get("/problems/{slug}/{tab}/", include_in_schema=False)
async def problem_tab(request: Request, slug: str, tab: str) -> Response:
    item = content.question(slug)
    known = {tab_id for tab_id, _ in WORKBENCH_TABS}
    if item is None or tab not in known:
        return _not_found(request)
    return _html(render("workbench.html", **_workbench_context(request, item, tab)))


def _submitted_cases(form: Any, item: content.Question) -> list[str]:
    """Reassemble the console's per-parameter fields back into whole cases.

    The console renders one labelled field per parameter, exactly as the source
    does, so a question with an arity of two posts two ``case_line`` values per
    case. A question with no parameter labels posts one field per case.
    """

    if not item.supports_custom_input:
        return list(item.cases)
    lines = [str(value) for value in form.getlist("case_line")]
    if not lines:
        return list(item.cases)
    arity = max(1, len(item.case_labels))
    cases = [
        "\n".join(part.strip() for part in lines[start : start + arity])
        for start in range(0, len(lines), arity)
    ]
    kept = [case for case in cases if case.strip()]
    return kept or list(item.cases)


def _prefers_json(request: Request) -> bool:
    """Whether the caller asked for the verdict as data rather than a page.

    The console posts the form and gets the whole workspace back, exactly as
    the source does. A script or an evaluator that sends ``Accept:
    application/json`` gets the same verdict as JSON instead.
    """

    accept = request.headers.get("accept", "")
    return "application/json" in accept and "text/html" not in accept


@app.post("/problems/{slug}/judge", include_in_schema=False)
async def problem_judge(request: Request, slug: str) -> Response:
    item = content.question(slug)
    if item is None:
        return _not_found(request)
    as_json = _prefers_json(request)
    form = await request.form()
    action = str(form.get("action", "run")).strip().casefold()
    if action not in {"run", "submit"}:
        action = "run"
    language = content.normalize_language(item, str(form.get("language", "")))
    source = str(form.get("source", ""))
    cases = _submitted_cases(form, item)

    member = _member(request)
    if member is None:
        if as_json:
            return JSONResponse(
                {"error": "authentication-required", "message": content.ANONYMOUS_JUDGE_NOTICE},
                status_code=403,
            )
        context = _workbench_context(
            request,
            item,
            "description",
            console_tab="result",
            cases=cases,
            source=source,
            language=language,
        )
        return _html(render("workbench.html", **context), status_code=403)

    subject_id = str(member["subject_id"])
    store.save_draft(subject_id, item.slug, language, source)
    if not item.workspace_ready:
        if as_json:
            return JSONResponse(
                {
                    "error": "no-workspace",
                    "message": content.NO_WORKSPACE_NOTICE,
                    "slug": item.slug,
                    "mode": action,
                },
                status_code=422,
            )
        context = _workbench_context(
            request,
            item,
            "description",
            console_tab="result",
            cases=cases,
            source=source,
            language=language,
            result={
                "mode": action,
                "status": "Not Available",
                "message": content.NO_WORKSPACE_NOTICE,
                "passed": 0,
                "total": 0,
                "cases": [],
                "runtime_ms": None,
                "memory_mb": None,
                "runtime_percentile": None,
                "memory_percentile": None,
            },
        )
        return _html(render("workbench.html", **context), status_code=422)

    graded = judge.evaluate(
        item,
        language,
        source,
        cases if action == "run" else cases + list(item.hidden_cases),
    )
    payload = graded.as_dict()
    payload["mode"] = action
    if action == "submit":
        record = store.record_submission(subject_id, item.slug, language, source, graded)
        payload["submission_id"] = record["submission_id"]
        payload["created_at"] = record["created_at"]
    if as_json:
        return JSONResponse({"slug": item.slug, "language": language, **payload})
    context = _workbench_context(
        request,
        item,
        "description",
        result=payload,
        console_tab="result",
        cases=cases,
        source=source,
        language=language,
    )
    return _html(render("workbench.html", **context))


# ---------------------------------------------------------------------------
# member surfaces
# ---------------------------------------------------------------------------


@app.get("/progress/", include_in_schema=False)
async def progress(request: Request) -> Response:
    member = _member(request)
    if member is None:
        return RedirectResponse(
            "/accounts/login/?next=" + quote("/progress/"), status_code=307
        )
    subject_id = str(member["subject_id"])
    return _html(
        render(
            "progress.html",
            member=member,
            body_class="app",
            summary=store.progress_summary(subject_id),
            recent=store.submissions(subject_id, limit=20),
        )
    )


@app.get("/submissions/", include_in_schema=False)
async def submissions(request: Request) -> Response:
    member = _member(request)
    if member is None:
        return RedirectResponse(
            "/accounts/login/?next=" + quote("/submissions/"), status_code=307
        )
    subject_id = str(member["subject_id"])
    return _html(
        render(
            "submissions.html",
            member=member,
            body_class="app",
            rows=store.submissions(subject_id, limit=50),
            total=store.submission_count(subject_id),
        )
    )


# ---------------------------------------------------------------------------
# accounts
# ---------------------------------------------------------------------------


def _auth_page(
    request: Request,
    template: str,
    *,
    status_code: int = 200,
    **context: Any,
) -> HTMLResponse:
    token, _ = _session(request)
    context.setdefault("member", _member(request))
    context.setdefault("body_class", "auth")
    context.setdefault("errors", {})
    context.setdefault("values", {})
    context.setdefault("notice", None)
    context.setdefault("social_notice", None)
    context["verification"] = accounts.verification_token(token)
    return _html(render(template, **context), status_code=status_code)


@app.get("/accounts/login/", include_in_schema=False)
async def login_form(request: Request) -> Response:
    if _member(request) is not None:
        return RedirectResponse(
            _safe_next(request.query_params.get("next"), "/problemset/"), status_code=307
        )
    return _auth_page(
        request,
        "login.html",
        next_query=_next_query(request.query_params.get("next")),
    )


def _next_query(value: str | None) -> str:
    target = _safe_next(value, "")
    return f"?next={quote(target)}" if target else ""


@app.post("/accounts/login/", include_in_schema=False)
async def login_submit(request: Request) -> Response:
    token, _ = _session(request)
    form = dict(await request.form())
    values = {"login": str(form.get("login", ""))}
    destination = _safe_next(request.query_params.get("next"), "/problemset/")
    if not accounts.verification_ok(token, {k: str(v) for k, v in form.items()}):
        return _auth_page(
            request,
            "login.html",
            status_code=400,
            errors={"verification": content.VERIFICATION_REQUIRED},
            values=values,
            next_query=_next_query(request.query_params.get("next")),
        )
    try:
        rotated = accounts.sign_in(token, {k: str(v) for k, v in form.items()})
    except accounts.FormError as error:
        return _auth_page(
            request,
            "login.html",
            status_code=400,
            errors=error.errors,
            values=values,
            next_query=_next_query(request.query_params.get("next")),
        )
    return _redirect(request, destination, rotated)


@app.get("/accounts/signup/", include_in_schema=False)
async def signup_form(request: Request) -> Response:
    if _member(request) is not None:
        return RedirectResponse("/problemset/", status_code=307)
    token, _ = _session(request)
    if accounts.pending_signup_stage(token):
        message = accounts.pending_message(token, "registration")
        return _auth_page(
            request,
            "signup.html",
            stage="verify",
            pending_email=(message or {}).get("recipient", ""),
        )
    return _auth_page(request, "signup.html", stage="collect")


@app.post("/accounts/signup/", include_in_schema=False)
async def signup_submit(request: Request) -> Response:
    token, _ = _session(request)
    form = {k: str(v) for k, v in (await request.form()).items()}
    values = {"username": form.get("username", ""), "email": form.get("email", "")}
    if not accounts.verification_ok(token, form):
        return _auth_page(
            request,
            "signup.html",
            status_code=400,
            stage="collect",
            errors={"verification": content.VERIFICATION_REQUIRED},
            values=values,
        )
    try:
        accounts.start_signup(token, form)
    except accounts.FormError as error:
        return _auth_page(
            request,
            "signup.html",
            status_code=400,
            stage="collect",
            errors=error.errors,
            values=values,
        )
    return _redirect(request, "/accounts/signup/")


@app.post("/accounts/signup/verify/", include_in_schema=False)
async def signup_verify(request: Request) -> Response:
    token, _ = _session(request)
    form = {k: str(v) for k, v in (await request.form()).items()}
    message = accounts.pending_message(token, "registration")
    try:
        rotated = accounts.confirm_signup(token, form.get("code", ""))
    except accounts.FormError as error:
        return _auth_page(
            request,
            "signup.html",
            status_code=400,
            stage="verify",
            errors=error.errors,
            pending_email=(message or {}).get("recipient", ""),
        )
    return _redirect(request, "/problemset/", rotated)


@app.post("/accounts/logout/", include_in_schema=False)
async def logout(request: Request) -> Response:
    token, _ = _session(request)
    accounts.sign_out(token)
    response = RedirectResponse("/", status_code=303)
    request.state.cleared_session = True
    return response


@app.get("/accounts/password/reset/", include_in_schema=False)
async def reset_form(request: Request) -> Response:
    token, _ = _session(request)
    stage = (
        "verify"
        if accounts.flow_status(token, "password-reset").get("state")
        in {"challenge", "verified"}
        else "request"
    )
    return _auth_page(request, "password_reset.html", stage=stage)


@app.post("/accounts/password/reset/", include_in_schema=False)
async def reset_submit(request: Request) -> Response:
    token, _ = _session(request)
    form = {k: str(v) for k, v in (await request.form()).items()}
    email = form.get("email", "")
    if not accounts.verification_ok(token, form):
        return _auth_page(
            request,
            "password_reset.html",
            status_code=400,
            stage="request",
            errors={"verification": content.VERIFICATION_REQUIRED},
            values={"email": email},
        )
    try:
        accounts.start_password_reset(token, email)
    except accounts.FormError as error:
        return _auth_page(
            request,
            "password_reset.html",
            status_code=400,
            stage="request",
            errors=error.errors,
            values={"email": email},
        )
    return _redirect(request, "/accounts/password/reset/")


@app.post("/accounts/password/reset/confirm/", include_in_schema=False)
async def reset_confirm(request: Request) -> Response:
    token, _ = _session(request)
    form = {k: str(v) for k, v in (await request.form()).items()}
    try:
        rotated = accounts.confirm_password_reset(
            token, form.get("code", ""), form.get("password", "")
        )
    except accounts.FormError as error:
        return _auth_page(
            request,
            "password_reset.html",
            status_code=400,
            stage="verify",
            errors=error.errors,
        )
    return _redirect(request, "/problemset/", rotated)


@app.get("/accounts/message/", include_in_schema=False)
async def account_message(request: Request) -> Response:
    """The local delivery surface for this device's verification code.

    Mail is ``LOCAL_ONLY``: nothing leaves the process. This page is the honest
    stand-in for the inbox, and it shows only the message belonging to the
    session that made the request.
    """

    token, _ = _session(request)
    purpose = request.query_params.get("purpose", "registration")
    if purpose not in {"registration", "password-reset"}:
        return _not_found(request)
    back = (
        "/accounts/signup/"
        if purpose == "registration"
        else "/accounts/password/reset/"
    )
    return _html(
        render(
            "message.html",
            member=_member(request),
            body_class="auth",
            message=accounts.pending_message(token, purpose),
            purpose=purpose,
            back_url=back,
        )
    )


@app.post("/accounts/social/{provider}", include_in_schema=False)
@app.post("/accounts/social/{provider}/", include_in_schema=False)
async def social_sign_in(request: Request, provider: str) -> Response:
    """The captured pages offer Google/GitHub/Apple sign-in.

    Federated identity needs a third party, and this clone reaches no remote
    origin, so the control is answered truthfully instead of pretending to
    authenticate.
    """

    known = {"google", "github", "apple", "more"}
    if provider not in known:
        return _not_found(request)
    return _auth_page(
        request,
        "login.html",
        status_code=200,
        next_query="",
        social_notice=content.social_notice(provider),
    )


@app.get("/accounts/google/login/", include_in_schema=False)
@app.get("/accounts/github/login/", include_in_schema=False)
@app.get("/accounts/apple/login/", include_in_schema=False)
async def social_sign_in_get(request: Request) -> Response:
    provider = request.url.path.split("/")[2]
    return _auth_page(
        request,
        "login.html",
        next_query="",
        social_notice=content.social_notice(provider),
    )


# ---------------------------------------------------------------------------
# local boundary pages and 404
# ---------------------------------------------------------------------------


def _boundary(request: Request, title: str, description: str) -> HTMLResponse:
    return _html(
        render(
            "boundary.html",
            member=_member(request),
            body_class="app",
            heading=title,
            description=description,
        )
    )


def _register_boundary(route: str, title: str, description: str) -> None:
    @app.get(route, include_in_schema=False)
    async def boundary_page(
        request: Request, _title: str = title, _description: str = description
    ) -> HTMLResponse:
        return _boundary(request, _title, _description)


for _route, (_title, _description) in BOUNDARY_PAGES.items():
    _register_boundary(_route, _title, _description)


def _page(request: Request, template: str, **context: Any) -> HTMLResponse:
    """Render one of the family-specific layouts in templates/family_*.html.

    Each captured family has its own template because the source layouts differ
    materially; the context each one wants is assembled by its route below.
    """

    context.setdefault("member", _member(request))
    context.setdefault("body_class", "app")
    context.setdefault("provenance", None)
    context.setdefault("boundary", None)
    return _html(render(template, **context))


def _monogram(name: str) -> str:
    """A local stand-in for the source's brand logo tile."""

    letters = [part[0] for part in str(name).split() if part[:1].isalnum()]
    return "".join(letters[:2]).upper() or "?"


#: The tiers the captured identity card shows beside its progress ring.
PROGRESS_TIERS: tuple[tuple[str, str, str], ...] = (
    ("easy", "Easy", "Easy"),
    ("medium", "Med.", "Medium"),
    ("hard", "Hard", "Hard"),
)


def _local_progress(
    request: Request, rows: list[dict[str, Any]]
) -> dict[str, Any] | None:
    """The identity card's progress block, counted over this clone's own rows.

    tag-array-desktop renders solved/total for the source's 4,029-problem bank.
    A clone cannot honestly repeat that figure, so the same block is filled
    from this clone's catalogue and the signed-in member's own progress.
    """

    if not rows:
        return None
    statuses = store.progress_map(_subject(request))
    totals = {key: 0 for key, _, _ in PROGRESS_TIERS}
    solved = {key: 0 for key, _, _ in PROGRESS_TIERS}
    attempting = 0
    for row in rows:
        key = str(row["difficulty"]).casefold()
        if key not in totals:
            continue
        totals[key] += 1
        status = statuses.get(row["slug"])
        if status == store.SOLVED:
            solved[key] += 1
        elif status == store.ATTEMPTED:
            attempting += 1
    return {
        "total": len(rows),
        "solved": sum(solved.values()),
        "attempting": attempting,
        "tiers": [
            {
                "key": key,
                "label": label,
                "total": totals[key],
                "solved": solved[key],
            }
            for key, label, _ in PROGRESS_TIERS
        ],
        "note": (
            "Counted over this clone's own catalogue and your own local "
            "submissions — never over a source account."
        ),
    }


def _paged(rows: list[Any], request: Request, per_page: int = 60) -> dict[str, Any]:
    """Shared paging for the family directories."""

    needle = str(request.query_params.get("q", "")).strip()[:60]
    if needle:
        lowered = needle.casefold()
        rows = [row for row in rows if lowered in str(row.get("label", "")).casefold()]
    try:
        page = int(str(request.query_params.get("page", "1")))
    except ValueError:
        page = 1
    pages = max(1, -(-len(rows) // per_page))
    page = max(1, min(page, pages))
    window = rows[(page - 1) * per_page : page * per_page]
    return {"rows": window, "page": page, "pages": pages, "total": len(rows), "q": needle}


def _directory_actions(base: str, paged: dict[str, Any]) -> list[dict[str, str]]:
    actions: list[dict[str, str]] = []
    if paged["page"] > 1:
        actions.append({"label": "Previous page", "href": f"{base}?page={paged['page'] - 1}"})
    if paged["page"] < paged["pages"]:
        actions.append({"label": "Next page", "href": f"{base}?page={paged['page'] + 1}"})
    return actions


# --- company ---------------------------------------------------------------


@app.get("/company/", include_in_schema=False)
async def company_index(request: Request) -> Response:
    rows = [
        {
            "label": row.get("name") or row["slug"],
            "href": f"/company/{row['slug']}/",
            "meta": (
                f"{row['source_question_count']} source questions"
                if row.get("source_question_count") is not None
                else ""
            ),
        }
        for row in families.COMPANY_ROWS
    ]
    paged = _paged(rows, request)
    return _page(
        request,
        "family_directory.html",
        heading="Companies",
        eyebrow="Company question banks",
        lead=(
            f"{families.COMPANY_SAMPLE} of the {families.COMPANY_POPULATION} company "
            "pages the Playwright capture enumerated have a local page here."
        ),
        stats=[
            {"label": "Source population", "value": families.COMPANY_POPULATION},
            {"label": "Captured sample", "value": families.COMPANY_SAMPLE},
            {"label": "Showing", "value": f"page {paged['page']} of {paged['pages']}"},
        ],
        rows=paged["rows"],
        query=paged["q"],
        search_action="/company/",
        search_placeholder="Search for a company...",
        pager=_directory_actions("/company/", paged),
        boundary=families.SEEDED_NOTE,
    )


#: The gated panel copy is transcribed verbatim from company-google-desktop.
COMPANY_PREMIUM_COPY = (
    "Unlock more popular interview questions with LeetCode Premium to "
    "enhance interview prep!"
)


def _collection_identity(
    *, name: str, monogram: str | None, meta: str, updated: str, rows: list[dict[str, Any]]
) -> dict[str, Any]:
    """The identity card shared by the company and topic-list layouts."""

    return {
        "name": name,
        "monogram": monogram,
        "meta": meta,
        "updated": updated,
        "practice_href": (
            rows[0]["href"] if rows else "/problemset/"
        ),
        "share_href": "/problemset/",
        "discuss_href": "/discuss/",
    }


@app.get("/company/{slug}/", include_in_schema=False)
async def company_page(request: Request, slug: str) -> Response:
    row = families.company(slug)
    if row is None:
        return _not_found(request)
    saved = row["source_saved_count"]
    questions = row["source_question_count"]
    meta_parts = ["LeetCode"]
    if questions is not None:
        meta_parts.append(f"{questions:,} questions")
    if saved is not None:
        meta_parts.append(f"{saved:,} Saved")
    return _page(
        request,
        "family_collection.html",
        heading=row["name"],
        rail_active="library",
        identity=_collection_identity(
            name=row["name"],
            monogram=_monogram(row["name"]),
            meta=" · ".join(meta_parts),
            updated=(
                f"Updated: {row['source_updated_label']}"
                if row["source_updated_label"]
                else ""
            ),
            rows=row["rows"],
        ),
        panel={
            "label": f"{row['name']} questions",
            "search_action": "/problemset/",
            "chips": [
                {"label": "All problems", "href": "/problemset/"},
                {"label": "Premium", "href": "/subscribe/", "accent": True},
            ],
            "claim": {
                "text": (
                    "The source lists this bank behind Premium and offers one free "
                    "interview question. This clone charges nothing and claims nothing."
                ),
                "href": "/subscribe/",
                "label": "Premium",
            },
            "note": row["seeded_note"],
            "rows": row["rows"],
            # Not "copy": ``dict.copy`` would shadow the value in Jinja.
            "premium": {"blurb": COMPANY_PREMIUM_COPY},
        },
        boundary=families.PREMIUM_BOUNDARY,
        provenance=(
            "The question and saved counts beside the name are source figures "
            "recorded by the Playwright capture; the rows below them are this "
            "clone's own catalogue."
        ),
    )


# --- tag / problem-list ----------------------------------------------------


@app.get("/problem-list/", include_in_schema=False)
@app.get("/list/", include_in_schema=False)
async def tag_index(request: Request) -> Response:
    rows = [
        {
            "label": row.get("label") or row["slug"],
            "href": f"/problem-list/{row['slug']}/",
            "meta": (
                f"{row['source_question_count']} source questions"
                if row.get("source_question_count") is not None
                else ""
            ),
        }
        for row in families.TAG_ROWS
    ]
    paged = _paged(rows, request, per_page=80)
    return _page(
        request,
        "family_directory.html",
        heading="Problem Lists",
        eyebrow="Topic tags",
        lead="Every topic tag the Playwright capture visited has a local list here.",
        stats=[{"label": "Captured tags", "value": len(families.TAG_ROWS)}],
        rows=paged["rows"],
        query=paged["q"],
        search_action="/problem-list/",
        search_placeholder="Search topics",
        pager=_directory_actions("/problem-list/", paged),
    )


@app.get("/problem-list/{slug}/", include_in_schema=False)
async def tag_page(request: Request, slug: str) -> Response:
    row = families.tag(slug)
    if row is None:
        return _not_found(request)
    saved = row["source_saved_count"]
    questions = row["source_question_count"]
    meta_parts = ["LeetCode"]
    if questions is not None:
        meta_parts.append(f"{questions:,} questions")
    if saved is not None:
        meta_parts.append(f"{saved:,} Saved")

    note = row["seeded_note"]
    if not row["list_available"]:
        note = (
            "The captured page for this list answered “This list is no longer "
            "available.”, so the heading here comes from the problem-set topic "
            "rail instead. " + note
        )
    return _page(
        request,
        "family_collection.html",
        heading=row["name"],
        rail_active="library",
        identity=_collection_identity(
            name=row["name"],
            monogram=None,
            meta=" · ".join(meta_parts),
            updated=(
                f"Updated: {row['source_updated_label']}"
                if row["source_updated_label"]
                else ""
            ),
            rows=row["rows"],
        ),
        progress=_local_progress(request, row["rows"]),
        panel={
            "label": f"{row['name']} questions",
            "search_action": "/problemset/",
            "chips": [
                {"label": "Filter the problem set", "href": row["filter_href"]},
                {"label": "All problem lists", "href": "/problem-list/"},
            ],
            "note": note,
            "rows": row["rows"],
        },
        provenance=(
            "The question and saved counts beside the name are source figures "
            "for the full 4,029-problem bank; the ring and the rows below count "
            "only this clone's own 1,000-problem catalogue."
        ),
    )


@app.get("/tag/{slug}/", include_in_schema=False)
@app.get("/tag/{slug}", include_in_schema=False)
async def tag_redirect(slug: str) -> Response:
    """The source redirects ``/tag/<slug>/`` to ``/problem-list/<slug>/``."""

    if slug in families.TAG_BY_SLUG:
        return RedirectResponse(f"/problem-list/{slug}/", status_code=307)
    return RedirectResponse("/problem-list/", status_code=307)


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


@app.get("/quest/", include_in_schema=False)
async def quest_page(request: Request) -> Response:
    return _page(
        request,
        "family_quest.html",
        heading="LeetCode Quest",
        quests=[
            {"title": "Data Structures and Algorithms", "levels": 35, "mark": "DS", "href": "/studyplan/leetcode-75/"},
            {"title": "Database", "levels": 5, "mark": "DB", "href": "/problemset/database/"},
            {"title": "System & Software Design", "levels": 5, "mark": "SD", "href": "/explore/"},
            {"title": "Maths", "levels": 7, "mark": "∑", "href": "/problem-list/math/"},
            {"title": "2026 Spring Sprint", "levels": 9, "mark": "26", "href": "/studyplan/"},
        ],
    )


@app.get("/studyplan/", include_in_schema=False)
async def studyplan_index(request: Request) -> Response:
    items = [
        {
            "label": row.get("label") or row["slug"],
            "href": f"/studyplan/{row['slug']}/",
            "premium": bool(row.get("premium")),
            "detail": (
                "Captured plan list"
                if row["slug"] in families.STUDYPLAN_DETAIL
                else "Index entry only"
            ),
        }
        for row in families.STUDYPLANS
    ]
    return _page(
        request,
        "family_studyplan_index.html",
        heading="Study Plan",
        eyebrow="Structured practice",
        lead="Every study plan the captured index linked to has a local page.",
        stats=[
            {"label": "Captured plans", "value": len(items)},
            {"label": "With a captured problem list", "value": len(families.STUDYPLAN_DETAIL)},
        ],
        plans=items,
    )


@app.get("/studyplan/{slug}/", include_in_schema=False)
async def studyplan_page(request: Request, slug: str) -> Response:
    plan = families.studyplan(slug)
    if plan is None:
        return _not_found(request)

    title = plan["title"]
    label = plan["label"]
    subtitle = label[len(title) :].strip() if label.startswith(title) else label
    statuses = store.progress_map(_subject(request))
    groups = [
        {
            "name": group["name"],
            "problems": [
                {**problem, "solved": statuses.get(problem["slug"]) == store.SOLVED}
                for problem in group["problems"]
            ],
        }
        for group in plan["groups"]
    ]

    sample_rows: list[dict[str, Any]] = []
    if not plan["detail"]:
        sample_rows = families.question_rows(
            families.sample_questions(f"studyplan:{slug}", 12)
        )
        entry_note = (
            "The capture visited this plan's index entry but not the plan itself, "
            "so the rows below are a deterministic local sample of this clone's "
            "catalogue rather than the source plan."
        )
        summary = [
            f"{len(sample_rows)} locally sampled questions",
            "No source problem list was captured for this plan",
            "Every row opens in this clone's own workspace",
        ]
    else:
        entry_note = (
            f"{plan['local_total']} of the {plan['problem_total']} captured plan "
            "entries are inside this clone's 1,000-problem sample and open "
            "locally; the rest are listed without a link."
        )
        summary = [
            f"{plan['problem_total']} captured plan entries",
            f"{len(groups)} sections in the captured plan",
            f"{plan['local_total']} open locally in this clone",
        ]

    related = [
        {
            "name": entry.get("label") or entry["slug"],
            "note": "Study plan",
            "href": f"/studyplan/{entry['slug']}/",
            "mark": _monogram(entry.get("label") or entry["slug"]),
            "tint": tint,
        }
        for entry, tint in zip(
            [row for row in families.STUDYPLANS if row["slug"] != slug][:4],
            (
                "rgb(118, 75, 232)",
                "rgb(24, 130, 92)",
                "rgb(45, 122, 234)",
                "rgb(206, 138, 14)",
            ),
        )
    ]

    first_word = (title.split() or [title])[0]
    return _page(
        request,
        "family_studyplan.html",
        heading=title,
        plan={
            "title": title,
            "subtitle": subtitle or "Study Plan",
            "art_word": first_word[:4].upper(),
            "start_href": (
                groups[0]["problems"][0]["href"]
                if groups and groups[0]["problems"] and groups[0]["problems"][0]["href"]
                else (sample_rows[0]["href"] if sample_rows else "/problemset/")
            ),
            "share_href": "/problemset/",
            "groups": groups,
            "sample_rows": sample_rows,
            "sample_title": "Local practice set",
            "entry_note": entry_note,
            "summary": summary,
            "award_note": (
                "Badges belong to a source account. This clone tracks your own "
                "solved rows on /progress/."
            ),
            "related": related,
        },
        boundary=(families.PREMIUM_BOUNDARY if plan["premium"] else None),
        provenance=(
            "The section names and plan entries above are the captured plan; the "
            "solved marks are your own local submissions."
        ),
    )


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


@app.get("/explore/", include_in_schema=False)
@app.get("/explore/{section}/", include_in_schema=False)
@app.get("/explore/user/{section}/all/", include_in_schema=False)
async def explore_page(request: Request, section: str = "") -> Response:
    path = request.url.path
    row = families.explore_section(path)
    if row is None:
        return _not_found(request)
    tints = ("a", "b", "c", "d", "e")
    cards = [
        {**card, "tint": tints[index % len(tints)]}
        for index, card in enumerate(row["cards"])
    ]
    return _page(
        request,
        "family_explore.html",
        heading="Explore",
        eyebrow=path,
        lead="Guided cards, as the captured Explore index listed them.",
        cards_title=row["title"],
        cards=cards,
        empty=(
            "The captured page rendered no card here for an anonymous visitor: "
            "this list is per-account on the source."
        ),
        sections=[
            {"title": entry["title"], "href": entry["path"]}
            for entry in families.EXPLORE_SECTIONS
        ],
    )


@app.get("/explore/{section}/card/{slug}/", include_in_schema=False)
async def explore_card_page(request: Request, section: str, slug: str) -> Response:
    card = families.explore_card(request.url.path)
    if card is None:
        return _not_found(request)
    meta_parts = ["LeetCode Explore"]
    if card["chapters"] is not None:
        meta_parts.append(f"{card['chapters']} Chapters")
    if card["items"] is not None:
        meta_parts.append(f"{card['items']} Items")
    return _page(
        request,
        "family_collection.html",
        heading=card["caption"],
        rail_active="explore",
        identity=_collection_identity(
            name=card["caption"],
            monogram=_monogram(card["caption"]),
            meta=" · ".join(meta_parts),
            updated="",
            rows=card["rows"],
        ),
        panel={
            "label": "Local practice set",
            "search_action": "/problemset/",
            "chips": [
                {"label": "Back to Explore", "href": "/explore/"},
                {"label": "All problems", "href": "/problemset/"},
            ],
            "note": (
                "The card body renders client-side behind an account on the "
                "source, so the anonymous capture recorded only the page chrome "
                "and the Explore index's chapter and item counts. The rows below "
                "are a deterministic local sample of this clone's catalogue, "
                "shown in place of the uncaptured chapter list."
            ),
            "rows": card["rows"],
        },
        boundary=(families.PREMIUM_BOUNDARY if card["locked"] else None),
    )


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


@app.get("/contest", include_in_schema=False)
@app.get("/contest/", include_in_schema=False)
async def contest_index(request: Request) -> Response:
    upcoming = [
        {
            "name": row["name"],
            "href": f"/contest/{row['slug']}/",
            "starts": row.get("starts", ""),
        }
        for row in families.CONTEST["upcoming"]
    ]
    past = [
        {
            "name": row["name"],
            "href": f"/contest/{row['slug']}/",
            "starts": row.get("starts", ""),
            "biweekly": row["slug"].startswith("biweekly"),
            "score": "0 / 4",
        }
        for row in families.CONTEST["past"]
    ]
    ranking = []
    for index, row in enumerate(families.CONTEST["ranking"], start=1):
        # The captured label is "<place?> <name> Rating: n Attended: n" for the
        # rows below the podium and "<name> <rating>" for the top three.
        label = str(row["label"])
        name, _, stat = label.partition(" Rating: ")
        place = str(index)
        if name.split(" ", 1)[0] == place:
            name = name.split(" ", 1)[1] if " " in name else name
        ranking.append(
            {
                "place": place,
                "name": name,
                "stat": ("Rating: " + stat) if stat else "",
                "href": (f"/u/{row['handle']}/" if row.get("handle") else None),
            }
        )
    return _page(
        request,
        "family_contest.html",
        active="contest",
        heading="LeetCode Contest",
        lead="Contest every week. Compete and see your ranking!",
        upcoming=upcoming,
        past=past,
        ranking=ranking,
        ranking_note=(
            "Ranked accounts hosted on the regional site have no local profile "
            "page and are shown as text."
        ),
        pages=1,
        my_contests_href="/progress/",
        boundary=(
            "Contest entry, virtual contests and live ranking need a server-side "
            "contest engine and other competitors. This clone reproduces the "
            "captured schedule and ranking board only."
        ),
    )


@app.get("/contest/{slug}/", include_in_schema=False)
async def contest_page(request: Request, slug: str) -> Response:
    row = families.contest(slug)
    if row is None:
        return _not_found(request)
    return _page(
        request,
        "family_contest_detail.html",
        active="contest",
        heading=row["name"],
        lead=row["starts"],
        state="Upcoming" if row["upcoming"] else "Finished",
        biweekly=slug.startswith("biweekly"),
        rows=row["rows"],
        note=(
            "The source contest problem set is published only to entrants, so "
            "these four rows are a deterministic local sample of this clone's "
            "catalogue."
        ),
        boundary=(
            "There is no local contest engine: nothing here is timed, ranked or "
            "submitted to a leaderboard."
        ),
    )


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


#: The promo tiles discuss-desktop rendered above the category strip. Each
#: caption is captured text; each destination is the local page that carries it.
DISCUSS_PROMOS: tuple[dict[str, str], ...] = (
    {
        "name": "LeetCode at Your Fingertips",
        "note": "The mobile app announcement",
        "href": "/app/",
    },
    {
        "name": "Quest",
        "note": "Turn coding practice into an epic adventure",
        "href": "/quest/",
    },
    {
        "name": "LeetCode's Interview Crash Course: System Design for Interviews and Beyond",
        "note": "Explore card",
        "href": "/explore/",
    },
    {
        "name": "LeetCode's Interview Crash Course: Data Structures and Algorithms",
        "note": "Explore card",
        "href": "/explore/",
    },
)


@app.get("/discuss/", include_in_schema=False)
async def discuss_index(request: Request) -> Response:
    items = [
        {
            "label": row.get("label") or f"Post {row['id']}",
            "href": row["path"],
            "meta": f"Post {row['id']}",
        }
        for row in families.DISCUSS["posts"]
    ]
    paged = _paged(items, request, per_page=25)
    featured = families.DISCUSS.get("featured_post") or {}
    posts = []
    for row in paged["rows"]:
        title = str(row["label"])
        posts.append(
            {
                "initial": _monogram(title)[:1],
                "byline": "Captured on the source Discuss index",
                "title": title,
                "excerpt": (
                    (featured.get("captured_text") or "")[:220]
                    if featured.get("path") == row["href"]
                    else ""
                ),
                "href": row["href"],
                "meta": row["meta"],
            }
        )
    tints = ("a", "b", "c", "d")
    promos = [
        {
            "name": entry["name"],
            "note": entry["note"],
            "href": entry["href"],
            "tint": tints[index % len(tints)],
        }
        for index, entry in enumerate(DISCUSS_PROMOS)
    ]
    return _page(
        request,
        "family_discuss.html",
        active="discuss",
        heading="Discuss",
        query=paged["q"],
        promos=promos,
        tabs=[
            {"label": label, "href": "/discuss/"}
            for label in families.DISCUSS["categories"]
        ],
        posts=posts,
        pager=_directory_actions("/discuss/", paged),
        aside_groups=[
            {
                "title": f"#{label}",
                "items": [
                    {"label": entry["label"], "href": entry["href"]}
                    for entry in items[index * 2 : index * 2 + 2]
                ],
            }
            for index, label in enumerate(families.DISCUSS["categories"][:4])
        ],
        boundary=(
            "Post bodies are visitor-written content attributed to named "
            "accounts. Only the one post the capture opened carries its captured "
            "body; every other row is a titled local route."
        ),
    )


@app.get("/discuss/create/", include_in_schema=False)
async def discuss_create(request: Request) -> Response:
    return _page(
        request,
        "family_discuss_post.html",
        active="discuss",
        heading="Create a post",
        eyebrow="Discuss",
        lead="Posting is disabled in this offline reconstruction.",
        captured_body="",
        empty=(
            "This clone stores no visitor-written community content: the "
            "captured board is other people's writing, and a local editor that "
            "pretended to publish would be dishonest about it."
        ),
        links=[{"label": "Back to Discuss", "href": "/discuss/"}],
    )


@app.get("/discuss/post/{identifier}/{slug}/", include_in_schema=False)
async def discuss_post_page(request: Request, identifier: str, slug: str) -> Response:
    row = families.discuss_post(identifier)
    if row is None:
        return _not_found(request)
    return _page(
        request,
        "family_discuss_post.html",
        active="discuss",
        heading=row["title"],
        eyebrow="Discuss post",
        lead=f"Post {identifier}",
        captured_body=row["captured_body"],
        empty=(
            "The Playwright run enumerated this post from the index but opened "
            "only one thread, so the body was never captured and is not invented "
            "here."
        ),
        links=[{"label": "Back to Discuss", "href": "/discuss/"}],
    )


# --- public profile --------------------------------------------------------


@app.get("/u/{handle}", include_in_schema=False)
@app.get("/u/{handle}/", include_in_schema=False)
async def member_profile(request: Request, handle: str) -> HTMLResponse:
    row = families.profile(handle[:64])
    return _page(
        request,
        "family_profile.html",
        heading=row["title"],
        lead=f"/u/{handle[:64]}/",
        initial=_monogram(row["title"])[:1],
        captured_text=row["captured_text"],
        card_title=("Captured profile" if row["captured"] else "Not captured"),
        card_body=(
            "The Playwright run captured two public profiles. This handle was "
            "not one of them, so this page carries no source figures at all."
        ),
        own_progress=(
            "Solved counts, badges and submission history on a public profile "
            "belong to a real account. Your own local progress lives behind your "
            "own session."
        ),
        captured_profiles=[
            {"label": entry["handle"], "href": f"/u/{entry['handle']}/"}
            for entry in families.PROFILES
        ],
        boundary=(
            "Solved counts, badges and submission history on a public profile "
            "belong to a real account. This clone shows its own members' progress "
            "only on /progress/, behind their own session."
        ),
    )


# --- premium, store, interview, assessment, business -----------------------


#: Prices, cycles and plan copy transcribed from subscribe-desktop. Nothing
#: here is ever charged; see PREMIUM_BOUNDARY.
PREMIUM_PLANS: tuple[dict[str, Any], ...] = (
    {
        "id": "monthly",
        "name": "Monthly",
        "cycle": "billed monthly",
        "amount": "$35 /mo",
        "was": "$39",
        "now": "$35",
        "popular": False,
        "flag": "",
        # "blurb", not "copy": ``dict.copy`` would shadow the value in Jinja.
        "blurb": (
            "Our monthly plan grants access to all premium features, the best "
            "plan for short-term subscribers."
        ),
        "note": "billed monthly — captured price, never charged here",
    },
    {
        "id": "yearly",
        "name": "Yearly",
        "cycle": "billed yearly ($159)",
        "amount": "$13.25 /mo",
        "was": "$24.91",
        "now": "$13.25",
        "popular": True,
        "flag": "🎉 Most popular",
        "blurb": (
            "Our most popular plan previously sold for $299 and is now only "
            "$13.25/month. This plan saves you over 62% in comparison to the "
            "monthly plan."
        ),
        "note": "billed yearly ($159) — captured price, never charged here",
    },
)

#: The feature grid under the plan cards, transcribed from subscribe-desktop.
PREMIUM_FEATURES: tuple[dict[str, str], ...] = (
    {
        "name": "Ask Leet",
        "body": (
            "Your coding agent — brainstorm solutions, optimize code, generate "
            "test cases, and debug. Premium members get 500 extra monthly "
            "credits to unlock the most advanced models, plus up to 30 solution "
            "analysis per day."
        ),
    },
    {
        "name": "Company-Specific Interview Questions",
        "body": (
            "Practice smarter with real questions from top companies. Sort by "
            "role, time, or frequency to focus on what matters most for your "
            "prep."
        ),
    },
    {
        "name": "Lightning Judge",
        "body": (
            "Premium gives you priority judging — up to 10× faster during peak "
            "hours — so you can stay ahead in your interview prep."
        ),
    },
    {
        "name": "Access to Premium Content",
        "body": (
            "Gain exclusive access to our ever-growing collection of premium "
            "content, such as questions, Explore cards, and premium solutions "
            "like this."
        ),
    },
    {
        "name": "Autocomplete",
        "body": (
            "Get smart code autocompletion based on your language and code — no "
            "memorization needed."
        ),
    },
    {
        "name": "Debugger",
        "body": (
            "Done with print debugging? Set breakpoints and debug interactively "
            "in our editor."
        ),
    },
)


@app.get("/subscribe/", include_in_schema=False)
async def subscribe_page(request: Request) -> Response:
    return _page(
        request,
        "family_premium.html",
        heading="Premium",
        lead="Get started with a LeetCode Subscription that works for you.",
        plans=list(PREMIUM_PLANS),
        features=list(PREMIUM_FEATURES),
        boundary=families.PREMIUM_BOUNDARY,
        provenance=(
            "Every price and feature line above is captured marketing copy. No "
            "payment provider is reached and no card field exists."
        ),
    )


@app.get("/premium/", include_in_schema=False)
async def premium_redirect() -> Response:
    return RedirectResponse("/subscribe/", status_code=307)


@app.post("/subscribe/checkout/", include_in_schema=False)
async def subscribe_checkout(request: Request) -> Response:
    """The Subscribe control answers locally; no payment is ever attempted."""

    form = await request.form()
    plan = str(form.get("plan", ""))
    known = {row["id"]: row for row in PREMIUM_PLANS}
    chosen = known.get(plan)
    return _page(
        request,
        "family_premium_result.html",
        heading="Checkout is not available offline",
        lead=(
            f"You chose the {chosen['name']} plan ({chosen['amount']})."
            if chosen
            else "No plan was selected."
        ),
        body=(
            "Nothing was charged and nothing was stored. This clone's payment "
            "profile is the local sandbox declared in backend/runtime.json; it "
            "accepts no card data and reaches no payment provider."
        ),
        links=[
            {"label": "Back to Premium", "href": "/subscribe/"},
            {"label": "Browse problems", "href": "/problemset/"},
        ],
        boundary=families.PREMIUM_BOUNDARY,
    )


@app.get("/store/", include_in_schema=False)
async def store_page(request: Request) -> Response:
    return _page(
        request,
        "family_store.html",
        heading="Store",
        body=(
            "The store renders entirely client-side behind an account. The "
            "anonymous capture recorded this loading state and nothing else, so "
            "no catalogue, price or balance is reproduced."
        ),
        links=[
            {"label": "Premium", "href": "/subscribe/"},
            {"label": "Quest", "href": "/quest/"},
            {"label": "Redeem — not available offline", "href": None},
        ],
        boundary=families.PREMIUM_BOUNDARY,
    )


def _captured_article(
    request: Request,
    payload: dict[str, Any],
    *,
    heading: str,
    eyebrow: str,
    links: list[dict[str, Any]] | None = None,
    boundary: str | None = None,
) -> Response:
    """The centred prose layout privacy-desktop recorded for the legal pages."""

    return _page(
        request,
        "family_article.html",
        heading=heading,
        eyebrow=eyebrow,
        captured_text=payload.get("captured_text", ""),
        links=links or [],
        boundary=boundary,
    )


@app.get("/interview/", include_in_schema=False)
async def interview_page(request: Request) -> Response:
    return _page(
        request,
        "family_interview.html",
        heading="LeetCode Interview",
        lead="Online coding interview platform for professionals",
        cta_href="/problemset/",
        cta_label="Practice in this clone",
        sessions=[
            {
                "name": "No interview session exists offline",
                "meta": "Live interviews need video, a second participant and a hosted judge",
            },
            {
                "name": "Local workspace",
                "meta": "Run and submit against this clone's own judge instead",
            },
        ],
        captured_text=families.INTERVIEW.get("captured_text", ""),
        links=[
            {"label": "Assessment", "href": "/assessment/"},
            {"label": "Business contact", "href": "/business/contact/"},
            {"label": "Start an interview — not available offline", "href": None},
        ],
        boundary=(
            "Live interviews need video, a second participant and a hosted judge. "
            "None of that exists offline."
        ),
    )


#: The three anonymous cards assessment-desktop rendered above the
#: company-specific (Premium) rows.
ASSESSMENT_CARDS: tuple[dict[str, Any], ...] = (
    {
        "kind": "Online Assessment",
        "name": "Random question set from a real company.",
        "stats": ("Attempted: 1832355 times", "Success rate: 36.77%"),
        "href": "/problemset/",
        "action": "Start",
    },
    {
        "kind": "Phone Interview",
        "name": "Random question set from a real company.",
        "stats": ("Attempted: 646015 times", "Success rate: 43.15%"),
        "href": "/problemset/",
        "action": "Start",
    },
    {
        "kind": "Onsite Interview",
        "name": "Random question set from a real company.",
        "stats": ("Attempted: 437430 times", "Success rate: 29.87%"),
        "href": "/problemset/",
        "action": "Start",
    },
    {
        "kind": "Online Assessment · Premium",
        "name": "Company-specific sets",
        "stats": ("Premium-gated on the source", "No set was captured"),
        "href": None,
        "action": "Premium — not available offline",
    },
)


@app.get("/assessment/", include_in_schema=False)
async def assessment_page(request: Request) -> Response:
    return _page(
        request,
        "family_assessment.html",
        heading="Mock Assessment",
        lead=(
            "Prepare yourself. Start a practice assessment from a collection of "
            "real company questions."
        ),
        links=[
            {"label": "Go to My Overview", "href": "/progress/"},
            {"label": "Go to My Assessment History", "href": "/submissions/"},
        ],
        cards=list(ASSESSMENT_CARDS),
        captured_text=families.ASSESSMENT.get("captured_text", ""),
        boundary=(
            "The assessment product renders behind an employer account; the "
            "anonymous capture saw the chrome only. Every Start control above "
            "opens this clone's own problem set — no assessment is timed, scored "
            "or reported anywhere."
        ),
    )


#: The enquiry fields business-contact-desktop asked for. The source posts them
#: to a sales inbox; this clone offers no such submission, so each row states
#: what the source asks for instead of pretending to collect it.
BUSINESS_BLOCKS: tuple[dict[str, Any], ...] = (
    {
        "legend": "Fill in fields below",
        "fields": (
            {"label": "First name *", "note": "Required on the source form"},
            {"label": "Last name *", "note": "Required on the source form"},
            {
                "label": "Your Email (Organizational Email Only) *",
                "note": "Required on the source form",
            },
            {"label": "Your organization *", "note": "Required on the source form"},
            {"label": "Your Role/Title *", "note": "Required on the source form"},
            {
                "label": "You are interested in *",
                "note": "A select on the source form; its options render client-side",
            },
        ),
    },
    {
        "legend": "Write in the box below",
        "fields": (
            {
                "label": "Anything else you'd like to share",
                "note": "A free-text box on the source form",
            },
        ),
    },
)


@app.get("/business/contact/", include_in_schema=False)
async def business_contact(request: Request) -> Response:
    return _page(
        request,
        "family_business.html",
        heading="Business Contact",
        lead=(
            "Our Business Development Associate will reach out to you within 2 "
            "business days! Please stay tuned ;)"
        ),
        blocks=list(BUSINESS_BLOCKS),
        captured_text=families.BUSINESS.get("captured_text", ""),
        links=[
            {"label": "LeetCode Interview", "href": "/interview/"},
            {"label": "Assessment", "href": "/assessment/"},
            {"label": "Send an enquiry — not available offline", "href": None},
        ],
        boundary=(
            "The enquiry form posts to a sales inbox. This clone sends no mail "
            "outside its own local verification flow, so the fields are described "
            "rather than offered."
        ),
    )


# --- help centre and legal -------------------------------------------------


@app.get("/support/", include_in_schema=False)
@app.get("/hc/en-us", include_in_schema=False)
@app.get("/hc/en-us/", include_in_schema=False)
async def support_page(request: Request) -> Response:
    payload = families.SUPPORT["index"]
    return _page(
        request,
        "family_support.html",
        heading="Help Center",
        query=str(request.query_params.get("q", ""))[:60],
        categories=[
            {"label": "Your Account", "href": "/accounts/login/"},
            {"label": "Billing", "href": "/subscribe/"},
            {"label": "Technical Questions", "href": "/bugbounty/"},
            {"label": "Premium Subscription", "href": "/subscribe/"},
            {"label": "Contest", "href": "/contest/"},
            {"label": "Tutorial", "href": "/explore/"},
        ],
        articles=[
            {"label": "What Are Time Travel Tickets?", "href": None},
            {"label": "I am unable to verify my email. Help?", "href": "/accounts/signup/"},
            {
                "label": "What is LeetCode's Cancellation, Refund, and Termination Policy?",
                "href": "/terms/",
            },
            {
                "label": "How to create test cases on LeetCode?",
                "href": (
                    "/hc/en-us/articles/"
                    "32442719377939-How-to-create-test-cases-on-LeetCode/"
                ),
            },
            {
                "label": "Why all my solutions in the code editor suddenly went missing?",
                "href": None,
            },
            {
                "label": "What are the environments for the programming languages?",
                "href": "/problems/two-sum/description/",
            },
        ],
        captured_text=payload.get("captured_text", ""),
        boundary=(
            "The captured help-centre article URL answered 404 on the source, so "
            "its local page states that rather than inventing an article body. "
            "Rows without a local destination are shown as text."
        ),
    )


@app.get("/hc/en-us/articles/{slug}/", include_in_schema=False)
async def support_article(request: Request, slug: str) -> Response:
    payload = families.SUPPORT["article"]
    return _page(
        request,
        "family_article.html",
        heading="Help article",
        eyebrow=slug[:120],
        captured_text="",
        empty=(
            "The Playwright run requested this article and the source answered "
            f"{payload.get('response_status', 404)} Page Not Found. The clone "
            "reproduces that fact instead of inventing an article."
        ),
        links=[{"label": "Back to the Help Center", "href": "/support/"}],
    )


@app.get("/privacy/", include_in_schema=False)
async def privacy_page(request: Request) -> Response:
    return _captured_article(
        request,
        families.LEGAL["privacy"],
        heading="Privacy Policy",
        eyebrow="",
        links=[
            {"label": "Terms of Service", "href": "/terms/"},
            {"label": "Help Center", "href": "/support/"},
        ],
    )


@app.get("/terms/", include_in_schema=False)
async def terms_page(request: Request) -> Response:
    return _captured_article(
        request,
        families.LEGAL["terms"],
        heading="Terms of Service",
        eyebrow="",
        links=[
            {"label": "Privacy Policy", "href": "/privacy/"},
            {"label": "Help Center", "href": "/support/"},
        ],
    )


# --- small captured static pages ------------------------------------------


STATIC_HEADINGS: dict[str, tuple[str, str]] = {
    "/app/": ("LeetCode at Your Fingertips", "Mobile app"),
    "/bugbounty/": ("Bug Bounty", "Security"),
    "/student/": ("Bring LeetCode to Your School", "Students"),
    "/region/": ("Choose Country or Region", "Region"),
    "/link/": ("Leaving LeetCode", "External link interstitial"),
    "/jobs/": ("Current Openings", "Careers"),
}


def _register_static(path: str, heading: str, eyebrow: str) -> None:
    @app.get(path, include_in_schema=False)
    async def static_page(
        request: Request, _path: str = path, _h: str = heading, _e: str = eyebrow
    ) -> Response:
        payload = families.STATIC_PAGES.get(_path, {})
        external = bool(payload.get("final_path")) and not str(
            payload.get("final_path")
        ).startswith(_path)
        links = [
            {"label": "Problems", "href": "/problemset/"},
            {"label": "Help Center", "href": "/support/"},
        ]
        boundary = None
        if external:
            boundary = (
                "The source redirects this path to a third-party host. This clone "
                "reaches no remote origin, so the destination is described rather "
                "than followed."
            )
        return _captured_article(
            request,
            payload,
            heading=_h,
            eyebrow=_e,
            links=links,
            boundary=boundary,
        )


for _path, (_heading, _eyebrow) in STATIC_HEADINGS.items():
    _register_static(_path, _heading, _eyebrow)


@app.get("/playground/new/empty", include_in_schema=False)
@app.get("/playground/new/empty/", include_in_schema=False)
@app.get("/profile/account/", include_in_schema=False)
async def login_gated(request: Request) -> Response:
    """The source sends both of these to the login page for an anonymous visitor."""

    target = request.url.path
    return RedirectResponse(
        "/accounts/login/?next=" + quote(target), status_code=307
    )


#: Path prefixes whose 404 must stay machine-readable. A caller that asked for
#: data gets an error object, not a rendered page it cannot parse.
JSON_PREFIXES: tuple[str, ...] = ("/api/", "/__admin")


def _not_found(request: Request) -> Response:
    path = request.url.path
    if path == "/api" or path.startswith(JSON_PREFIXES):
        return JSONResponse({"error": "not-found"}, status_code=404)
    return _html(
        render("not_found.html", member=_member(request), body_class="app"),
        status_code=404,
    )


@app.exception_handler(404)
async def not_found_handler(request: Request, exc: Exception) -> Response:
    return _not_found(request)


def main() -> None:  # pragma: no cover - process entry point
    import uvicorn

    uvicorn.run(
        app,
        host=os.environ.get("HOST", "127.0.0.1"),
        port=int(os.environ.get("PORT", "8451")),
        log_level="warning",
    )


if __name__ == "__main__":  # pragma: no cover - process entry point
    main()