File size: 115,552 Bytes
187ef74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Source-grounded Lowe's offline clone frontend shell.

The visual states and local image assets are derived from the Playwright
evidence pack in materials/lowes/source-current and source-assets.
"""

from __future__ import annotations

import json
from html import escape
from pathlib import Path
from typing import Any, Mapping, Sequence
from urllib.parse import parse_qs, quote_plus, urlencode

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

import commerce
import landing
from backend import accounts as account_backend
from backend import store as site_store
from ui.artwork import VIEWS, product_svg


SITE_ID = "lowes"
DISPLAY_NAME = "Lowe's"
ROOT = Path(__file__).resolve().parent
MATERIAL_ROOT = ROOT.parent
STATIC_ROOT = ROOT / "static"
ASSET_ROOT = MATERIAL_ROOT / "source-assets" / "playwright-20260821"
MULTIPAGE_ASSET_ROOT = STATIC_ROOT / "assets" / "playwright-multipage-20260821"

app = FastAPI(title=DISPLAY_NAME)
app.mount("/static", StaticFiles(directory=STATIC_ROOT), name="static")
app.mount("/source-assets", StaticFiles(directory=ASSET_ROOT), name="source-assets")
app.mount(
    "/multipage-assets",
    StaticFiles(directory=MULTIPAGE_ASSET_ROOT),
    name="multipage-assets",
)


PRODUCTS = [
    {
        "backend_id": 1001,
        "slug": "frigidaire-professional-french-door-refrigerator",
        "brand": "Frigidaire Professional",
        "title": "21.4-cu ft Counter-Depth French Door Refrigerator with Dual Ice Maker",
        "price": 2999.00,
        "was": 3999.00,
        "rating": "4.6",
        "reviews": 812,
        "image": "005-753ec6507385a84d.avif",
        "category": "Appliances",
    },
    {
        "backend_id": 1002,
        "slug": "frigidaire-professional-convection-range",
        "brand": "Frigidaire Professional",
        "title": "30-in 6-Burner Convection Range with Air Fry",
        "price": 1699.00,
        "was": 2999.00,
        "rating": "4.7",
        "reviews": 441,
        "image": "005-289c2ff5d6cb25ae.avif",
        "category": "Appliances",
    },
    {
        "backend_id": 1005,
        "slug": "frigidaire-gallery-french-door-refrigerator",
        "brand": "Frigidaire Gallery",
        "title": "French Door Refrigerator with Custom-Flex Temp Drawer",
        "price": 1999.00,
        "was": 2799.00,
        "rating": "4.5",
        "reviews": 668,
        "image": "005-dfaf191432b00001.avif",
        "category": "Appliances",
    },
    {
        "backend_id": 1006,
        "slug": "frigidaire-energy-star-refrigerator",
        "brand": "Frigidaire",
        "title": "ENERGY STAR French Door Refrigerator with Ice Maker",
        "price": 1599.00,
        "was": 2399.00,
        "rating": "4.4",
        "reviews": 503,
        "image": "009-82acfde0786311c2.avif",
        "category": "Appliances",
    },
    {
        "backend_id": 1003,
        "slug": "frigidaire-dishwasher",
        "brand": "Frigidaire",
        "title": "Top Control 24-in Built-In Dishwasher",
        "price": 499.00,
        "was": 649.00,
        "rating": "4.3",
        "reviews": 1159,
        "image": "011-c6564a958b49fc75.avif",
        "category": "Appliances",
    },
    {
        "backend_id": 1004,
        "slug": "electrolux-front-load-laundry-pair",
        "brand": "Electrolux",
        "title": "Front-Load Washer and Electric Dryer Laundry Pair",
        "price": 1599.00,
        "was": 2199.00,
        "rating": "4.6",
        "reviews": 924,
        "image": "011-baeb3a51751a722c.avif",
        "category": "Appliances",
    },
]

BEST_SELLER_DEPARTMENTS = [
    ("Accessible Home", "6af8471da47c294fdc6c.webp"),
    ("Animal & Pet Care", "41a8e365a49148ee412e.webp"),
    ("Appliances", "ba41fa97d7383500c4b6.webp"),
    ("Automotive", "6c36e70a664e0848d90d.avif"),
    ("Bathroom", "dda585b6cae61ddd07ea.webp"),
    ("Building Supplies", "dd7f3b1d215945e9f098.avif"),
    ("Cleaning Supplies", "d2732d99a54a164ff9fe.webp"),
    ("Clothing & Work Apparel", "eed3b304716ed0e28843.webp"),
    ("Dining & Entertaining", "1c049e30d66740306d57.avif"),
    ("Drinks & Snacks", "a1a0b97fcf109d04fd4a.webp"),
    ("Electrical", "1e30e7d63a3040a0bf02.webp"),
    ("Flooring", "3f72678a92b47aca55df.webp"),
]

STATES = {
    "A": ["Alabama", "Alaska", "Arizona", "Arkansas"],
    "C": ["California", "Colorado", "Connecticut"],
    "D": ["Delaware", "District Of Columbia"],
    "F": ["Florida"],
    "G": ["Georgia"],
    "H": ["Hawaii"],
    "I": ["Idaho", "Illinois", "Indiana", "Iowa"],
    "K": ["Kansas", "Kentucky"],
    "L": ["Louisiana"],
    "M": ["Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana"],
    "N": ["Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota"],
    "O": ["Ohio", "Oklahoma", "Oregon"],
    "P": ["Pennsylvania"],
    "R": ["Rhode Island"],
    "S": ["South Carolina", "South Dakota"],
    "T": ["Tennessee", "Texas"],
    "U": ["Utah"],
    "V": ["Vermont", "Virginia"],
    "W": ["Washington", "West Virginia", "Wisconsin", "Wyoming"],
}

# Routes that predate the source-path inventory and are still reachable from
# bookmarks. Each one now names the source-compatible path it belongs to, so the
# clone has a single canonical URL per surface instead of two parallel ones.
LEGACY_REDIRECTS = {
    "credit": "/l/Credit",
    "pro": "/l/Pro",
    "ai-assist": "/ai",
    "installations": "/l/install",
    "ideas": "/diy-projects-and-ideas",
    "maintenance": "/l/shop/home-maintenance",
    "terms": "/l/about/terms-and-conditions-of-use",
    "privacy": "/l/about/privacy-and-security-statement",
    "info": "/l/help",
}

# The Playwright probe recorded Access Denied for most source paths, so pages
# reconstructed from a URL alone say so in one consistent sentence rather than
# implying a verified reproduction.
SOURCE_RESTRICTED_NOTE = landing.SOURCE_RESTRICTED_NOTE

SYNTHETIC_COMMERCE_NOTE = (
    "Prices, ratings, reviews, specifications and artwork on this page come "
    "from this clone's frozen synthetic catalog, not from Lowe's. The source "
    "page answered Access Denied to the recorded Playwright session, so no "
    "source layout or product data was observed for it."
)

EMPTY_CART: dict[str, Any] = {
    "items": [],
    "count": 0,
    "units": 0,
    "subtotal_cents": 0,
    "savings_cents": 0,
    "needs_delivery": False,
    "all_free_delivery": True,
}


def money(value: float) -> str:
    return f"${value:,.2f}"


def cents(value: int) -> str:
    return f"${site_store.money(int(value))}"


def product_by_slug(slug: str) -> dict[str, object] | None:
    return next((product for product in PRODUCTS if product["slug"] == slug), None)


CAPTURED_BY_BACKEND_ID = {int(item["backend_id"]): item for item in PRODUCTS}


def captured_product(product_id: int) -> dict[str, object] | None:
    """The captured-asset display record for a backend id, when there is one."""

    return CAPTURED_BY_BACKEND_ID.get(int(product_id))


def catalog_art(product_id: int, view: str = "front") -> str:
    """Locally generated artwork URL for any catalog product."""

    return f"/img/p/{int(product_id)}/{view}.svg"


# ---------------------------------------------------------------------------
# shared page furniture
# ---------------------------------------------------------------------------


def breadcrumb_bar(trail: Sequence[tuple[str, str | None]]) -> str:
    parts = []
    for label, href in trail:
        if href:
            parts.append(f'<a href="{escape(href, quote=True)}">{escape(label)}</a>')
        else:
            parts.append(f"<span>{escape(label)}</span>")
    return (
        '<nav class="breadcrumbs" aria-label="Breadcrumb">'
        + " / ".join(parts)
        + "</nav>"
    )


def sandbox_notice(text: str) -> str:
    return f'<p class="notice notice--sandbox">{escape(text)}</p>'


def action_row(actions: Sequence[tuple[str, str]]) -> str:
    if not actions:
        return ""
    links = "".join(
        f'<a href="{escape(href, quote=True)}">{escape(label)}</a>'
        for label, href in actions
    )
    return f'<div class="category-links">{links}</div>'


def highlight_grid(highlights: Sequence[tuple[str, str]]) -> str:
    if not highlights:
        return ""
    cards = "".join(
        f"<article class=\"service-card\"><h3>{escape(title)}</h3><p>{escape(copy)}</p></article>"
        for title, copy in highlights
    )
    return f'<div class="service-grid">{cards}</div>'


def fact_table(facts: Sequence[tuple[str, str]]) -> str:
    if not facts:
        return ""
    rows = "".join(
        f'<tr><th scope="row">{escape(term)}</th><td>{escape(value)}</td></tr>'
        for term, value in facts
    )
    return f'<table class="spec-table"><tbody>{rows}</tbody></table>'


def rating_line(product: Mapping[str, Any]) -> str:
    filled = int(float(product["rating"]) + 0.5)
    stars = "★" * filled + "☆" * (5 - filled)
    return (
        f'<div class="rating"><span class="rating__stars">{stars}</span> '
        f'{float(product["rating"]):.1f} ({int(product["review_count"]):,})</div>'
    )


def price_line(product: Mapping[str, Any]) -> str:
    price = int(product["price_cents"])
    was = product.get("was_cents")
    extra = ""
    if was:
        extra = (
            f'<span class="price__was">Was {cents(int(was))}</span>'
            f'<span class="price__save">Save {cents(int(was) - price)}</span>'
        )
    return f'<div class="price"><span class="price__amount">{cents(price)}</span>{extra}</div>'


def catalog_card(product: Mapping[str, Any]) -> str:
    """A product tile for the synthetic catalog, using locally drawn artwork."""

    flag = ""
    if product.get("badge"):
        flag = (
            '<span class="product-card__flag"></span>'
            f'<span class="product-card__flag-text">{escape(str(product["badge"]))}</span>'
        )
    url = escape(str(product["url"]), quote=True)
    return f"""
    <article class="product-card">{flag}
      <a class="product-card__media" href="{url}"><img src="{catalog_art(int(product['id']))}" width="320" height="320" loading="lazy" alt="{escape(str(product['title']), quote=True)}"></a>
      <div class="product-card__body"><span class="product-card__brand">{escape(str(product['brand']))}</span>
        <a class="product-card__title" href="{url}">{escape(str(product['title']))}</a>
        {rating_line(product)}{price_line(product)}
        <form action="/cart/add" method="post"><input type="hidden" name="product_id" value="{int(product['id'])}"><button class="button button--primary button--block" type="submit">Add to Cart</button></form>
      </div>
    </article>"""


def catalog_grid(products: Sequence[Mapping[str, Any]]) -> str:
    if not products:
        return (
            '<div class="empty-state"><h2>No matching items</h2>'
            "<p>Clear a filter or widen the price range to see this clone's "
            "catalog again.</p></div>"
        )
    return '<div class="card-grid">' + "".join(catalog_card(row) for row in products) + "</div>"


def auth_services():
    return site_store.services()[1]


def site_backend():
    return site_store.services()[0]


# The session cookie is not named here: ``backend/runtime.json`` derives it from
# the site id and the vendored runtime returns the mandated Host-only options
# (``__Host-`` prefix, Secure, HttpOnly, SameSite, Path=/, never a Domain).
def session_cookie_spec() -> dict[str, Any]:
    return dict(site_backend().session_cookie)


def session_cookie_name() -> str:
    return str(session_cookie_spec()["name"])


def read_session_token(request: Request) -> str | None:
    return request.cookies.get(session_cookie_name())


def set_session_cookie(response: Response, token: str) -> Response:
    options = session_cookie_spec()
    name = str(options.pop("name"))
    response.set_cookie(name, token, **options)
    return response


def clear_session_cookie(response: Response) -> Response:
    options = session_cookie_spec()
    name = str(options.pop("name"))
    response.delete_cookie(name, path=str(options.get("path", "/")))
    return response


def existing_owner(request: Request) -> str | None:
    token = read_session_token(request)
    if not token:
        return None
    try:
        return auth_services().session_owner_digest(token)
    except Exception:
        return None


def ensured_owner(request: Request) -> tuple[str, str]:
    token, _session = auth_services().ensure_session(read_session_token(request))
    return token, auth_services().session_owner_digest(token)


def current_session(request: Request) -> dict[str, Any] | None:
    try:
        return auth_services().resolve_session(read_session_token(request))
    except Exception:
        return None


def current_account(request: Request) -> dict[str, Any] | None:
    return account_backend.public_account(current_session(request))


def current_account_id(request: Request) -> str | None:
    session = current_session(request)
    if not session or not session.get("authenticated"):
        return None
    return str(session["account"]["account_id"])


def cart_units_for_token(token: str) -> int:
    """Cart size for an explicit token, used after a session rotation.

    The request cookie still holds the revoked token on the response that
    performs the rotation, so the shell has to be counted from the new one.
    """

    try:
        owner = auth_services().session_owner_digest(token)
    except Exception:
        return 0
    return int(site_store.cart_units(owner))


def cart_for(request: Request) -> tuple[str | None, dict[str, Any]]:
    """The session's cart exactly as the backend holds it.

    The shell reads this on every render, so it has to cover the whole catalog
    rather than only the six captured-asset products: a line added from a
    ``/pd/`` page must count in the masthead and appear on ``/cart``.
    """

    owner = existing_owner(request)
    if owner is None:
        return None, dict(EMPTY_CART)
    return owner, site_store.get_cart(owner)


def icon(name: str) -> str:
    icons = {
        "search": "⌕",
        "store": "▣",
        "account": "◉",
        "cart": "🛒",
        "ai": "✦",
        "close": "×",
        "menu": "☰",
    }
    return f'<span aria-hidden="true" class="ui-icon">{icons.get(name, "•")}</span>'


def account_utility(account: dict[str, Any] | None) -> str:
    """The masthead account control, truthful about the current session."""

    if not account:
        label = "Sign In"
    else:
        first = str(account.get("display_name", "")).split(" ")[0] or "Account"
        label = f"Hi, {first[:14]}"
    return (
        f'<button class="utility" type="button" data-account-open>{icon("account")}'
        f"<span>{escape(label)}</span></button>"
    )


CATNAV_ITEMS = (
    ("▦ Shop All", "/c/Departments", (("Appliances", "/c/Appliances"), ("Bathroom", "/c/Bathroom"), ("Building Supplies", "/c/Building-supplies"), ("Doors & Windows", "/c/Windows-doors"))),
    ("♙ Installations", "/l/install", (("Installation Services", "/l/install"), ("Store Services", "/l/about/store-services"), ("Bathroom Installation", "/c/Bathroom"), ("Appliance Installation", "/c/Appliances"))),
    ("◇ Deals", "/l/savings", (("Daily Deals", "/l/savings/daily-deals"), ("Coupons", "/l/savings/coupons"), ("All Deals", "/pl/Deals/1611079983848"), ("Rebate Center", "/l/help/rebate-center"))),
    ("♧ Design & Ideas", "/diy-projects-and-ideas", (("DIY Projects & Ideas", "/diy-projects-and-ideas"), ("Workshops", "/diy-projects-and-ideas/workshops"), ("Fresh Inspiration", "/l/fresh-projects-and-inspiration"), ("Paint Ideas", "/c/Paint"))),
    ("$99 Maintenance", "/l/shop/home-maintenance", (("Home Maintenance", "/l/shop/home-maintenance"), ("Seasonal Projects", "/diy-projects-and-ideas"), ("Services", "/l/about/store-services"))),
    ("Appliances", "/c/Appliances", (("Refrigerators", "/c/Refrigerators"), ("Ranges", "/c/Ranges"), ("Dishwashers", "/c/Dishwashers"), ("Washers & Dryers", "/c/Washers-dryers"))),
    ("Bathroom", "/c/Bathroom", (("Bathroom Vanities", "/c/Bathroom-vanities"), ("Toilets", "/c/Toilets"), ("Showers", "/c/Showers"), ("Bathroom Faucets", "/c/Bathroom-faucets"))),
    ("Building Supplies", "/c/Building-supplies", (("Lumber", "/c/Lumber"), ("Decking", "/c/Decking"), ("Concrete & Masonry", "/c/Concrete-masonry"), ("Roofing", "/c/Roofing"), ("Insulation", "/c/Insulation"), ("Drywall", "/c/Drywall"))),
    ("Doors & Windows", "/c/Windows-doors", (("Exterior Doors", "/c/Exterior-doors"), ("Interior Doors", "/c/Interior-doors"), ("Windows", "/c/Windows"), ("Garage Doors", "/c/Garage-doors"))),
)


def catnav() -> str:
    items = []
    for index, (label, href, children) in enumerate(CATNAV_ITEMS):
        strong = " catnav__link--strong" if index < 4 else ""
        badge = ' <span class="badge-new">New</span>' if label == "$99 Maintenance" else ""
        child_links = "".join(
            f'<a href="{child_href}">{escape(child_label)}</a>'
            for child_label, child_href in children
        )
        items.append(
            '<li class="catnav__item"><details data-catnav-menu>'
            f'<summary class="catnav__link{strong}">{escape(label)}{badge}</summary>'
            f'<div class="catnav__menu"><strong>{escape(label.lstrip("▦♙◇♧ "))}</strong>'
            f'{child_links}<a class="catnav__all" href="{href}">View all →</a></div>'
            "</details></li>"
        )
    return '<nav class="catnav" aria-label="Primary"><ul class="shell catnav__list">' + "".join(items) + "</ul></nav>"


def header(
    cart_count: int = 0, query: str = "", account: dict[str, Any] | None = None
) -> str:
    q = escape(query, quote=True)
    return f"""
    <div class="promo-strip"><div class="shell">
      <span class="promo-strip__deal">Shop this week’s top deals now. &gt;</span>
      <ul class="promo-strip__links"><li><a href="/l/Credit">Lowe's Credit Center</a></li><li><a href="/mylowes/orders">Order Status</a></li><li><a href="/weekly-ad">Weekly Ad</a></li><li><a href="/l/Pro">Lowe's PRO</a></li></ul>
    </div></div>
    <header class="masthead"><div class="shell masthead__row">
      <button class="header-menu" type="button" aria-label="Open menu">{icon('menu')}</button>
      <a class="brand-logo lowes-wordmark" href="/" aria-label="Lowe's home"><span>LOWE'S</span></a>
      <div class="locator"><button class="locator__button" type="button">{icon('store')} <strong>Find a Store Near Me</strong>⌄</button></div>
      <div class="searchbar">
        <form class="searchbar__form" action="/search" method="get" data-suggest-form>
          {icon('search')}<input class="searchbar__input" name="q" value="{q}" placeholder="What can we help you find?" autocomplete="off" data-suggest-input aria-expanded="false">
          <button class="icon-button" type="submit" aria-label="Search">⌕</button>
        </form><div class="suggestions" data-suggest-panel hidden></div>
      </div>
      <nav class="masthead__utilities" aria-label="Utilities">
        <a class="utility utility-ai" href="/ai">{icon('ai')}<span>AI Assist</span></a>
        {account_utility(account)}
        <a class="utility utility--cart" href="/cart">{icon('cart')}<span>Cart</span>{f'<b class="utility__count">{cart_count}</b>' if cart_count else ''}</a>
      </nav>
    </div></header>
    {catnav()}<div class="mobile-locator"><button type="button">{icon('store')} Find a Store Near Me⌄</button></div>
    """


DRAWER_BENEFITS = (
    '<ul class="drawer__benefits"><li>▣ <a href="/orders">Order Status</a></li>'
    '<li>⚒ <a href="/l/install">Projects &amp; Installations</a></li>'
    '<li>♡ <a href="/lists">Lists</a></li>'
    '<li>♟ <a href="/l/about/honor-our-military">Military Discount</a></li>'
    '<li>✱ <a href="/l/about/mylowes-rewards">MyLowe\'s Rewards Benefits</a></li></ul>'
)


def drawer(opened: bool = False, account: dict[str, Any] | None = None) -> str:
    hidden = "hidden" if not opened else ""
    state = "open" if opened else "closed"
    if account:
        title = "Your Account"
        contents = f"""
      <p class="drawer__intro">Signed in as <strong>{escape(str(account.get('contact_display', '')))}</strong> in this offline clone. Nothing here exists at Lowe's.</p>
      <form action="/account/signout" method="post">
        <button class="button button--primary button--block" type="submit">Sign Out</button>
      </form>
      <p class="drawer__legal">Signing out revokes this local session on the server before the cookie is deleted.</p>
      {DRAWER_BENEFITS}"""
    else:
        title = "Sign In or Create Account"
        contents = f"""
      <p class="drawer__intro">Enter your <strong>email or phone number</strong> to get started. We'll check if you have an account.</p>
      <form action="/account/start" method="post">
        <label class="field"><span class="visually-hidden">Email or Phone Number</span><input class="field__control" name="identifier" placeholder="Email or Phone Number" required></label>
        <label class="checkbox"><input type="checkbox" checked name="remember"> Remember me on this device ⓘ</label>
        <button class="button button--primary button--block" type="submit">Continue</button>
      </form>
      <p class="drawer__legal"><a href="/account/reset">Forgot your password?</a></p>
      <p class="drawer__legal">By signing in, you're agreeing to our <a href="/l/about/terms-and-conditions-of-use">Terms of Use</a>, <a href="/l/about/privacy-and-security-statement">Privacy Statement</a>, and local clone terms.</p>
      {DRAWER_BENEFITS}"""
    return f"""
    <div class="drawer-overlay" data-account-overlay {hidden}></div>
    <aside class="drawer" data-account-drawer="{state}" {hidden} aria-label="{escape(title, quote=True)}">
      <div class="drawer__head"><h2 class="drawer__title">{escape(title)}</h2><button class="icon-button" data-account-close aria-label="Close">{icon('close')}</button></div>{contents}
    </aside>
    """


# Every footer destination is a source-compatible path this clone serves, so no
# footer control leaves the origin or lands on a shared filler page.
FOOTER_GROUPS: dict[str, tuple[tuple[str, str], ...]] = {
    "Customer Service": (
        ("Customer Service", "/l/help"),
        ("Order Status", "/mylowes/orders/checkorderstatus"),
        ("Returns Policy", "/l/help/returns-policy"),
        ("Shipping & Delivery", "/l/help/shipping-delivery"),
        ("Special Orders", "/l/help/special-orders"),
    ),
    "Resources": (
        ("Weekly Ad", "/weekly-ad"),
        ("Store Directory", "/Lowes-Stores"),
        ("DIY Projects & Ideas", "/diy-projects-and-ideas"),
        ("Lowe's Gift Cards", "/l/shop/gift-cards"),
        ("Subscriptions", "/subscriptions"),
    ),
    "About Lowe's": (
        ("How We Help", "/l/about/how-we-help"),
        ("MyLowe's Rewards", "/l/about/mylowes-rewards"),
        ("Lowe's Marketplace", "/l/about/lowes-marketplace"),
        ("Suppliers", "/l/about/suppliers"),
        ("Privacy & Security", "/l/about/privacy-and-security-statement"),
        ("Terms & Conditions of Use", "/l/about/terms-and-conditions-of-use"),
    ),
    "For Pros": (
        ("Lowe's for Pros", "/l/Pro"),
        ("Pro Benefits", "/l/Pro/pro-benefits"),
        ("Resources for Pros", "/l/Pro/resources-for-pros"),
        ("Pro Credit", "/l/Credit"),
        ("Tool Rental", "/l/shop/rental"),
    ),
}


def footer() -> str:
    columns = "".join(
        f"<section><h3>{escape(title)}</h3><ul>"
        + "".join(
            f'<li><a href="{escape(href, quote=True)}">{escape(label)}</a></li>'
            for label, href in items
        )
        + "</ul></section>"
        for title, items in FOOTER_GROUPS.items()
    )
    return f'<footer class="site-footer"><div class="shell"><div class="footer-grid">{columns}</div><p class="footer-note">Offline WebsiteBench clone for evaluation. No real Lowe\'s account, payment, fulfillment, message, or order is created.</p></div></footer>'


def product_card(product: dict[str, object]) -> str:
    price = float(product["price"])
    was = float(product["was"])
    return f"""
    <article class="product-card">
      <span class="product-card__flag"></span><span class="product-card__flag-text">SALE</span>
      <a class="product-card__media" href="/product/{product['slug']}"><img src="/static/assets/playwright-20260821/{product['image']}" alt="{escape(str(product['title']), quote=True)}"></a>
      <div class="product-card__body"><span class="product-card__brand">{escape(str(product['brand']))}</span>
        <a class="product-card__title" href="/product/{product['slug']}">{escape(str(product['title']))}</a>
        <div class="rating"><span class="rating__stars">★★★★★</span> {product['rating']} ({product['reviews']})</div>
        <div class="price"><span class="price__amount">{money(price)}</span><span class="price__was">Was {money(was)}</span><span class="price__save">Save {money(was-price)}</span></div>
        <form action="/cart/add" method="post"><input type="hidden" name="slug" value="{product['slug']}"><button class="button button--primary button--block" type="submit">Add to Cart</button></form>
      </div>
    </article>"""


def document(title: str, body: str, cart_count: int = 0, query: str = "", account_open: bool = False, account: dict[str, Any] | None = None) -> str:
    return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{escape(title)}</title><link rel="icon" href="/static/site/img/lowes-logo.svg" type="image/svg+xml"><link rel="stylesheet" href="/static/site/lowes.css"><link rel="stylesheet" href="/static/site/overrides.css"></head><body>{header(cart_count, query, account)}{body}{footer()}{drawer(account_open, account)}<script src="/static/site/lowes.js" defer></script></body></html>"""


def render(
    request: Request,
    title: str,
    body: str,
    *,
    query: str = "",
    account_open: bool = False,
    status_code: int = 200,
) -> HTMLResponse:
    """Render one page with the session-derived cart count and account state."""

    _owner, cart = cart_for(request)
    return HTMLResponse(
        document(
            title,
            body,
            int(cart["units"]),
            query,
            account_open,
            current_account(request),
        ),
        status_code=status_code,
    )


@app.get("/healthz")
def healthz() -> dict[str, object]:
    return {"ok": True, "site_id": SITE_ID}


@app.get("/", response_class=HTMLResponse)
def home(request: Request, account: str = "") -> HTMLResponse:
    cards = "".join(product_card(product) for product in PRODUCTS[:4])
    body = f"""
    <main><section class="section shell recommendation"><div class="section__head"><h2 class="section__title">Recommended searches</h2></div><div class="chip-row">
      <a class="chip" href="/search?q=cordless+drill">Cordless drills</a><a class="chip" href="/search?q=refrigerator">Refrigerators</a><a class="chip" href="/search?q=patio">Patio furniture</a><a class="chip" href="/search?q=paint">Interior paint</a><a class="chip" href="/search?q=grill">Grills</a>
    </div></section>
    <section class="shell hero-wrap"><div class="hero"><h1 class="hero__title">Electrolux End-of-Summer Sale</h1><div class="hero__brands">ELECTROLUX · FRIGIDAIRE · FRIGIDAIRE GALLERY · FRIGIDAIRE PROFESSIONAL</div><div class="playwright-hero"><img src="/static/assets/playwright-20260821/004-a219863c39ce7ce3.webp" alt="Save up to $300 when you bundle select Frigidaire major appliances"></div><div class="members"><strong>myLowe's Rewards — Members Get More</strong><span>FREE Delivery and Haul Away</span><span>FREE Basic Installation and Installation Parts</span><span>2-Year Lowe's Protection Plan</span></div></div></section>
    <section class="section shell"><div class="section__head"><h2 class="section__title">Featured appliance deals</h2><a class="section__more" href="/search?q=appliances">Shop all deals</a></div><div class="card-grid">{cards}</div></section>
    <section class="section shell"><div class="section__head"><h2 class="section__title">Services for every project</h2></div><div class="service-grid"><article class="service-card"><h3>Installation Services</h3><p>Get help from independent installers in this local demo flow.</p><a href="/installations">Explore installations</a></article><article class="service-card"><h3>Find a Store</h3><p>Select a synthetic store for pickup and local availability.</p><a href="/stores">Choose a store</a></article><article class="service-card"><h3>Lowe's for Pros</h3><p>Tools and savings represented as offline-only sample data.</p><a href="/pro">Explore Pro services</a></article></div></section>
    </main>"""
    return render(request, "Lowe’s Home Improvement", body, account_open=account == "open")


@app.get("/best-sellers", response_class=HTMLResponse)
def best_sellers(request: Request) -> HTMLResponse:
    sidebar = "".join(f'<li><a href="/c/{quote_plus(label.lower().replace(" & ", "-").replace(" ", "-"))}">{escape(label)}</a></li>' for label, _image in BEST_SELLER_DEPARTMENTS)
    cards = "".join(
        f'<a class="department-card" href="/c/{quote_plus(label.lower().replace(" & ", "-").replace(" ", "-"))}"><span class="department-card__image"><img src="/multipage-assets/{image}" alt=""></span><strong>{escape(label)}</strong></a>'
        for label, image in BEST_SELLER_DEPARTMENTS
    )
    body = f"""<main class="best-sellers-page">
      <section class="best-sellers-hero"><h1>Lowe’s Best Sellers</h1></section>
      <button class="mobile-departments" type="button">Departments <span>›</span></button>
      <div class="shell best-sellers-layout"><aside class="department-sidebar"><h2>All Departments</h2><ul>{sidebar}</ul></aside><section class="department-grid">{cards}<a class="button button--outline all-departments" href="/search">See All Departments</a></section></div>
    </main>"""
    return render(request, "Lowe's Best Sellers - The Most Popular Items on Lowes.com", body)


@app.get("/diy-projects-and-ideas/workshops", response_class=HTMLResponse)
def workshops(request: Request) -> HTMLResponse:
    body = """<main class="shell campaign-page">
      <div class="breadcrumbs"><a href="/">Home</a> / Workshops</div>
      <h1>Welcome to MyLowe’s Rewards™ Kids Club!</h1>
      <img class="campaign-wide" src="/multipage-assets/6413d48a98ac64be263b.webp" alt="Kids Club — your next family adventure starts here">
      <a href="/?account=open"><img class="campaign-wide campaign-strip" src="/multipage-assets/c1a3471e45fbf690307d.avif" alt="Create your Kids Profile and sign up for workshops"></a>
      <img class="campaign-wide" src="/multipage-assets/ebc23e062899cdd23b5a.avif" alt="Build, laugh and learn at a free workshop">
      <section class="campaign-copy"><h2>Free workshops and family fun</h2><p>MyLowe’s Rewards members can create a kids profile, collect digital badges and register for hands-on family workshops in this local demo.</p><a class="button button--primary" href="/?account=open">Get Started</a></section>
    </main>"""
    return render(request, "Lowe’s Kids Club: Free Workshops & Family Fun", body)


@app.get("/Lowes-Stores", response_class=HTMLResponse)
@app.get("/stores", response_class=HTMLResponse)
def stores_directory(request: Request) -> HTMLResponse:
    groups = "".join(
        f'<section class="state-group"><h2>{letter}</h2>{"".join(f"<a href=/stores/{quote_plus(state.lower().replace(chr(32), chr(45)))}>{escape(state)}</a>" for state in states)}</section>'
        for letter, states in STATES.items()
    )
    body = f"""<main class="shell stores-page"><div class="breadcrumbs"><a href="/stores">Find a Store</a> / Store Directory</div><h1>State Directory</h1><p>Lowe's Stores in the U.S.</p><div class="states-grid">{groups}</div></main>"""
    return render(request, "Lowe's Store Directory - Find Locations by State and City", body)


@app.get("/stores/{state}", response_class=HTMLResponse)
def stores_in_state(request: Request, state: str) -> HTMLResponse:
    label = state.replace("-", " ").title()
    body = f'<main class="shell section"><div class="breadcrumbs"><a href="/Lowes-Stores">Store Directory</a> / {escape(label)}</div><h1>Lowe\'s Stores in {escape(label)}</h1><div class="store-results"><article class="service-card"><h2>{escape(label)} Lowe\'s</h2><p>Select a location in the header to see local pickup availability.</p><button class="button button--primary" type="button">Set as My Store</button></article></div></main>'
    return render(request, f"Lowe's Stores in {label}", body)


@app.get("/mylowes/orders", response_class=HTMLResponse)
def order_search(request: Request, result: str = "") -> HTMLResponse:
    result_box = '<div class="notice notice--sandbox">No matching local order was found. This form never contacts Lowe\'s.</div>' if result else ""
    body = f"""<main class="order-search-page"><div class="shell"><div class="breadcrumbs"><a href="/">Home</a> / Orders Search</div><section class="order-search-card"><h1>Check Order Status</h1><div class="order-tabs"><button class="active" type="button">Online Orders</button><button type="button">Store Purchases</button><button type="button">Projects</button></div><form action="/mylowes/orders" method="get"><label class="field"><span class="visually-hidden">Email address</span><input class="field__control" type="email" name="email" placeholder="✉  Enter email address" required><small>Please enter the email address used to place the order</small></label><label class="field"><span class="visually-hidden">Order Number</span><input class="field__control" name="order_number" placeholder="▧  Enter Order Number" required><small>Found in your Order confirmation email</small></label><input type="hidden" name="result" value="not-found"><button class="button button--primary button--block">Check Order Status</button></form>{result_box}<p class="order-account-copy"><a href="/?account=open">Sign up</a> for a free MyLowe's account to track your orders and enjoy all the benefits.</p><p>Already have a MyLowe's account? <a href="/?account=open">Sign In</a></p></section></div></main>"""
    return render(request, "Check Order Status", body)


@app.get("/subscriptions", response_class=HTMLResponse)
def subscriptions(request: Request) -> HTMLResponse:
    categories = [
        ("Air Filters", "b1b525b77407e16c4857.avif"),
        ("Cleaning Supplies", "f3a5af534697d6b76954.webp"),
        ("Hardware", "7679add5dce57126b778.webp"),
        ("Lawn Care", "dec89f8f5b922b47de43.webp"),
    ]
    tiles = "".join(f'<a class="subscription-tile" href="/search?q={quote_plus(label)}"><img src="/multipage-assets/{image}" alt=""><strong>{escape(label)}</strong></a>' for label, image in categories)
    body = f"""<main class="subscriptions-page"><section class="subscriptions-hero"><img src="/multipage-assets/1c329ae2e5024a0fc51d.png" alt="Woman changing an air filter"><div class="subscriptions-panel"><h1><span>SUBSCRIPTIONS</span><br>MADE SIMPLE</h1><ul><li>Free Standard Shipping</li><li>5% Off Select Items</li><li>Automatic Repeat Deliveries</li><li>Cancel Anytime</li></ul><a class="button button--primary button--block" href="#how-it-works">Learn More</a><a href="/terms">Terms &amp; Conditions</a></div></section><section id="how-it-works" class="section shell"><h2 class="center-title">How does it work?</h2><div class="subscription-steps"><article><b>1</b><h3>Find eligible products</h3><p>Shop items available for repeat delivery.</p></article><article><b>2</b><h3>Choose your schedule</h3><p>Select a delivery frequency that works for you.</p></article><article><b>3</b><h3>Save automatically</h3><p>Manage or cancel your local demo subscription anytime.</p></article></div><h2 class="center-title">Popular subscription categories</h2><div class="subscription-grid">{tiles}</div></section></main>"""
    return render(request, "Subscriptions | Lowe's", body)


@app.get("/c/{category_slug}", response_class=HTMLResponse)
def category_page(request: Request, category_slug: str) -> HTMLResponse:
    label = category_slug.replace("-", " ").title()
    cards = "".join(product_card(product) for product in PRODUCTS)
    child_map = {
        "appliances": ("Refrigerators", "Ranges", "Dishwashers", "Washers-dryers"),
        "bathroom": ("Bathroom-vanities", "Toilets", "Showers", "Bathroom-faucets"),
        "building-supplies": ("Lumber", "Decking", "Concrete-masonry", "Roofing", "Insulation", "Drywall"),
        "windows-doors": ("Exterior-doors", "Interior-doors", "Windows", "Garage-doors"),
    }
    children = child_map.get(category_slug.lower(), ())
    category_links = "".join(
        f'<a href="/c/{child}"><span class="category-link__art" aria-hidden="true">{escape(child[0])}</span>{escape(child.replace("-", " ").title())}</a>'
        for child in children
    )
    if not category_links:
        category_links = f'<a href="/best-sellers">Best Sellers</a><a href="/search?q={quote_plus(label)}">Shop All {escape(label)}</a><a href="/subscriptions">Subscriptions</a>'
    body = f'<main class="shell section category-page"><div class="breadcrumbs"><a href="/">Home</a> / {escape(label)}</div><h1>{escape(label)}</h1><div class="category-links">{category_links}</div><section class="section"><div class="section__head"><h2 class="section__title">Featured {escape(label)}</h2></div><div class="card-grid">{cards}</div></section></main>'
    return render(request, f"Shop {label} at Lowes.com", body)


@app.get("/api/suggest")
def suggest(q: str = "") -> JSONResponse:
    needle = q.strip().lower()
    labels = ["cordless drill", "refrigerator", "refrigerator water filter", "Frigidaire appliances", "dishwasher", "range", "washer and dryer"]
    matched = [label for label in labels if needle in label.lower()][:6]
    products = [{"label": p["title"], "href": f"/product/{p['slug']}"} for p in PRODUCTS if needle in str(p["title"]).lower()][:3]
    return JSONResponse({"groups": [{"label": "Search suggestions", "items": [{"label": label, "href": f"/search?q={quote_plus(label)}"} for label in matched]}, {"label": "Products", "items": products}]})


@app.get("/search", response_class=HTMLResponse)
def search(request: Request, q: str = "") -> HTMLResponse:
    needle = q.strip().lower()
    matches = PRODUCTS if not needle or needle in {"deals", "appliances"} else [p for p in PRODUCTS if needle in json.dumps(p).lower()]
    cards = "".join(product_card(product) for product in matches)
    body = f'<main class="shell section"><div class="breadcrumbs"><a href="/">Home</a> / Search</div><div class="results-head"><div><h1 class="page-title">{escape(q) if q else "Shop All"}</h1><span class="results-head__count">{len(matches)} results</span></div><select class="field__control sort-select" aria-label="Sort"><option>Sort by: Relevance</option><option>Price: Low to High</option><option>Top Rated</option></select></div>{f"<div class=card-grid>{cards}</div>" if cards else "<div class=empty-state><h2>No exact results</h2><p>Try appliances, refrigerator, dishwasher, or range.</p></div>"}</main>'
    return render(request, f"{q or 'Shop All'} | Lowe's", body, query=q)


@app.get("/product/{slug}", response_class=HTMLResponse)
def product(request: Request, slug: str) -> HTMLResponse:
    product = product_by_slug(slug)
    if not product:
        return render(request, "Product not found", '<main class="shell section empty-state"><h1>Product not found</h1><a href="/search">Continue shopping</a></main>', status_code=404)
    body = f"""<main class="shell section"><div class="breadcrumbs"><a href="/">Home</a> / <a href="/search?q=appliances">Appliances</a> / {escape(str(product['brand']))}</div><div class="pdp"><div class="pdp__thumbs"><button class="pdp__thumb"><img src="/static/assets/playwright-20260821/{product['image']}" alt=""></button></div><div class="pdp__stage"><img src="/static/assets/playwright-20260821/{product['image']}" alt="{escape(str(product['title']), quote=True)}"></div><section class="pdp__buybox"><span class="product-card__brand">{escape(str(product['brand']))}</span><h1 class="pdp__title">{escape(str(product['title']))}</h1><div class="rating"><span class="rating__stars">★★★★★</span> {product['rating']} ({product['reviews']})</div><div class="price"><span class="price__amount">{money(float(product['price']))}</span><span class="price__was">Was {money(float(product['was']))}</span></div><div class="fulfillment"><h2>How do you want to get your item?</h2><label class="fulfillment-choice"><input type="radio" checked name="fulfillment"> Pickup — Select a store</label><label class="fulfillment-choice"><input type="radio" name="fulfillment"> Delivery — Available</label></div><form action="/cart/add" method="post"><input type="hidden" name="slug" value="{product['slug']}"><button class="button button--primary button--block" type="submit">Add to Cart</button></form><p class="notice notice--sandbox">Local demo only. No real inventory, fulfillment, or charge.</p></section></div><section class="section"><h2>Product details</h2><table class="spec-table"><tr><th>Brand</th><td>{escape(str(product['brand']))}</td></tr><tr><th>Category</th><td>{escape(str(product['category']))}</td></tr><tr><th>Model</th><td>WB-{str(product['slug'])[:12].upper()}</td></tr></table></section></main>"""
    return render(request, f"{product['title']} | Lowe's", body)


def resolve_cart_products(values: Mapping[str, list[str]]) -> list[int]:
    """Backend product ids for an add-to-cart post.

    ``slug`` is the captured-asset form used by the home, search and
    ``/product/`` tiles; ``product_id`` is the catalog form used by every
    ``/pd/``, ``/pl/``, ``/collections/`` and ``/configure/`` control, and a
    package page posts it once per suite member.
    """

    ids = [
        int(raw.strip())
        for raw in values.get("product_id", [])
        if raw.strip().isdigit()
    ]
    if ids:
        return ids
    captured = product_by_slug(values.get("slug", [""])[0])
    return [int(captured["backend_id"])] if captured else []


def resolve_cart_product(values: Mapping[str, list[str]]) -> int | None:
    ids = resolve_cart_products(values)
    return ids[0] if ids else None


def local_next(values: Mapping[str, list[str]], fallback: str = "/cart") -> str:
    """A redirect target restricted to this origin's own absolute paths."""

    target = values.get("next", [""])[0]
    if target.startswith("/") and not target.startswith("//"):
        return target
    return fallback


@app.post("/cart/add")
async def add_to_cart(request: Request) -> RedirectResponse:
    values = parse_qs((await request.body()).decode("utf-8", "replace"))
    token, owner = ensured_owner(request)
    raw_quantity = values.get("quantity", ["1"])[0]
    quantity = int(raw_quantity) if raw_quantity.isdigit() else 1
    requested = values.get("fulfillment", ["pickup"])[0]
    fulfillment = requested if requested in site_store.FULFILLMENTS else "pickup"
    for product_id in resolve_cart_products(values):
        try:
            site_store.add_to_cart(
                owner,
                product_id=product_id,
                quantity=quantity,
                fulfillment=fulfillment,
            )
        except site_store.CheckoutError:
            # A pickup-ineligible item is the only expected rejection here; the
            # delivery line is still a real add rather than a silent no-op.
            site_store.add_to_cart(
                owner,
                product_id=product_id,
                quantity=quantity,
                fulfillment="delivery",
            )
    return set_session_cookie(
        RedirectResponse(local_next(values), status_code=303), token
    )


@app.post("/cart/update")
async def update_cart(request: Request) -> RedirectResponse:
    values = parse_qs((await request.body()).decode("utf-8", "replace"))
    action = values.get("action", [""])[0]
    token, owner = ensured_owner(request)
    backend_cart = site_store.get_cart(owner)

    raw_item = values.get("item_id", [""])[0].strip()
    if raw_item.isdigit():
        item = next(
            (row for row in backend_cart["items"] if int(row["item_id"]) == int(raw_item)),
            None,
        )
    else:
        product_id = resolve_cart_product(values)
        item = next(
            (
                row
                for row in backend_cart["items"]
                if product_id is not None and int(row["product_id"]) == product_id
            ),
            None,
        )
    if item:
        quantity = int(item["quantity"])
        if action == "remove":
            site_store.remove_cart_item(owner, item_id=int(item["item_id"]))
        elif action == "minus":
            site_store.update_cart_item(
                owner, item_id=int(item["item_id"]), quantity=quantity - 1
            )
        elif action == "plus":
            site_store.update_cart_item(
                owner, item_id=int(item["item_id"]), quantity=quantity + 1
            )
    return set_session_cookie(RedirectResponse("/cart", status_code=303), token)


def cart_line(item: Mapping[str, Any]) -> str:
    """One cart row, linking back to whichever page owns the item's display."""

    product_id = int(item["product_id"])
    captured = captured_product(product_id)
    if captured:
        href = f"/product/{captured['slug']}"
        art = f"/static/assets/playwright-20260821/{captured['image']}"
    else:
        href = str(item["url"])
        art = catalog_art(product_id)
    fulfillment = (
        "Store pickup" if item["fulfillment"] == "pickup" else "Delivery"
    )
    return (
        '<article class="cart-line">'
        f'<a class="cart-line__media" href="{escape(href, quote=True)}">'
        f'<img src="{art}" alt=""></a><div>'
        f'<span class="product-card__brand">{escape(str(item["brand"]))}</span>'
        f'<a class="product-card__title" href="{escape(href, quote=True)}">{escape(str(item["title"]))}</a>'
        f"<p>{fulfillment} in this local demo.</p>"
        '<form class="cart-line__actions" action="/cart/update" method="post">'
        f'<input type="hidden" name="item_id" value="{int(item["item_id"])}">'
        '<button name="action" value="minus">−</button>'
        f'<strong>{int(item["quantity"])}</strong>'
        '<button name="action" value="plus">+</button>'
        '<button class="link-button" name="action" value="remove">Remove</button>'
        "</form></div>"
        f'<strong>{cents(int(item["line_total_cents"]))}</strong></article>'
    )


@app.get("/cart", response_class=HTMLResponse)
def cart_page(request: Request) -> HTMLResponse:
    _owner, cart = cart_for(request)
    if not cart["items"]:
        body = '<main class="shell section empty-state"><h1>Your cart is empty</h1><p>Find everything you need for your next project.</p><a class="button button--primary" href="/search">Start shopping</a></main>'
        return render(request, "Cart | Lowe's", body)
    lines = "".join(cart_line(item) for item in cart["items"])
    savings = int(cart["savings_cents"])
    savings_row = (
        f'<div class="summary__row"><span>Savings</span><strong>-{cents(savings)}</strong></div>'
        if savings
        else ""
    )
    body = (
        '<main class="shell section">'
        f'<h1 class="page-title">Cart ({int(cart["units"])} items)</h1>'
        f'<div class="cart-layout"><section>{lines}</section>'
        '<aside class="summary"><h2>Order Summary</h2>'
        f'<div class="summary__row"><span>Subtotal</span><strong>{cents(int(cart["subtotal_cents"]))}</strong></div>'
        f"{savings_row}"
        '<div class="summary__row"><span>Estimated tax</span><span>Calculated at checkout</span></div>'
        f'<div class="summary__row summary__row--total"><span>Estimated total</span><strong>{cents(int(cart["subtotal_cents"]))}</strong></div>'
        '<a class="button button--primary button--block" href="/checkout">Checkout</a>'
        '<p class="notice notice--sandbox">All payments are local sandbox simulations.</p>'
        "</aside></div></main>"
    )
    return render(request, "Cart | Lowe's", body)


@app.get("/checkout", response_class=HTMLResponse)
def checkout(request: Request) -> HTMLResponse:
    owner = existing_owner(request)
    backend_cart = site_store.get_cart(owner) if owner else {"items": [], "subtotal_cents": 0, "savings_cents": 0, "all_free_delivery": True}
    totals = site_store.price_cart(backend_cart, fulfillment="pickup", state="NC")
    scenarios = site_store.payment_scenarios()
    options = "".join(f'<option value="{escape(item["id"], quote=True)}">{escape(item["display_label"])} — {escape(item["outcome"])}</option>' for item in scenarios)
    button_disabled = "disabled" if not backend_cart["items"] else ""
    body = f'<main class="shell section"><div class="breadcrumbs"><a href="/cart">Cart</a> / Checkout</div><h1 class="page-title">Checkout</h1><form class="checkout-layout" action="/checkout/place" method="post"><section><div class="notice notice--sandbox"><strong>WebsiteBench local sandbox</strong><br>No real Lowe\'s order or payment will be created.</div><h2>Contact information</h2><div class="card-grid card-grid--two"><label class="field"><span class="field__label">First name</span><input class="field__control" name="first_name" required value="Site"></label><label class="field"><span class="field__label">Last name</span><input class="field__control" name="last_name" required value="Tester"></label></div><label class="field"><span class="field__label">Email</span><input class="field__control" type="email" name="email" required value="annotator@example.test"></label><h2>Fulfillment</h2><label class="fulfillment-choice"><input type="radio" checked name="fulfillment" value="pickup"> Store pickup</label><input type="hidden" name="store_id" value="{escape(site_store.stores()[0]["id"], quote=True)}"><h2>Sandbox payment outcome</h2><label class="field"><span class="field__label">Scenario</span><select class="field__control" name="scenario_id">{options}</select></label></section><aside class="summary"><h2>Order summary</h2><div class="summary__row"><span>Subtotal</span><strong>${site_store.money(totals["subtotal_cents"])}</strong></div><div class="summary__row"><span>Estimated tax</span><strong>${site_store.money(totals["tax_cents"])}</strong></div><div class="summary__row summary__row--total"><span>Total</span><strong>${site_store.money(totals["total_cents"])}</strong></div><button class="button button--primary button--block" {button_disabled}>Place sandbox order</button><p>No card number, CVV, expiry, bank, or wallet information is accepted.</p></aside></form></main>'
    return render(request, "Checkout | Lowe's", body)


async def form_values(request: Request) -> dict[str, str]:
    body = (await request.body()).decode("utf-8", "replace")
    return {key: entries[0] for key, entries in parse_qs(body).items()}


@app.post("/account/start")
async def account_start(request: Request) -> HTMLResponse:
    values = parse_qs((await request.body()).decode("utf-8", "replace"))
    identifier_raw = values.get("identifier", [""])[0]
    token, _owner = ensured_owner(request)
    try:
        identified = account_backend.identify(auth_services(), identifier_raw)
    except Exception as exc:
        _field, message = account_backend.friendly_error(exc)
        return set_session_cookie(
            render(request, "Account | Lowe's", f'<main class="shell section"><div class="notice notice--error"><h1>Check your entry</h1><p>{escape(message)}</p><a class="button button--primary" href="/?account=open">Try again</a></div></main>', account_open=True),
            token,
        )
    identity = identified["identity"]
    if identified["account_exists"]:
        body = f'<main class="shell section"><h1>Welcome back</h1><form action="/account/signin" method="post"><input type="hidden" name="identifier" value="{escape(identifier_raw, quote=True)}"><label class="field"><span class="field__label">Password</span><input class="field__control" type="password" name="password" required></label><button class="button button--primary">Sign In</button></form><p><a href="/account/reset?identifier={quote_plus(identifier_raw)}">Forgot your password?</a></p></main>'
    else:
        phone_note = '<p class="notice notice--sandbox">Phone registration uses reserved test numbers only: 555-0100 through 555-0199, such as (213) 555-0142.</p>' if identity["kind"] == "phone" else ''
        body = f'<main class="shell section"><h1>Create your local account</h1>{phone_note}<p>Verification will go only to the local WebsiteBench outbox for <strong>{escape(identity["display"])}</strong>.</p><form action="/account/create" method="post"><input type="hidden" name="identifier" value="{escape(identifier_raw, quote=True)}"><div class="card-grid card-grid--two"><label class="field"><span class="field__label">First name</span><input class="field__control" name="first_name" required></label><label class="field"><span class="field__label">Last name</span><input class="field__control" name="last_name" required></label></div><label class="field"><span class="field__label">Password</span><input class="field__control" type="password" name="password" minlength="8" required></label><button class="button button--primary">Send local verification code</button></form></main>'
    return set_session_cookie(render(request, "Account | Lowe's", body), token)


@app.post("/account/create")
async def account_create(request: Request) -> HTMLResponse:
    values = parse_qs((await request.body()).decode("utf-8", "replace"))
    token, _owner = ensured_owner(request)
    try:
        result = account_backend.start_registration(auth_services(), token, identifier=values.get("identifier", [""])[0], first_name=values.get("first_name", [""])[0], last_name=values.get("last_name", [""])[0], password=values.get("password", [""])[0])
        code = account_backend.sandbox_code(auth_services(), token)
        help_box = f'<div class="notice notice--sandbox"><strong>Local sandbox code:</strong> <code>{escape(code or "unavailable")}</code><br>This value comes from the repository-approved local outbox and was not sent externally.</div>'
        body = f'<main class="shell section"><h1>Verify your contact</h1><p>Enter the local code for <strong>{escape(result["identity"]["display"])}</strong>.</p>{help_box}<form action="/account/verify" method="post"><label class="field"><span class="field__label">Verification code</span><input class="field__control" name="code" inputmode="numeric" required></label><button class="button button--primary">Verify and create account</button></form></main>'
    except Exception as exc:
        _field, message = account_backend.friendly_error(exc)
        body = f'<main class="shell section"><div class="notice notice--error"><h1>Could not start registration</h1><p>{escape(message)}</p><a class="button button--primary" href="/">Start again</a></div></main>'
    return set_session_cookie(render(request, "Verify account | Lowe's", body), token)


@app.post("/account/verify")
async def account_verify(request: Request) -> HTMLResponse:
    values = parse_qs((await request.body()).decode("utf-8", "replace"))
    token, _owner = ensured_owner(request)
    try:
        completed = account_backend.verify_and_complete(auth_services(), token, values.get("code", [""])[0])
        new_token = str(completed["session_token"])
        name = escape(str(completed["account"]["display_name"]))
        body = f'<main class="shell section"><div class="order-banner"><h1>Account created</h1><p>Welcome, {name}. Your account and contact verification exist only in this offline clone.</p><a class="button button--primary" href="/">Continue shopping</a></div></main>'
        # The account page must reflect the rotated session, not the anonymous
        # one the request arrived with, so the shell is rendered from the new
        # token rather than from ``request.cookies``.
        account = account_backend.public_account(auth_services().resolve_session(new_token))
        page = HTMLResponse(
            document(
                "Account created | Lowe's",
                body,
                cart_units_for_token(new_token),
                account=account,
            )
        )
        return set_session_cookie(page, new_token)
    except Exception as exc:
        _field, message = account_backend.friendly_error(exc)
        body = f'<main class="shell section"><div class="notice notice--error"><h1>Verification failed</h1><p>{escape(message)}</p><a href="/">Start again</a></div></main>'
        return set_session_cookie(
            render(request, "Verification failed | Lowe's", body), token
        )


@app.post("/account/signin")
async def account_signin(request: Request) -> HTMLResponse:
    values = parse_qs((await request.body()).decode("utf-8", "replace"))
    token, _owner = ensured_owner(request)
    try:
        signed = account_backend.sign_in(auth_services(), token, identifier=values.get("identifier", [""])[0], password=values.get("password", [""])[0])
        return set_session_cookie(
            RedirectResponse("/", status_code=303), str(signed["session_token"])
        )
    except Exception as exc:
        _field, message = account_backend.friendly_error(exc)
        return set_session_cookie(
            render(request, "Sign in | Lowe's", f'<main class="shell section"><div class="notice notice--error"><h1>Sign in failed</h1><p>{escape(message)}</p><a href="/">Try again</a></div></main>'),
            token,
        )


@app.post("/account/signout")
async def account_signout(request: Request) -> RedirectResponse:
    """Revoke the server-side session first, then drop the cookie.

    The anonymous cart is deliberately not migrated: the revoked session's
    owner digest keeps its rows, and the next request starts a fresh anonymous
    session, which is what a real sign-out looks like from the browser.
    """

    account_backend.sign_out(auth_services(), read_session_token(request))
    return clear_session_cookie(RedirectResponse("/", status_code=303))


# ---------------------------------------------------------------------------
# password recovery
# ---------------------------------------------------------------------------

RESET_STEP_INTRO = (
    "<p>Enter the email or reserved test phone number on your local account. "
    "This clone answers the same way whether or not an account exists.</p>"
)


def reset_request_form(identifier: str = "", notice: str = "") -> str:
    return (
        '<main class="shell section"><h1>Reset your password</h1>'
        f"{notice}{RESET_STEP_INTRO}"
        '<form action="/account/reset/start" method="post">'
        '<label class="field"><span class="field__label">Email or Phone Number</span>'
        '<input class="field__control" name="identifier" required '
        f'value="{escape(identifier, quote=True)}"></label>'
        '<button class="button button--primary">Send local reset code</button>'
        "</form></main>"
    )


@app.get("/account/reset", response_class=HTMLResponse)
def account_reset(request: Request, identifier: str = "") -> HTMLResponse:
    return render(request, "Reset your password | Lowe's", reset_request_form(identifier))


@app.post("/account/reset/start")
async def account_reset_start(request: Request) -> HTMLResponse:
    values = await form_values(request)
    identifier_raw = values.get("identifier", "")
    token, _owner = ensured_owner(request)
    try:
        result = account_backend.start_password_reset(
            auth_services(), token, identifier=identifier_raw
        )
    except Exception as exc:
        _field, message = account_backend.friendly_error(exc)
        notice = f'<div class="notice notice--error"><p>{escape(message)}</p></div>'
        return set_session_cookie(
            render(
                request,
                "Reset your password | Lowe's",
                reset_request_form(identifier_raw, notice),
                status_code=400,
            ),
            token,
        )
    # The store's public message is identical for a known and an unknown
    # identity. The sandbox block below is the one place they differ, and only
    # while the local development helper is on: with
    # ``LOWES_LOCAL_SANDBOX_HELP=0`` ``sandbox_code`` returns None for both and
    # the two responses become byte-identical.
    code = account_backend.sandbox_code(
        auth_services(), token, purpose=account_backend.PURPOSE_PASSWORD_RESET
    )
    help_box = (
        '<div class="notice notice--sandbox"><strong>Local sandbox code:</strong> '
        f'<code>{escape(code)}</code><br>This value comes from the local outbox '
        "and was not sent externally.</div>"
        if code
        else '<div class="notice notice--sandbox">No local sandbox code is '
        "available to display. Nothing was sent to any external service.</div>"
    )
    body = (
        '<main class="shell section"><h1>Check your local outbox</h1>'
        f'<p>{escape(str(result["flow"]["message"]))}</p>{help_box}'
        '<form action="/account/reset/verify" method="post">'
        '<label class="field"><span class="field__label">Verification code</span>'
        '<input class="field__control" name="code" inputmode="numeric" required>'
        "</label><button class=\"button button--primary\">Verify code</button>"
        "</form></main>"
    )
    return set_session_cookie(
        render(request, "Reset your password | Lowe's", body), token
    )


@app.post("/account/reset/verify")
async def account_reset_verify(request: Request) -> HTMLResponse:
    values = await form_values(request)
    token, _owner = ensured_owner(request)
    try:
        account_backend.verify_password_reset(
            auth_services(), token, values.get("code", "")
        )
    except Exception as exc:
        _field, message = account_backend.friendly_error(exc)
        body = (
            '<main class="shell section"><div class="notice notice--error">'
            f"<h1>Verification failed</h1><p>{escape(message)}</p>"
            '<a class="button button--primary" href="/account/reset">Start again</a>'
            "</div></main>"
        )
        return set_session_cookie(
            render(request, "Reset your password | Lowe's", body, status_code=400),
            token,
        )
    body = (
        '<main class="shell section"><h1>Choose a new password</h1>'
        '<form action="/account/reset/complete" method="post">'
        '<label class="field"><span class="field__label">New password</span>'
        '<input class="field__control" type="password" name="password" '
        'minlength="8" required></label>'
        '<button class="button button--primary">Save new password</button>'
        "</form></main>"
    )
    return set_session_cookie(
        render(request, "Reset your password | Lowe's", body), token
    )


@app.post("/account/reset/complete")
async def account_reset_complete(request: Request) -> HTMLResponse:
    values = await form_values(request)
    token, _owner = ensured_owner(request)
    try:
        new_token = account_backend.complete_password_reset(
            auth_services(), token, new_password=values.get("password", "")
        )
    except Exception as exc:
        _field, message = account_backend.friendly_error(exc)
        body = (
            '<main class="shell section"><div class="notice notice--error">'
            f"<h1>Password was not changed</h1><p>{escape(message)}</p>"
            '<a class="button button--primary" href="/account/reset">Start again</a>'
            "</div></main>"
        )
        return set_session_cookie(
            render(request, "Reset your password | Lowe's", body, status_code=400),
            token,
        )
    body = (
        '<main class="shell section"><div class="order-banner"><h1>Password updated</h1>'
        "<p>Every earlier local session for this account was revoked and you are "
        "signed in on this device only.</p>"
        '<a class="button button--primary" href="/">Continue shopping</a></div></main>'
    )
    account = account_backend.public_account(auth_services().resolve_session(new_token))
    page = HTMLResponse(
        document(
            "Password updated | Lowe's",
            body,
            cart_units_for_token(new_token),
            account=account,
        )
    )
    return set_session_cookie(page, new_token)


@app.post("/checkout/place")
async def checkout_place(request: Request) -> HTMLResponse:
    values = await form_values(request)
    token, owner = ensured_owner(request)
    cart = site_store.get_cart(owner)
    try:
        checkout_data = site_store.validate_checkout(values, cart=cart, scenario_ids=[item["id"] for item in site_store.payment_scenarios()])
        # Binding the order to the account as well as to the session digest is
        # what keeps it visible after a sign-out/sign-in rotates the session.
        result = site_store.place_order(
            owner, checkout_data, account_id=current_account_id(request)
        )
        if result["placed"]:
            order = result["order"]
            body = f'<main class="shell section"><div class="order-banner"><span class="tag tag--approved">Approved local simulation</span><h1>Thanks, your offline order is recorded</h1><p>Order <strong>{escape(order["order_number"])}</strong> totals <strong>${site_store.money(order["total_cents"])}</strong>.</p><p>A simulated confirmation was queued in the local outbox; nothing was sent to Lowe\'s or an external provider.</p><a class="button button--primary" href="/orders">View orders</a></div></main>'
        else:
            payment = result["payment"]
            body = f'<main class="shell section"><div class="notice notice--error"><span class="tag tag--declined">{escape(payment["status"])}</span><h1>Sandbox payment was not approved</h1><p>Your cart is unchanged. Choose the approved scenario to continue.</p><a class="button button--primary" href="/checkout">Try another scenario</a></div></main>'
        response = render(request, "Order result | Lowe's", body)
    except Exception as exc:
        if isinstance(exc, site_store.CheckoutError):
            message = " ".join(exc.errors.values())
        else:
            message = "The local checkout could not be completed."
        response = render(request, "Checkout error | Lowe's", f'<main class="shell section"><div class="notice notice--error"><h1>Check your checkout details</h1><p>{escape(message)}</p><a href="/checkout">Return to checkout</a></div></main>', status_code=400)
    return set_session_cookie(response, token)


@app.get("/orders", response_class=HTMLResponse)
def orders(request: Request) -> HTMLResponse:
    owner = existing_owner(request)
    rows = site_store.orders_for_owner(owner, current_account_id(request)) if owner else []
    if not rows:
        body = '<main class="shell section empty-state"><h1>Order Status</h1><p>No offline orders are associated with this browser session.</p><a class="button button--primary" href="/search">Start shopping</a></main>'
    else:
        cards = "".join(f'<article class="service-card"><span class="tag tag--approved">{escape(str(order["status"]))}</span><h2>{escape(str(order["order_number"]))}</h2><p>{escape(str(order["customer_name"]))} · ${site_store.money(int(order["total_cents"]))} · {escape(str(order["fulfillment"]))}</p><p>{len(order["items"])} line item(s), payment {escape(str(order["payment_status"]))}</p></article>' for order in rows)
        body = f'<main class="shell section"><h1 class="page-title">Order Status</h1><div class="service-grid">{cards}</div></main>'
    return render(request, "Order Status | Lowe's", body)


# ---------------------------------------------------------------------------
# locally generated product artwork
# ---------------------------------------------------------------------------


@app.get("/img/p/{product_id}/{view}.svg")
def product_artwork(product_id: int, view: str) -> Response:
    """Deterministic SVG for a catalog product.

    The clone ships no source photography for the synthetic catalog, so the
    ``/pd/``, ``/pl/``, ``/collections/`` and ``/configure/`` families draw their
    own artwork from the product's category palette and id.
    """

    product = site_store.get_product(product_id)
    if product is None:
        return Response(status_code=404)
    category = commerce.category_index().get(str(product["category_id"]), {})
    svg = product_svg(product, category, view if view in VIEWS else "front")
    return Response(svg, media_type="image/svg+xml")


# ---------------------------------------------------------------------------
# /l/... landing families
# ---------------------------------------------------------------------------


def landing_catalog(page: landing.Landing) -> str:
    if not page.catalog:
        return ""
    query, category_id, sort = page.catalog
    result = site_store.search(
        query=query,
        category_ids=[category_id] if category_id else (),
        sort=sort,
        page_size=8,
    )
    heading = page.catalog_heading or "From this clone's catalog"
    return (
        '<section class="section"><div class="section__head">'
        f'<h2 class="section__title">{escape(heading)}</h2>'
        '<a class="section__more" href="/best-sellers">Browse best sellers</a></div>'
        f'{catalog_grid(result["products"])}</section>'
    )


def landing_body(page: landing.Landing) -> str:
    trail = list(page.trail)
    if not trail or trail[-1][0] != page.heading:
        trail.append((page.heading, None))
    return (
        '<main class="shell section landing-page">'
        + breadcrumb_bar(trail)
        + f'<p class="results-head__count">{escape(page.family)}</p>'
        + f'<h1 class="page-title">{escape(page.heading)}</h1>'
        + f'<p class="landing-intro">{escape(page.intro)}</p>'
        + sandbox_notice(SOURCE_RESTRICTED_NOTE)
        + action_row(page.actions)
        + (
            '<section class="section"><div class="section__head">'
            '<h2 class="section__title">On this page</h2></div>'
            + highlight_grid(page.highlights)
            + "</section>"
            if page.highlights
            else ""
        )
        + (
            '<section class="section"><h2 class="section__title">'
            "What this clone actually does</h2>" + fact_table(page.facts) + "</section>"
            if page.facts
            else ""
        )
        + landing_catalog(page)
        + "</main>"
    )


@app.get("/l/{path:path}", response_class=HTMLResponse)
def landing_route(request: Request, path: str) -> HTMLResponse:
    page = landing.LANDING_PAGES.get("/l/" + path.rstrip("/"))
    if page is None:
        return not_found(request, "/l/" + path)
    return render(request, page.title, landing_body(page))


# ---------------------------------------------------------------------------
# /ai — local shopping assistant
# ---------------------------------------------------------------------------

AI_STARTERS = (
    "refrigerator",
    "cordless drill",
    "interior paint",
    "ceiling fan",
    "water heater",
    "lawn mower",
)


@app.get("/ai", response_class=HTMLResponse)
def ai_assistant(request: Request, q: str = "") -> HTMLResponse:
    question = q.strip()
    starters = "".join(
        f'<a class="chip" href="/ai?q={quote_plus(term)}">{escape(term)}</a>'
        for term in AI_STARTERS
    )
    if question:
        result = site_store.search(query=question, sort="relevance", page_size=6)
        if result["products"]:
            answer = (
                f'<p class="landing-intro">{int(result["total"])} item(s) in this '
                f"clone's catalog match “{escape(question)}”. The ranking is the "
                "same deterministic relevance score the search page uses.</p>"
                + catalog_grid(result["products"])
            )
        else:
            answer = (
                '<div class="empty-state"><h2>Nothing in this catalog matches that</h2>'
                f"<p>“{escape(question)}” returned no rows. This assistant can only "
                "answer from the frozen local catalog — it never calls a model, a "
                "search service or any other network endpoint.</p></div>"
            )
    else:
        answer = (
            '<div class="empty-state"><h2>Ask about something in this catalog</h2>'
            "<p>Pick a starter above or type a product, brand or category.</p></div>"
        )
    body = (
        '<main class="shell section ai-page">'
        + breadcrumb_bar([("Home", "/"), ("AI Assist", None)])
        + '<p class="results-head__count">AI Assist</p>'
        + '<h1 class="page-title">Lowe\'s AI Assist</h1>'
        + '<p class="landing-intro">A local, deterministic shopping assistant. It '
        "answers only from this clone's frozen catalog, so the same question "
        "always returns the same items.</p>"
        + sandbox_notice(
            "No model, inference endpoint or third-party service is contacted. "
            "The source /ai page answered Access Denied to the recorded "
            "Playwright session, so this is not a reproduction of it."
        )
        + '<form class="ai-form" action="/ai" method="get">'
        '<label class="field"><span class="field__label">What are you looking for?</span>'
        f'<input class="field__control" name="q" value="{escape(question, quote=True)}" '
        'placeholder="Describe the project or the product"></label>'
        '<button class="button button--primary" type="submit">Ask</button></form>'
        f'<div class="chip-row">{starters}</div>'
        + answer
        + "</main>"
    )
    title = (
        f"AI Assist: {question} | Lowe's" if question else "Lowe's AI Assist | Lowe's"
    )
    return render(request, title, body, query=question)


# ---------------------------------------------------------------------------
# /b/lowesbrands — brand directory
# ---------------------------------------------------------------------------


@app.get("/b/lowesbrands", response_class=HTMLResponse)
def brand_directory(request: Request, brand: str = "") -> HTMLResponse:
    all_brands = site_store.brands()
    counts = site_store.search(page_size=1)["facet_brands"]
    selected = brand if brand in all_brands else ""
    tiles = "".join(
        f'<a class="brand-tile{" brand-tile--active" if name == selected else ""}" '
        f'href="/b/lowesbrands?brand={quote_plus(name)}">'
        f"<strong>{escape(name)}</strong>"
        f'<span>{int(counts.get(name, 0))} items</span></a>'
        for name in all_brands
    )
    if selected:
        result = site_store.search(brand_names=[selected], sort="top-sellers", page_size=12)
        listing = (
            '<section class="section"><div class="section__head">'
            f'<h2 class="section__title">{escape(selected)} in this catalog</h2>'
            '<a class="section__more" href="/b/lowesbrands">Show every brand</a></div>'
            f'{catalog_grid(result["products"])}</section>'
        )
    else:
        listing = (
            '<section class="section"><p class="landing-intro">Choose a brand to see '
            "everything this clone's catalog carries under it.</p></section>"
        )
    body = (
        '<main class="shell section brand-page">'
        + breadcrumb_bar([("Home", "/"), ("Brands", None)])
        + '<p class="results-head__count">Brand Directory</p>'
        + "<h1 class=\"page-title\">Lowe's Brands</h1>"
        + '<p class="landing-intro">Every brand below is invented for this offline '
        "clone and deliberately names no real Lowe's vendor, so a brand page here "
        "can never be mistaken for a captured one.</p>"
        + sandbox_notice(SOURCE_RESTRICTED_NOTE)
        + f'<div class="brand-grid">{tiles}</div>'
        + listing
        + "</main>"
    )
    title = (
        f"{selected} | Lowe's Brands" if selected else "Lowe's Brands Directory | Lowe's"
    )
    return render(request, title, body)


# ---------------------------------------------------------------------------
# /diy-projects-and-ideas and /n/how-to/...
# ---------------------------------------------------------------------------

DIY_THEMES = (
    (
        "Outdoor cooking",
        "Clean, season and store a grill so it lights first time next season.",
        "/n/how-to/clean-and-maintain-your-grill-ht",
        "Read the how-to",
    ),
    (
        "Family workshops",
        "Free hands-on builds for the MyLowe's Rewards Kids Club.",
        "/diy-projects-and-ideas/workshops",
        "See workshops",
    ),
    (
        "Seasonal refresh",
        "Room-by-room ideas that need paint, lighting and hardware only.",
        "/l/fresh-projects-and-inspiration",
        "Get inspired",
    ),
    (
        "Home maintenance",
        "The seasonal checklist behind this clone's repeat-delivery categories.",
        "/l/shop/home-maintenance",
        "See the checklist",
    ),
    (
        "Window treatments",
        "Measure an opening and configure a blind to it, priced server-side.",
        "/configure/blinds/allen-roth-Cordless-Cellular-Shade/5015737843",
        "Open the configurator",
    ),
    (
        "Paint projects",
        "Sheens, primers and coverage for interior and exterior work.",
        "/l/shop/online-paint-store",
        "Visit the paint store",
    ),
)


@app.get("/diy-projects-and-ideas", response_class=HTMLResponse)
def diy_projects(request: Request) -> HTMLResponse:
    cards = "".join(
        '<article class="service-card">'
        f"<h3>{escape(title)}</h3><p>{escape(copy)}</p>"
        f'<a class="button button--outline" href="{escape(href, quote=True)}">{escape(cta)}</a>'
        "</article>"
        for title, copy, href, cta in DIY_THEMES
    )
    body = (
        '<main class="shell section diy-page">'
        + breadcrumb_bar([("Home", "/"), ("DIY Projects & Ideas", None)])
        + '<p class="results-head__count">Ideas &amp; Inspiration</p>'
        + '<h1 class="page-title">DIY Projects &amp; Ideas</h1>'
        + '<p class="landing-intro">The project hub that sits above this clone\'s '
        "how-to article, its family workshops page and its configurable window "
        "treatments. Every card below opens a page this clone serves itself.</p>"
        + sandbox_notice(SOURCE_RESTRICTED_NOTE)
        + f'<div class="service-grid">{cards}</div>'
        + "</main>"
    )
    return render(request, "DIY Projects & Ideas | Lowe's", body)


GRILL_HOW_TO = {
    "intro": (
        "A grill that is cleaned after the season lights faster, cooks more "
        "evenly and lasts longer. This is the full sequence, from a burnt-on "
        "grate to a covered grill ready for storage."
    ),
    "time": "About 60 minutes, plus drying time",
    "difficulty": "Beginner",
    "steps": (
        (
            "Burn off the residue",
            "Run the grill on high with the lid closed for 15 minutes so food "
            "residue turns to ash, then turn it off and let it cool enough to "
            "handle.",
        ),
        (
            "Brush the grates",
            "Work along the bars, not across them, with a stiff grate brush. "
            "Replace a brush as soon as bristles start to shed.",
        ),
        (
            "Empty the grease tray",
            "Pull the tray and the catch cup, scrape them out and wash them. A "
            "full tray is the most common cause of a flare-up.",
        ),
        (
            "Clean the burner tubes",
            "Brush along the tubes so every port is open, and check that the "
            "flame is blue and even when you relight.",
        ),
        (
            "Wash the exterior",
            "Warm water and dish soap on the lid and cart, rinsed and dried. "
            "Wipe stainless steel along the grain.",
        ),
        (
            "Season and cover",
            "Coat the grates with a thin film of high-smoke-point oil, run the "
            "grill for 15 minutes, let it cool and fit the cover.",
        ),
    ),
    "supplies": (
        "Grate brush or scraper",
        "Bucket, warm water and dish soap",
        "Non-abrasive cloths",
        "High-smoke-point cooking oil",
        "Replacement grease cups",
        "A fitted grill cover",
    ),
}


@app.get("/n/how-to/{article}", response_class=HTMLResponse)
def how_to_article(request: Request, article: str) -> HTMLResponse:
    slug = article.rstrip("/")
    if not slug:
        return not_found(request, "/n/how-to/")
    # The captured inventory carries exactly one how-to path; anything else that
    # matches the pattern gets the same structure with its own URL-derived title
    # rather than a shared filler body.
    is_grill = slug.startswith("clean-and-maintain-your-grill")
    display = commerce.humanize(slug.removesuffix("-ht"))
    heading = "How to Clean and Maintain Your Grill" if is_grill else f"How to {display}"
    intro = GRILL_HOW_TO["intro"] if is_grill else (
        f"A step-by-step local article for {display.lower()}. This clone ships "
        "one fully written how-to; every other path in the family renders this "
        "same structure from its own URL."
    )
    steps = "".join(
        f"<li><h3>{escape(title)}</h3><p>{escape(copy)}</p></li>"
        for title, copy in (
            GRILL_HOW_TO["steps"] if is_grill else (("Plan the work", intro),)
        )
    )
    supplies = "".join(
        f"<li>{escape(item)}</li>"
        for item in (GRILL_HOW_TO["supplies"] if is_grill else ("Project-specific supplies",))
    )
    related = site_store.search(
        query="grill" if is_grill else "", category_ids=("outdoor-living",), page_size=4
    )
    body = (
        '<main class="shell section how-to-page">'
        + breadcrumb_bar(
            [
                ("Home", "/"),
                ("DIY Projects & Ideas", "/diy-projects-and-ideas"),
                (heading, None),
            ]
        )
        + '<p class="results-head__count">How-To</p>'
        + f'<h1 class="page-title">{escape(heading)}</h1>'
        + f'<p class="landing-intro">{escape(intro)}</p>'
        + sandbox_notice(SOURCE_RESTRICTED_NOTE)
        + fact_table(
            (
                ("Time", str(GRILL_HOW_TO["time"]) if is_grill else "Varies"),
                ("Difficulty", str(GRILL_HOW_TO["difficulty"]) if is_grill else "Varies"),
                ("Steps", str(len(GRILL_HOW_TO["steps"]) if is_grill else 1)),
            )
        )
        + f'<section class="section"><h2 class="section__title">Steps</h2><ol class="how-to-steps">{steps}</ol></section>'
        + f'<section class="section"><h2 class="section__title">What you need</h2><ul class="how-to-supplies">{supplies}</ul></section>'
        + (
            '<section class="section"><div class="section__head">'
            '<h2 class="section__title">Shop this project</h2>'
            '<a class="section__more" href="/c/Outdoors">Shop outdoors</a></div>'
            + catalog_grid(related["products"])
            + "</section>"
            if related["products"]
            else ""
        )
        + "</main>"
    )
    return render(request, f"{heading} | Lowe's", body)


# ---------------------------------------------------------------------------
# /store/ — store finder
# ---------------------------------------------------------------------------


@app.get("/store/", response_class=HTMLResponse)
def store_finder(request: Request, q: str = "") -> HTMLResponse:
    needle = q.strip().casefold()
    rows = site_store.stores()
    matches = [
        row
        for row in rows
        if not needle
        or needle
        in " ".join(
            str(row[key]).casefold() for key in ("name", "city", "state", "zip")
        )
    ]
    cards = "".join(
        '<article class="service-card">'
        f'<h3>{escape(str(row["name"]))}</h3>'
        f'<p>{escape(str(row["city"]))}, {escape(str(row["state"]))} {escape(str(row["zip"]))}<br>'
        f'Closes at {escape(str(row["closes_at"]))}</p>'
        f'<a class="button button--outline" href="/stores/{quote_plus(str(row["state"]).lower())}">'
        f'Stores in {escape(str(row["state"]))}</a>'
        "</article>"
        for row in matches
    )
    if not matches:
        cards = (
            '<div class="empty-state"><h2>No store matches that search</h2>'
            "<p>This clone carries four synthetic stores. Clear the search to see "
            "them all.</p></div>"
        )
    body = (
        '<main class="shell section store-finder">'
        + breadcrumb_bar([("Home", "/"), ("Find a Store", None)])
        + '<p class="results-head__count">Store Finder</p>'
        + "<h1 class=\"page-title\">Find a Lowe's Store</h1>"
        + '<p class="landing-intro">These four stores are the ones the local pickup '
        "selector and the sandbox checkout actually use. Searching filters them "
        "on the server.</p>"
        + sandbox_notice(SOURCE_RESTRICTED_NOTE)
        + '<form class="store-search" action="/store/" method="get">'
        '<label class="field"><span class="field__label">City, state or ZIP code</span>'
        f'<input class="field__control" name="q" value="{escape(q, quote=True)}" '
        'placeholder="Hawthorne, CA or 90250"></label>'
        '<button class="button button--primary" type="submit">Find stores</button></form>'
        f'<p class="results-head__count">{len(matches)} of {len(rows)} stores</p>'
        f'<div class="service-grid">{cards}</div>'
        + action_row(
            (
                ("Full store directory", "/Lowes-Stores"),
                ("In-store services", "/l/about/store-services"),
            )
        )
        + "</main>"
    )
    return render(request, "Find a Lowe's Store Near You | Lowe's", body)


# ---------------------------------------------------------------------------
# /weekly-ad
# ---------------------------------------------------------------------------

WEEKLY_AD_EVIDENCE_NOTE = (
    "Evidence gap: the recorded Playwright replay of the source Weekly Ad only "
    "ever captured a loading skeleton, so no source layout was observed for this "
    "route at all. The circular below is built entirely from this clone's own "
    "catalog savings."
)


@app.get("/weekly-ad", response_class=HTMLResponse)
def weekly_ad(request: Request, store: str = "") -> HTMLResponse:
    stores = site_store.stores()
    selected = next(
        (row for row in stores if str(row["id"]) == store), stores[0] if stores else None
    )
    options = "".join(
        f'<option value="{escape(str(row["id"]), quote=True)}"'
        + (" selected" if selected and row["id"] == selected["id"] else "")
        + f'>{escape(str(row["name"]))} — {escape(str(row["city"]))}, {escape(str(row["state"]))}</option>'
        for row in stores
    )
    front = site_store.search(sort="savings", page_size=4)
    inside = site_store.search(sort="savings", page_size=8, page=2)
    body = (
        '<main class="shell section weekly-ad-page">'
        + breadcrumb_bar([("Home", "/"), ("Weekly Ad", None)])
        + '<p class="results-head__count">Weekly Ad</p>'
        + '<h1 class="page-title">This Week\'s Ad</h1>'
        + '<p class="landing-intro">Every offer below is computed from the local '
        "catalog's own was-and-now prices, so the ad, the product card and the "
        "cart all quote the same number.</p>"
        + sandbox_notice(WEEKLY_AD_EVIDENCE_NOTE)
        + '<form class="weekly-ad-store" action="/weekly-ad" method="get">'
        '<label class="field"><span class="field__label">Ad for store</span>'
        f'<select class="field__control" name="store" data-autosubmit>{options}</select></label>'
        '<button class="button button--outline" type="submit">Show this ad</button></form>'
        + (
            f'<p class="results-head__count">Showing the ad for {escape(str(selected["name"]))},'
            f' {escape(str(selected["city"]))}, {escape(str(selected["state"]))}.</p>'
            if selected
            else ""
        )
        + '<section class="section"><div class="section__head">'
        '<h2 class="section__title">Front page</h2></div>'
        + catalog_grid(front["products"])
        + "</section>"
        '<section class="section"><div class="section__head">'
        '<h2 class="section__title">Inside the ad</h2>'
        '<a class="section__more" href="/l/savings">All savings</a></div>'
        + catalog_grid(inside["products"])
        + "</section>"
        + action_row(
            (
                ("Coupons", "/l/savings/coupons"),
                ("Daily deals", "/l/savings/daily-deals"),
                ("Find a store", "/store/"),
            )
        )
        + "</main>"
    )
    return render(request, "Weekly Ad | Lowe's", body)


# ---------------------------------------------------------------------------
# /mylowes/orders/checkorderstatus — guest order lookup
# ---------------------------------------------------------------------------


@app.get("/mylowes/orders/checkorderstatus", response_class=HTMLResponse)
def check_order_status(
    request: Request, email: str = "", order_number: str = ""
) -> HTMLResponse:
    result = ""
    if email.strip() and order_number.strip():
        order = site_store.get_order(order_number.strip().upper())
        # The same wording covers "no such order" and "wrong email", so the form
        # cannot be used to discover which order numbers exist.
        if order and str(order["email"]).casefold() == email.strip().casefold():
            items = "".join(
                f'<tr><th scope="row">{escape(str(item["title"]))}</th>'
                f'<td>{int(item["quantity"])}</td>'
                f'<td>{cents(int(item["line_total_cents"]))}</td></tr>'
                for item in order["items"]
            )
            result = (
                '<div class="order-banner">'
                f'<span class="tag tag--approved">{escape(str(order["status"]))}</span>'
                f'<h2>{escape(str(order["order_number"]))}</h2>'
                f'<p>{escape(str(order["customer_name"]))} · '
                f'{escape(str(order["fulfillment"]))} · '
                f'{cents(int(order["total_cents"]))}</p>'
                '<table class="spec-table"><thead><tr><th>Item</th><th>Qty</th>'
                f"<th>Line total</th></tr></thead><tbody>{items}</tbody></table>"
                "<p>This is a local sandbox order. No Lowe's order exists.</p></div>"
            )
        else:
            result = (
                '<div class="notice notice--error">No local order matches that '
                "order number and email address. This lookup only reads orders "
                "placed inside this clone.</div>"
            )
    body = (
        '<main class="order-search-page"><div class="shell">'
        + breadcrumb_bar(
            [
                ("Home", "/"),
                ("Orders Search", "/mylowes/orders"),
                ("Check Order Status", None),
            ]
        )
        + '<section class="order-search-card">'
        "<h1>Look Up an Order</h1>"
        '<p>Enter the order number from a local sandbox confirmation together with '
        "the email address it was placed under. The lookup runs against this "
        "clone's own database.</p>"
        '<form action="/mylowes/orders/checkorderstatus" method="get">'
        '<label class="field"><span class="visually-hidden">Email address</span>'
        f'<input class="field__control" type="email" name="email" value="{escape(email, quote=True)}" '
        'placeholder="✉  Enter email address" required>'
        "<small>The email address used at local checkout</small></label>"
        '<label class="field"><span class="visually-hidden">Order Number</span>'
        f'<input class="field__control" name="order_number" value="{escape(order_number, quote=True)}" '
        'placeholder="▧  Enter Order Number, for example LWS-700001" required>'
        "<small>Shown on the local order confirmation</small></label>"
        '<button class="button button--primary button--block">Look Up Order</button>'
        "</form>"
        + result
        + '<p class="order-account-copy">Signed in? Your local order history is on '
        '<a href="/orders">Order Status</a>.</p>'
        '<p><a href="/mylowes/orders">Back to Orders Search</a></p>'
        "</section></div></main>"
    )
    return render(request, "Look Up an Order — Check Order Status | Lowe's", body)


# ---------------------------------------------------------------------------
# /lists
# ---------------------------------------------------------------------------


@app.get("/lists", response_class=HTMLResponse)
def lists_page(request: Request) -> HTMLResponse:
    body = (
        '<main class="shell section">'
        + breadcrumb_bar([("Home", "/"), ("Lists", None)])
        + '<h1 class="page-title">Lists</h1>'
        + '<p class="landing-intro">Saved lists are an account feature. This clone '
        "keeps a real per-session cart instead, and does not persist a separate "
        "list.</p>"
        + '<div class="empty-state"><h2>No saved lists</h2>'
        '<p><a class="button button--primary" href="/cart">Go to your cart</a></p></div>'
        + "</main>"
    )
    return render(request, "Lists | Lowe's", body)


# ---------------------------------------------------------------------------
# /pd/{source-slug}/{item-id} — product detail
# ---------------------------------------------------------------------------


@app.get("/pd/{slug}/{item_id}", response_class=HTMLResponse)
def product_detail_route(request: Request, slug: str, item_id: str) -> HTMLResponse:
    detail = commerce.product_detail(slug, item_id)
    product = detail["product"]
    thumbs = "".join(
        f'<button class="pdp__thumb" type="button" aria-current="{"true" if index == 0 else "false"}"'
        f' data-gallery-thumb="{catalog_art(int(product["id"]), view)}"'
        f' data-gallery-alt="{escape(detail["display_title"], quote=True)} — {view} view">'
        f'<img src="{catalog_art(int(product["id"]), view)}" width="80" height="80" alt="">'
        "</button>"
        for index, view in enumerate(VIEWS)
    )
    specs = "".join(
        f'<tr><th scope="row">{escape(str(name))}</th><td>{escape(str(value))}</td></tr>'
        for name, value in product["specs"]
    )
    specs += (
        f'<tr><th scope="row">Model</th><td>{escape(str(product["model_number"]))}</td></tr>'
        f'<tr><th scope="row">Item</th><td>{escape(item_id)}</td></tr>'
        f'<tr><th scope="row">Category</th><td>{escape(detail["category_label"])}</td></tr>'
    )
    pickup_note = (
        "Free pickup today at your selected store"
        if product["pickup_today"]
        else "Not available for store pickup"
    )
    body = (
        '<main class="shell section pdp-page">'
        + breadcrumb_bar(
            [
                ("Home", "/"),
                (detail["category_label"], f'/c/{quote_plus(detail["category_label"])}'),
                (detail["display_title"], None),
            ]
        )
        + '<div class="pdp">'
        f'<div class="pdp__thumbs">{thumbs}</div>'
        f'<div class="pdp__stage"><img src="{catalog_art(int(product["id"]))}" '
        f'alt="{escape(detail["display_title"], quote=True)}" data-gallery-stage></div>'
        '<section class="pdp__buybox">'
        f'<span class="product-card__brand">{escape(str(product["brand"]))}</span>'
        f'<h1 class="pdp__title">{escape(detail["display_title"])}</h1>'
        f'<p class="results-head__count">Item # {escape(item_id)} · '
        f'Model # {escape(str(product["model_number"]))}</p>'
        + rating_line(product)
        + price_line(product)
        + f'<p>{escape(str(product["summary"]))}</p>'
        '<form action="/cart/add" method="post">'
        f'<input type="hidden" name="product_id" value="{int(product["id"])}">'
        '<div class="fulfillment"><h2>How do you want to get your item?</h2>'
        '<label class="fulfillment-choice"><input type="radio" name="fulfillment" '
        f'value="pickup"{" checked" if product["pickup_today"] else " disabled"}> '
        f"Pickup — {escape(pickup_note)}</label>"
        '<label class="fulfillment-choice"><input type="radio" name="fulfillment" '
        f'value="delivery"{"" if product["pickup_today"] else " checked"}> '
        f'Delivery — {"Free" if product["free_delivery"] else "Fee applies"} in '
        f'{int(product["delivery_days"])} days</label></div>'
        '<div class="quantity" data-quantity>'
        '<button type="button" data-quantity-step="-1" aria-label="Decrease quantity">−</button>'
        '<label class="visually-hidden" for="pdp-quantity">Quantity</label>'
        '<input id="pdp-quantity" type="number" name="quantity" value="1" min="1" max="99" step="1">'
        '<button type="button" data-quantity-step="1" aria-label="Increase quantity">+</button></div>'
        '<button class="button button--primary button--block" type="submit">Add to Cart</button>'
        "</form>"
        f'<p class="results-head__count">{int(product["stock"])} in stock in this '
        "clone's synthetic inventory.</p>"
        + sandbox_notice(SYNTHETIC_COMMERCE_NOTE)
        + "</section></div>"
        f'<section class="section"><h2 class="section__title">Product details</h2>'
        f'<table class="spec-table"><tbody>{specs}</tbody></table></section>'
        + (
            '<section class="section"><div class="section__head">'
            '<h2 class="section__title">Customers also viewed</h2></div>'
            + catalog_grid(detail["related"])
            + "</section>"
            if detail["related"]
            else ""
        )
        + "</main>"
    )
    return render(request, f"{detail['display_title']} | Lowe's", body)


# ---------------------------------------------------------------------------
# /pl/... — product list
# ---------------------------------------------------------------------------


def query_string(request: Request, **overrides: Any) -> str:
    pairs: list[tuple[str, str]] = [
        (key, value)
        for key, value in request.query_params.multi_items()
        if key not in overrides
    ]
    for key, value in overrides.items():
        if value in (None, "", False):
            continue
        if isinstance(value, (list, tuple)):
            pairs.extend((key, str(item)) for item in value)
        else:
            pairs.append((key, str(value)))
    return urlencode(pairs)


def list_filters_form(
    action: str, request: Request, result: Mapping[str, Any]
) -> str:
    selected_brands = set(request.query_params.getlist("brand"))
    facet_brands = result["facet_brands"]
    brand_options = "".join(
        '<label class="filters__option"><input type="checkbox" name="brand"'
        f' value="{escape(name, quote=True)}"'
        + (" checked" if name in selected_brands else "")
        + f'><span>{escape(name)}</span>'
        f'<span class="results-head__count">({count})</span></label>'
        for name, count in sorted(facet_brands.items())
    )
    rating = request.query_params.get("rating", "")
    rating_options = "".join(
        '<label class="filters__option"><input type="radio" name="rating"'
        f' value="{value}"' + (" checked" if rating == value else "")
        + f"><span>{value} stars &amp; up</span></label>"
        for value in ("4.5", "4", "3")
    )
    return (
        f'<form class="filters" method="get" action="{escape(action, quote=True)}">'
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Brand</legend>'
        + (brand_options or '<p class="results-head__count">No brands in scope</p>')
        + "</fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Price</legend>'
        '<div class="filters__price">'
        '<label class="visually-hidden" for="min-price">Minimum price</label>'
        '<input class="field__control" id="min-price" type="number" min="0" step="1"'
        f' name="min_price" value="{escape(request.query_params.get("min_price", ""), quote=True)}" placeholder="Min">'
        '<label class="visually-hidden" for="max-price">Maximum price</label>'
        '<input class="field__control" id="max-price" type="number" min="0" step="1"'
        f' name="max_price" value="{escape(request.query_params.get("max_price", ""), quote=True)}" placeholder="Max">'
        "</div></fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Customer Rating</legend>'
        + rating_options
        + "</fieldset>"
        '<fieldset class="filters__group">'
        '<legend class="filters__legend">Availability</legend>'
        '<label class="filters__option"><input type="checkbox" name="pickup" value="1"'
        + (" checked" if request.query_params.get("pickup") else "")
        + "><span>Pickup today</span></label>"
        '<label class="filters__option"><input type="checkbox" name="free_delivery" value="1"'
        + (" checked" if request.query_params.get("free_delivery") else "")
        + "><span>Free delivery</span></label>"
        "</fieldset>"
        f'<input type="hidden" name="sort" value="{escape(request.query_params.get("sort", "relevance"), quote=True)}">'
        '<button class="button button--primary button--block" type="submit">Apply filters</button>'
        f'<a class="link-button" href="{escape(action, quote=True)}">Clear all filters</a>'
        "</form>"
    )


def pagination_bar(path: str, request: Request, result: Mapping[str, Any]) -> str:
    if int(result["page_count"]) <= 1:
        return ""
    links = "".join(
        '<a class="pagination__link"'
        + (' aria-current="page"' if number == int(result["page"]) else "")
        + f' href="{escape(path, quote=True)}?{escape(query_string(request, page=number), quote=True)}">{number}</a>'
        for number in range(1, int(result["page_count"]) + 1)
    )
    return f'<nav class="pagination" aria-label="Result pages">{links}</nav>'


@app.get("/pl/{path:path}", response_class=HTMLResponse)
def product_list_route(request: Request, path: str) -> HTMLResponse:
    segments = [segment for segment in path.split("/") if segment]
    if len(segments) < 2:
        return not_found(request, "/pl/" + path)
    collection_id = segments[-1]
    title_segments = segments[:-1]
    params = request.query_params
    page = params.get("page", "1")
    listing = commerce.list_page(
        title_segments,
        collection_id,
        brands=params.getlist("brand"),
        min_price=params.get("min_price", ""),
        max_price=params.get("max_price", ""),
        rating=params.get("rating", ""),
        pickup=bool(params.get("pickup")),
        free_delivery=bool(params.get("free_delivery")),
        sort=params.get("sort", "relevance"),
        page=int(page) if page.isdigit() else 1,
    )
    result = listing["result"]
    action = "/pl/" + path
    sort_options = "".join(
        f'<option value="{key}"'
        + (" selected" if result["sort"] == key else "")
        + f">{escape(label)}</option>"
        for key, label in site_store.SORT_OPTIONS
    )
    refinement_chips = "".join(
        f'<span class="applied-filters__chip">{escape(label)}</span>'
        for label in listing["refinements"]
    )
    body = (
        '<main class="shell section plp-page">'
        + breadcrumb_bar(
            [("Home", "/"), ("Shop", "/c/Departments"), (listing["heading"], None)]
        )
        + '<p class="results-head__count">Collection ' + escape(collection_id) + "</p>"
        + f'<h1 class="page-title">{escape(listing["heading"])}</h1>'
        + (f'<div class="applied-filters">{refinement_chips}</div>' if refinement_chips else "")
        + sandbox_notice(SYNTHETIC_COMMERCE_NOTE)
        + '<div class="results-layout">'
        + list_filters_form(action, request, result)
        + "<section>"
        + '<div class="results-head">'
        + (
            f'<p class="results-head__count">Showing {int(result["first_index"])}–'
            f'{int(result["last_index"])} of {int(result["total"])} results in '
            f'{escape(listing["scope"]["label"])}</p>'
            if int(result["total"])
            else '<p class="results-head__count">0 results</p>'
        )
        + f'<form method="get" action="{escape(action, quote=True)}">'
        + "".join(
            f'<input type="hidden" name="brand" value="{escape(name, quote=True)}">'
            for name in params.getlist("brand")
        )
        + '<label class="visually-hidden" for="pl-sort">Sort by</label>'
        f'<select class="field__control sort-select" id="pl-sort" name="sort" data-autosubmit>{sort_options}</select>'
        '<button class="visually-hidden" type="submit">Sort</button></form>'
        "</div>"
        + catalog_grid(result["products"])
        + pagination_bar(action, request, result)
        + "</section></div></main>"
    )
    return render(request, f"{listing['heading']} at Lowes.com", body)


# ---------------------------------------------------------------------------
# /collections/{source-slug}/{collection-id} — appliance suites
# ---------------------------------------------------------------------------


@app.get("/collections/{slug}/{collection_id}", response_class=HTMLResponse)
def collection_route(request: Request, slug: str, collection_id: str) -> HTMLResponse:
    package = commerce.collection_package(slug, collection_id)
    rows = "".join(
        '<article class="package-member">'
        f'<a class="package-member__media" href="{escape(str(product["url"]), quote=True)}">'
        f'<img src="{catalog_art(int(product["id"]))}" width="320" height="320" alt=""></a>'
        f'<div><span class="results-head__count">{escape(role)}</span>'
        f'<span class="product-card__brand">{escape(str(product["brand"]))}</span>'
        f'<a class="product-card__title" href="{escape(str(product["url"]), quote=True)}">'
        f'{escape(str(product["title"]))}</a>{rating_line(product)}</div>'
        f'<strong>{cents(int(product["price_cents"]))}</strong></article>'
        for role, product in package["members"]
    )
    hidden_ids = "".join(
        f'<input type="hidden" name="product_id" value="{product_id}">'
        for product_id in package["product_ids"]
    )
    body = (
        '<main class="shell section collection-page">'
        + breadcrumb_bar(
            [
                ("Home", "/"),
                ("Appliances", "/c/Appliances"),
                (package["display_title"], None),
            ]
        )
        + '<p class="results-head__count">Appliance Suite '
        + escape(collection_id)
        + "</p>"
        + f'<h1 class="page-title">{escape(package["display_title"])}</h1>'
        + '<p class="landing-intro">A four-piece suite assembled from this clone\'s '
        "catalog. Adding the suite adds every member as a real cart line, priced "
        "at each member's own catalog price.</p>"
        + sandbox_notice(SYNTHETIC_COMMERCE_NOTE)
        + '<div class="cart-layout"><section class="package-list">'
        + rows
        + "</section>"
        '<aside class="summary"><h2>Suite total</h2>'
        f'<div class="summary__row"><span>{len(package["members"])} items at list</span>'
        f'<strong>{cents(package["list_total_cents"])}</strong></div>'
        f'<div class="summary__row"><span>Suite savings</span>'
        f'<strong>-{cents(package["discount_cents"])}</strong></div>'
        '<div class="summary__row summary__row--total"><span>Suite price</span>'
        f'<strong>{cents(package["package_total_cents"])}</strong></div>'
        '<form action="/cart/add" method="post">'
        + hidden_ids
        + '<input type="hidden" name="fulfillment" value="delivery">'
        '<button class="button button--primary button--block" type="submit">'
        "Add all four to cart</button></form>"
        '<p class="results-head__count">The suite discount is a local display rule; '
        "each cart line is recorded at its own catalog price.</p>"
        "</aside></div>"
        + action_row(
            (
                ("Shop appliances", "/c/Appliances"),
                ("Installation services", "/l/install"),
                ("Delivery details", "/l/help/shipping-delivery"),
            )
        )
        + "</main>"
    )
    return render(request, f"{package['display_title']} | Lowe's", body)


# ---------------------------------------------------------------------------
# /configure/blinds/{source-slug}/{item-id} — made-to-measure configurator
# ---------------------------------------------------------------------------


def option_select(
    name: str, label: str, options: Sequence[tuple[str, str]], selected: str
) -> str:
    choices = "".join(
        f'<option value="{escape(value, quote=True)}"'
        + (" selected" if value == selected else "")
        + f">{escape(text)}</option>"
        for value, text in options
    )
    return (
        f'<label class="field"><span class="field__label">{escape(label)}</span>'
        f'<select class="field__control" name="{name}">{choices}</select></label>'
    )


@app.get("/configure/blinds/{slug}/{item_id}", response_class=HTMLResponse)
def blinds_configurator(
    request: Request, slug: str, item_id: str
) -> HTMLResponse:
    quote = commerce.blind_configuration(slug, item_id, dict(request.query_params))
    product = quote["product"]
    action = f"/configure/blinds/{slug}/{item_id}"
    body = (
        '<main class="shell section configure-page">'
        + breadcrumb_bar(
            [
                ("Home", "/"),
                ("Window Treatments", "/c/Window-treatments-Home-decor"),
                (quote["display_title"], None),
            ]
        )
        + '<p class="results-head__count">Made to Measure · Item # '
        + escape(item_id)
        + "</p>"
        + f'<h1 class="page-title">Configure: {escape(quote["display_title"])}</h1>'
        + '<p class="landing-intro">Choose a size and the lift, opacity and colour '
        "options. The quote is recalculated on the server from a frozen option "
        "table, so a hand-edited query string cannot produce an unpriced "
        "configuration.</p>"
        + sandbox_notice(SYNTHETIC_COMMERCE_NOTE)
        + '<div class="cart-layout"><section>'
        f'<form class="configure-form" method="get" action="{escape(action, quote=True)}">'
        + option_select(
            "width",
            "Width (inches)",
            tuple((str(value), f"{value} in") for value in commerce.BLIND_WIDTHS),
            str(quote["width"]),
        )
        + option_select(
            "height",
            "Height (inches)",
            tuple((str(value), f"{value} in") for value in commerce.BLIND_HEIGHTS),
            str(quote["height"]),
        )
        + option_select("mount", "Mount", commerce.BLIND_MOUNTS, quote["mount"])
        + option_select(
            "control",
            "Lift control",
            tuple((value, label) for value, label, _extra in commerce.BLIND_CONTROLS),
            quote["control"],
        )
        + option_select("opacity", "Opacity", commerce.BLIND_ROOMS, quote["opacity"])
        + option_select("color", "Colour", commerce.BLIND_COLORS, quote["color"])
        + '<button class="button button--primary" type="submit">Update quote</button>'
        "</form>"
        f'<div class="configure-preview"><img src="{catalog_art(int(product["id"]), "detail")}" '
        f'width="320" height="320" alt="{escape(quote["display_title"], quote=True)}"></div>'
        "</section>"
        '<aside class="summary"><h2>Your configuration</h2>'
        + "".join(
            f'<div class="summary__row"><span>{escape(label)}</span><span>{escape(value)}</span></div>'
            for label, value in (
                ("Size", f'{quote["width"]} in × {quote["height"]} in'),
                ("Area", f'{quote["square_feet"]} sq ft'),
                ("Mount", quote["labels"]["mount"]),
                ("Lift", quote["labels"]["control"]),
                ("Opacity", quote["labels"]["opacity"]),
                ("Colour", quote["labels"]["color"]),
            )
        )
        + f'<div class="summary__row"><span>Base</span><span>{cents(quote["base_cents"])}</span></div>'
        f'<div class="summary__row"><span>Oversize</span><span>{cents(quote["size_cents"])}</span></div>'
        f'<div class="summary__row"><span>Lift upgrade</span><span>{cents(quote["control_cents"])}</span></div>'
        '<div class="summary__row summary__row--total"><span>Configured quote</span>'
        f'<strong>{cents(quote["unit_cents"])}</strong></div>'
        '<form action="/cart/add" method="post">'
        f'<input type="hidden" name="product_id" value="{int(product["id"])}">'
        '<input type="hidden" name="fulfillment" value="delivery">'
        '<button class="button button--primary button--block" type="submit">'
        "Add the base item to cart</button></form>"
        '<p class="results-head__count">Truthful-simulation boundary: the local '
        "cart records the base catalog item at "
        f"{cents(quote['base_cents'])}. The configured quote above is computed "
        "for display and is not stored as a cart line, because this clone's cart "
        "schema holds no configuration.</p>"
        "</aside></div>"
        + action_row(
            (
                ("Special orders", "/l/help/special-orders"),
                ("Installation services", "/l/install"),
                ("Shop window treatments", "/c/Window-treatments-Home-decor"),
            )
        )
        + "</main>"
    )
    return render(
        request, f"Configure {quote['display_title']} | Lowe's", body
    )


# ---------------------------------------------------------------------------
# not found
# ---------------------------------------------------------------------------


def not_found(request: Request, path: str) -> HTMLResponse:
    body = (
        '<main class="shell section empty-state"><h1>Page not found</h1>'
        f"<p>Nothing is served at <code>{escape(path)}</code> in this offline "
        "clone.</p>"
        '<p><a class="button button--primary" href="/">Back to home</a> '
        '<a class="button button--outline" href="/c/Departments">Shop all departments</a></p>'
        "</main>"
    )
    return render(request, "Page not found | Lowe's", body, status_code=404)


@app.get("/{path:path}")
def informational(request: Request, path: str) -> Response:
    target = LEGACY_REDIRECTS.get(path.strip("/"))
    if target:
        # A pre-inventory alias keeps working, but the source-compatible path is
        # the one canonical URL from here on.
        return RedirectResponse(target, status_code=308)
    return not_found(request, "/" + path)