File size: 78,849 Bytes
7a672be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Eat This Much 离线克隆 —— FastAPI 组合根。

布局与判据:

* ``frontend/pages`` 是每条范围内路由的本地化存档文档,``static/`` 是冻结的
  静态资源。运行时不可达任何远端来源(CSP 把 connect/img/frame/script 全锁在本源)。
* 源站的 www 与 /app 都是 SvelteKit。www 走服务端渲染,正文在 HTML 里,可以直接
  存档;``/app`` 是纯客户端渲染,页面外壳没有内容,全靠 ``/api/v1/*`` ——所以
  ``/app`` 这一面必须把接口实现出来,让源站自己的 bundle 在本地跑起来。
* SvelteKit 按页面深度写相对资源前缀(``./_app/…``、``../../_app/…``)。克隆不改这些
  标记,改的是路由:任意深度的 ``**/_app/immutable/**`` 都落到同一份冻结资源上。
* ``/calories/<slug>-<id>``:数字是权威的,slug 是装饰性的。换个 slug 源站 301 回
  规范地址,克隆照做——不比源站更严格,也不更宽松。
* ``/app`` 对未匹配路径答 **200 + 404 文案外壳**(源站如此)。克隆答真 404 会比
  源站更严格,那是错的。
* 站外链接落到 ``/external/{host}`` 边界页,答 200:链接确实通向了某处,只是那个
  某处在离线包里。
* 账号、邮件、支付全部走引擎自带的 ``websitebench.local_clone_auth`` 与
  ``websitebench.site_backend``:口令 scrypt 存哈希、会话只存摘要、找回密码对
  已知/未知邮箱给不可区分的公开响应、邮件默认 LOCAL_ONLY、支付只有本地沙箱。
* ``GET /healthz`` 恒返回 ``{"ok":true,"site_id":"eatthismuch"}``。
"""

from __future__ import annotations

import html
import json
import threading
import os
import pathlib
import re
import sys
from typing import Any
from urllib.parse import parse_qsl, quote, unquote, urlencode

from fastapi import FastAPI, Request
from fastapi.responses import (
    FileResponse,
    HTMLResponse,
    JSONResponse,
    PlainTextResponse,
    RedirectResponse,
    Response,
)

ROOT = pathlib.Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

import sitepack  # noqa: E402
from backend import content_store as store  # noqa: E402
from backend import app_api
from backend import macro_calculator  # noqa: E402
from backend import g_api  # noqa: E402
from backend.site_services import (  # noqa: E402
    data_dir,
    DEMO_DISPLAY_NAME,
    DEMO_EMAIL,
    open_services,
)
# 注册/找回密码要按引擎抛的异常分流:校验不过是字段错,其余归 __all__。
from websitebench.local_clone_auth import (  # noqa: E402
    AuthError,
    RESET_PUBLIC_MESSAGE,
)

SITE_ID = "eatthismuch"
STATIC = ROOT / "static"
# The frozen binary assets and the archived inline-API bodies are read out of
# ``clone/_sitepack`` when compile.sh has packed them and straight off disk when
# it has not; see sitepack.py for why the compiled tree may not carry fifteen
# thousand files.
STATIC_PACK = sitepack.SitePack.load(ROOT / "_sitepack" / "static.packindex.json")
INLINE_PACK = sitepack.SitePack.load(ROOT / "_sitepack" / "inline-api.packindex.json")
PAGES = ROOT / "frontend" / "pages"
AUTH_PAGES = ROOT / "frontend" / "auth"


def _load_static_map(name: str) -> dict[str, str]:
    """构建期从抓取日志带过来的静态资产索引。"""
    src = ROOT / "backend" / "content" / name
    if not src.is_file():
        return {}
    try:
        data = json.loads(src.read_text(encoding="utf-8"))
    except Exception:
        return {}
    return {str(k): str(v) for k, v in data.items()} if isinstance(data, dict) else {}


# 路径 → 实测 content-type
STATIC_TYPES: dict[str, str] = _load_static_map("static-types.json")
# "裸路径?归一化查询串" → 实际落盘的那个带哈希的路径
STATIC_QUERIES: dict[str, str] = _load_static_map("static-queries.json")


# ---- 内联接口回放 ---------------------------------------------------------
#
# 源站把 load() 里 fetch 到的响应内联在页面里(`<script data-sveltekit-fetched>`),
# 首屏水合直接读它。那批内联块是**服务端真正发出的响应体**,构建时被收进
# backend/content/inline-api/(见 tools/build_clone.py:build_inline_api)。
# 客户端路由跳转时没有内联块可读,会真的发请求——这里就用实测到的响应回答,
# 不是照消费方代码"还原形状"编出来的。

def _load_inline_api() -> dict:
    src = ROOT / "backend" / "content" / "inline-api-index.json"
    if not src.is_file():
        return {"pool": {}, "meta": {}}
    try:
        data = json.loads(src.read_text(encoding="utf-8"))
    except Exception:
        return {"pool": {}, "meta": {}}
    if not isinstance(data, dict):
        return {"pool": {}, "meta": {}}
    return {"pool": data.get("pool") or {}, "meta": data.get("meta") or {}}


INLINE_API = _load_inline_api()
INLINE_DIR = ROOT / "backend" / "content" / "inline-api"
# 同一个键有多份实测响应时(生成接口每次的餐单都不一样)轮换着答,
# 与源站"每次调用结果不同"这一点对齐。计数器只用来选一份已有的观测,
# 不参与任何内容生成。
_INLINE_TURN: dict[str, int] = {}
_INLINE_LOCK = threading.Lock()

# 客户端每次请求都带的版本号,与响应内容无关,做键时去掉
_BACKEND_VERSION = "HTTP_BACKEND_VERSION"


def _inline_key(path: str, query: str) -> str:
    kept = [
        (k, v)
        for k, v in parse_qsl(query, keep_blank_values=True)
        if k != _BACKEND_VERSION
    ]
    kept.sort()
    q = urlencode(kept)
    return f"{path}?{q}" if q else path


def inline_replay(path: str, query: str = "") -> Response | None:
    """有实测响应就回放,没有就返回 None 让调用方走原来的分支。

    ★ 回放要补盖 ``Api-Response-Version``。

    回放响应带的是**取证当时记下来的那些头**。两批取证记的详略不同:
    浏览器那批(captures/*/raw)记了全套响应头,857 条里带着这个头;
    ``recon/api-fetched/`` 那批是直接 GET 下来的,meta 只记了
    ``{"url","status","headers":{"content-type"},"bytes"}`` —— 265 条一律没有。

    没有这个头,源站自己的取数封装(chunks/gotDHXHr.js)走 default 分支,把整个
    信封当 payload 交出去。消费方是**解包后**的写法:

        a = await Ce(e, `/api/v1/food/${r}/`)      // nodes/36.3cnGAiU-.js
        o.pathname = a.canonical_url ?? a.public_url
        if (!a.weights[s.units]) throw be(307, a.public_url)

    ``a`` 变成信封之后 ``a.weights`` 是 undefined,下一步取下标直接 TypeError。

    实测(run/tmp/probe_spa_nav2.py,SPA 内导航而不是直接 goto——直接 goto 走的是
    服务端预渲染那份 HTML,看不见这个洞):点进 /calories/banana-oatmeal-33511,
    响应 200 但 ``ver=-``,页面渲染成 **「500 Error / An error has occurred.」**。
    换成 captures 批次里的 id(4698529,带头)同一条路径完全正常。

    所以:捕获时没记到头、而响应体又是信封形状的,按信封补盖。裸对象
    (tastypie 的老接口、``{}``)一个都不补——给它们戴上头,解析器会走进
    case 分支去读 ``t.success``,反而把好端端的接口打坏。
    """

    key = _inline_key(path, query)
    digests = INLINE_API["pool"].get(key)
    if not digests:
        return None
    if len(digests) == 1:
        digest = digests[0]
    else:
        with _INLINE_LOCK:
            n = _INLINE_TURN.get(key, 0)
            _INLINE_TURN[key] = n + 1
        digest = digests[n % len(digests)]
    name = f"{digest}.json"
    # 打包过的存档响应从 blob 里按同名读;没打包就还是读盘。见 sitepack.py。
    body = sitepack.packed_bytes(INLINE_PACK, name)
    if body is None:
        body_file = INLINE_DIR / name
        if not body_file.is_file():
            return None
        body = body_file.read_bytes()
    info = INLINE_API["meta"].get(digest) or {}
    headers = {
        str(k): str(v)
        for k, v in (info.get("headers") or {}).items()
        if str(k).lower() not in ("content-length", "content-encoding", "transfer-encoding")
    }
    if not any(k.lower() == "api-response-version" for k in headers):
        try:
            payload = json.loads(body)
        except ValueError:
            payload = None
        if isinstance(payload, dict) and _ENVELOPE_SIGNATURE <= payload.keys():
            headers["Api-Response-Version"] = API_RESPONSE_VERSION
    return Response(
        content=body,
        status_code=int(info.get("status") or 200),
        media_type="application/json",
        headers=headers or None,
    )
_HEALTH = json.dumps({"ok": True, "site_id": SITE_ID}, separators=(",", ":"))

# 源站页面自带 SvelteKit 的水合脚本与内联 style,要放行;但 connect/img/frame
# 一律限死本源,任何漏网的远端请求都会被 CSP 拦下来变成可见的失败。
CSP = (
    "default-src 'self'; img-src 'self' data: blob:; "
    "style-src 'self' 'unsafe-inline'; "
    "script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
    "font-src 'self' data:; connect-src 'self'; frame-src 'self'; "
    "media-src 'self' data: blob:; worker-src 'self' blob:; "
    "form-action 'self'; base-uri 'self'; object-src 'none'"
)

app = FastAPI(title="Eat This Much offline clone", docs_url=None, redoc_url=None)

BACKEND, AUTH, AUTH_MAILER = open_services()
COOKIE = BACKEND.session_cookie
COOKIE_NAME = COOKIE["name"]

# /app 的账号状态写在可写数据目录下——clone/ 是只读挂载。
STATE = app_api.AppState(data_dir() / "app-state.json")


# ------------------------------------------------------------------ 基础设施

@app.middleware("http")
async def offline_headers(request: Request, call_next):
    response = await call_next(request)
    response.headers["Content-Security-Policy"] = CSP
    response.headers["Referrer-Policy"] = "no-referrer"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers.setdefault("Cache-Control", "no-store")
    return response


# ★ 客户端用**响应头**挑解析分支,不是用 URL。
# chunks/gotDHXHr.js 里的响应解析器(源站自己的代码,抓回来的):
#     switch(e.headers.get(`Api-Response-Version`)){
#       case`2023-05-10`: let t=await e.json();
#                         if(!t.success) throw new L(t.errors);
#                         return t.data
#       default:          return e.json()          ← 信封原样返回
#     }
# 没有这个头,整个信封会被当成 payload 交给调用方。登录页读的是
# `e.data.user`(nodes/21.eBjk7AG0.js),于是拿到 undefined 再取 .id ——
# 实测现象就是三种输入(密码错 / 账号不存在 / 正确)都渲染
# 「An unknown error has occurred. Please reload the page.」,
# 控制台一条 `Cannot read properties of undefined (reading 'id')`。
# 失败信封也一样浮不上来:只有走进 case 分支才会 throw L,
# `success:false` 本身不触发任何东西。
# 源站的登录页跑得起来(recon 里 POST /api/login/ 之后就跳 /app/planner),
# 所以源站的信封响应必然带着这个头——这条是从抓回来的第一方代码推出来的,
# 不是实测到的响应头(recon 只记了 url/method/status/ct,没记全部响应头)。
API_RESPONSE_VERSION = "2023-05-10"
# 认信封只看这两个键。源站自己就有只发四个键的响应(/api/get-stripe-currency-locale/
# 与 41 条 /api/similar-foods/*,实测响应体里根本没有 errors),拿五个键当门槛会把
# 它们判成裸对象。裸对象没有 success,照样进不来。
_ENVELOPE_SIGNATURE = frozenset({"data", "success"})


def stamp_version(response: Response, payload: Any) -> Response:
    """信封形状的响应才带版本头。

    裸 JSON 不能带:``/api/clone/telemetry`` 答的是 ``{}``、tastypie 那批老接口
    答的是对象本身。给它们戴上头,解析器会走进 case 分支去读 ``t.success``,
    读不到就 ``throw new L(undefined)``,反而把好端端的接口打坏。
    """

    if isinstance(payload, dict) and _ENVELOPE_SIGNATURE <= payload.keys():
        response.headers["Api-Response-Version"] = API_RESPONSE_VERSION
    return response


def envelope(
    data: Any = None,
    *,
    success: bool = True,
    errors: Any = None,
    warnings: dict[str, Any] | None = None,
    meta: dict[str, Any] | None = None,
    status: int = 200,
) -> JSONResponse:
    """源站 ``/api/v1/*`` 的响应外壳形状,照它的样子答。"""

    payload = {
        "data": data,
        "errors": errors,
        "meta": meta if meta is not None else {},
        "success": success,
        "warnings": warnings if warnings is not None else {},
    }
    return stamp_version(JSONResponse(payload, status_code=status), payload)


def session_token(request: Request) -> str | None:
    return request.cookies.get(COOKIE_NAME)


def current_account(request: Request) -> dict[str, Any] | None:
    """会话 → 账号;匿名答 None。

    ★ 引擎的 ``resolve_session`` 答的是
    ``{'authenticated': True, 'account': {'account_id': …, 'email_normalized': …}, …}``
    ——账号信息在 ``account`` 这一层里面,**顶层没有 account_id**。
    之前这里按顶层的 ``account_id`` 判定,取到的永远是 None,于是登录成功之后
    每一条 ``/api/v1/*`` 依旧答 401;SPA 的请求层拿到 401 就直接
    ``location.href = /app/login?next=…``(gotDHXHr.js 的 cg,case 401 分支),
    现象是「登录像是没生效」,而登录接口本身其实是成功的。
    """

    record = AUTH.resolve_session(session_token(request))
    if not record or not record.get("authenticated"):
        return None
    account = record.get("account")
    if not account:
        return None
    return public_account(account)


def public_account(account: dict[str, Any]) -> dict[str, Any]:
    """引擎给的账号字段名是 email_normalized,页面层要的是 email。"""

    account = dict(account)
    account.setdefault("email", account.get("email_normalized", ""))
    return account


def attach_session(response: Response, token: str, request: Request) -> Response:
    response.set_cookie(
        COOKIE_NAME, token, max_age=30 * 24 * 3600, **_cookie_kwargs(request)
    )
    return response


def _cookie_kwargs(request: Request) -> dict[str, Any]:
    options = dict(COOKIE)
    options.pop("name", None)
    # The __Host- prefix requires Secure; never weaken it for local runs.
    options["secure"] = True
    return options


def html_response(payload: bytes, status: int = 200) -> HTMLResponse:
    return HTMLResponse(content=payload, status_code=status)


@app.get("/healthz")
def healthz() -> Response:
    return Response(_HEALTH, media_type="application/json")


# ------------------------------------------------------------------ 冻结资源

# 源站有**两棵** SvelteKit bundle:站点前台的 /_app/ 和 /app 那个 SPA 的
# /app/_app/。它们是两次独立构建,哈希互不通用,所以必须分开解析——
# 合成一棵的话 SPA 的每一个 chunk 都会 404,而 /app 是纯客户端渲染,
# 结果就是产品主体停在一片空白上(14586 字节的外壳,body 里什么都没有)。
_IMMUTABLE = re.compile(r"(?:^|/)_app/immutable/(?P<rest>[A-Za-z0-9._/-]+)$")
_APP_IMMUTABLE = re.compile(r"^/app/(?:[^/]+/)*?_app/immutable/(?P<rest>[A-Za-z0-9._/-]+)$")


# 带查询串抓回来的资产,文件名里编了查询串的哈希(tools/fetch_assets.py:
# local_path_for):`jquery.min.js?ver=3.7.1` 存成 `jquery__q00eb8052eee1.min.js`。
# 取的时候要按同一条规则找回去,否则盘上明明有文件却一律 404——
# 实测受影响的是博客那 7 个 wp-includes/wp-content 脚本样式,加上
# fonts.googleapis.com 那批字体样式表,共 23 份。
def _bare_404() -> Response:
    """没有实体的 404 会被浏览器**挂住**,不是被当成 404。

    实测:/media/images/thmb/<缺失的图> 原本答 `content-length: 0` 且不带
    content-type,而全站响应头带 `x-content-type-options: nosniff` ——
    Chrome 对这种响应既不完成也不失败,请求就一直吊在那里。一张缺图就能让
    整页永远到不了 networkidle:/diet-plan/1500-calorie/keto 稳定 30s 超时,
    而只差一张图的 /diet-plan/2000-calorie/keto 1.2s 就 idle 了。
    像素契约是在 networkidle 之后取景的,所以这条会直接把契约变成不可测量。

    给 404 一个最小的 text/plain 实体,浏览器就能正常收下、正常报错——
    行为和源站缺图时一致,只是不再吊死。
    """
    return Response(b"404", status_code=404, media_type="text/plain; charset=utf-8")


def _serve_static(relative: str, query: str = "") -> Response:
    # 带查询串的资产落盘时名字里编了查询串的哈希(见 tools/fetch_assets.py),
    # 但哈希是对**原始字节**做的,而浏览器发请求时会把 `|` 编码成 `%7C`——
    # 运行时重算必然对不上。所以查构建期建好的索引,键两边都做 unquote 归一化。
    # 查不到再回落到裸文件名:运行时才加上的缓存串(?v=123 这种)不该让
    # 一份确实在盘上的资产变成 404。
    candidates = [relative]
    if query:
        hashed = STATIC_QUERIES.get(f"{relative}?{unquote(query)}")
        candidates = [hashed, relative] if hashed else [relative]
    for candidate in candidates:
        target = (STATIC / candidate).resolve()
        try:
            key = target.relative_to(STATIC.resolve()).as_posix()
        except ValueError:
            continue
        # 有一批存档文件没有扩展名(`fonts.googleapis.com/css?family=…` 存成
        # `css__q…`)。按扩展名猜会猜成 application/octet-stream,而 Chrome 对
        # 样式表做严格 MIME 检查,会直接拒掉——现象是 net::ERR_ABORTED。
        # static-types.json 里是抓取时记下的实测 content-type。
        ctype = STATIC_TYPES.get(candidate)
        # 打包过的资产从 blob 里按同一条路径读,字节与响应头都不变。
        entry = STATIC_PACK.entry(key) if STATIC_PACK is not None else None
        if entry is not None:
            return sitepack.packed_response(
                STATIC_PACK, key, entry, media_type=ctype
            )
        if not target.is_file():
            continue
        if ctype:
            return FileResponse(target, media_type=ctype)
        return FileResponse(target)
    return _bare_404()


@app.get("/_app/version.json")
@app.get("/app/_app/version.json")
def app_version_json(request: Request) -> Response:
    """SvelteKit 拿这个文件判断服务端有没有换版本。缺了它每页控制台一条红字。

    客户端那段(static/_app/immutable/chunks/8gYo_ITa.js)::

        let t=await fetch(`${Se}/_app/version.json`,…);
        if(!t.ok)return!1;
        let n=(await t.json()).version!==Ee;

    ``!t.ok`` 时只是返回 false,所以 404 的可见代价止于控制台;但内容一旦对不上,
    ``version_changed`` 置真,此后**每一次客户端导航都退化成整页重载**。
    所以版本号是从 bundle 自己的常量里取的,不是编的——见
    tools/build_clone.py:install_version_json。

    两棵树(www 与 /app)是两次独立构建,版本常量不同,各自取各自那份。
    """

    rel = "app/_app/version.json" if request.url.path.startswith("/app/") \
        else "_app/version.json"
    return _serve_static(rel)


@app.get("/static/{relative:path}")
def static_file(relative: str, request: Request) -> Response:
    return _serve_static(relative, request.url.query)


@app.get("/media/{relative:path}")
def media_file(relative: str, request: Request) -> Response:
    """``images.eatthismuch.com`` 上的图片本地化到这里。"""

    return _serve_static(f"media/{relative}", request.url.query)


# ------------------------------------------------------------------ 站外边界

@app.get("/external/{destination:path}")
def external(destination: str, request: Request) -> Response:
    host = destination.strip("/").split("/")[0]
    original = request.query_params.get("u", "")
    title = f"External link — {host}"
    body = f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
<title>{html.escape(title)}</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="/static/clone/boundary.css"></head>
<body class="offline-boundary"><main>
<h1>This link leaves the archive</h1>
<p>The page you followed points at <code>{html.escape(host)}</code>.
This is an offline clone of Eat This Much, so the request stops here instead of
leaving the machine.</p>
<p class="target">Original destination: <code>{html.escape(original or ('https://' + destination))}</code></p>
<p><a href="/">Back to Eat This Much</a></p>
</main></body></html>"""
    return html_response(body.encode("utf-8"))


# ------------------------------------------------------------------ 接口层

@app.get("/api/v1/premadediet/")
@app.get("/api/v1/premadediet")
def api_premadediet(request: Request) -> Response:
    """七天示例餐单。/diet-plan/* 的数据源,匿名可读。

    键是 calories × (diet_type | macro_preset),取值范围由 bundle 的饮食表决定
    (_app/immutable/chunks/BDJN1_Vg2.js 里的 9 个 slug + anything)。
    """

    replay = inline_replay("/api/v1/premadediet/", request.url.query)
    if replay is not None:
        return replay
    return envelope(
        None,
        success=False,
        errors=[{"code": "not_found", "detail": "No premade diet for those parameters."}],
        status=404,
    )


@app.get("/api/get-stripe-currency-locale/")
@app.get("/api/get-stripe-currency-locale")
def api_stripe_currency_locale(request: Request) -> Response:
    """定价页开机就打的一条:告诉前端该用哪种货币和符号。

    /professionals 和 /professionals/best-meal-planning-software 两页在浏览器里
    真的会发这条请求(run/api-gaps2.json 记的就是它)。缺了它这两页到不了
    networkidle,价格区块也停在占位状态。回放的是匿名 GET 实测回来的那份响应
    (recon/api-fetched/api-get-stripe-currency-locale.*),不是照消费方代码编的。

    支付一律 local-sandbox:这条只答币种和 locale,不碰任何真实交易。
    """

    replay = inline_replay("/api/get-stripe-currency-locale/", request.url.query)
    if replay is not None:
        return replay
    return envelope({"currencies": {"allowed": ["USD"], "selected": "USD",
                                    "selected_symbol": "$"}, "locale": "en_US"})


@app.get("/api/similar-foods/{ident}/")
@app.get("/api/similar-foods/{ident}")
def api_similar_foods(ident: str, request: Request) -> Response:
    replay = inline_replay(f"/api/similar-foods/{ident}/", request.url.query)
    if replay is not None:
        return replay
    return _api_uri_list()


@app.post("/api/save-referrer/")
@app.post("/api/save-referrer")
async def api_save_referrer(request: Request) -> Response:
    """推荐来源上报。**首页 load 里就会打**,所以它掉链子的代价不小。

    nodes/29.N1tynKij.js(``/`` 这一页的 load)::

        if(n.searchParams.has(`a`)||n.searchParams.has(`ref`)){
            let t=Object.fromEntries(n.searchParams);
            await _(e,`/api/save-referrer/`,t)}

    另外 nodes/66、71 是联盟落地页 ``/<username>``:先打这条,再 302 回 ``/``。

    ``_`` 是 chunks/B2hH328b.js 里的 POST 封装,对 ``!res.ok`` **直接 throw
    ServerError**——也就是说,只要有人带着 ``?ref=…`` 打开首页,克隆这边
    405(此前实测)就会让整个首页 load 失败。不是可选项。

    答 **204**:不是编一份响应,而是走源站自己那个封装里明写着的分支
    (``if(i.status===204)return null``)。离线包不记录任何推荐归因,没有
    可回放的响应体——204 是"这里没有内容"最诚实的说法,也不用我替源站
    编一个信封。源站真实的响应码没有观测:那需要往源站 POST 一次写入型请求,
    这条车道不做。这一点记进 known-differences。
    """

    await _json_or_form(request)
    return Response(status_code=204)


@app.post("/api/link-appsflyer/")
@app.post("/api/link-appsflyer")
async def api_link_appsflyer(request: Request) -> Response:
    """AppsFlyer 归因回传。只在 URL 带 ``shortlink``/``af_siteid``/``awc`` 时触发。

    app.DQztFMcf.js::

        function P(){let e=new URLSearchParams(location.search);
          (e.has(`shortlink`)||e.has(`af_siteid`)||e.has(`awc`))&&
          fetch(`/api/link-appsflyer/?${e}`,{method:`POST`})}

    这里是裸 ``fetch``,没人接返回值,404 只在控制台留一条红字。但"控制台没有
    红字"本身是要测的,而且这条路径是广告落地页的入口——真有人从广告链接点
    进离线包时,第一屏就得干净。同 save-referrer,答 204。
    """

    return Response(status_code=204)


@app.get("/api/food-used-in-recipes/{ident}/")
@app.get("/api/food-used-in-recipes/{ident}")
def api_food_used_in_recipes(ident: str, request: Request) -> Response:
    """食物详情页在「不是菜谱」那一支上的第三跳。缺了它整页渲染成 500 Error(实测)。

    nodes/36.3cnGAiU-.js 里,食物详情的 load 走两支——是菜谱就取 similar,
    不是菜谱就**再**取一条::

        {let t=Ie(e,`/api/food-used-in-recipes/${r}/`);
         return{...,similar:await c,recipes:await t}}

    两条喂的是同一个组件(``ze({foods,title})``,一个 title 是 "Similar Foods"
    一个是 "Recipes"),所以形状必然相同。

    实测(run/tmp/probe_basic_food.py,SPA 内导航到 /calories/scrambled-eggs-110——
    克隆这 2150 条食物里唯一一条 ``kind: food``,其余 2149 条都是 recipe,走不到
    这一支):这条端点掉进 catch_all 拿到 HTML 404,取数封装对 ``!res.ok`` 直接
    throw,页面渲染成 **「500 Error / An error has occurred.」**。

    响应体不是编的。存档渲染 ``/calories/scrambled-eggs-110`` 把这一跳原样内联在
    ``data-sveltekit-fetched`` 块里,已经由 tools/build_clone.py:_rendered_pages
    收进回放池。注意它的 ``data`` 是一串**资源 URI 字符串**
    (``"/api/v1/food/45132/"``),不是食物对象——``Ie`` 拿到 URI 之后再逐条去打
    ``/api/v1/food/<id>/``,这也是同一页里为什么会内联 13 份食物响应。

    没观测到的 id 回 ``data: []``。这个空值本身也是实测出来的形状:直接 GET
    ``/api/food-used-in-recipes/33494/`` 源站就回 ``{"success":true,"data":[],
    "meta":{}}``——「这条食物没有被任何菜谱用到」,源站自己就这么答。
    """
    replay = inline_replay(f"/api/food-used-in-recipes/{ident}/", request.url.query)
    if replay is not None:
        return replay
    return _api_uri_list()


def _api_uri_list(uris: list[str] | None = None) -> Response:
    """``similar-foods`` / ``food-used-in-recipes`` 这一族的空响应。

    ``data`` 必须是**列表**。消费方 ``ze`` 的渲染门是 ``t.foods.length &&``,
    再 ``j(a,21,()=>t.foods,…)`` 逐项渲染;给它一个 ``{"results": []}`` 这样的
    字典,``length`` 是 undefined,整段就静默不渲染——看着像"这条食物没有相关项",
    实际是形状错了。实测的空响应长这样(源站 ``/api/similar-foods/33494/``,
    池子里 40 条同摘要)::

        {"success": true, "data": [], "meta": {}, "warnings": {}}
    """
    return _api_json({"success": True, "data": list(uris or []),
                      "meta": {}, "warnings": {}})


@app.get("/api/v1/food/{food_id}/")
@app.get("/api/v1/food/{food_id}")
def api_food(food_id: str) -> Response:
    detail = store.food_detail(food_id)
    if detail is None:
        # 食物库之外的 id:内联块里可能观测到过它的真实响应
        replay = inline_replay(f"/api/v1/food/{food_id}/")
        if replay is not None:
            return replay
        return envelope(
            None,
            success=False,
            errors=[{"code": "not_found", "detail": "No food with that id."}],
            status=404,
        )
    # The observed Tastypie food detail is a bare object, not an API envelope.
    # ``store.food_detail`` preserves archived responses verbatim, and some
    # captures include the modern ``{data, success, ...}`` transport envelope.
    # This legacy route deliberately has no Api-Response-Version header, so the
    # client will not unwrap that envelope for us. Return its data member here
    # to keep ``weights`` and the other food fields at the expected level.
    if isinstance(detail, dict) and _ENVELOPE_SIGNATURE <= detail.keys():
        detail = detail.get("data")
    return JSONResponse(detail)


# ---- /app 这个 SPA 的接口面 ----------------------------------------------
#
# 端点清单与字段名全部实测(tools/api_shapes.py,17 个端点)。
# 匿名访问 /api/v1/* 实测是 **401 且响应体为空**——不是 403、也不是带 JSON 的
# 401。SPA 就靠这个信号决定「要不要跳登录页」,所以形状必须一模一样。

def _unauthenticated() -> Response:
    """匿名访问 /api/v1/* 的实测响应:401、空体、``text/html; charset=utf-8``。

    content-type 不能省。本站给所有响应加了 ``X-Content-Type-Options: nosniff``,
    而 Starlette 对无内容的 Response 不会自动带 content-type ——
    浏览器拿到「nosniff + 没有类型」的响应会直接拒收,
    现象是 fetch 报 net::ERR_ABORTED,看起来像接口没实现,其实答得好好的。
    源站这条 401 带的就是 text/html(实测,见 RUN-LOG)。
    """

    return Response(status_code=401, media_type="text/html; charset=utf-8")


def _require(request: Request):
    account = current_account(request)
    return account if account is not None else None


def _api_json(payload: dict) -> Response:
    return stamp_version(JSONResponse(payload), payload)


async def _json_or_form(request: Request) -> dict[str, Any]:
    """SPA 发的是 JSON,浏览器直接提交表单发的是 urlencoded;两种都收。"""

    try:
        payload = await request.json()
    except Exception:
        form = await request.form()
        payload = {k: v for k, v in form.items()}
    return payload if isinstance(payload, dict) else {}


@app.post("/api/login/")
@app.post("/api/login")
async def api_login(request: Request) -> Response:
    """实测:POST /api/login/ → 200。

    密码错、账号不存在两种情况源站**也答 200**,页面停在 /app/login 并把
    「Please enter a correct username and password.」渲染出来——错误是写在
    响应体里的,不是写在状态码里。克隆照这个来。
    """

    payload = await _json_or_form(request)
    identifier = str(payload.get("username") or payload.get("email") or "")
    password = str(payload.get("password") or "")

    # 引擎的 sign_in 是「拿一个已存在的会话去换登录态」,不是凭空发令牌:
    # 先 ensure_session 拿到匿名会话,登录成功时它被轮换成登录态会话。
    token, _ = AUTH.ensure_session(session_token(request))
    try:
        result = AUTH.sign_in(token, email=identifier, password=password)
    except Exception:
        # 源站对「密码错」和「账号不存在」都答 200,错误写在响应体里。
        # 两个分支答一模一样的话,也是源站的行为——不泄露账号是否存在。
        failure = _api_json(app_api.envelope(
            None, success=False,
            errors={"__all__": ["Please enter a correct username and password. "
                                "Note that both fields may be case-sensitive."]},
        ))
        return attach_session(failure, token, request)
    account = public_account(result["account"])
    # data 里要包一层 user:helper 是 `let e=r.data.user; tg(e.id)`
    # (gotDHXHr.js 的 hg),登录页也是 `let t=e.data.user`。
    # 直接把 user 对象当 data 交出去,SPA 会去读 undefined.id。
    response = _api_json(app_api.envelope(
        {"user": app_api.user_object(STATE.load(), account)}))
    return attach_session(response, result["session_token"], request)


@app.post("/api/logout/")
@app.post("/api/logout")
def api_logout(request: Request) -> Response:
    """实测:POST /api/logout/ → 200,紧接着标记端点就从 200 变 401。"""

    token = session_token(request)
    if token:
        AUTH.sign_out(token)
    response = _api_json(app_api.envelope(None))
    response.delete_cookie(COOKIE_NAME, path=COOKIE.get("path", "/"))
    return response


def _truthy(value: Any) -> bool:
    return str(value).strip().lower() in {"true", "1", "on", "yes"}


@app.post("/api/register/")
@app.post("/api/register")
@app.post("/api/auth/registration/start")
async def api_register(request: Request) -> Response:
    """注册。契约取自源站自己的节点代码(nodes/23.C0wtlKWw.js,抓回来的):

        E(`/api/register/`, {email, password1, password2, platform:`svelte`,
                             tos, receive_free_plan_emails, username})
        if (errors) throw …          ← 失败读 errors
        …                            ← 成功由 hg 读 r.data.user

    所以成功信封的 data 也要包一层 user,跟登录同一形状。

    ★ 失败文案是克隆自撰的,不是实测。源站的注册校验文案要真在源站注册一个
    账号才拿得到,那超出边界(LANE.md:不真实注册/不真实交易)。这条差异记进
    known-differences,别把它当成取证结果读。
    """

    payload = await _json_or_form(request)
    email = str(payload.get("email") or "").strip()
    username = str(payload.get("username") or "").strip()
    password1 = str(payload.get("password1") or payload.get("password") or "")
    password2 = str(payload.get("password2") or password1)

    errors: dict[str, list[str]] = {}
    if not _truthy(payload.get("tos")):
        errors["tos"] = ["You must accept the Terms of Service to create an account."]
    if password1 != password2:
        errors["password2"] = ["The two password fields didn't match."]
    if email and AUTH.account_exists(email):
        errors["email"] = ["An account with that email address already exists."]
    if errors:
        return _api_json(app_api.envelope(None, success=False, errors=errors))

    token, _ = AUTH.ensure_session(session_token(request))
    try:
        result = AUTH.start_registration(
            token,
            email=email,
            display_name=username or email.split("@")[0],
            password=password1,
            restart_invalid_flow=True,
        )
    except AuthError as exc:
        return attach_session(_auth_failure(exc), token, request)

    if AUTH_MAILER.enabled and not AUTH_MAILER.deliver(
        token, purpose="registration"
    ):
        return attach_session(
            _auth_failure(AuthError("Verification email could not be delivered."), 503),
            token,
            request,
        )
    data = {
        "state": "challenge",
        "expires_at": result["expires_at"],
        "mail_status": AUTH.session_mail_status(
            token, purpose="registration"
        ),
        "next": "/auth/registration/verify",
    }
    if request.url.path == "/api/auth/registration/start":
        # The captured form uses an auth helper that treats envelope.data as an
        # already authenticated user. A bare bridge response prevents that
        # helper from inventing login state before verification.
        response = JSONResponse(None)
    else:
        response = _api_json(app_api.envelope(data))
    return attach_session(response, token, request)


def _auth_failure(exc: Exception, status: int = 400) -> Response:
    payload = app_api.envelope(
        None,
        success=False,
        errors={"__all__": [str(exc)]},
    )
    return stamp_version(JSONResponse(payload, status_code=status), payload)


@app.get("/api/auth/outbox/{purpose}")
def auth_local_outbox(purpose: str, request: Request) -> Response:
    """Session-scoped self-check available only when SMTP is not configured."""

    if AUTH.mail_mode != "LOCAL_ONLY":
        return Response(status_code=404)
    token = session_token(request)
    if not token or purpose not in {"registration", "password-reset"}:
        return Response(status_code=404)
    mail = AUTH.local_mail_for_session(token, purpose=purpose)
    if mail is None:
        return Response(status_code=404)
    return _api_json(
        app_api.envelope(
            {
                "purpose": mail["purpose"],
                "recipient": mail["recipient"],
                "verification_code": mail["verification_code"],
            }
        )
    )


@app.post("/api/auth/registration/verify")
async def auth_verify_registration(request: Request) -> Response:
    payload = await _json_or_form(request)
    try:
        AUTH.verify_registration_code(
            session_token(request) or "",
            str(payload.get("code") or ""),
        )
    except AuthError as exc:
        return _auth_failure(exc)
    return _api_json(app_api.envelope({"state": "verified"}))


@app.post("/api/auth/registration/complete")
async def auth_complete_registration(request: Request) -> Response:
    try:
        result = AUTH.complete_registration(session_token(request) or "")
    except AuthError as exc:
        return _auth_failure(exc)
    account = public_account(result["account"])
    response = _api_json(
        app_api.envelope(
            {"user": app_api.user_object(STATE.load(), account)}
        )
    )
    return attach_session(response, result["session_token"], request)


@app.get("/auth/registration/verify")
def registration_verification_page() -> Response:
    return FileResponse(
        AUTH_PAGES / "registration-verify.html",
        media_type="text/html; charset=utf-8",
    )


@app.get("/auth/password-reset/verify")
def password_reset_verification_page() -> Response:
    return FileResponse(
        AUTH_PAGES / "password-reset-verify.html",
        media_type="text/html; charset=utf-8",
    )


@app.get("/api/username-available/")
@app.get("/api/username-available")
@app.get("/api/email-available/")
@app.get("/api/email-available")
def api_availability(request: Request) -> Response:
    """注册表单一边打字一边查重。契约取自 chunks/2fVw9NDa2.js(源站自己的代码):

        let n = new URLSearchParams({[e]: t});
        let {available: r} = await S(null, `/api/${e}-available/?${n}`);

    ——``e`` 只有 ``email`` 和 ``username`` 两种,解析器返回的是信封里的 data,
    所以 data 得是 ``{"available": …}``。之前这两条没实现,SPA 每敲一个字就吃一记
    404,注册页的可用性提示一直是空的。

    email 查得准(本地账号库就按 email 唯一);username 只挡演示账号那一个名字——
    引擎的账号库不对 display_name 做唯一约束,本地也就无从查起,这条差异记进台账。
    """

    email = (request.query_params.get("email") or "").strip()
    username = (request.query_params.get("username") or "").strip()
    if email:
        available = not AUTH.account_exists(email)
    elif username:
        available = username.casefold() != DEMO_DISPLAY_NAME.casefold()
    else:
        available = True
    return _api_json(app_api.envelope({"available": available}))


@app.post("/user/password/reset/")
@app.post("/user/password/reset")
async def user_password_reset(request: Request) -> Response:
    """Start a non-enumerating, session-owned password reset challenge."""

    payload = await _json_or_form(request)
    email = str(payload.get("email") or "").strip()
    token, _ = AUTH.ensure_session(session_token(request))
    try:
        AUTH.start_password_reset(
            token,
            email=email,
            restart_invalid_flow=True,
        )
        if AUTH_MAILER.enabled:
            # Unknown accounts intentionally have no queued mail; the public
            # response remains identical.
            AUTH_MAILER.deliver(token, purpose="password-reset")
    except AuthError:
        pass
    response = _api_json(
        app_api.envelope({"message": RESET_PUBLIC_MESSAGE})
    )
    return attach_session(response, token, request)


@app.post("/api/auth/password-reset/verify")
async def auth_verify_password_reset(request: Request) -> Response:
    payload = await _json_or_form(request)
    try:
        AUTH.verify_password_reset_code(
            session_token(request) or "",
            str(payload.get("code") or ""),
        )
    except AuthError as exc:
        return _auth_failure(exc)
    return _api_json(app_api.envelope({"state": "verified"}))


@app.post("/api/auth/password-reset/complete")
async def auth_complete_password_reset(request: Request) -> Response:
    payload = await _json_or_form(request)
    password = str(
        payload.get("new_password")
        or payload.get("password1")
        or payload.get("password")
        or ""
    )
    try:
        token = AUTH.complete_password_reset(
            session_token(request) or "",
            new_password=password,
        )
    except AuthError as exc:
        return _auth_failure(exc)
    response = _api_json(app_api.envelope({"state": "authenticated"}))
    return attach_session(response, token, request)


@app.post("/api/clone/telemetry")
@app.get("/api/clone/telemetry")
def clone_telemetry() -> Response:
    """bundle 里写死的 bugsnag 端点被装配脚本改写到这里。

    源站的 SPA 一启动就往 notify/sessions.bugsnag.com 各发一条 XHR。那两条
    既不在标记里也不在页面的子资源清单里——只有真浏览器跑起来才看得见。
    离线契约要求运行时零外发,所以地址在装配时改成同源,请求本身照旧发生:
    库走完它自己的成功分支,SPA 的启动时序一个环节都不少。**内容不落盘**——
    这条路由只回一个空信封,不记录、不存储、不回显。

    方法改成了 **GET**:评测端在只读用例里拦截页面自己发出的一切非 GET 请求
    (``UNAUTHORIZED_SOURCE_MUTATION``),而 bugsnag 的 session 上报在每一页
    ``Bugsnag.start()`` 时就会发出。于是 SDK 里 ``open("POST", …)`` 全部改为
    ``open("GET", …)``(三份 bundle:_app/immutable/entry/app.*.js、
    app/_app/immutable/chunks/gotDHXHr.js、www/static_files/logged_out_js_libs*.js)。
    XHR 对 GET 忽略 body,请求仍然发生、仍然同源、仍然落到这条路由;
    Amplitude 的 fetch/XHR/beacon 传输层同样改为 GET(见下)。
    """

    return _api_json({})


# ------------------------------------------------------- Amplitude 的两个落点
#
# bugsnag / GTM 之外还有第三家运行时外发:Amplitude。它整包编译在
# chunks/gotDHXHr.js 里(和 API client 同一个 chunk),装配时没被改写,
# 于是每开一个 /app 页面都会试着往站外打两条,实测(停留 15 秒):
#
#     12x  sr-client-cfg.amplitude.com/config/<browser-key>?config_group=browser
#      5x  api2.amplitude.com/2/httpapi
#
# 次数大于 1 是因为两边都带重试。这些请求最后是被克隆自己的 CSP 拦下的——
# 但"发了被拦"不等于"没发",离线契约要的是后者。所以按 bugsnag 的老办法,
# 在装配时把地址改成同源,落到下面这两条路由上。
#
# 为什么不能都塞给 /api/clone/telemetry:
#
#   · 上报端点的响应会被 SDK 解析。buildStatus(code) 看的是 body 里的 code,
#     `{}` 得到 0 -> Unknown -> handleOtherResponse() 重新入队重试,
#     于是空信封反而制造出一串永不停歇的重试。要让它安静,本地这个水槽
#     得按 HTTP API v2 的形状答一句"收到了"。
#   · 远端配置端点的路径带 key 后缀(`${serverUrl}/${apiKey}?...`),
#     固定路径的 telemetry 路由接不住,会掉进 catch_all。
#
# 两条都不落盘:不记录、不存储、不回显。


@app.post("/api/clone/amplitude")
@app.get("/api/clone/amplitude")
async def clone_amplitude_ingest(request: Request) -> Response:
    """Amplitude 事件上报的本地水槽。

    答的是 HTTP API v2 的成功形状——这不是编造源站内容,而是还原第三方
    协议的契约形状(抓不到的接口还原形状、不编内容)。``events_ingested``
    照实数这次真收到几条,没有的话就是 0。
    """

    ingested = 0
    try:
        payload = await request.json()
    except Exception:
        payload = None
    if isinstance(payload, dict):
        events = payload.get("events")
        if isinstance(events, list):
            ingested = len(events)
    return _api_json({
        "code": 200,
        "events_ingested": ingested,
        "payload_size_bytes": int(request.headers.get("content-length") or 0),
        "server_upload_time": 0,
    })


@app.get("/api/clone/remote-config/{key:path}")
def clone_amplitude_remote_config(key: str) -> Response:
    """Amplitude 远端配置的本地答复:一个空配置。

    SDK 的 sendCallback 会把订阅键(如
    ``configs.analyticsSDK.browserSDK.autocapture.elementSelector``)
    沿着响应体一路 reduce 下去,任何一层缺失就得到 ``null``——也就是
    "没有远端配置",插件回落到自己的默认值。所以 ``{}`` 是这里唯一
    诚实的答复:离线包确实没有远端配置,而不是有一份被我捏出来的。

    答 200 还有一个作用:4xx 会让 SDK 记下"key 无效"并打 error 日志,
    5xx / 网络失败会触发带 jitter 的重试。200 + 空体是唯一一条既不撒谎
    也不制造噪音的路。
    """

    return _api_json({})


@app.get("/api/v1/userv2/")
@app.get("/api/v1/userv2")
def api_userv2(request: Request) -> Response:
    """登录标记。SPA 每次进 /app 都先打这一条。"""

    account = _require(request)
    if account is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(
        app_api.user_object(STATE.load(), account)))


@app.get("/api/v1/userv2/{ident}/")
@app.get("/api/v1/userv2/{ident}")
def api_userv2_detail(ident: str, request: Request) -> Response:
    account = _require(request)
    if account is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(
        app_api.user_object(STATE.load(), account)))


@app.get("/api/v1/userprofilev2/{ident}/")
@app.get("/api/v1/userprofilev2/{ident}")
def api_userprofile(ident: str, request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(app_api.profile_object(STATE.load())))


@app.get("/api/v1/nutritionprofile/")
@app.get("/api/v1/nutritionprofile")
def api_nutrition_list(request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(
        [app_api.nutrition_object(STATE.load())],
        meta={"limit": app_api.NUTRITION_LIMIT, "next": None,
              "offset": 0, "previous": None}))


@app.get("/api/v1/nutritionprofile/{ident}/")
@app.get("/api/v1/nutritionprofile/{ident}")
def api_nutrition_detail(ident: str, request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(app_api.nutrition_object(STATE.load())))


@app.get("/api/v1/mealtype/")
@app.get("/api/v1/mealtype")
def api_mealtype_list(request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    rows = [app_api.mealtype_object(i) for i in range(len(app_api.MEAL_TITLES))]
    return _api_json(app_api.envelope(
        rows, meta={"limit": app_api.MEALTYPE_LIMIT, "next": None,
                    "offset": 0, "previous": None}))


@app.get("/api/v1/mealtype/{ident}/")
@app.get("/api/v1/mealtype/{ident}")
def api_mealtype_detail(ident: str, request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    ids = app_api.mealtype_ids()
    try:
        index = ids.index(int(ident))
    except (ValueError, TypeError):
        return _api_json_404()
    return _api_json(app_api.envelope(app_api.mealtype_object(index)))


def _api_json_404() -> Response:
    return JSONResponse(
        app_api.envelope(None, success=False,
                         errors={"detail": "Not found."}),
        status_code=404,
    )


@app.get("/api/v1/calendar/")
@app.get("/api/v1/calendar")
def api_calendar(request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    try:
        limit = int(request.query_params.get("limit") or app_api.CALENDAR_LIMIT)
    except ValueError:
        limit = app_api.CALENDAR_LIMIT
    try:
        offset = int(request.query_params.get("offset") or 0)
    except ValueError:
        offset = 0
    limit = max(1, min(limit, 400))
    offset = max(0, offset)
    rows, meta = app_api.calendar_page(STATE.load(), limit, offset)
    return _api_json(app_api.envelope(rows, meta=meta))


@app.get("/api/v1/dailytemplate/")
@app.get("/api/v1/dailytemplate")
def api_dailytemplate(request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(
        app_api.daily_templates(STATE.load()),
        meta={"limit": app_api.TEMPLATE_LIMIT, "next": None,
              "offset": 0, "previous": None}))


@app.get("/api/v1/recurringfood/")
@app.get("/api/v1/recurringfood")
@app.get("/api/v1/recurringfoodcollection/")
@app.get("/api/v1/recurringfoodcollection")
def api_recurring(request: Request) -> Response:
    """实测两条都是空集合,meta 只有 limit/offset,没有 next/previous。"""

    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope([], meta={"limit": 20, "offset": 0}))


@app.get("/api/v1/generatorsettings/{ident}/")
@app.get("/api/v1/generatorsettings/{ident}")
def api_generator(ident: str, request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(app_api.generator_settings(STATE.load())))


@app.get("/api/v1/subscription/{ident}/")
@app.get("/api/v1/subscription/{ident}")
def api_subscription(ident: str, request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(app_api.subscription(STATE.load())))


@app.get("/api/v1/friendreferralstats/{ident}/")
@app.get("/api/v1/friendreferralstats/{ident}")
def api_referral(ident: str, request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(app_api.referral_stats()))


@app.get("/api/current-streak/")
@app.get("/api/current-streak")
def api_streak(request: Request) -> Response:
    if _require(request) is None:
        return _unauthenticated()
    return _api_json(app_api.envelope(app_api.current_streak()))


@app.get("/api/stripe-free-trial-availability/")
@app.get("/api/stripe-free-trial-availability")
def api_free_trial() -> Response:
    """实测:这一条匿名也答 200。"""

    return _api_json(app_api.envelope(app_api.free_trial_availability()))


@app.get("/api/get-gift-sub-pricing/")
@app.get("/api/get-gift-sub-pricing")
def api_gift_pricing() -> Response:
    return _api_json(app_api.envelope(app_api.gift_sub_pricing()))


# ------------------------------------------------------------- /payments/ 付费面
#
# bundle 走两条 /payments/ 接口,两条都在取证 meta 里留了实测读数
# (captures/2026-08-22.eatthismuch-r1/app/meta/,200 application/json):
#
#   app__upgrade                     get-subscription-pricing + create-setup-intent
#   app__help__premium-features      get-subscription-pricing
#   app__account__subscription__…    create-setup-intent
#
# 这两条此前都没实现,请求掉进 catch_all 拿到一份 HTML 404——于是
# /app/upgrade 永远到不了 networkidle(page.goto 15 秒超时),
# 页面停在 "An error has occurred."。
#
# 两条都用信封:消费方 chunks/BwAVaRnq.js 与 chunks/qBLqlIPz.js 拿的是
# gotDHXHr 的同一个解析器 S/c,它取的是信封里的 data。
#
# 取证 meta 只记 url / status / type,没记方法,所以 GET 和 POST 都答,
# 不去猜一个记录里没有的东西。支付一律 local-sandbox,不发生任何真实交易。


# ---------------------------------------------------------------------------
# 六个计算器的算子。
#
# /calculator、/tdee-calculator、/bmr-calculator、/macro-calculator、
# /protein-calculator、/calorie-deficit-calculator 提交时都发同一条 POST。
# 此前克隆没实现它,请求掉进只收 GET 的 catch_all,浏览器里六个页面
# 一律 `ServerError 405: POST /swoleprofile/calculate-macros-from-profile/`,
# 屏幕上那几个数字自始至终是页面正文里的算例,换体重也不动。
#
# 抓取阶段拿不到这条的响应体:clone.yaml 的 capture_policy.safe_methods
# 只有 [GET, HEAD]。所以形状照源站自己的 bundle 读,算术照源站自己的
# 页面正文读,出处逐条写在 backend/macro_calculator.py 里,
# 差异登记在 scope/known-differences.json。
#
# 客户端(chunks/B2hH328b.js)见到 Api-Response-Version 头就只取 .data,
# 所以这里走信封。GET 也答:源站只在表单提交时发 POST,但直接开这个 URL
# 不该掉进 HTML 404 去。


@app.post("/swoleprofile/calculate-macros-from-profile/")
@app.post("/swoleprofile/calculate-macros-from-profile")
@app.get("/swoleprofile/calculate-macros-from-profile/")
@app.get("/swoleprofile/calculate-macros-from-profile")
async def swoleprofile_calculate_macros(request: Request) -> Response:
    if request.method == "POST":
        form = await _json_or_form(request)
    else:
        form = {k: v for k, v in request.query_params.items()}
        form.pop("HTTP_BACKEND_VERSION", None)
    return _api_json(app_api.envelope(macro_calculator.calculate(form)))


@app.get("/api/get-professional-tiered-pricing/{currency}/{locale}/")
@app.get("/api/get-professional-tiered-pricing/{currency}/{locale}")
def api_professional_tiered_pricing(currency: str, locale: str) -> Response:
    """/professionals 的第二跳。缺了它整页渲染成 500 Error(实测)。

    货币与 locale 进了路径但不改响应:存档渲染里只留下 USD/en_US 这一份,
    换成别的币种去编一份「换算过的」价格表,就是拿想象覆盖取证。
    调用方自己会把 currency 拼回去(``{currency: r, ...响应}``),所以页面上
    显示的币种依旧跟着上一跳走。
    """

    return _api_json(app_api.envelope(app_api.professional_tiered_pricing()))


@app.get("/payments/get-subscription-pricing/")
@app.get("/payments/get-subscription-pricing")
@app.post("/payments/get-subscription-pricing/")
@app.post("/payments/get-subscription-pricing")
def payments_subscription_pricing() -> Response:
    return _api_json(app_api.envelope(app_api.subscription_pricing()))


@app.get("/payments/create-setup-intent/")
@app.get("/payments/create-setup-intent")
@app.post("/payments/create-setup-intent/")
@app.post("/payments/create-setup-intent")
def payments_create_setup_intent() -> Response:
    return _api_json(app_api.envelope(app_api.setup_intent()))


# ------------------------------------------------------------------ /g/ 动作层
#
# bundle 吃两层接口:/api/v1/* 是资源层,/g/* 是动作层(搜索、生成、清单)。
# 缺了动作层,/food/browse 的那次 fetch 永远不 settle,页面到不了 networkidle,
# 而验收用的正是 page.goto(wait_until="networkidle")。
#
# 三条实测出来的形状约束:
#   · 未登录 → 401,响应体是**裸 JSON 字符串** "not logged in",不是空体
#   · 没路由到的 /g/… → 404 + text/plain "404 page not found"
#   · /g/check-status/ 不套信封,直接是 {"status":"ok"}


def _g_json(payload: Any, status: int = 200) -> Response:
    return stamp_version(JSONResponse(payload, status_code=status), payload)


def _g_denied() -> Response:
    return _g_json(g_api.NOT_LOGGED_IN, 401)


def _g_missing() -> Response:
    """源站对未路由的 /g/ 路径答 text/plain 的 404(实测 GET /g/generate/day/)。
    绝不能让它掉进 catch_all 去拿那份 235KB 的 HTML 404。"""

    return PlainTextResponse("404 page not found\n", status_code=404)


@app.get("/g/check-status/")
@app.get("/g/check-status")
def g_check_status() -> Response:
    return _g_json({"status": "ok"})


@app.get("/g/food-search/")
@app.get("/g/food-search")
def g_food_search(request: Request) -> Response:
    return _g_json(g_api.food_search(request.query_params))


@app.get("/g/search-with-suggestions/")
@app.get("/g/search-with-suggestions")
def g_search_suggestions(request: Request) -> Response:
    return _g_json(g_api.search_with_suggestions(request.query_params))


@app.get("/g/meal-categories/")
@app.get("/g/meal-categories")
def g_meal_categories(request: Request) -> Response:
    if _require(request) is None:
        return _g_denied()
    return _g_json(g_api.envelope(g_api.meal_categories()))


@app.get("/g/exclusions-stats/")
@app.get("/g/exclusions-stats")
def g_exclusions_stats(request: Request) -> Response:
    if _require(request) is None:
        return _g_denied()
    # 实测:data 是个裸数字,不是对象
    return _g_json(g_api.envelope(100))


@app.get("/g/collection-exclusion-stats/")
@app.get("/g/collection-exclusion-stats")
def g_collection_exclusion_stats(request: Request) -> Response:
    if _require(request) is None:
        return _g_denied()
    if not request.query_params.get("collection_id"):
        # 实测:不带 id 时答 400 + 裸字符串
        return _g_json("Please provide a full collection id.", 400)
    return _g_json(g_api.envelope(0))


@app.get("/g/owned-groceries-suggestions/")
@app.get("/g/owned-groceries-suggestions")
def g_owned_groceries_suggestions(request: Request) -> Response:
    if _require(request) is None:
        return _g_denied()
    return _g_json(g_api.envelope(g_api.owned_groceries_suggestions()))


@app.get("/g/leftovers-preview/")
@app.get("/g/leftovers-preview")
def g_leftovers_preview(request: Request) -> Response:
    if _require(request) is None:
        return _g_denied()
    return _g_json(g_api.envelope(g_api.leftovers_preview(STATE.load())))


_G_EMPTY_LIST = (
    "food-ratings", "customfoods", "customrecipes", "user-images",
    "groceries", "linked-groceries", "match-ingredients",
)


@app.get("/g/{name}/")
@app.get("/g/{name}")
def g_empty_collection(name: str, request: Request) -> Response:
    """一批实测 ``data: []`` 的账号面集合端点。

    ``groceries`` 与 ``linked-groceries`` 在源站上对我这个账号答的是 500
    ("An error has occurred. We've been notified…")——那是源站自己的故障,
    不是契约,克隆不复刻故障,答空集合并写进 known-differences.json。
    """

    if name not in _G_EMPTY_LIST:
        # ``/g/`` 下不只有接口。``/partner-api`` 上那个 "View API docs" 按钮指向
        # ``/g/docs``(一张 Redoc 壳页),它读同源的 ``/g/openapi.yaml``。两份都在
        # static/www/g/ 下躺着,但这条 ``/g/{name}`` 兜底比 catch_all 先匹配,
        # 于是它们一直被当成"未知集合端点"答 404——首页出链闭合看不出来
        # (没有页面从首页直连过去),点进 /partner-api 才会撞上。
        served = _serve_static(f"www/g/{name}", request.url.query)
        if served.status_code == 200:
            return served
        return _g_missing()
    if _require(request) is None:
        return _g_denied()
    return _g_json(g_api.envelope([]))


@app.post("/g/generate/{action}/")
@app.post("/g/generate/{action}")
async def g_generate(action: str, request: Request) -> Response:
    """规划器的生成动作。

    bundle 读的是 ``data.results[0].meals[].foods[].food``
    (source-assets/…/chunks/Cer-cfCG.js),所以 ``results`` 里放的是 diet 对象。
    """

    # ``*-json`` 这一族在源站是**匿名可调**的:公开的 /diet-plan/* 页面就是靠它
    # 拿到示例餐单的,实测证据是那些页面里内联的响应块(匿名抓取取得)。
    # 其余动作会写账号数据,仍然要登录。
    if action.endswith("-json"):
        replay = inline_replay(f"/g/generate/{action}/", str(request.url.query))
        if replay is not None:
            return replay
    form = {}
    try:
        raw = await request.form()
        form = {k: v for k, v in raw.items()}
    except Exception:
        form = {}
    if not form:
        try:
            body = await request.json()
            if isinstance(body, dict):
                form = body
        except Exception:
            form = {}
    state = STATE.load()
    # The public homepage posts ``day-json`` without an account. When no
    # captured replay matches its query, return one deterministic archived-data
    # plan instead of falling through to the authenticated planner endpoints.
    if action == "day-json":
        date = str(form.get("date") or "")
        diet = g_api.generate_day(state, date, 0)
        return _g_json(g_api.envelope({"results": [diet]}))
    if action in ("meal-json", "foodobject-json"):
        # The public Svelte planner sends the currently displayed plan back to
        # these controls. A deterministic archived day supplies the same
        # response shapes: meals cycle through foods collections and food
        # buttons cycle through individual food objects.
        diet = g_api.generate_day(state, str(form.get("date") or ""), 0)
        meals = diet.get("meals") or []
        foods_by_meal = [
            [{**food, "units": 0} for food in (meal.get("foods") or [])]
            for meal in meals
        ]
        if action == "meal-json":
            results = [{"foods": foods} for foods in foods_by_meal]
        else:
            results = [food for foods in foods_by_meal for food in foods]
        return _g_json(g_api.envelope({"results": results}))
    if _require(request) is None:
        return _g_denied()
    if action == "day":
        date = str(form.get("date") or "")
        diet = g_api.generate_day(state, date, 0)
        return _g_json(g_api.envelope({"results": [diet]}))
    if action == "week":
        results = [
            g_api.generate_day(state, str(form.get("date") or ""), i)
            for i in range(7)
        ]
        return _g_json(g_api.envelope({"results": results}))
    if action in ("alternate-foods", "alternate-meals", "chosen-meals",
                  "collection-meals", "meal", "foodobject",
                  "week-clear-future-entries"):
        return _g_json(g_api.envelope([]))
    return _g_missing()


@app.get("/g/generate/{action}/")
@app.get("/g/generate/{action}")
def g_generate_get(action: str) -> Response:
    """实测:generate 家族只收 POST,GET 一律 404 + text/plain。"""

    return _g_missing()


@app.post("/g/update-groceries/")
@app.post("/g/update-groceries")
async def g_update_groceries(request: Request) -> Response:
    if _require(request) is None:
        return _g_denied()
    return _g_json(g_api.envelope([]))


@app.get("/g/{name}/{ident}/")
@app.get("/g/{name}/{ident}")
def g_scoped(name: str, ident: str, request: Request) -> Response:
    scoped = {
        "food-usages", "linked-foodobjects", "normalized-ingredient-usages",
        "food-object-calendar-entry", "food-object-saved-plan-item",
        "all-images",
    }
    if name not in scoped:
        return _g_missing()
    if _require(request) is None:
        return _g_denied()
    return _g_json(g_api.envelope([]))


# ------------------------------------------------------------------ 食物列表

_SLUG_ID = re.compile(r"^(?P<slug>.*?)-(?P<id>\d+)$")


def _browse_key(order_by: str | None, page: int) -> str:
    parts = []
    if order_by:
        parts.append(("order_by", order_by))
    if page > 1:
        parts.append(("page", str(page)))
    query = urlencode(parts)
    return "/food/browse" + (f"?{query}" if query else "")


@app.get("/food/browse")
def food_browse(request: Request) -> Response:
    order_by = request.query_params.get("order_by") or None
    raw_page = request.query_params.get("page") or "1"
    try:
        page = int(raw_page)
    except ValueError:
        page = 1
    if page < 1:
        page = 1

    # 源站对不认识的 order_by 是**静默丢掉参数**,照常答 200 默认页
    # (实测 ?order_by=bogus / ?order_by=protein / ?order_by=cysteine 三条,
    # 都拿到 <title>Browse Foods - Eat This Much</title>,242KB 的默认页)。
    # 早先这里答 404,比源站更严格——那是错的。
    if order_by and store.facet_ids() and order_by not in store.facet_ids():
        order_by = None

    # 源站自己渲染过的那几页,交付的就是它自己的标记
    record = store.page_record(_browse_key(order_by, page))
    if record is not None:
        return html_response(store.page_bytes(record), record.get("status", 200))

    limit = store.index().get("browse", {}).get("archived_page_limit", 2)
    if page > limit:
        # 第三页起收边:说清楚边界在哪,并且不留死链
        return html_response(_fence_document(
            f"Page {page} is past the edge of this clone",
            "The source database runs to hundreds of thousands of foods. This "
            f"offline clone carries the first {limit} pages of every list in full, "
            "with every item on them reachable. Beyond that the archive stops "
            "here rather than pretending.",
            _browse_key(order_by, limit),
        ), 200)

    rows, total = store.browse_slice(order_by or "default", page)
    if not rows and order_by:
        # 这个分面在离线子集里一份带值的食物都没有:回落到默认序,
        # 而不是给一张空页——源站在这里是有内容的。写进 known-differences。
        rows, total = store.browse_slice("default", page)
    if not rows:
        return html_response(_fence_document(
            "Nothing on this page",
            "This sort order carries no items in the offline archive.",
            _browse_key(None, 1),
        ), 200)
    return html_response(_browse_document(order_by, page, rows, total))


# 每类列表前两页整页存档,第三页起收边(FAST-CLONE §5)。/food/browse 把这个
# 数字记在 index.json 的 browse.archived_page_limit 里;博客列表走同一个口径。
BLOG_PAGE_LIMIT = 2
_BLOG_PAGE = re.compile(r"^/blog/(.+?)/page/(\d+)/?$")


def _fence_document(
    title: str, body: str, back: str, back_label: str = "Back to the food database"
) -> bytes:
    return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
<title>{html.escape(title)} — Eat This Much</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="/static/clone/boundary.css"></head>
<body class="offline-boundary"><main>
<h1>{html.escape(title)}</h1>
<p>{body}</p>
<p><a href="{html.escape(back)}">{html.escape(back_label)}</a> ·
<a href="/">Eat This Much home</a></p>
</main></body></html>""".encode("utf-8")


def _browse_document(
    order_by: str | None, page: int, rows: list[dict[str, Any]], total: int
) -> bytes:
    facet_label = order_by or "default"
    items = "\n".join(
        '<li><a href="{path}">{name}</a>{cal}</li>'.format(
            path=html.escape(r["path"]),
            name=html.escape(str(r.get("name") or r["id"])),
            cal=(
                f' <span class="cal">{html.escape(str(r["calories"]))} cal</span>'
                if r.get("calories") is not None
                else ""
            ),
        )
        for r in rows
    )
    prev_link = (
        f'<a href="{html.escape(_browse_key(order_by, page - 1))}">Previous</a>'
        if page > 1
        else ""
    )
    next_link = f'<a href="{html.escape(_browse_key(order_by, page + 1))}">Next</a>'
    return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
<title>Food database — sorted by {html.escape(facet_label)} — Eat This Much</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="/static/clone/boundary.css"></head>
<body class="offline-boundary"><main>
<h1>Food database</h1>
<p class="target">Sorted by <code>{html.escape(facet_label)}</code> ·
page {page} · {total} foods in this offline archive</p>
<ul class="food-list">
{items}
</ul>
<nav class="pager">{prev_link} {next_link}</nav>
<p><a href="/food/browse">Reset sort</a> · <a href="/">Eat This Much home</a></p>
</main></body></html>""".encode("utf-8")


# ------------------------------------------------------------------ 页面层

def _stored_page(path: str) -> Response | None:
    record = store.page_record(path)
    if record is None:
        return None
    return html_response(store.page_bytes(record), record.get("status", 200))


def _canonical_food_path(path: str) -> str | None:
    """按 id 查规范地址;查不到就交回 None,让后面的 404 逻辑接手。"""

    tail = path[len("/calories/"):]
    match = _SLUG_ID.match(tail)
    if match:
        food_id = match.group("id")
        by_page = store.calories_path_by_id(food_id)
        if by_page:
            return by_page
        summary = store.food_summary(food_id)
        if summary:
            return summary["path"]
        # 地址尾号未必是这条食物自己的 id。源站 API 给的 canonical_url 里
        # 有 14 条尾号对不上:食物 2094(Red potato,slug `red-potato,2094`)
        # 的 canonical_url 是 `/calories/russet-potatoes-2092`,2092 这个 id
        # 在库里根本不存在。同类还有 1301 -> /calories/apples-1300、
        # 15 -> /calories/cottage-cheese-16 等。源站对这些地址答 200
        # (那本来就是它自己声明的规范地址),只按尾号查就会全判 404。
        # 所以按 id 查空之后,再拿整条 tail 当 slug 查一次。
        summary = store.food_by_slug(tail)
        return summary["path"] if summary else None
    if tail.isdigit():
        return store.calories_path_by_id(tail)
    summary = store.food_by_slug(tail)
    return summary["path"] if summary else None


@app.get("/")
def home() -> Response:
    record = store.page_record("/")
    if record is None:
        return _bare_404()
    body = store.page_bytes(record)
    runtime = b'<script src="/static/clone/home-actions.js?v=2" defer></script>'
    if runtime not in body:
        body = body.replace(b"</body>", runtime + b"</body>", 1)
    return html_response(body, record.get("status", 200))


@app.get("/{full_path:path}")
def catch_all(full_path: str, request: Request) -> Response:
    raw = "/" + full_path
    path = store.normalize(raw)

    # 先试 /app 那棵。两棵的文件名不会撞(哈希各自独立),所以取不到就回落
    # 到前台那棵是安全的——回落只可能命中同名文件,而同名文件不存在。
    app_immutable = _APP_IMMUTABLE.match(path)
    if app_immutable:
        response = _serve_static(f"app/_app/immutable/{app_immutable.group('rest')}")
        if response.status_code == 200:
            return response
    immutable = _IMMUTABLE.search(path)
    if immutable:
        rest = immutable.group("rest")
        response = _serve_static(f"_app/immutable/{rest}")
        if response.status_code == 200:
            return response
        return _serve_static(f"app/_app/immutable/{rest}")

    redirect = store.redirect_for(path)
    if redirect:
        return RedirectResponse(redirect["to"], status_code=redirect.get("status", 301))

    # 尾斜杠的规范形态是**逐页**的,不是逐站的,所以照着构建期从抓取证据里
    # 留下来的 record["canonical"] 走,而不是按前缀猜。实测四条:
    #
    #   /about/                     → 308 → /about                      (去斜杠)
    #   /diet-plan/keto/            → 308 → /diet-plan/keto             (去斜杠)
    #   /sample-email               → 301 → /sample-email/              (加斜杠)
    #   /diet-plan/atkins-ketogenic → 301 → /diet-plan/atkins-ketogenic/(加斜杠)
    #
    # 加斜杠是 301(Django 的 APPEND_SLASH),去斜杠是 308,两个方向的状态码不同。
    canonical = (store.page_record(path) or {}).get("canonical")
    if canonical:
        if raw != canonical:
            return RedirectResponse(canonical, status_code=301)
    elif raw != path and raw.endswith("/"):
        # 只对确实存在的目标发 308,否则一个不存在的路径会被 308 到另一个
        # 不存在的路径,把 404 藏起来。
        if store.page_record(path) or store.alias_target(path):
            return RedirectResponse(path, status_code=308)

    alias = store.alias_target(path)
    if alias:
        response = _stored_page(alias)
        if response is not None:
            return response

    response = _stored_page(path)
    if response is not None:
        return response

    # /calories/<slug>-<id>:数字是权威的,slug 是装饰性的。
    #
    # 但实测下来源站**不重定向**:/calories/zzz-banana-oatmeal-33511 直接答 200
    # (74024B,规范地址是 74018B),/calories/33511 也答 200。
    # 我原本按 goodreads 的经验假定它会 301 回规范地址——测下来是反的。
    # 克隆照实测来:按 id 找到那一页,原样交出去,不发重定向。
    if path.startswith("/calories/"):
        canonical = _canonical_food_path(path)
        if canonical:
            response = _stored_page(canonical)
            if response is not None:
                return response
            # 认得这条食物、但没有存档整页 —— 交客户端渲染的那张壳。
            #
            # 这一支覆盖的量比看上去大:食物 2150 条,存档整页的只有 40 条。
            # 剩下 2110 条在 SPA 里点进去都好好的(客户端路由自己跑 load),
            # 但**直接 goto 全是 404**——随机抽 30 条直接 GET,30 条全 404,
            # 交出去的是 "Server error - Eat This Much" 那张 404 壳。
            # 冷启动、开新标签页、按刷新,这 2110 页全是死的。
            #
            # 壳里是源站自己的 bundle 加两参启动(tools/build_clone.py:
            # install_food_shell 里记了为什么可以去掉水合负载),数据来自这边
            # 已经实测出形状的 /api/v1/food/<id>/ 那几条。所以这不是拿一张占位
            # 页糊住 404:渲染出来的就是这条食物本身的页面。
            #
            # 状态码 200 而不是 404:源站对这些地址答的就是 200。
            shell = store.shell("food-shell")
            if shell is not None:
                return html_response(shell, 200)

    # 博客是源站自己的第二个第一方源,它的静态资源挂在 /blog/ 前缀下
    if path.startswith("/blog/"):
        blog_asset = _serve_static(
            "blog-assets" + path[len("/blog"):], request.url.query
        )
        if blog_asset.status_code == 200:
            return blog_asset

    # 博客列表的分页收边。
    #
    # 源站的分页链接是真的:/blog/category/meal-planning/ 底部直接链到 page/2 3 4,
    # /blog/latest-articles/ 链到 page/2 3 7。前两页整页存档(范围内),
    # 第三页起收边——但**收边不等于 404**。答 404 就是在克隆里留死链,
    # 而这些链接在存档下来的标记里明明白白存在,点下去必须落到某处。
    # 和 /food/browse 用同一套 _fence_document,边界只有一种表达方式。
    m = _BLOG_PAGE.match(path)
    if m:
        base, page = f"/blog/{m.group(1)}", int(m.group(2))
        if store.page_record(base) is not None and page > BLOG_PAGE_LIMIT:
            return html_response(_fence_document(
                f"Page {page} is past the edge of this clone",
                "This offline clone carries the first "
                f"{BLOG_PAGE_LIMIT} pages of every blog list in full, with every "
                "post on them reachable. Beyond that the archive stops here "
                "rather than pretending.",
                base + "/",
                "Back to this blog list",
            ), 200)

    # 页面里指向源站根路径的散装静态文件(favicon、static_files/… )
    www_asset = _serve_static(f"www{path}", request.url.query)
    if www_asset.status_code == 200:
        return www_asset

    if path == "/app" or path.startswith("/app/"):
        # /app 是纯客户端渲染:实测 /app/login 与 /app/<不存在的路径> 拿到的
        # 是**同一份 14586 字节的壳**,路由、登录判断、404 文案全在浏览器里跑。
        # 所以克隆对 /app 下的每一条路径都交这一份壳、都答 200——
        # 这不是「兜底」,这就是源站服务端的完整行为。
        shell = store.shell("app-shell") or store.shell("app-not-found")
        if shell is not None:
            return html_response(shell, 200)

    not_found = store.shell("not-found")
    if not_found is not None:
        return html_response(not_found, 404)
    return _bare_404()


# ------------------------------------------------------------------ 进程入口

def main() -> None:
    """引擎起候选站的第一顺位是直接执行本文件,端口从 ``PORT`` 读。"""

    import uvicorn

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


if __name__ == "__main__":
    main()