File size: 128,516 Bytes
eddbbf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
"""
BuildAI - AI Engine v7 β€” ULTRA UPGRADE
New providers: Cerebras (ultra-fast), Gemini Flash (smart), DeepSeek (reasoning)
Pipeline: Cerebras β†’ Gemini β†’ Groq, with deep fallback chains
Higher quality output: v0/Lovable-level websites
"""

import os
import json
import asyncio
import httpx
from typing import AsyncGenerator

try:
    from google import genai as genai_new
    _GENAI_AVAILABLE = True
    _GENAI_NEW = True
except ImportError:
    try:
        import google.generativeai as genai
        _GENAI_AVAILABLE = True
        _GENAI_NEW = False
    except ImportError:
        _GENAI_AVAILABLE = False
        _GENAI_NEW = False


# ─────────────────────────────────────────────────────────────────
# REFERENCE FILE LOADER
# ─────────────────────────────────────────────────────────────────

_ref_cache = {}

def load_ref(filename: str) -> str:
    global _ref_cache
    if filename in _ref_cache:
        return _ref_cache[filename]
    # Search root, designs subfolder, and common app paths
    paths = [
        filename,
        f"./{filename}",
        f"/home/user/app/{filename}",
        f"./designs/{filename}",
        f"/home/user/app/designs/{filename}",
    ]
    for path in paths:
        try:
            with open(path, "r", encoding="utf-8") as f:
                content = f.read()
                _ref_cache[filename] = content
                print(f"[BuildAI] βœ“ Loaded {filename} from {path} ({len(content)} chars)")
                return content
        except FileNotFoundError:
            continue
    print(f"[BuildAI] ⚠ Not found: {filename} (checked {len(paths)} paths)")
    return ""


def get_references(prompt: str) -> tuple[str, str]:
    p = prompt.lower()
    # ── E-Commerce & Retail ──────────────────────────────────────────
    if any(k in p for k in ['ecommerce','e-commerce','store','shop','product','cart','buy','sell',
                              'marketplace','clothing','fashion','sneaker','brand','retail','boutique']):
        return load_ref("ref_ecommerce.html"), "E-COMMERCE"
    # ── Restaurant & Food ────────────────────────────────────────────
    elif any(k in p for k in ['restaurant','cafe','coffee','food','menu','kitchen','chef','dining',
                               'pizza','burger','sushi','bakery','bistro','bar','catering','eatery']):
        return load_ref("ref_restaurant.html"), "RESTAURANT"
    # ── Gym, Fitness & Wellness ──────────────────────────────────────
    elif any(k in p for k in ['gym','fitness','workout','sport','yoga','spa','wellness','pilates',
                               'crossfit','training','health club','athletic','bodybuilding']):
        return load_ref("ref_gym.html"), "FITNESS & WELLNESS"
    # ── Music, Band & Artist ─────────────────────────────────────────
    elif any(k in p for k in ['music','band','artist','concert','album','singer','rapper','dj',
                               'podcast','studio','sound','beats','producer','musician']):
        return load_ref("ref_music.html"), "MUSIC & ARTIST"
    # ── Photography & Visual Arts ────────────────────────────────────
    elif any(k in p for k in ['photography','photographer','photo','gallery','wedding photo',
                               'portrait','shoot','lens','lightroom','visual artist']):
        return load_ref("ref_photography.html"), "PHOTOGRAPHY"
    # ── Travel & Hospitality ─────────────────────────────────────────
    elif any(k in p for k in ['travel','tourism','hotel','resort','airbnb','hostel','vacation',
                               'trip','destination','adventure','tour','booking','flights']):
        return load_ref("ref_travel.html"), "TRAVEL & HOSPITALITY"
    # ── Crypto, Web3 & Fintech ───────────────────────────────────────
    elif any(k in p for k in ['crypto','blockchain','defi','nft','web3','token','bitcoin','ethereum',
                               'fintech','trading','wallet','exchange','dao','solana']):
        return load_ref("ref_crypto.html"), "CRYPTO & WEB3"
    # ── Medical, Healthcare & Clinic ─────────────────────────────────
    elif any(k in p for k in ['medical','clinic','hospital','doctor','healthcare','dentist','therapy',
                               'mental health','pharmacy','wellness clinic','telehealth','patient']):
        return load_ref("ref_medical.html"), "HEALTHCARE"
    # ── Education & E-Learning ───────────────────────────────────────
    elif any(k in p for k in ['education','school','university','course','learning','teaching',
                               'elearning','tutoring','bootcamp','academy','lms','classroom']):
        return load_ref("ref_education.html"), "EDUCATION"
    # ── Real Estate & Property ───────────────────────────────────────
    elif any(k in p for k in ['real estate','property','realty','housing','apartment','mortgage',
                               'home listing','interior design','architecture','construction']):
        return load_ref("ref_real_estate.html"), "REAL ESTATE"
    # ── Agency, Studio & Creative ────────────────────────────────────
    elif any(k in p for k in ['agency','creative agency','design studio','marketing agency',
                               'advertising','branding','production house','creative studio']):
        return load_ref("ref_agency.html"), "CREATIVE AGENCY"
    # ── Startup & SaaS App ───────────────────────────────────────────
    elif any(k in p for k in ['startup','app','saas app','mobile app','platform','tool','software',
                               'product launch','mvp','tech startup','b2b']):
        return load_ref("ref_startup.html"), "STARTUP"
    # ── Blog & Content ───────────────────────────────────────────────
    elif any(k in p for k in ['blog','news','magazine','newsletter','content','editorial',
                               'publication','media','journal','articles','writing']):
        return load_ref("ref_blog.html"), "BLOG & MEDIA"
    # ── Portfolio & Personal ─────────────────────────────────────────
    elif any(k in p for k in ['portfolio','designer','developer','cv','resume','case study',
                               'my work','showcase','freelance','personal site','personal brand']):
        return load_ref("ref_portfolio.html"), "PORTFOLIO"
    # ── Dashboard & Analytics ────────────────────────────────────────
    elif any(k in p for k in ['dashboard','admin','analytics','crm','chart','kpi','metric',
                               'report','data','fintech dashboard','saas dashboard']):
        return load_ref("ref_dashboard.html"), "DASHBOARD"
    # ── Default: SaaS Landing ────────────────────────────────────────
    else:
        return load_ref("ref_saas_app.html") or load_ref("ref_landing.html"), "SAAS LANDING PAGE"


# ─────────────────────────────────────────────────────────────────
# SMART IMAGE KEYWORD EXTRACTOR
# ─────────────────────────────────────────────────────────────────

IMAGE_KEYWORDS = {
    "cafe": ["coffee,cafe,cup", "barista,coffee,making", "cafe,interior,cozy", "coffee,latte,art"],
    "coffee": ["coffee,espresso,cup", "coffee,beans,roasted", "barista,coffee,brewing", "coffee,cafe,table"],
    "restaurant": ["restaurant,food,plating", "restaurant,interior,dining", "chef,cooking,kitchen", "food,gourmet,dish"],
    "pizza": ["pizza,italian,fresh", "pizza,oven,baking", "pizza,toppings,cheese", "pizzeria,italian,food"],
    "burger": ["burger,beef,fresh", "hamburger,restaurant,juicy", "burger,fries,meal", "fast,food,burger"],
    "sushi": ["sushi,japanese,fresh", "sushi,roll,seafood", "sushi,chef,making", "japanese,food,restaurant"],
    "bakery": ["bakery,bread,fresh", "pastry,croissant,baked", "cake,decoration,bakery", "bread,oven,baking"],
    "tea": ["tea,cup,hot", "tea,leaves,herbal", "teapot,ceramic,drink", "tea,ceremony,japan"],
    "bar": ["bar,cocktail,drinks", "bartender,mixing,cocktail", "whiskey,glass,bar", "nightlife,bar,drinks"],
    "fashion": ["fashion,clothing,style", "model,outfit,trendy", "clothes,boutique,store", "fashion,designer,wear"],
    "sneaker": ["sneakers,shoes,white", "athletic,shoes,sport", "sneaker,collection,display", "shoes,fashion,urban"],
    "clothing": ["clothing,fashion,store", "outfit,stylish,model", "wardrobe,clothes,fashion", "apparel,shopping,retail"],
    "jewelry": ["jewelry,gold,elegant", "necklace,diamond,luxury", "ring,jewelry,sparkle", "bracelet,fashion,accessories"],
    "saas": ["technology,software,laptop", "office,team,collaboration", "startup,tech,modern", "dashboard,analytics,screen"],
    "startup": ["startup,office,modern", "team,meeting,business", "entrepreneur,laptop,coffee", "tech,office,workspace"],
    "agency": ["office,creative,team", "agency,design,creative", "meeting,business,professional", "workspace,modern,office"],
    "tech": ["technology,innovation,laptop", "coding,developer,screen", "tech,startup,modern", "software,computer,code"],
    "gym": ["gym,workout,fitness", "exercise,weights,strong", "fitness,training,athlete", "gym,equipment,sport"],
    "yoga": ["yoga,meditation,peace", "yoga,pose,wellness", "mindfulness,yoga,calm", "yoga,studio,class"],
    "spa": ["spa,relaxation,wellness", "massage,therapy,calm", "beauty,spa,treatment", "wellness,retreat,peaceful"],
    "medical": ["doctor,medical,hospital", "healthcare,professional,clinic", "medical,team,care", "hospital,health,medicine"],
    "real estate": ["house,modern,architecture", "interior,luxury,home", "property,real,estate", "living,room,design"],
    "interior": ["interior,design,modern", "furniture,home,decor", "living,space,elegant", "home,decoration,style"],
    "education": ["education,students,learning", "classroom,school,teaching", "university,campus,study", "books,learning,knowledge"],
    "course": ["online,learning,laptop", "education,course,digital", "student,studying,desk", "elearning,digital,course"],
    "travel": ["travel,destination,adventure", "landscape,beautiful,nature", "tourism,city,explore", "travel,photography,world"],
    "hotel": ["hotel,luxury,room", "resort,pool,vacation", "hotel,lobby,elegant", "travel,accommodation,comfort"],
    "portfolio": ["designer,creative,workspace", "creative,studio,modern", "photographer,camera,art", "design,portfolio,work"],
    "photography": ["camera,photography,lens", "photo,shoot,studio", "photographer,nature,outdoor", "portrait,photography,light"],
    "music": ["music,studio,recording", "guitar,musician,performance", "concert,music,stage", "headphones,music,listening"],
    "gaming": ["gaming,computer,setup", "game,controller,neon", "esports,gaming,tournament", "game,developer,screen"],
    "finance": ["finance,investment,chart", "money,banking,professional", "stock,market,trading", "wealth,management,business"],
    "law": ["law,office,professional", "lawyer,justice,court", "legal,business,meeting", "attorney,desk,documents"],
    "default_hero": ["modern,business,professional", "office,team,success", "technology,innovation,future", "startup,growth,success"],
    "default_product": ["product,design,modern", "item,display,showcase", "product,photography,clean", "goods,retail,store"],
    "default_person": ["professional,portrait,business", "person,team,corporate", "headshot,professional,smile", "team,member,office"],
}

def extract_image_keywords(prompt: str, website_type: str) -> dict:
    p = prompt.lower()
    keywords = {"hero": None, "section": None, "card": None, "person": None}
    for topic, kw_list in IMAGE_KEYWORDS.items():
        if topic in p:
            if not keywords["hero"]:
                keywords["hero"] = kw_list[0]
            if not keywords["section"] and len(kw_list) > 1:
                keywords["section"] = kw_list[1]
            if not keywords["card"] and len(kw_list) > 2:
                keywords["card"] = kw_list[2]
            break
    if not keywords["hero"]:
        type_defaults = {
            "E-COMMERCE": "product,fashion,store",
            "RESTAURANT": "restaurant,food,dining",
            "PORTFOLIO": "creative,designer,workspace",
            "DASHBOARD": "office,technology,business",
            "SAAS LANDING PAGE": "technology,startup,modern",
        }
        keywords["hero"] = type_defaults.get(website_type, "business,modern,professional")
    if not keywords["section"]:
        keywords["section"] = keywords["hero"]
    if not keywords["card"]:
        keywords["card"] = keywords["hero"]
    keywords["person"] = "professional,portrait,person"
    return keywords


def get_photo_instructions(prompt: str, website_type: str) -> str:
    kw = extract_image_keywords(prompt, website_type)
    h = kw["hero"].replace(",", "%20").replace(" ", "%20")
    s = kw["section"].replace(",", "%20").replace(" ", "%20")
    c = kw["card"].replace(",", "%20").replace(" ", "%20")
    p = kw["person"].replace(",", "%20").replace(" ", "%20")
    return f"""
━━━ REAL PHOTOS β€” USE UNSPLASH (FREE, NO API KEY, ALWAYS LOADS) ━━━
URL FORMAT: https://source.unsplash.com/WIDTHxHEIGHT/?keyword,keyword&sig=N

Hero background (full-width behind text):
  style="background-image: url('https://source.unsplash.com/1600x900/?{h.replace(',','%2C')}&sig=1'); background-size: cover; background-position: center; background-repeat: no-repeat;"

Section/feature image:
  <img src="https://source.unsplash.com/800x500/?{s.replace(",","%2C")}&sig=2" class="w-full h-64 object-cover rounded-2xl" loading="lazy" decoding="async" alt="..." />

Card/product image:
  <img src="https://source.unsplash.com/600x500/?{c.replace(",","%2C")}&sig=3" class="w-full h-52 object-cover" loading="lazy" decoding="async" alt="..." />

Person/team avatar:
  <img src="https://source.unsplash.com/200x200/?{p.replace(",","%2C")}&sig=4" class="w-16 h-16 rounded-full object-cover" loading="lazy" decoding="async" alt="..." />

Change seed=1 seed=2 seed=3 etc for each image to get variety.

STRICT RULES:
- Use class NOT className on all img tags
- Use style="background-image: url('...')" NOT style={{{{...}}}}
- 6 to 8 images MINIMUM in the site β€” more is better
- EVERY product card, blog card, testimonial MUST have an image
- Hero MUST have background-image photo
- NEVER use placeholder.com or loremflickr β€” gray boxes kill design
- ALWAYS add loading="lazy" decoding="async" alt="description"
"""


# ─────────────────────────────────────────────────────────────────
# PYTHON-LEVEL SCRIPT INJECTION
# These scripts are GUARANTEED to be injected by Python.
# Even if the AI forgets them, the site will still work.
# ─────────────────────────────────────────────────────────────────

_NAVIGATE_SCRIPT = """
<script>
/* ── Multi-Page Router injected by BuildAI ── */
function navigate(page) {
  document.querySelectorAll('.page').forEach(function(p) {
    p.classList.remove('active');
    p.style.display = 'none';
  });
  var target = document.getElementById('page-' + page);
  if (target) {
    target.classList.add('active');
    target.style.display = 'block';
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
  document.querySelectorAll('[data-page]').forEach(function(link) {
    link.classList.toggle('active', link.dataset.page === page);
  });
  if (typeof AOS !== 'undefined') { AOS.refresh(); }
}
document.addEventListener('DOMContentLoaded', function() {
  var first = document.querySelector('.page');
  if (first) { navigate(first.id.replace('page-', '')); }
});
</script>"""

_INIT_SCRIPT = """
<script>
/* ── BuildAI Required Init Script ── */
if (typeof gsap !== 'undefined') {
  gsap.registerPlugin(ScrollTrigger);
  var heroEl = document.querySelector('.hero-content');
  if (heroEl) {
    gsap.from('.hero-content > *', {
      opacity: 0, y: 40, duration: 0.9, stagger: 0.12,
      ease: 'power2.out', delay: 0.15
    });
  }
}
if (typeof AOS !== 'undefined') {
  AOS.init({ duration: 750, once: true, offset: 60, easing: 'ease-out-cubic' });
}
/* Hamburger toggle */
var menuBtn = document.getElementById('menu-btn');
var mobileMenu = document.getElementById('mobile-menu');
if (menuBtn && mobileMenu) {
  menuBtn.addEventListener('click', function() { mobileMenu.classList.toggle('hidden'); });
}
/* Scroll-to-top */
var topBtn = document.getElementById('scroll-top');
if (topBtn) {
  window.addEventListener('scroll', function() {
    topBtn.style.opacity = window.scrollY > 400 ? '1' : '0';
    topBtn.style.pointerEvents = window.scrollY > 400 ? 'auto' : 'none';
  });
  topBtn.addEventListener('click', function() { window.scrollTo({ top: 0, behavior: 'smooth' }); });
}
/* FAQ accordion */
document.querySelectorAll('.faq-item').forEach(function(item) {
  var btn = item.querySelector('.faq-btn');
  var ans = item.querySelector('.faq-ans');
  var icon = item.querySelector('.faq-icon');
  if (btn && ans) {
    btn.addEventListener('click', function() {
      var open = !ans.classList.contains('hidden');
      document.querySelectorAll('.faq-ans').forEach(function(a) { a.classList.add('hidden'); });
      document.querySelectorAll('.faq-icon').forEach(function(i) { if (i) i.textContent = '+'; });
      if (!open) { ans.classList.remove('hidden'); if (icon) icon.textContent = 'Γ—'; }
    });
  }
});
/* Smooth scroll for anchor links */
document.querySelectorAll('a[href^="#"]').forEach(function(a) {
  a.addEventListener('click', function(e) {
    var href = this.getAttribute('href');
    if (href === '#') return;
    var t = document.querySelector(href);
    if (t) { e.preventDefault(); t.scrollIntoView({ behavior: 'smooth' }); }
  });
});
</script>"""


def inject_required_scripts(html: str, pages: list) -> str:
    """
    Python-level guarantee: inject navigate() and init scripts before </body>.
    Called on EVERY round output. Even if AI forgets these, the site works.
    """
    if not html or "</body>" not in html:
        return html

    to_inject = []

    # 1. navigate() β€” only for multi-page sites
    if pages and len(pages) > 1 and "function navigate" not in html:
        to_inject.append(_NAVIGATE_SCRIPT)
        print(f"[BuildAI] Injected navigate() for pages: {pages}")

    # 2. AOS.init() β€” CRITICAL: without this all data-aos elements are INVISIBLE forever
    if "AOS.init" not in html:
        to_inject.append(_INIT_SCRIPT)
        print("[BuildAI] Injected AOS/GSAP init script (was missing from AI output)")
    elif "gsap.registerPlugin" not in html and "gsap" in html:
        to_inject.append("""<script>
if(typeof gsap!=='undefined'){gsap.registerPlugin(ScrollTrigger);var h=document.querySelector('.hero-content');if(h)gsap.from('.hero-content > *',{opacity:0,y:40,duration:0.9,stagger:0.12,ease:'power2.out',delay:0.15});}
</script>""")

    if to_inject:
        injection = "\n".join(to_inject)
        html = html.replace("</body>", injection + "\n</body>", 1)

    return html

CDN_STACK = """
━━━ TECHNOLOGY STACK β€” VANILLA HTML + GSAP + AOS ━━━

PUT IN <head>:
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
  theme: {
    extend: {
      fontFamily: {
        display: ['Syne', 'system-ui', 'sans-serif'],
        sans: ['DM Sans', 'system-ui', 'sans-serif'],
        mono: ['JetBrains Mono', 'monospace'],
      },
      animation: {
        'fade-up': 'fadeUp 0.7s ease forwards',
        'fade-in': 'fadeIn 0.5s ease forwards',
        'float': 'float 4s ease-in-out infinite',
        'gradient': 'gradientFlow 6s ease infinite',
        'shimmer': 'shimmer 2s infinite',
        'spin-slow': 'spin 8s linear infinite',
      },
      keyframes: {
        fadeUp: { '0%': { opacity: '0', transform: 'translateY(32px)' }, '100%': { opacity: '1', transform: 'translateY(0)' } },
        fadeIn: { '0%': { opacity: '0' }, '100%': { opacity: '1' } },
        float: { '0%,100%': { transform: 'translateY(0)' }, '50%': { transform: 'translateY(-16px)' } },
        gradientFlow: { '0%,100%': { backgroundPosition: '0% 50%' }, '50%': { backgroundPosition: '100% 50%' } },
        shimmer: { '0%': { backgroundPosition: '-200% center' }, '100%': { backgroundPosition: '200% center' } },
      },
      backgroundSize: { '200%': '200%', '300%': '300%' },
    }
  }
}
</script>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700;800&family=DM+Sans:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="https://unpkg.com/aos@2.3.4/dist/aos.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>
<script src="https://unpkg.com/aos@2.3.4/dist/aos.js"></script>

━━━ DO NOT PUT ANY INIT SCRIPT β€” BuildAI injects it automatically ━━━

━━━ VANILLA JS RULES ━━━
- Pure HTML5 + CSS + vanilla JavaScript β€” NO React, NO Babel, NO JSX
- Use class NOT className; use for NOT htmlFor; inline style="..." NOT style={{}}
- All interactivity via vanilla JS addEventListener or onclick="..." on buttons
- GSAP and AOS will be initialized automatically β€” just use data-aos="fade-up" on elements
- Add data-aos="fade-up" to EVERY feature card, section header, testimonial, and content div
- Add data-aos-delay="0" "100" "200" for staggered grid items
- Hero section: wrap content in <div class="hero-content"> for GSAP animation
- Mobile hamburger: id="menu-btn" button + id="mobile-menu" div.hidden
- FAQ accordion: class="faq-item" > button.faq-btn + div.faq-ans.hidden + span.faq-icon
- Scroll-to-top: id="scroll-top" button with style="opacity:0"
- NEVER use bg-surface or bg-surface-2 β€” use bg-[#07080f] bg-[#0d0e1a] directly
- Images: use EXACT URLs from REAL PHOTOS section below β€” NEVER placeholder.com
- All images: loading="lazy" decoding="async" alt="description"
"""


# ─────────────────────────────────────────────────────────────────
# ELITE DESIGN SYSTEM β€” v7 UPGRADE
# ─────────────────────────────────────────────────────────────────

DESIGN_BIBLE = """
━━━ ELITE DESIGN SYSTEM v8 β€” VANILLA HTML ━━━

CSS CUSTOM PROPERTIES (add to <style> in <head>):
:root {
  --brand-500: #6366f1; --brand-600: #4f46e5; --brand-700: #4338ca;
  --surface: #0a0b14; --surface-2: #0d0e1a; --surface-3: #111327;
  --border: rgba(255,255,255,0.07); --border-brand: rgba(99,102,241,0.3);
}

TYPOGRAPHY:
- Hero: font-display text-5xl sm:text-7xl lg:text-[88px] font-bold tracking-[-3px] leading-[0.95] text-white
- Section title: font-display text-3xl sm:text-4xl lg:text-5xl font-bold tracking-tight
- Eyebrow: font-mono text-xs font-bold tracking-[0.25em] uppercase text-indigo-400

GRADIENT TEXT:
<span class="bg-gradient-to-r from-indigo-400 via-violet-300 to-cyan-400 bg-clip-text text-transparent">Text</span>

BUTTONS (vanilla HTML β€” use class NOT className):
Primary:
  <a href="#" onclick="navigate('page')" class="group relative inline-flex items-center gap-2 px-8 py-4 bg-indigo-600 hover:bg-indigo-500 text-white font-semibold rounded-2xl transition-all duration-200 hover:-translate-y-0.5 hover:shadow-[0_20px_40px_rgba(99,102,241,0.4)] active:scale-95 overflow-hidden cursor-pointer">
    <span class="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent translate-x-[-200%] group-hover:translate-x-[200%] transition-transform duration-700"></span>
    Button Text
  </a>
Secondary:
  <a href="#" class="px-8 py-4 border border-white/10 text-white font-semibold rounded-2xl hover:bg-white/5 hover:border-white/20 transition-all duration-200 backdrop-blur-sm cursor-pointer">Label</a>

CARDS (use class NOT className):
  <div class="relative bg-white/[0.03] backdrop-blur-sm border border-white/[0.07] rounded-3xl p-6 hover:-translate-y-1 hover:border-indigo-500/20 hover:bg-white/[0.05] transition-all duration-300 group overflow-hidden" data-aos="fade-up" data-aos-delay="0">

NAVBAR:
<nav class="fixed top-0 left-0 right-0 z-50 px-6 py-4 flex items-center justify-between backdrop-blur-2xl bg-black/50 border-b border-white/[0.06]">
  <a href="#" onclick="navigate('home')" class="font-display font-bold text-lg text-white">Logo</a>
  <div class="hidden md:flex items-center gap-8">
    <a href="#" data-page="home" onclick="navigate('home');return false;" class="nav-link text-gray-400 hover:text-white text-sm font-medium transition-colors cursor-pointer">Home</a>
    <a href="#" onclick="navigate('shop');return false;" class="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white text-sm font-semibold rounded-xl transition-colors cursor-pointer">Shop Now</a>
  </div>
  <button id="menu-btn" class="md:hidden flex flex-col justify-center items-center gap-1.5 w-9 h-9 cursor-pointer" aria-label="Menu">
    <span class="w-5 h-0.5 bg-gray-400 transition-all duration-200"></span>
    <span class="w-5 h-0.5 bg-gray-400 transition-all duration-200"></span>
    <span class="w-5 h-0.5 bg-gray-400 transition-all duration-200"></span>
  </button>
</nav>
<div id="mobile-menu" class="hidden fixed top-[72px] left-0 right-0 z-40 bg-black/95 backdrop-blur-2xl border-b border-white/[0.06] py-4 px-6 flex flex-col gap-4">
  <a href="#" onclick="navigate('home');return false;" class="text-gray-300 hover:text-white py-2 text-sm font-medium cursor-pointer">Home</a>
</div>

HERO (wrap ALL content in hero-content div for GSAP animation):
<section class="relative min-h-screen flex items-center justify-center text-center px-6 pt-20 overflow-hidden">
  <div class="absolute inset-0" style="background-image: url('URL'); background-size: cover; background-position: center;">
    <div class="absolute inset-0 bg-gradient-to-b from-black/60 to-black/90"></div>
  </div>
  <div class="absolute inset-0 overflow-hidden pointer-events-none">
    <div class="absolute top-1/4 left-1/4 w-[500px] h-[500px] bg-indigo-600/15 rounded-full blur-[120px]"></div>
    <div class="absolute bottom-1/4 right-1/4 w-[400px] h-[400px] bg-violet-600/10 rounded-full blur-[100px]"></div>
  </div>
  <div class="relative z-10 max-w-5xl mx-auto hero-content">
    <!-- eyebrow + h1 + p + buttons here β€” GSAP animates these -->
  </div>
</section>

SECTION HEADER:
<div class="text-center mb-16" data-aos="fade-up">
  <div class="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-indigo-500/10 border border-indigo-500/20 text-indigo-300 font-mono text-xs tracking-widest uppercase mb-6">✦ Label</div>
  <h2 class="font-display text-4xl lg:text-5xl font-bold text-white tracking-tight mb-4">Title</h2>
  <p class="text-gray-400 text-lg max-w-2xl mx-auto leading-relaxed">Subtitle</p>
</div>

FAQ ACCORDION (works with injected init script):
<div class="faq-item py-5 border-b border-white/[0.06]">
  <button class="faq-btn w-full flex justify-between items-center text-left cursor-pointer">
    <span class="font-semibold text-white">Question?</span>
    <span class="faq-icon text-indigo-400 text-xl font-light ml-4">+</span>
  </button>
  <div class="faq-ans hidden mt-3 text-gray-400 text-sm leading-relaxed">Answer.</div>
</div>

SCROLL-TO-TOP:
<button id="scroll-top" class="fixed bottom-6 right-6 z-50 w-10 h-10 bg-indigo-600 hover:bg-indigo-500 text-white rounded-full shadow-lg flex items-center justify-center transition-all duration-300" style="opacity:0;pointer-events:none">↑</button>

PRICING CARDS:
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 max-w-5xl mx-auto">
  <div class="bg-white/[0.03] border border-white/[0.07] rounded-3xl p-8" data-aos="fade-up" data-aos-delay="0">...</div>
  <div class="relative bg-indigo-600 rounded-3xl p-8 md:scale-105 shadow-[0_0_80px_rgba(99,102,241,0.3)]" data-aos="fade-up" data-aos-delay="100">
    <div class="absolute -top-3 left-1/2 -translate-x-1/2 px-4 py-1 bg-amber-400 text-black text-xs font-bold rounded-full">Most Popular</div>
  </div>
  <div class="bg-white/[0.03] border border-white/[0.07] rounded-3xl p-8" data-aos="fade-up" data-aos-delay="200">...</div>
</div>

FOOTER:
<footer class="bg-[#050608] border-t border-white/[0.05] pt-16 pb-8 px-6">
  <div class="max-w-6xl mx-auto">
    <div class="grid grid-cols-2 md:grid-cols-5 gap-8 mb-12">
      <div class="col-span-2"><!-- Brand + tagline + social --></div>
    </div>
    <div class="border-t border-white/[0.05] pt-6 text-center text-gray-600 text-sm">Β© 2025 Brand. All rights reserved.</div>
  </div>
</footer>
"""


# ─────────────────────────────────────────────────────────────────
# MANDATORY SECTIONS PER TYPE
# ─────────────────────────────────────────────────────────────────

SECTIONS_MAP = {
    "SAAS LANDING PAGE": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” sticky glassmorphic, logo (font-display), nav links, "Start free" CTA + mobile hamburger
2. Hero β€” full viewport mesh-gradient bg, eyebrow pill ("✦ Now powered by AI"), giant display headline with animated gradient text, 2-line subtext, 2 CTA buttons (primary + secondary), floating product screenshot with glow border + floating stat badges
3. Social proof β€” "Trusted by 10,000+ teams" + 6 real company name logos in muted grayscale
4. Features bento β€” "Built different" heading, BENTO GRID layout with 6 feature cells (1 large + 5 standard), each with icon box, title, 2-line description
5. How it works β€” "Simple as 1, 2, 3", 3 numbered steps with connecting line, icon + bold title + description + screenshot
6. Stats β€” 4 big numbers in dark row (users, revenue, countries, rating)
7. Testimonials β€” "Loved by builders worldwide", 3 card grid with stars + quote + avatar + name + company
8. Pricing β€” 3 tiers, middle card highlighted indigo with scale-105 + "Most Popular" badge, full feature list with checkmarks
9. FAQ β€” 6 questions with smooth accordion, max-w-2xl
10. Final CTA β€” dark gradient section, huge headline, email capture, "No credit card" note
11. Footer β€” 4-col links, social icons, copyright
""",
    "E-COMMERCE": """
MANDATORY SECTIONS IN THIS ORDER:
1. Announcement bar β€” promo text + dismiss button, indigo bg
2. Navbar β€” logo, search bar, cart icon (badge count), account, hamburger
3. Hero banner β€” full-bleed image bg + dark overlay, large headline, 2 CTAs (Shop Now / View Lookbook)
4. Categories β€” "Shop by Category", 4–6 category cards each with image + label overlay + hover zoom
5. Featured products β€” "Best Sellers", 4-col product grid; each card: image (hover zoom), wishlist heart, sale badge, brand name, product name, price + strikethrough, star rating, Add to Cart button
6. Flash sale β€” countdown timer (useEffect setInterval hours:mins:secs), 4 discounted products
7. Value props β€” 4 icons row (Free Shipping / Easy Returns / Secure Pay / 24/7 Support)
8. Brand story β€” split: image left + text right with "Our Story" + signature
9. Reviews β€” 3 customer cards with product photo, stars, quote, reviewer name + date
10. Newsletter β€” "Get 15% off", email input + submit
11. Footer β€” links, payment icons, social, copyright
""",
    "RESTAURANT": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” logo, nav links, "Reserve a Table" warm CTA, phone number
2. Hero β€” full-screen image bg + dark overlay, restaurant name + tagline, 2 CTAs (View Menu / Book Table), floating badge ("Michelin Recommended")
3. Story β€” split: chef photo left + story text right, signature, award badges
4. Menu β€” "Our Menu", tab switcher (Starters/Mains/Desserts/Drinks with useState), menu items in grid: image + name + description + price
5. Gallery β€” "From Our Kitchen", masonry-style 3-col grid with varied heights, food + ambiance photos with hover overlay
6. Reservation form β€” date picker, time select, party size, name, email, notes, CTA button
7. Chef special β€” featured dish card: large image + ingredient tags + story text
8. Reviews β€” 3 Google-style cards: stars + quote + reviewer + occasion
9. Location & Hours β€” address + opening hours table (day + time) + map placeholder
10. Footer β€” social, newsletter, copyright
""",
    "PORTFOLIO": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” name/monogram, nav (Work/About/Skills/Contact), "Hire Me" CTA
2. Hero β€” split or centered; name + role with typewriter effect (useEffect + setInterval), tagline, available indicator (green pulse dot + "Open to work"), 2 CTAs + social links
3. Skills β€” horizontal scrollable chips, each with emoji/icon + skill name, show 15-20 skills
4. Work β€” "Selected Work", 2-col grid; each project: image with hover overlay showing title + tags + visit links
5. About β€” photo + bio + experience timeline with years
6. Services β€” 3 cards: icon + service + description + included items
7. Testimonials β€” 2–3 client quotes: avatar + name + company + quote
8. Process β€” "How I Work", 4 numbered steps with icon + title + description
9. Contact β€” "Let's Create Together", email + social icons, contact form (name/email/message/send)
10. Footer β€” minimal: name + copyright + social
""",
    "DASHBOARD": """
MANDATORY LAYOUT:
Fixed sidebar (w-64) + scrollable main area

SIDEBAR:
- Logo + app name at top
- Nav groups: Overview / Analytics / Projects / Team / Settings
- Each item: icon + label, active state highlighted
- User profile card at bottom (avatar + name + email + sign out)

TOPBAR (sticky within main):
- Page title left
- Search center
- Notifications bell + avatar right

MAIN CONTENT SECTIONS:
1. Welcome banner β€” "Good morning, [Name]" + date + quick action buttons
2. KPI cards β€” 4 cards: Total Revenue / Active Users / Conversion Rate / Monthly Growth
   Each: icon box + big number + % change badge (green up / red down) + sparkline SVG
3. Charts row β€” large area/line chart (col-span-2) + donut/pie chart (col-span-1)
4. Recent activity table β€” headers + 6 rows with avatar + name + action + amount + status badge
5. Bottom row β€” activity feed (left) + top performers list (right)

MOBILE: sidebar collapses to bottom tab bar on small screens
""",
    "FITNESS & WELLNESS": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” logo, nav links (Classes/Trainers/Pricing/Contact), "Join Now" CTA
2. Hero β€” full-screen gym/yoga image bg, dark overlay, bold headline, 2 CTAs (Free Trial / View Classes), floating badge ("1000+ Members")
3. Stats β€” 4 big numbers: Members / Trainers / Classes/Week / Years Open
4. Classes β€” tab switcher (Strength/Cardio/Yoga/HIIT), class cards: image + name + trainer + duration + spots left + book button
5. Trainers β€” "Expert Trainers", 4-col grid: photo + name + specialty + certifications + social links
6. Features/Amenities β€” bento grid: 6 facility features with icons (Pool, Sauna, 24/7 Access, etc.)
7. Transformation β€” before/after slider or 3 success story cards with photos + stats
8. Pricing β€” 3 tiers (Basic/Pro/Elite) with monthly/annual toggle, feature lists
9. Schedule β€” weekly class timetable grid with time slots + class names + trainer
10. Testimonials β€” 3 member cards: photo + stars + quote + weight lost / muscle gained
11. Trial CTA β€” "Start Your 7-Day Free Trial", email capture, no credit card needed
12. Footer β€” links, social, app store badges, copyright
""",
    "MUSIC & ARTIST": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” artist name/logo, nav (Music/Tour/Merch/About), "Stream Now" CTA
2. Hero β€” full-screen dark concert/studio image bg, artist name in massive display font, latest release badge, 2 CTAs (Listen Now / Watch Video), floating audio waveform decoration
3. Latest Release β€” featured album/single card: large artwork + title + tracklist preview + streaming platform buttons (Spotify/Apple Music/YouTube)
4. Discography β€” "Music" section, grid of album cards: artwork + title + year + play icon hover
5. Tour Dates β€” "On Tour", list/table of upcoming shows: date + city + venue + ticket link button
6. Music Video β€” embedded YouTube player or large thumbnail with play overlay
7. Gallery β€” "In the Studio / On Stage", masonry photo grid
8. Merch β€” 4-product grid: item photo + name + price + "Shop Now"
9. About β€” artist bio split: moody photo left + story right, stats (streams/followers/awards)
10. Press Quotes β€” 3 media mention cards: outlet logo + quote
11. Newsletter β€” "Join the Fan Club", email capture + exclusive content promise
12. Footer β€” streaming links, social icons, copyright
""",
    "PHOTOGRAPHY": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” photographer name, nav (Portfolio/Services/About/Contact), minimal style
2. Hero β€” full-screen stunning photo bg, dark overlay, name + tagline, "View Portfolio" CTA
3. Portfolio β€” tab filter (Weddings/Portraits/Commercial/Nature), masonry grid with hover overlay + zoom icon
4. Featured Work β€” 3 large showcase images with story behind each shoot
5. Services β€” 3 cards: Wedding / Portrait / Commercial β€” icon + description + starting price
6. Process β€” "How It Works", 4 steps: Inquiry β†’ Booking β†’ Shoot β†’ Delivery
7. Testimonials β€” 3 client reviews with couple/subject photos + stars + quote
8. About β€” photographer bio: portrait photo + story + equipment used + awards
9. Pricing β€” packages table: Basic/Standard/Premium with what's included
10. Contact β€” booking form: name + email + event date + type + message + submit
11. Footer β€” social, Instagram grid preview (6 photos), copyright
""",
    "TRAVEL & HOSPITALITY": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” logo, nav (Destinations/Hotels/Tours/About), "Book Now" CTA
2. Hero β€” full-screen stunning destination image, search bar (destination + dates + guests), tagline
3. Featured Destinations β€” "Popular Destinations", 6-card grid: full-bleed image + overlay + location name + price from
4. Tours & Packages β€” "Best Packages", 3 card row: image + badge + name + duration + highlights + price + Book button
5. Why Choose Us β€” 4 feature icons: Expert Guides / Best Price / 24/7 Support / Flexible Booking
6. Hotels β€” "Top Rated Hotels", 3 hotel cards: photo + name + location + stars + amenity chips + price/night
7. Testimonials β€” 3 traveler cards: destination photo + stars + quote + traveler name + trip type
8. Gallery β€” "Unforgettable Moments", masonry grid of destination/experience photos
9. Newsletter β€” "Get Exclusive Deals", email capture + promise of early access
10. Footer β€” destinations links, company links, social, trust badges, copyright
""",
    "CRYPTO & WEB3": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” logo + token name, nav (About/Tokenomics/Roadmap/Team), "Connect Wallet" CTA
2. Hero β€” dark mesh gradient bg, massive headline, price ticker badge, 2 CTAs (Buy Token / Whitepaper), floating coin/chart animation, live market stats (price/market cap/volume)
3. Stats β€” 4 live-style metrics: Total Supply / Holders / Trading Volume / Market Cap
4. About β€” "What is [Project]", split: animated diagram left + description right, key USPs
5. Tokenomics β€” pie chart visualization + allocation breakdown (Team/Dev/Community/Liquidity)
6. How It Works β€” 3 steps: Connect Wallet β†’ Stake/Swap β†’ Earn Rewards
7. Roadmap β€” horizontal or vertical timeline: Q1-Q4 phases with completed/upcoming badges
8. Features β€” bento grid: 6 protocol features with icons (Security/Speed/Decentralized/etc.)
9. Team β€” 4-col grid: avatar + name + role + Twitter/LinkedIn links
10. Partners β€” "Backed By", logo strip of investors/partners in muted grayscale
11. FAQ β€” 6 questions accordion about tokenomics, staking, security
12. Footer β€” links, audit report badge, legal disclaimer, social icons
""",
    "HEALTHCARE": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” clinic name/logo, nav (Services/Doctors/About/Contact), "Book Appointment" CTA, phone number
2. Hero β€” clean light or dark image bg, headline emphasizing care/trust, 2 CTAs (Book Now / Our Services), trust badges (Certified/Licensed/Years of Experience)
3. Services β€” "Our Specialties", 6-card grid: icon + service name + short description + Learn More link
4. Doctors β€” "Meet Our Team", 4-col grid: professional photo + name + specialty + credentials + Book button
5. Stats β€” 4 numbers: Patients Treated / Years Experience / Specialist Doctors / 5-Star Reviews
6. How It Works β€” 3 steps: Book Online β†’ Consultation β†’ Treatment Plan
7. Testimonials β€” 3 patient cards: avatar + stars + condition treated + quote
8. Insurance β€” "We Accept Your Insurance", logo grid of accepted providers
9. Appointment Form β€” large form: name + phone + service + preferred date + message + submit
10. Location & Hours β€” address + hours table + map embed placeholder
11. Footer β€” HIPAA badge, social, links, copyright
""",
    "EDUCATION": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” institution/platform logo, nav (Courses/Instructors/Pricing/About), "Start Learning" CTA
2. Hero β€” engaging image or illustration bg, headline about transformation, search bar for courses, 3 stat badges (Students/Courses/Rating)
3. Featured Courses β€” "Top Courses", 4-col grid: thumbnail + category badge + title + instructor + rating stars + student count + price
4. Categories β€” "Browse by Topic", 8 category pills/cards with icon + label + course count
5. How It Works β€” 3 steps: Choose Course β†’ Learn at Your Pace β†’ Get Certificate
6. Instructors β€” "World-Class Instructors", 4 cards: photo + name + specialty + rating + students taught
7. Stats β€” 4 big numbers: Students / Courses / Instructors / Countries
8. Testimonials β€” 3 student success cards: photo + name + career change + quote
9. Pricing β€” Free/Pro/Team tiers with feature lists
10. Certificate β€” "Earn Recognized Certificates", mockup + employer logos who accept them
11. FAQ β€” 5 questions accordion
12. Footer β€” links, social, app store badges, copyright
""",
    "REAL ESTATE": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” agency name/logo, nav (Buy/Sell/Rent/Agents), "List Your Property" CTA, phone
2. Hero β€” full-screen luxury property image, prominent search bar (location + type + price range), tagline
3. Featured Listings β€” "Premium Properties", 3-col grid: photo + price + beds/baths/sqft + location + "View Details" button
4. Why Us β€” 4 feature cards: icon + stat + description (Properties Sold / 5-Star Reviews / Years / Agents)
5. Property Types β€” tab filter (Homes/Apartments/Commercial/Land) + filtered card grid
6. Neighborhood Guide β€” 3 area cards: aerial/street photo + name + avg price + walkability + highlights
7. Agents β€” "Our Expert Agents", 4 cards: professional photo + name + area specialty + sales count + contact button
8. Testimonials β€” 3 buyer/seller success stories with property photo + quote + timeline
9. Market Stats β€” "Current Market Trends", 3 chart-style cards with price trends/inventory/days on market
10. Contact/Valuation β€” "Get Your Free Home Valuation", form: address + property type + contact info
11. Footer β€” office locations, social, realtor badge, copyright
""",
    "CREATIVE AGENCY": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” agency name, nav (Work/Services/About/Blog), "Start a Project" CTA
2. Hero β€” bold editorial design, large agency statement headline, reel/showreel thumbnail with play button, 2 CTAs
3. Clients β€” "Brands We've Worked With", scrolling logo marquee of 10+ brand names
4. Work β€” "Selected Projects", 2-col asymmetric grid: project image + hover overlay with title + category + view link
5. Services β€” "What We Do", 3 cards: Brand Identity / Web Design / Campaign Strategy β€” with process steps
6. Stats β€” 4 metrics: Projects Completed / Clients / Countries / Awards Won
7. Process β€” "How We Work", 4 phases: Discover β†’ Strategy β†’ Create β†’ Launch
8. Team β€” "The Humans Behind the Work", 4-col grid: candid photo + name + role
9. Testimonials β€” 3 client testimonials: company logo + quote + client name + role
10. Blog/Insights β€” 3 article cards: image + category + title + read time + date
11. Contact/CTA β€” "Let's Build Something Great", inquiry form: name + company + budget + project type
12. Footer β€” social, email, phone, awards/certifications, copyright
""",
    "STARTUP": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” product logo, nav links, "Get Early Access" CTA
2. Hero β€” mesh gradient bg, product name + one-liner value prop, email waitlist capture, floating product screenshot with glow, social proof badge ("2,000+ on waitlist")
3. Problem β†’ Solution β€” "The Old Way vs The New Way", side-by-side comparison
4. Features β€” bento grid: 6 core product features with icons + title + description
5. How It Works β€” 3-step walkthrough with screenshot/illustration for each step
6. Social Proof β€” press mentions (TechCrunch/ProductHunt/Forbes logos) + user count
7. Testimonials β€” 3 beta user cards: avatar + name + company + quote
8. Pricing β€” 3 tiers with "Launch pricing" badge, feature lists
9. FAQ β€” 5 questions about product, pricing, launch date
10. Team β€” 4 founder/team cards: photo + name + role + LinkedIn
11. Final CTA β€” "Join the Waitlist", email capture + launch date countdown
12. Footer β€” social, legal links, copyright
""",
    "BLOG & MEDIA": """
MANDATORY SECTIONS IN THIS ORDER:
1. Navbar β€” publication name/logo, nav (Topics/Authors/Newsletter/About), "Subscribe" CTA
2. Hero β€” featured article: large image + category badge + headline + author + read time + "Read Now"
3. Latest Articles β€” "Latest Stories", 3-col grid: thumbnail + category + title + excerpt + author avatar + date
4. Topics β€” "Browse by Topic", 8 pill/card categories with article count
5. Featured Author β€” author spotlight: photo + bio + article count + follow button
6. Newsletter β€” "Don't Miss a Story", email capture + subscriber count
7. Popular Articles β€” "Most Read", sidebar-style list with ranking numbers + thumbnails
8. Video/Podcast β€” "Watch & Listen", 3 media cards with thumbnails + duration + play icon
9. More Articles β€” "You Might Also Like", 3 more article cards
10. Footer β€” topic links, social, RSS feed, legal, copyright
"""
}


# ─────────────────────────────────────────────────────────────────
# SYSTEM PROMPTS
# ─────────────────────────────────────────────────────────────────

# ─────────────────────────────────────────────────────────────────
# AUTO DESIGN.MD SCANNER
# ─────────────────────────────────────────────────────────────────
_DESIGN_CACHE = {}
_DESIGN_INDEX = []
_DESIGN_BUILT = False

_BUILTIN_SKILLS = {
    "glassmorphism.md": "# Glassmorphism\nGlass cards: backdrop-filter:blur(20px), bg:rgba(255,255,255,0.04), border:rgba(255,255,255,0.08). Frosted nav. Keywords: glass frosted blur premium modern",
    "dark-saas.md": "# Dark SaaS\nBase #07080f, sections #0d0e1a, cards #111327. Accent indigo #6366f1. Bento grid. Gradient hero text. Stat badges. Keywords: saas startup landing dark tech software app",
    "ecommerce.md": "# E-Commerce\nAnnouncement bar top. Product grid hover zoom. Wishlist heart button. Cart drawer slide-in. Size/color selector. Flash sale countdown timer. Category filter tabs. Quick view modal. Keywords: shop store ecommerce product cart buy sell fashion retail",
    "restaurant.md": "# Restaurant\nFull bleed hero dark overlay. Tab menu (Starters/Mains/Desserts). Chef story split. Masonry food gallery. Reservation form. Keywords: restaurant cafe food menu dining chef kitchen bistro",
    "portfolio.md": "# Portfolio\nTypewriter role animation. Open-to-work badge. Skill chips scroll. Project grid hover overlay + links. Experience timeline. Keywords: portfolio designer developer creative freelance resume",
    "animations.md": "# Animations\nIntersectionObserver reveal every section. Stagger i*0.1s delays. Floating blur orbs. Cards hover:-translate-y-1. Gradient text animation. Shimmer CTAs. Keywords: animation scroll reveal motion interactive",
    "bento-grids.md": "# Bento Grid\n6-col grid. 1 large card col-span-4 + small cells col-span-2. Each: icon+title+desc+hover glow. Keywords: bento grid layout features cards dashboard",
    "pricing.md": "# Pricing\n3 tiers. Middle: bg-indigo-600 scale-105 shadow glow Most Popular badge amber. Feature checklist. Keywords: pricing plans tiers subscription billing saas",
}

def _extract_design_keywords(fname: str, raw: str) -> set:
    """
    Smart keyword extractor that reads the Overview + section headers
    from design .md files β€” not just the first 500 chars.
    """
    kw = set()
    # Always include filename words (e.g. flip7, card, game, feedloop, retro)
    kw |= set(fname.lower().replace("-", " ").replace("_", " ").replace(".md", "").split())

    lines = raw.splitlines()
    in_overview = False
    overview_lines = []
    for line in lines:
        stripped = line.strip()
        # Grab section headers as keywords (## Colors β†’ "colors", ## Typography β†’ "typography")
        if stripped.startswith("## "):
            section_name = stripped[3:].lower()
            kw |= set(section_name.split())
            in_overview = (section_name == "overview")
            continue
        # Grab the title (#) as keywords
        if stripped.startswith("# ") and not stripped.startswith("## "):
            kw |= set(stripped[2:].lower().split())
        # Collect overview section lines (most descriptive use-case text)
        if in_overview and stripped and not stripped.startswith("#"):
            overview_lines.append(stripped.lower())
            if len(overview_lines) >= 10:   # cap at 10 lines
                in_overview = False

    # All words from overview section β€” this is where "social media feed", "card game", "retro", "playful" etc live
    for line in overview_lines:
        kw |= set(line.replace(",", " ").replace(".", " ").replace("-", " ").split())

    # Also grab words from first 1500 chars as a safety net
    kw |= set(raw[:1500].lower().replace("-", " ").split())

    # Remove noise words
    noise = {"the","and","for","with","its","are","not","this","that","from","into","they","use",
             "add","can","has","all","any","but","our","you","more","each","will","been","have",
             "your","used","both","very","also","only","when","then","over","into","it","is","in",
             "of","to","a","an","at","by","as","on","or","be","do","so","if","we","he","she"}
    kw -= noise
    # Keep words that are at least 3 chars
    kw = {w for w in kw if len(w) >= 3}
    return kw


def _extract_useful_content(raw: str) -> str:
    """
    Extract only the AI-actionable sections from a design .md file:
    Colors, Typography, Key Components, Animations, Do's and Don'ts.
    Skips Spacing/Border Radius tables to save tokens.
    Caps at ~2500 chars so 3 skills = ~7500 chars in the prompt.
    """
    KEEP_SECTIONS = {"overview", "colors", "colour", "typography", "components",
                     "animations", "animation", "do's and don'ts", "dos and don'ts",
                     "buttons", "cards", "elevation", "key components"}
    SKIP_SECTIONS = {"spacing", "border radius", "grid", "breakpoints", "icons"}

    lines = raw.splitlines()
    result_lines = []
    # Always keep the title
    if lines and lines[0].startswith("# "):
        result_lines.append(lines[0])

    current_keep = True  # keep overview by default
    for line in lines[1:]:
        stripped = line.strip()
        if stripped.startswith("## "):
            section_name = stripped[3:].lower()
            if any(s in section_name for s in SKIP_SECTIONS):
                current_keep = False
            elif any(s in section_name for s in KEEP_SECTIONS):
                current_keep = True
            else:
                current_keep = True  # keep unknown sections by default
        if current_keep:
            result_lines.append(line)

    content = "\n".join(result_lines)
    return content[:2500]  # hard cap to protect prompt budget


def _build_design_index():
    global _DESIGN_CACHE, _DESIGN_INDEX, _DESIGN_BUILT
    if _DESIGN_BUILT:
        return
    _DESIGN_BUILT = True
    # Always load built-ins first
    for fname, content in _BUILTIN_SKILLS.items():
        fp = f"__builtin__/{fname}"
        _DESIGN_CACHE[fp] = content
        kw = _extract_design_keywords(fname, content)
        _DESIGN_INDEX.append((fp, fname, kw))

    # Scan disk
    script_dir = os.path.dirname(os.path.abspath(__file__))
    cwd = os.getcwd()
    print(f"[BuildAI] Scanner cwd={cwd}")
    disk_found = 0
    checked = []

    # Explicitly check designs/ folder at all likely paths
    for designs_path in ["./designs", "/home/user/app/designs",
                         os.path.join(cwd, "designs"), os.path.join(script_dir, "designs")]:
        if os.path.isdir(designs_path):
            md_files = [f for f in os.listdir(designs_path) if f.endswith(".md")]
            print(f"[BuildAI] βœ“ designs/ at {designs_path} β€” {len(md_files)} .md files")
        else:
            print(f"[BuildAI] βœ— designs/ not at {designs_path}")

    for base in [script_dir, cwd, "/home/user/app", "/app"]:
        for sub in ["designs", "skills", "design_skills", ""]:
            candidate = os.path.join(base, sub) if sub else base
            if candidate in checked: continue
            checked.append(candidate)
            if not os.path.isdir(candidate): continue
            for dirpath, dirnames, filenames in os.walk(candidate):
                dirnames[:] = [d for d in dirnames
                               if not d.startswith(".") and d not in ("__pycache__", ".git", "node_modules")]
                for fname in filenames:
                    if not fname.lower().endswith(".md"): continue
                    fp = os.path.join(dirpath, fname)
                    if fp in _DESIGN_CACHE: continue
                    try:
                        raw = open(fp, encoding="utf-8", errors="ignore").read()
                        if len(raw) < 30: continue
                        # Store only the useful extracted content (saves prompt tokens)
                        _DESIGN_CACHE[fp] = _extract_useful_content(raw)
                        kw = _extract_design_keywords(fname, raw)
                        _DESIGN_INDEX.append((fp, fname, kw))
                        disk_found += 1
                    except Exception as e:
                        print(f"[BuildAI] Error reading {fp}: {e}")

    total = len(_BUILTIN_SKILLS) + disk_found
    print(f"[BuildAI] Design index: {total} files ({len(_BUILTIN_SKILLS)} built-in + {disk_found} from disk)")


def get_design_skills(prompt: str, website_type: str) -> str:
    _build_design_index()
    if not _DESIGN_INDEX: return ""

    prompt_clean = prompt.lower().replace("-", " ").replace(",", " ")
    pw = set(prompt_clean.split())
    ww = set(website_type.lower().replace("&", "").replace("-", " ").split())

    # Score each design file
    scored = []
    for fp, fn, kw in _DESIGN_INDEX:
        score = 0
        # Prompt word match: 3 pts each
        score += sum(3 for w in pw if len(w) > 2 and w in kw)
        # Website type match: 5 pts each (stronger signal)
        score += sum(5 for w in ww if w in kw)
        # Bonus: exact 2-word phrase match in filename (e.g. "card game" in "flip7-card-game")
        fn_clean = fn.lower().replace("-", " ").replace("_", " ")
        for w in pw:
            if len(w) > 4 and w in fn_clean:
                score += 8   # strong bonus for filename hit
        scored.append((score, fp, fn))

    scored = [(s, fp, fn) for s, fp, fn in scored if s > 0]
    scored.sort(key=lambda x: -x[0])
    top = scored[:3]

    # If nothing matched, pick 1 animations skill + 1 random (keep it lean)
    if not top:
        import random
        fallbacks = [(0, fp, fn) for fp, fn, _ in _DESIGN_INDEX
                     if "animation" in fn.lower() or "dark" in fn.lower()]
        rest = [(0, fp, fn) for fp, fn, _ in _DESIGN_INDEX if (0, fp, fn) not in fallbacks]
        top = (fallbacks[:1] + random.sample(rest, min(1, len(rest))))[:2]

    result = ""
    for s, fp, fn in top:
        ct = _DESIGN_CACHE.get(fp, "")
        if ct:
            result += f"\n\n### Apply design patterns from: {fn}\n{ct}"
            print(f"[BuildAI] Design skill: {fn} (score={s})")

    if not result:
        return ""

    return (
        f"\n━━━ DESIGN SKILLS β€” EXTRACT COLORS, COMPONENTS & ANIMATIONS ━━━"
        f"{result}"
        f"\n━━━ Use the above colors, typography, component patterns, and animations as inspiration. "
        f"Adapt them to the user's brief β€” do NOT blindly copy. Translate rpx to px/rem for web. ━━━\n"
    )


def get_builder_prompt(ref_content: str, website_type: str, prompt: str = "", design_skills: str = "") -> str:
    sections = SECTIONS_MAP.get(website_type, SECTIONS_MAP["SAAS LANDING PAGE"])
    photo_instructions = get_photo_instructions(prompt, website_type)

    ref_section = ""
    if ref_content:
        ref_section = f"""
━━━ DESIGN REFERENCE β€” STUDY AND ADAPT ━━━
Learn the spacing rhythm, color tokens, animation approach, and component patterns.
Adapt these to the user's specific brand β€” do NOT copy verbatim.

{ref_content[:5000]}
━━━ END REFERENCE ━━━
"""

    return f"""You are a world-class senior frontend engineer who has shipped production code at Stripe, Linear, Vercel, and Loom. You build websites so visually stunning they go viral on Twitter. Your work is indistinguishable from Lovable, v0.dev, or Framer β€” except yours is BETTER.

You are building a {website_type} right now.

{CDN_STACK}

{design_skills}

{sections}

{ref_section}

{photo_instructions}

━━━ QUALITY MANDATE (10 rules) ━━━
1. Return ONLY raw HTML from <!DOCTYPE html> to </html>. NOTHING else. No markdown. No backticks.
2. Output MUST end with </html> β€” NEVER truncate mid-code. Close every tag.
3. EVERY mandatory section listed above MUST exist β€” no skipping, no "<!-- more here -->".
4. Dark theme: bg-[#07080f] base, bg-[#0d0e1a] alternate sections.
5. Typography: Syne (font-display) for headlines, DM Sans (font-sans) for body.
6. Hero must be breathtaking β€” mesh gradient bg, massive headline, floating orb blobs.
7. Every card must have hover state: hover:-translate-y-1 + border color change or glow.
8. useReveal (IntersectionObserver) on every section for scroll animations.
9. Working JS: hamburger toggle, FAQ accordion, scroll-to-top, smooth scroll, form handlers.
10. Real copy everywhere β€” zero lorem ipsum. Real brand names, real prices, real stats."""


PHOTO_SYSTEM = """
Use Unsplash for ALL images (free, no API key, always loads in iframes):
URL FORMAT: https://source.unsplash.com/WIDTHxHEIGHT/?keyword,keyword&sig=N

Examples:
- Hero bg: style="background-image: url('https://source.unsplash.com/1600x900/?television,modern,dark&sig=1'); background-size: cover; background-position: center;"
- Product img: <img src="https://source.unsplash.com/800x600/?product,electronics&sig=2" class="w-full h-64 object-cover rounded-2xl" loading="lazy" decoding="async" alt="..." />
- Card img: <img src="https://source.unsplash.com/600x500/?technology,device&sig=3" class="w-full h-52 object-cover" loading="lazy" decoding="async" alt="..." />
- Person: <img src="https://source.unsplash.com/200x200/?person,portrait&sig=4" class="w-16 h-16 rounded-full object-cover" loading="lazy" decoding="async" alt="..." />

Rules:
- Use class NOT className on img tags
- Use style="background-image: url('...')" NOT style={{...}} on divs
- Change sig=1 sig=2 sig=3 for every image (gives different photos)
- Minimum 8 images per page
- NEVER use placeholder.com, loremflickr, or pollinations.ai (they fail in iframes)
"""

REVIEWER_PROMPT = """You are a world-class design director at a top-tier product studio. Your job: take a good website and make it extraordinary β€” Stripe/Linear/Vercel caliber.

OUTPUT RULES:
1. Return ONLY the complete improved HTML. Nothing else. No backticks.
2. KEEP ALL sections and images. Only elevate β€” never remove.
3. PRESERVE the vanilla HTML structure β€” keep all section ids, keep navigate() calls, keep data-page attributes.

{DESIGN_BIBLE}

{DESIGN_SKILLS_PLACEHOLDER}

{PHOTO_SYSTEM}

━━━ YOUR ENHANCEMENT CHECKLIST ━━━

TYPOGRAPHY UPGRADE:
β–‘ Hero headline must be MASSIVE (text-7xl lg:text-[96px] font-bold) β€” if it doesn't feel oversized, go bigger
β–‘ Use font-display class on all headlines (Syne font)
β–‘ Gradient text on main hero headline β€” animated gradientFlow
β–‘ Eyebrow labels use font-mono tracking-widest uppercase text-indigo-400

VISUAL HIERARCHY:
β–‘ Hero is the most impressive thing on the page β€” period
β–‘ Strong contrast between sections (alternate bg-[#07080f] and bg-[#0d0e1a])
β–‘ Section headers centered with eyebrow label + large title + muted subtitle
β–‘ Generous white space β€” padding on sections should be py-28 lg:py-36

ANIMATIONS β€” NON-NEGOTIABLE:
β–‘ useReveal hook (IntersectionObserver) on EVERY section
β–‘ Staggered animation delays on grid items (i * 0.1s)
β–‘ Hero content animates in on mount (useEffect)
β–‘ Cards: hover:-translate-y-1 + hover:border-indigo-500/20
β–‘ CTA buttons have shimmer/shine effect on hover
β–‘ Floating orb blobs behind hero (blur-[120px] large circles)

BENTO GRID FEATURES:
β–‘ Features section uses bento grid, NOT just a uniform 3-col grid
β–‘ One large featured card + smaller cells

SOCIAL PROOF:
β–‘ Hero has "Join 25,000+ teams" badge
β–‘ Real company names in trust bar
β–‘ Specific metrics with decimal places (not "many" but "14,832")
β–‘ Star ratings on ALL testimonials

PREMIUM DETAILS:
β–‘ Gradient border on highlighted pricing card
β–‘ Scroll-to-top button (fixed, bottom-right)
β–‘ Active anchor links with smooth scroll behavior
β–‘ FAQ accordion (useState) smooth expand/collapse
β–‘ Input focus rings (ring-2 ring-indigo-500/50)
β–‘ All interactive elements: cursor-pointer

MOBILE:
β–‘ All grids: grid-cols-1 sm:grid-cols-2 lg:grid-cols-3
β–‘ Hamburger with animated lines (rotate on open)
β–‘ No horizontal overflow
β–‘ Tap targets at least 44px height

{CDN_STACK}"""


POLISHER_PROMPT = """You are the creative director doing the final QA pass before launch. Make it flawless.

OUTPUT RULES:
1. Return ONLY the final complete HTML. Nothing else.
2. Do NOT remove anything. Only polish.

{PHOTO_SYSTEM}

━━━ FINAL POLISH CHECKLIST ━━━

SEO + META:
β–‘ <title> specific, compelling, under 60 chars
β–‘ <meta name="description"> under 160 chars
β–‘ <meta property="og:title"> and <meta property="og:description">
β–‘ <link rel="icon"> emoji favicon
β–‘ <meta name="theme-color"> matching brand color (#6366f1)
β–‘ <meta name="viewport" content="width=device-width, initial-scale=1.0">

MICRO-INTERACTIONS:
β–‘ Nav links: underline slide-in on hover via CSS
β–‘ Feature icons: scale on card hover (transition in CSS, applied via group)
β–‘ CTA primary button: shimmer overlay on hover
β–‘ All interactive elements have cursor-pointer
β–‘ Buttons: active:scale-95 press feedback

VISUAL FINAL TOUCHES:
β–‘ Color palette consistent across ALL sections
β–‘ No section looks out of place
β–‘ Fonts loading correctly from Google Fonts
β–‘ Images all have loading="lazy" decoding="async" and alt text
β–‘ CSS custom properties in :root are complete

JAVASCRIPT:
β–‘ Hamburger toggle works flawlessly
β–‘ FAQ accordion opens/closes smoothly
β–‘ Scroll-to-top shows at 300px and works
β–‘ Smooth scroll on all anchor links
β–‘ No console errors from React
β–‘ No className in HTML (use class). No React or JSX anywhere.

PERFORMANCE:
β–‘ will-change: transform on animated elements
β–‘ Images have loading="lazy" and decoding="async"
β–‘ No unused CDN imports

FOOTER FINAL:
β–‘ Dark bg (#050608 or #07080f)
β–‘ 3-4 link columns
β–‘ Social icons with hover color
β–‘ Copyright with current year
β–‘ Brief brand tagline

{CDN_STACK}"""


# ─────────────────────────────────────────────────────────────────
# API CALLERS
# ─────────────────────────────────────────────────────────────────

async def call_cerebras(system_role: str, user_message: str, previous_code: str = "") -> str:
    """Cerebras β€” ultra-fast inference (1000+ tokens/sec). PRIMARY generator."""
    api_key = os.environ.get("CEREBRAS_API_KEY", "")
    if not api_key:
        print("[BuildAI] No CEREBRAS_API_KEY β€” fallback Gemini")
        return await call_gemini(system_role, user_message, previous_code)
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode to improve:\n\n{previous_code[:10000]}"
    # Try best model first, then fall back to smaller one
    for model in ["llama-3.3-70b", "llama3.3-70b", "llama3.1-8b"]:
        try:
            payload = {
                "model": model,
                "messages": [{"role": "system", "content": system_role}, {"role": "user", "content": full_message}],
                "max_tokens": 16000,
                "temperature": 0.65,
            }
            headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
            async with httpx.AsyncClient(timeout=120.0) as client:
                r = await client.post("https://api.cerebras.ai/v1/chat/completions", json=payload, headers=headers)
            if r.status_code == 429:
                print(f"[BuildAI] Cerebras rate limited on {model}")
                break
            if r.status_code == 404:
                print(f"[BuildAI] Cerebras 404 on {model} β€” trying next model")
                continue
            if not r.is_success:
                print(f"[BuildAI] Cerebras {r.status_code} on {model}")
                continue
            result = clean_code(r.json()["choices"][0]["message"]["content"])
            print(f"[BuildAI] Cerebras βœ“ {model}")
            return result
        except Exception as e:
            print(f"[BuildAI] Cerebras error on {model}: {e}")
            continue
    print("[BuildAI] Cerebras all models failed β€” fallback Gemini")
    return await call_gemini(system_role, user_message, previous_code)


async def call_gemini(system_role: str, user_message: str, previous_code: str = "") -> str:
    """Gemini β€” with auto-retry on rate limit + new google.genai SDK support."""
    api_key = os.environ.get("GEMINI_API_KEY", "")
    if not api_key:
        print("[BuildAI] No GEMINI_API_KEY β€” fallback OpenRouter")
        return await call_openrouter(system_role, user_message, previous_code)
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode to improve (keep ALL sections + images):\n\n{previous_code[:20000]}"

    MODELS = ["gemini-2.5-flash-preview-05-20", "gemini-2.0-flash", "gemini-1.5-flash", "gemini-1.5-flash-8b"]

    # ── New google.genai SDK ──
    if _GENAI_AVAILABLE and _GENAI_NEW:
        for model_name in MODELS:
            try:
                client_g = genai_new.Client(api_key=api_key)
                resp = client_g.models.generate_content(
                    model=model_name,
                    contents=full_message,
                    config=genai_new.types.GenerateContentConfig(
                        system_instruction=system_role,
                        max_output_tokens=65536,
                        temperature=0.6,
                    )
                )
                result = resp.text
                if result and len(result) > 500:
                    print(f"[BuildAI] Gemini New SDK βœ“ {model_name} ({len(result)} chars)")
                    return clean_code(result)
            except Exception as e:
                err = str(e)
                if any(x in err for x in ["429", "quota", "rate", "RESOURCE_EXHAUSTED", "limit: 0"]):
                    print(f"[BuildAI] Gemini rate limited on {model_name} β€” trying next model")
                    continue   # try next model, don't break
                print(f"[BuildAI] Gemini New SDK error on {model_name}: {e}")
                continue

    # ── Old google.generativeai SDK ──
    elif _GENAI_AVAILABLE and not _GENAI_NEW:
        for model_name in MODELS:
            try:
                genai.configure(api_key=api_key)
                m = genai.GenerativeModel(model_name=model_name, system_instruction=system_role)
                resp = m.generate_content(
                    full_message,
                    generation_config=genai.types.GenerationConfig(max_output_tokens=65536, temperature=0.6)
                )
                result = resp.text
                if result and len(result) > 500:
                    print(f"[BuildAI] Gemini Old SDK βœ“ {model_name} ({len(result)} chars)")
                    return clean_code(result)
            except Exception as e:
                err = str(e)
                if any(x in err for x in ["429", "quota", "rate", "RESOURCE_EXHAUSTED", "limit: 0"]):
                    print(f"[BuildAI] Gemini rate limited on {model_name} β€” trying next")
                    continue
                print(f"[BuildAI] Gemini Old SDK error on {model_name}: {e}")
                continue

    # ── OpenAI-compat REST fallback ──
    for model in MODELS:
        try:
            payload = {"model": model,
                       "messages": [{"role": "system", "content": system_role},
                                    {"role": "user", "content": full_message}],
                       "max_tokens": 16000, "temperature": 0.6}
            headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
            async with httpx.AsyncClient(timeout=180.0) as client:
                r = await client.post(
                    "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
                    json=payload, headers=headers)
            if r.status_code == 429:
                print(f"[BuildAI] Gemini REST rate limited on {model} β€” trying next"); continue
            if r.status_code == 404:
                print(f"[BuildAI] Gemini 404 on {model}"); continue
            if not r.is_success:
                print(f"[BuildAI] Gemini {r.status_code} on {model}"); continue
            result = clean_code(r.json()["choices"][0]["message"]["content"])
            print(f"[BuildAI] Gemini REST βœ“ {model}")
            return result
        except Exception as e:
            print(f"[BuildAI] Gemini REST error on {model}: {e}"); continue

    print("[BuildAI] Gemini all models exhausted β€” fallback OpenRouter")
    return await call_openrouter(system_role, user_message, previous_code)




async def call_cloudflare_workers_ai(system_role: str, user_message: str, previous_code: str = "") -> str:
    """Cloudflare Workers AI β€” free tier, always available fallback."""
    account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
    api_token  = os.environ.get("CLOUDFLARE_API_TOKEN", "")
    if not account_id or not api_token:
        raise ValueError("No Cloudflare credentials")
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode:\n\n{previous_code[:8000]}"
    headers = {"Authorization": f"Bearer {api_token}", "Content-Type": "application/json"}
    for model in ["@cf/meta/llama-3.3-70b-instruct-fp8-fast", "@cf/qwen/qwen2.5-coder-32b-instruct"]:
        try:
            payload = {"messages": [{"role": "system", "content": system_role[:2000]},
                                    {"role": "user", "content": full_message}],
                       "max_tokens": 8192, "temperature": 0.7}
            async with httpx.AsyncClient(timeout=90.0) as client:
                r = await client.post(
                    f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model}",
                    headers=headers, json=payload)
            if not r.is_success:
                print(f"[BuildAI] CF Workers AI {r.status_code} on {model}"); continue
            result = r.json().get("result", {}).get("response", "")
            if result and len(result) > 200:
                print(f"[BuildAI] CF Workers AI βœ“ {model}")
                return clean_code(result)
        except Exception as e:
            print(f"[BuildAI] CF Workers AI error on {model}: {e}"); continue
    raise ValueError("Cloudflare Workers AI all models failed")


async def call_groq(system_role: str, user_message: str, previous_code: str = "") -> str:
    # Support GROQ_API_KEY, GROQ_API_KEY_2, GROQ_API_KEY_3
    keys = [os.environ.get(f"GROQ_API_KEY{s}", "").strip() for s in ["","_2","_3"]]
    keys = [k for k in keys if k]
    if not keys:
        return await call_openrouter(system_role, user_message, previous_code)
    sys_trimmed = system_role[:2000]
    code = previous_code
    if code and len(code) > 6000:
        code = code[:3000] + "\n\n<!-- truncated -->\n\n" + code[-3000:]
    full_message = user_message[:1500] + (f"\n\nCode:\n\n{code}" if code else "")
    MODELS = ["llama-3.3-70b-versatile", "llama-3.1-70b-versatile", "llama-3.1-8b-instant"]
    for i, model in enumerate(MODELS):
        key = keys[i % len(keys)]
        try:
            payload = {"model": model, "messages": [{"role":"system","content":sys_trimmed},
                       {"role":"user","content":full_message}], "max_tokens": 8000, "temperature": 0.7}
            headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
            async with httpx.AsyncClient(timeout=90.0) as client:
                r = await client.post("https://api.groq.com/openai/v1/chat/completions", json=payload, headers=headers)
            if r.status_code in (413, 429):
                print(f"[BuildAI] Groq {r.status_code} on {model}"); continue
            if not r.is_success:
                print(f"[BuildAI] Groq {r.status_code} on {model}"); continue
            result = clean_code(r.json()["choices"][0]["message"]["content"])
            print(f"[BuildAI] Groq βœ“ {model}")
            return result
        except Exception as e:
            print(f"[BuildAI] Groq error: {e}"); continue
    return await call_openrouter(system_role, user_message, previous_code)


def _get_openrouter_keys() -> list:
    """Collect up to 10 OpenRouter keys from env: OPENROUTER_API_KEY, OPENROUTER_API_KEY_2 ... _10"""
    keys = []
    for suffix in ["", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9", "_10"]:
        k = os.environ.get(f"OPENROUTER_API_KEY{suffix}", "").strip()
        if k and k not in keys:
            keys.append(k)
    return keys


async def call_openrouter(system_role: str, user_message: str, previous_code: str = "") -> str:
    keys = _get_openrouter_keys()
    if not keys:
        return await call_together(system_role, user_message, previous_code)
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode to improve:\n\n{previous_code[:12000]}"
    MODELS = [
        "openai/gpt-oss-120b:free",
        "nvidia/nemotron-3-super-120b-a12b:free",
        "qwen/qwen3-235b-a22b:free",
        "deepseek/deepseek-v4-flash:free",
        "meta-llama/llama-3.3-70b-instruct:free",
        "google/gemini-2.0-flash-exp:free",
        "mistralai/mistral-small-3.2-24b-instruct:free",
        "meta-llama/llama-3.1-8b-instruct:free",
    ]
    # Rotate keys per model to spread load
    for i, model in enumerate(MODELS):
        key = keys[i % len(keys)]
        headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json",
                   "HTTP-Referer": "https://huggingface.co/spaces/VISHAL18for4/buildai", "X-Title": "BuildAI"}
        for attempt in range(2):
            try:
                token_limit = 32000 if "120b" in model or "235b" in model else (16000 if any(x in model for x in ["70b","nemotron"]) else 8000)
                payload = {"model": model,
                           "messages": [{"role":"system","content":system_role},
                                        {"role":"user","content":full_message}],
                           "max_tokens": token_limit, "temperature": 0.7}
                async with httpx.AsyncClient(timeout=120.0) as client:
                    r = await client.post("https://openrouter.ai/api/v1/chat/completions",
                                         json=payload, headers=headers)
                if r.status_code in (503, 502):
                    if attempt == 0: continue
                    else: break
                if r.status_code == 429:
                    # try next key for this model
                    next_key = keys[(i + attempt + 1) % len(keys)]
                    headers["Authorization"] = f"Bearer {next_key}"
                    if attempt == 0: continue
                    else: break
                if not r.is_success:
                    print(f"[BuildAI] OpenRouter {r.status_code} on {model}"); break
                try:
                    data = r.json()
                except Exception:
                    print(f"[BuildAI] OpenRouter bad JSON on {model}"); break
                if "choices" not in data or not data["choices"]: break
                result = data["choices"][0]["message"]["content"]
                if result and len(result) > 100:
                    print(f"[BuildAI] OpenRouter βœ“ {model} (key #{i % len(keys) + 1})")
                    return clean_code(result)
                break
            except Exception as e:
                print(f"[BuildAI] OpenRouter error on {model}: {e}"); break
    return await call_together(system_role, user_message, previous_code)


async def call_together(system_role: str, user_message: str, previous_code: str = "") -> str:
    """Together AI β€” free tier, strong models."""
    api_key = os.environ.get("TOGETHER_API_KEY", "").strip()
    if not api_key:
        return await call_deepseek(system_role, user_message, previous_code)
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode to improve:\n\n{previous_code[:12000]}"
    MODELS = [
        "meta-llama/Llama-3.3-70B-Instruct-Turbo-Free",
        "meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",
        "deepseek-ai/DeepSeek-R1-Distill-Llama-70B-Free",
    ]
    headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
    for model in MODELS:
        try:
            payload = {"model": model,
                       "messages": [{"role":"system","content":system_role},
                                    {"role":"user","content":full_message}],
                       "max_tokens": 16000, "temperature": 0.7}
            async with httpx.AsyncClient(timeout=120.0) as client:
                r = await client.post("https://api.together.xyz/v1/chat/completions",
                                      json=payload, headers=headers)
            if not r.is_success:
                print(f"[BuildAI] Together {r.status_code} on {model}"); continue
            data = r.json()
            result = data["choices"][0]["message"]["content"]
            if result and len(result) > 100:
                print(f"[BuildAI] Together βœ“ {model}")
                return clean_code(result)
        except Exception as e:
            print(f"[BuildAI] Together error: {e}"); continue
    return await call_deepseek(system_role, user_message, previous_code)


async def call_deepseek(system_role: str, user_message: str, previous_code: str = "") -> str:
    """DeepSeek β€” very cheap, excellent code quality."""
    api_key = os.environ.get("DEEPSEEK_API_KEY", "").strip()
    if not api_key:
        return await call_mistral(system_role, user_message, previous_code)
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode to improve:\n\n{previous_code[:12000]}"
    MODELS = ["deepseek-chat", "deepseek-coder"]
    headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
    for model in MODELS:
        try:
            payload = {"model": model,
                       "messages": [{"role":"system","content":system_role},
                                    {"role":"user","content":full_message}],
                       "max_tokens": 32000, "temperature": 0.6}
            async with httpx.AsyncClient(timeout=120.0) as client:
                r = await client.post("https://api.deepseek.com/v1/chat/completions",
                                      json=payload, headers=headers)
            if not r.is_success:
                print(f"[BuildAI] DeepSeek {r.status_code} on {model}"); continue
            result = r.json()["choices"][0]["message"]["content"]
            if result and len(result) > 100:
                print(f"[BuildAI] DeepSeek βœ“ {model}")
                return clean_code(result)
        except Exception as e:
            print(f"[BuildAI] DeepSeek error: {e}"); continue
    return await call_mistral(system_role, user_message, previous_code)


async def call_mistral(system_role: str, user_message: str, previous_code: str = "") -> str:
    """Mistral β€” European model, GDPR-friendly final polisher."""
    api_key = os.environ.get("MISTRAL_API_KEY", "")
    if not api_key:
        raise ValueError("All API keys exhausted. Please add at least one API key in HuggingFace Secrets.")
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode to polish:\n\n{previous_code}"
    payload = {
        "model": "mistral-small-latest",
        "messages": [{"role": "system", "content": system_role}, {"role": "user", "content": full_message}],
        "max_tokens": 7000,
        "temperature": 0.6,
    }
    headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
    async with httpx.AsyncClient(timeout=120.0) as client:
        r = await client.post("https://api.mistral.ai/v1/chat/completions", json=payload, headers=headers)
        if not r.is_success:
            raise ValueError(f"Mistral failed: {r.status_code} β€” {r.text[:200]}")
        return clean_code(r.json()["choices"][0]["message"]["content"])


MULTI_PAGE_PATTERN = """
━━━ MULTI-PAGE VANILLA JS SPA PATTERN ━━━

REQUIRED CSS in <style>:
.page { display: none; }
.page.active { display: block; }
.nav-link.active { color: #818cf8; border-bottom: 2px solid #6366f1; }

NOTE: BuildAI will auto-inject the navigate() function β€” you DO NOT need to write it.
Just use onclick="navigate('pagename')" on buttons and links.

HTML STRUCTURE:
<body class="bg-[#07080f] text-slate-100 antialiased">
  <nav>
    <a href="#" data-page="home" onclick="navigate('home');return false;" class="nav-link">Home</a>
    <a href="#" data-page="shop" onclick="navigate('shop');return false;" class="nav-link">Shop</a>
  </nav>
  <div id="mobile-menu" class="hidden">...</div>

  <section id="page-home" class="page">
    <!-- Full home page: hero + features + testimonials + CTA + etc. -->
  </section>
  <section id="page-shop" class="page">
    <!-- Full shop: product grid with real products + filters -->
  </section>
  <section id="page-cart" class="page">
    <!-- Cart: item list + order summary + checkout button -->
  </section>

  <footer>...</footer>
  <!-- DO NOT write any <script> tags β€” BuildAI injects them -->
</body>

EVERY page-change button MUST call navigate():
  <button onclick="navigate('shop')" class="...">Shop Now β†’</button>
  <button onclick="navigate('cart')" class="...">Add to Cart</button>
  <a href="#" onclick="navigate('checkout');return false;">Checkout</a>

Build ALL pages as FULL sections with real content β€” no placeholder text.
━━━ END MULTI-PAGE PATTERN ━━━
"""


def detect_multipage(prompt: str) -> list[str]:
    """Detect if user asked for multiple pages and return the page list."""
    import re
    p = prompt.lower()
    found_pages = []

    page_keywords = {
        'home':     ['home page', 'homepage'],
        'shop':     ['shop page', 'shop', 'store page', 'products page'],
        'cart':     ['cart page', 'cart', 'shopping cart'],
        'checkout': ['checkout page', 'checkout', 'payment page'],
        'account':  ['account page', 'my account', 'profile page', 'account'],
        'about':    ['about page', 'about us page'],
        'contact':  ['contact page', 'contact us page'],
        'blog':     ['blog page', 'articles page'],
        'order':    ['order page', 'orders page', 'order history', 'order tracking'],
        'wishlist': ['wishlist page', 'wish list page', 'favorites page'],
    }
    for page_id, keywords in page_keywords.items():
        if any(kw in p for kw in keywords):
            found_pages.append(page_id)

    # Also check for numeric "5 page", "3 page" etc
    count_match = re.search(r'(\d+)\s*(?:-\s*)?page', p)
    if count_match and int(count_match.group(1)) >= 2 and not found_pages:
        found_pages = ['home', 'shop', 'cart', 'checkout', 'account']

    return found_pages if len(found_pages) >= 2 else []


def clean_code(text: str) -> str:
    """Strip markdown fences and trim to valid HTML boundaries. Do NOT touch className or JSX."""
    import re
    text = text.strip()

    # Strip markdown code fences
    for fence in ["```html\n", "```html", "```\n", "```"]:
        if text.startswith(fence):
            text = text[len(fence):]
            break
    if text.endswith("```"):
        text = text[:-3].rstrip()

    # Trim to DOCTYPE or <html
    if "<!DOCTYPE" in text:
        text = text[text.index("<!DOCTYPE"):]
    elif "<html" in text:
        text = text[text.index("<html"):]

    # Find the last </html> that appears AFTER the last </script>
    last_script_end = text.rfind("</script>")
    search_from = last_script_end if last_script_end != -1 else 0
    html_close_pos = -1
    pos = text.find("</html>", search_from)
    while pos != -1:
        html_close_pos = pos
        pos = text.find("</html>", pos + 1)
    if html_close_pos != -1:
        text = text[:html_close_pos + 7]

    return text.strip()


def emergency_close_tags(code: str) -> str:
    import re
    code = code.rstrip()
    if code.endswith("</html>"):
        return code
    closing = []
    s_open = len(re.findall(r'<script[\s>]', code, re.IGNORECASE))
    s_close = code.count("</script>")
    for _ in range(max(0, s_open - s_close)):
        closing.append("</script>")
    f_open = len(re.findall(r'<footer[\s>]', code, re.IGNORECASE))
    f_close = code.count("</footer>")
    if f_open > f_close:
        closing.append("</footer>")
    d_open = len(re.findall(r'<div[\s>]', code))
    d_close = code.count("</div>")
    for _ in range(min(max(0, d_open - d_close), 8)):
        closing.append("</div>")
    if "<body" in code and "</body>" not in code:
        closing.append("</body>")
    if "<html" in code and "</html>" not in code:
        closing.append("</html>")
    if closing:
        print(f"[BuildAI] emergency_close_tags: appending {closing}")
        code = code + "\n" + "\n".join(closing)
    return code


def validate_html_structure(code: str) -> tuple[bool, list]:
    issues = []
    if "<!DOCTYPE" not in code and "<html" not in code:
        issues.append("No DOCTYPE or <html>")
    if "</html>" not in code:
        issues.append("Missing </html>")
    if "<body" not in code:
        issues.append("Missing <body>")
    if "</body>" not in code:
        issues.append("Missing </body>")
    if "<nav" not in code.lower() and "navbar" not in code.lower():
        issues.append("Missing navbar/nav")
    if "<footer" not in code.lower():
        issues.append("Missing footer")
    import re
    s_open = len(re.findall(r'<script[\s>]', code, re.IGNORECASE))
    s_close = code.count("</script>")
    if abs(s_open - s_close) > 2:
        issues.append(f"Unbalanced script tags ({s_open} open, {s_close} close)")
    if "text/babel" in code or "ReactDOM" in code:
        issues.append("React/Babel found β€” remove it (vanilla HTML only)")
    return len(issues) == 0, issues


def is_complete(html: str) -> bool:
    h = html.strip()
    return (
        h.endswith("</html>")
        and "</footer>" in h
        and "</body>" in h
        and ("<nav" in h or "navbar" in h.lower())
    )


async def ensure_complete(system_role: str, task: str, code: str, caller_fn) -> str:
    """
    True fallback chain for completion:
    1. emergency_close_tags() β€” zero API, always runs first
    2. Try primary caller
    3. Try call_openrouter with slim prompt
    4. Try call_huggingface
    5. Return best available (never return broken code from a failed attempt)
    """
    # Step 1: Always run emergency_close_tags first (free, instant)
    code = emergency_close_tags(code)

    if is_complete(code):
        valid, issues = validate_html_structure(code)
        if issues:
            print(f"[BuildAI] Validation issues (non-fatal): {issues}")
        return code

    print(f"[BuildAI] ⚠ Still incomplete after emergency_close_tags ({len(code)} chars) β€” trying API chain...")

    tail = code[-2000:]
    slim_system = "You are completing truncated HTML. Continue EXACTLY where it stopped. Output ONLY the missing closing code. Must end with </script></body></html>."
    continuation_task = (
        f"This HTML/JSX was cut off. Continue from EXACTLY where it stopped β€” no overlap, no preamble.\n"
        f"Output ONLY the missing continuation. Must end with </script></body></html>.\n\n"
        f"LAST 2000 CHARS:\n{tail}"
    )

    best_code = code  # track best result across attempts

    for fn_name, fn, sys_prompt in [
        ("primary", caller_fn, system_role),
        ("openrouter-slim", call_openrouter, slim_system),
        ("huggingface", call_huggingface, slim_system),
    ]:
        if fn_name != "primary" and fn == caller_fn:
            continue
        try:
            cont = await fn(sys_prompt, continuation_task, "")
            cont = cont.strip()
            # If model returned a full page, check if it's better than what we have
            if "<!DOCTYPE" in cont or "<html" in cont[:50]:
                candidate = clean_code(cont)
                candidate = emergency_close_tags(candidate)
                if is_complete(candidate) and len(candidate) >= len(best_code) * 0.8:
                    print(f"[BuildAI] βœ“ Completion via {fn_name}: full page ({len(candidate)} chars)")
                    return candidate
                continue
            merged = clean_code(code.rstrip() + "\n" + cont)
            merged = emergency_close_tags(merged)
            if is_complete(merged):
                print(f"[BuildAI] βœ“ Completion via {fn_name}: merged ({len(merged)} chars)")
                return merged
            if len(merged) > len(best_code):
                best_code = merged
            print(f"[BuildAI] {fn_name} cont still incomplete, trying next...")
        except Exception as e:
            print(f"[BuildAI] Completion via {fn_name} failed: {e}")
            continue

    print(f"[BuildAI] All completions failed β€” returning best available ({len(best_code)} chars)")
    return best_code

async def call_huggingface(system_role: str, user_message: str, previous_code: str = "") -> str:
    """HuggingFace free inference β€” Qwen2.5-Coder-32B matches GPT-4o for HTML/CSS."""
    api_key = os.environ.get("HF_TOKEN", "") or os.environ.get("HUGGINGFACE_TOKEN", "")
    if not api_key:
        print("[BuildAI] No HF_TOKEN β€” fallback Groq")
        return await call_groq(system_role, user_message, previous_code)
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode to improve:\n\n{previous_code[:10000]}"
    for model in ["Qwen/Qwen2.5-Coder-32B-Instruct", "Qwen/Qwen3-32B", "meta-llama/Llama-3.3-70B-Instruct"]:
        try:
            payload = {
                "model": model,
                "messages": [{"role":"system","content":system_role},{"role":"user","content":full_message}],
                "max_tokens": 12000,
                "temperature": 0.65,
            }
            headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
            async with httpx.AsyncClient(timeout=180.0) as client:
                r = await client.post("https://router.huggingface.co/v1/chat/completions", json=payload, headers=headers)
            if r.status_code == 429:
                print(f"[BuildAI] HF rate limit {model}"); continue
            if not r.is_success:
                print(f"[BuildAI] HF {r.status_code} on {model}"); continue
            result = r.json()["choices"][0]["message"]["content"]
            if result and len(result) > 200:
                print(f"[BuildAI] HF βœ“ {model}")
                return clean_code(result)
        except Exception as e:
            print(f"[BuildAI] HF error {model}: {e}"); continue
    # Try Cloudflare Workers AI before Groq
    try:
        result = await call_cloudflare_workers_ai(system_role, user_message, previous_code)
        if result: return result
    except Exception:
        pass
    return await call_groq(system_role, user_message, previous_code)


CONTINUATION_SYSTEM = """You are an expert HTML developer. The HTML was cut off mid-generation.
Continue from EXACTLY where it stopped β€” no overlap, no preamble.
Output ONLY the missing continuation HTML.
The final output MUST end with </footer></body></html>.
Do NOT repeat any content already generated. Just continue seamlessly.
Use class NOT className. Vanilla JS only β€” no React, no Babel, no JSX."""


async def call_together(system_role: str, user_message: str, previous_code: str = "") -> str:
    """Together AI β€” generous free tier, fast Llama/Qwen models. Extra free fallback."""
    api_key = os.environ.get("TOGETHER_API_KEY", "")
    if not api_key:
        print("[BuildAI] No TOGETHER_API_KEY β€” skipping Together AI")
        raise ValueError("No TOGETHER_API_KEY")
    full_message = user_message
    if previous_code:
        full_message += f"\n\nCode to improve:\n\n{previous_code[:10000]}"
    for model in [
        "meta-llama/Llama-3.3-70B-Instruct-Turbo-Free",
        "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo",
        "Qwen/Qwen2.5-72B-Instruct-Turbo",
    ]:
        try:
            payload = {
                "model": model,
                "messages": [{"role": "system", "content": system_role}, {"role": "user", "content": full_message}],
                "max_tokens": 12000,
                "temperature": 0.65,
            }
            headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
            async with httpx.AsyncClient(timeout=180.0) as client:
                r = await client.post("https://api.together.xyz/v1/chat/completions", json=payload, headers=headers)
            if r.status_code == 429:
                print(f"[BuildAI] Together rate limit on {model}"); continue
            if not r.is_success:
                print(f"[BuildAI] Together {r.status_code} on {model}"); continue
            result = r.json()["choices"][0]["message"]["content"]
            if result and len(result) > 200:
                print(f"[BuildAI] Together βœ“ {model}")
                return clean_code(result)
        except Exception as e:
            print(f"[BuildAI] Together error on {model}: {e}"); continue
    raise ValueError("Together AI all models failed")


# ─────────────────────────────────────────────────────────────────
# ORCHESTRATOR β€” Smart prompt enhancer + pipeline manager
# ─────────────────────────────────────────────────────────────────

ORCHESTRATOR_SYSTEM = """You are the orchestration engine for BuildAI, a professional website builder.
Your job: analyze the user's request and return a JSON object that directs the build pipeline.

Return ONLY valid JSON. No markdown, no explanation, just the JSON object.

JSON schema:
{
  "enhanced_prompt": "expanded version of the user's request with specific details added",
  "website_type": "one of: E-COMMERCE / RESTAURANT / FITNESS & WELLNESS / MUSIC & ARTIST / PHOTOGRAPHY / TRAVEL & HOSPITALITY / CRYPTO & WEB3 / HEALTHCARE / EDUCATION / REAL ESTATE / CREATIVE AGENCY / STARTUP / BLOG & MEDIA / PORTFOLIO / DASHBOARD / SAAS LANDING PAGE",
  "pages": ["home", "shop", "cart", "checkout", "account"],
  "color_theme": "describe a specific color palette e.g. dark navy + electric indigo + gold accents",
  "key_sections": ["list the 5-8 most important sections for this specific business"],
  "business_name": "extracted business name or empty string",
  "tone": "one of: luxurious / playful / professional / bold / minimal / energetic",
  "primary_model": "one of: openrouter / huggingface / groq",
  "quality_notes": "any specific quality requirements the builder should focus on"
}

Rules:
- enhanced_prompt must add specific details (colors, sections, features) the user didn't mention but would want
- pages array: include ONLY if user explicitly asks for multiple pages, else return []
- primary_model: openrouter for complex sites, huggingface for large multi-page, groq for simple/fast
- always extract the real business name from the prompt
"""


async def orchestrate(prompt: str, is_edit: bool = False) -> dict:
    import json as _json, re as _re
    default = {"enhanced_prompt": prompt, "pages": [], "primary_model": "gemini",
                "business_name": "", "color_theme": "", "quality_notes": ""}
    if is_edit:
        return default

    api_key = os.environ.get("GEMINI_API_KEY", "")
    if not api_key:
        print("[BuildAI] Orchestrator: no GEMINI_API_KEY β€” skipping")
        return default
    try:
        if _GENAI_AVAILABLE and _GENAI_NEW:
            client_g = genai_new.Client(api_key=api_key)
            resp = client_g.models.generate_content(
                model="gemini-2.0-flash",
                contents=f"Analyze this website build request:\n\n{prompt}",
                config=genai_new.types.GenerateContentConfig(
                    system_instruction=ORCHESTRATOR_SYSTEM,
                    max_output_tokens=800, temperature=0.3)
            )
            content = resp.text
        elif _GENAI_AVAILABLE and not _GENAI_NEW:
            genai.configure(api_key=api_key)
            m = genai.GenerativeModel("gemini-2.0-flash", system_instruction=ORCHESTRATOR_SYSTEM)
            resp = m.generate_content(
                f"Analyze this website build request:\n\n{prompt}",
                generation_config=genai.types.GenerationConfig(max_output_tokens=800, temperature=0.3)
            )
            content = resp.text
        else:
            payload = {"model": "gemini-2.0-flash",
                       "messages": [{"role":"system","content":ORCHESTRATOR_SYSTEM},
                                    {"role":"user","content":f"Analyze:\n\n{prompt}"}],
                       "max_tokens": 800, "temperature": 0.3}
            headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
            async with httpx.AsyncClient(timeout=20.0) as client:
                r = await client.post(
                    "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
                    json=payload, headers=headers)
            if not r.is_success:
                raise ValueError(f"Orchestrator HTTP {r.status_code}")
            content = r.json()["choices"][0]["message"]["content"]

        json_match = _re.search(r'\{.*\}', content, _re.DOTALL)
        if json_match:
            content = json_match.group()
        result = _json.loads(content)
        result.setdefault("primary_model", "gemini")
        print(f"[BuildAI] 🎯 Orchestrator: type={result.get('website_type','')} | "
              f"pages={result.get('pages',[])} | model={result.get('primary_model','')} | "
              f"business={result.get('business_name','')}")
        return result
    except Exception as e:
        print(f"[BuildAI] Orchestrator failed: {e} β€” using defaults")
        return default


def _extract_design_colors(design_skills_text: str) -> str:
    """Pull out colors + fonts from design .md and inject directly into the build task."""
    if not design_skills_text:
        return ""
    import re
    lines = design_skills_text.split('\n')
    colors = [l.strip() for l in lines if '#' in l and
              any(x in l.lower() for x in ['background','primary','accent','text','--'])]
    fonts  = [l.strip() for l in lines if 'font-family' in l.lower()]
    css_blocks = re.findall(r'```css\s*(.*?)\s*```', design_skills_text, re.DOTALL)
    result_parts = css_blocks[:1] + colors[:5] + fonts[:2]
    if not result_parts:
        return ""
    return "\n⚑ MANDATORY DESIGN COLORS & FONTS (OVERRIDE DEFAULTS WITH THESE):\n" + "\n".join(result_parts[:8]) + "\n"


# ─────────────────────────────────────────────────────────────────
# MAIN PIPELINE
# ─────────────────────────────────────────────────────────────────


# ─────────────────────────────────────────────────────────────────
# MULTI-FILE SPLITTER
# Splits a single HTML into index.html + styles.css + script.js + pages/*.html
# Each file stays under 500 lines β€” matches Lovable/v0 file structure
# ─────────────────────────────────────────────────────────────────

def split_into_files(html: str, project_name: str = "buildai-project") -> dict:
    """
    Splits generated HTML into separate files, each under 500 lines.
    Returns dict of {filename: content} ready for ZIP download.
    """
    import re as _re

    files = {}

    # Extract <style> blocks β†’ styles.css
    styles = _re.findall(r"<style[^>]*>(.*?)</style>", html, _re.DOTALL)
    css_content = "\n\n".join(s.strip() for s in styles)
    if css_content:
        files["styles.css"] = f"/* {project_name} β€” generated by BuildAI */\n{css_content}"
        for match in _re.finditer(r"<style[^>]*>.*?</style>", html, _re.DOTALL):
            html = html.replace(match.group(), "", 1)
        html = html.replace("</head>", '  <link rel="stylesheet" href="styles.css">\n</head>', 1)

    # Extract <script> blocks (excluding CDN src scripts) β†’ script.js
    inline_scripts = []
    def replace_script(m):
        full = m.group(0)
        if "src=" in full:
            return full  # keep CDN scripts in HTML
        inline_scripts.append(m.group(1).strip())
        return ""
    html = _re.sub(r"<script(?![^>]*src=)[^>]*>(.*?)</script>", replace_script, html, flags=_re.DOTALL)
    js_content = "\n\n".join(inline_scripts)
    if js_content:
        files["script.js"] = f"// {project_name} β€” generated by BuildAI\n{js_content}"
        html = html.replace("</body>", '  <script src="script.js"></script>\n</body>', 1)

    # Split multi-page: look for id="page-X" sections
    page_divs = _re.findall(r'(<div[^>]+id="page-([\w-]+)"[^>]*>)', html)
    if len(page_divs) >= 2:
        # Extract each page section into its own file
        parts = _re.split(r'(?=<div[^>]+id="page-[\w-]+")', html)
        main_html = parts[0] if parts else html
        for part in parts[1:]:
            m = _re.match(r'<div[^>]+id="page-([\w-]+)"', part)
            if m:
                page_id = m.group(1)
                page_file = f"pages/{page_id}.html"
                # Keep it under 500 lines
                lines = part.split("\n")
                if len(lines) > 500:
                    part = "\n".join(lines[:500]) + "\n<!-- truncated: see full file -->"
                files[page_file] = f"<!-- Page: {page_id} -->\n{part}"
        files["index.html"] = main_html
    else:
        # Single page β€” just chunk into index.html, keeping under 500 lines
        lines = html.split("\n")
        if len(lines) <= 500:
            files["index.html"] = html
        else:
            # Split into chunks of 400 lines with proper head/body
            head_end = next((i for i, l in enumerate(lines) if "</head>" in l), 10)
            head = "\n".join(lines[:head_end+1])
            body_lines = lines[head_end+1:]
            chunk_size = 400
            for chunk_idx, start in enumerate(range(0, len(body_lines), chunk_size)):
                chunk = body_lines[start:start+chunk_size]
                fname = "index.html" if chunk_idx == 0 else f"section_{chunk_idx}.html"
                files[fname] = head + "\n" + "\n".join(chunk) + "\n</html>"

    # Ensure index.html always exists
    if "index.html" not in files:
        files["index.html"] = html

    # Count lines and report
    for fname, fcontent in files.items():
        lc = len(fcontent.split("\n"))
        print(f"[BuildAI] File: {fname} ({lc} lines)")

    return files



# ═══════════════════════════════════════════════════════════════
# SEQUENTIAL MULTI-FILE GENERATION
# AI generates a manifest first, then each file separately.
# Each file < 400 lines. Supports HTML, CSS, JS, TSX, JSX, TS, PY
# ═══════════════════════════════════════════════════════════════

MANIFEST_SYSTEM = """You are a senior web architect. Given a website description, output ONLY a JSON manifest of files to generate.

HTML site example:
{"type":"html","framework":"vanilla","files":[
  {"name":"index.html","desc":"Hero, nav, features, testimonials, footer β€” main landing"},
  {"name":"pages/shop.html","desc":"Product grid, filters, cart sidebar"},
  {"name":"pages/about.html","desc":"Team, story, mission"},
  {"name":"styles.css","desc":"CSS variables, animations, responsive styles"},
  {"name":"script.js","desc":"navigate(), cart, mobile menu, AOS init"}
]}

React/TSX site example:
{"type":"react","framework":"react","files":[
  {"name":"App.tsx","desc":"Root component with routing between pages"},
  {"name":"components/Nav.tsx","desc":"Sticky navbar with mobile hamburger"},
  {"name":"components/Hero.tsx","desc":"Fullscreen hero with gradient and CTA buttons"},
  {"name":"components/Products.tsx","desc":"Product cards grid with add-to-cart"},
  {"name":"components/Footer.tsx","desc":"Links, social, copyright"},
  {"name":"index.css","desc":"Tailwind base + custom animations + CSS vars"}
]}

Rules:
- MAX 7 files, EACH under 400 lines
- Use HTML type for: e-commerce, restaurants, portfolios, landing pages
- Use React type for: dashboards, SaaS apps, admin panels, complex UIs
- Output ONLY the JSON object, nothing else, no markdown"""


FILE_GEN_SYSTEM = """You are an expert web developer generating ONE file at a time.

CRITICAL RULES:
1. Output ONLY the raw file content β€” no explanation, no markdown fences
2. Stay under 400 lines
3. For HTML: use Tailwind CDN, Unsplash images (https://source.unsplash.com/WxH/?keyword&sig=N), AOS animations
4. For CSS: use CSS variables, include all keyframes, mobile-first
5. For JS: vanilla JS only, no imports (everything in one script scope)
6. For TSX/JSX: use React hooks, Tailwind classes, no external imports except React
7. For HTML pages: include proper <html><head><body> structure with CDN scripts
8. Images: ALWAYS use https://source.unsplash.com/WIDTHxHEIGHT/?keyword&sig=N (change sig for variety)
9. NEVER use placeholder.com or pollinations.ai"""


async def generate_manifest(prompt: str, website_type: str, caller) -> dict:
    """Ask AI for a file manifest. Fast call, small response."""
    import json as _json, re as _re
    msg = f"Website request: {prompt}\nDetected type: {website_type}\nGenerate the file manifest JSON."
    try:
        raw = await caller(MANIFEST_SYSTEM, msg, "")
        # Extract JSON from response
        raw = raw.strip()
        m = _re.search(r'\{[\s\S]*\}', raw)
        if m:
            raw = m.group()
        result = _json.loads(raw)
        if "files" in result and len(result["files"]) > 0:
            print(f"[BuildAI] Manifest: {result['type']} | {len(result['files'])} files")
            return result
    except Exception as e:
        print(f"[BuildAI] Manifest failed: {e}")
    # Fallback manifest
    return {"type":"html","framework":"vanilla","files":[
        {"name":"index.html","desc":"Complete website with all sections"},
        {"name":"styles.css","desc":"All styles and animations"},
        {"name":"script.js","desc":"All JavaScript functionality"}
    ]}


async def generate_single_file(fname: str, fdesc: str, prompt: str, 
                                 all_files: list, existing_files: dict, 
                                 project_type: str, caller) -> str:
    """Generate one file given context of all other files."""
    # Build context of already-generated files (names + first 3 lines only to save tokens)
    ctx_parts = []
    for fn, fc in existing_files.items():
        preview = "\n".join(fc.split("\n")[:3])
        ctx_parts.append(f"// Already generated: {fn}\n// {preview}...")
    ctx = "\n".join(ctx_parts) if ctx_parts else "// First file being generated"
    
    all_names = ", ".join(f["name"] for f in all_files)
    
    msg = f"""Project: {prompt}
Project type: {project_type}
All files in project: {all_names}

Other files already generated:
{ctx}

NOW GENERATE: {fname}
Purpose: {fdesc}

Output ONLY the raw content of {fname}. No markdown, no explanation, no code fences."""

    result = await caller(FILE_GEN_SYSTEM, msg, "")
    # Clean code fences if AI added them
    result = result.strip()
    if result.startswith("```"):
        lines = result.split("\n")
        result = "\n".join(lines[1:-1] if lines[-1] == "```" else lines[1:])
    return result


async def run_sequential_pipeline(prompt: str, caller) -> AsyncGenerator[str, None]:
    """
    Generate multi-file project sequentially.
    Yields SSE events: file_start, file_done, all_done
    """
    _, website_type = get_references(prompt)
    
    yield make_sse({"type":"status","round":1,"done":False,
                    "message":"πŸ“‹ Planning file structure..."})
    
    manifest = await generate_manifest(prompt, website_type, caller)
    proj_type = manifest.get("type", "html")
    files_plan = manifest.get("files", [])
    
    yield make_sse({"type":"manifest","files":files_plan,"project_type":proj_type,
                    "message":f"πŸ“ {len(files_plan)} files to generate"})
    
    generated = {}  # filename β†’ content
    
    for i, file_info in enumerate(files_plan):
        fname = file_info["name"]
        fdesc = file_info.get("desc", "")
        
        yield make_sse({"type":"file_start","file":fname,"index":i,
                        "total":len(files_plan),
                        "message":f"βš™οΈ Generating {fname} ({i+1}/{len(files_plan)})..."})
        
        try:
            content = await generate_single_file(
                fname, fdesc, prompt, files_plan, generated, proj_type, caller)
            generated[fname] = content
            lines = len(content.split("\n"))
            print(f"[BuildAI] βœ“ {fname} ({lines} lines)")
            yield make_sse({"type":"file_done","file":fname,"content":content,
                            "index":i,"total":len(files_plan),
                            "message":f"βœ“ {fname} ({lines} lines)"})
        except Exception as e:
            print(f"[BuildAI] Failed to generate {fname}: {e}")
            yield make_sse({"type":"file_error","file":fname,"error":str(e)})
    
    # Combine into preview HTML
    preview_html = _combine_for_preview(generated, proj_type, prompt)
    
    yield make_sse({"type":"code","round":3,"done":True,"final":True,
                    "message":"πŸŽ‰ Website ready!",
                    "code": preview_html,
                    "files": generated,
                    "project_type": proj_type})


def _combine_for_preview(files: dict, proj_type: str, prompt: str) -> str:
    """Combine generated files into a single previewable HTML."""
    if proj_type == "react":
        return _combine_react_preview(files, prompt)
    else:
        return _combine_html_preview(files)


def _combine_html_preview(files: dict) -> str:
    """Merge HTML/CSS/JS files into one HTML file for preview."""
    index_html = files.get("index.html", "")
    css = files.get("styles.css", files.get("style.css", ""))
    js  = files.get("script.js",  files.get("app.js", ""))
    
    if css and "<style" not in index_html:
        index_html = index_html.replace("</head>", f"<style>\n{css}\n</style>\n</head>", 1)
    if js and index_html:
        index_html = index_html.replace("</body>", f"<script>\n{js}\n</script>\n</body>", 1)
    
    return index_html or next(iter(files.values()), "")


def _combine_react_preview(files: dict, prompt: str) -> str:
    """Bundle React/TSX files into a single HTML with Babel transpiler."""
    # Combine all TSX/JSX/TS files
    all_tsx = []
    app_file = files.get("App.tsx", files.get("App.jsx", files.get("app.tsx", "")))
    
    for fname, content in files.items():
        if fname.endswith((".tsx",".jsx",".ts",".js")) and fname not in ("index.js","main.js"):
            # Strip import statements (everything is global in browser)
            lines = []
            for line in content.split("\n"):
                if line.startswith("import ") and ("from '" in line or 'from "' in line):
                    continue  # skip imports
                if line.startswith("export default ") and fname != list(files.keys())[-1]:
                    line = line.replace("export default ", "// exported: ", 1)
                lines.append(line)
            all_tsx.append(f"// === {fname} ===\n" + "\n".join(lines))
    
    combined_tsx = "\n\n".join(all_tsx)
    css_content = ""
    for fname, content in files.items():
        if fname.endswith(".css"):
            css_content += content + "\n"
    
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{prompt[:40]}</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;700;800&family=DM+Sans:wght@400;500;600&display=swap" rel="stylesheet"/>
<style>
body{{margin:0;font-family:'DM Sans',sans-serif;background:#07080f;color:white}}
{css_content}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel" data-presets="react,typescript">
const {{ useState, useEffect, useRef, useCallback, useMemo }} = React;

{combined_tsx}

// Mount app
const rootEl = document.getElementById('root');
if (rootEl && typeof App !== 'undefined') {{
  ReactDOM.render(React.createElement(App), rootEl);
}}
</script>
</body>
</html>"""


async def run_pipeline(prompt: str, current_code: str = "") -> AsyncGenerator[str, None]:
    is_edit = bool(current_code and len(current_code) > 100)

    # ── Step 0: Orchestrator analyzes the request ─────────────────
    yield make_sse({"type":"status","round":0,"done":False,"message":"🎯 Analyzing your request..."})
    orch = await orchestrate(prompt, is_edit)

    effective_prompt = orch.get("enhanced_prompt", prompt)
    if not effective_prompt or len(effective_prompt) < len(prompt) * 0.5:
        effective_prompt = prompt  # never downgrade

    orch_pages = orch.get("pages", [])
    pages = orch_pages if orch_pages else (detect_multipage(prompt) if not is_edit else [])

    # ── ALWAYS use Gemini as primary β€” native SDK gives 65K tokens ──
    primary_model_name = "gemini"
    primary_caller = call_gemini

    # ── NEW BUILDS β†’ sequential multi-file pipeline ──────────────
    if not is_edit:
        async for event in run_sequential_pipeline(effective_prompt, primary_caller):
            yield event
        return

    ref_content, website_type = get_references(effective_prompt)
    orch_type = orch.get("website_type", "")
    if orch_type and orch_type in SECTIONS_MAP:
        website_type = orch_type

    print(f"[BuildAI] Building: {website_type} | {'edit' if is_edit else 'new'} | "
          f"model={primary_model_name} | pages={pages} | business='{orch.get('business_name','')}'")

    design_skills = get_design_skills(effective_prompt, website_type)
    design_colors = _extract_design_colors(design_skills)   # ← NEW: force colors into task
    builder_system = get_builder_prompt(ref_content, website_type, effective_prompt, design_skills)

    page_instruction = ""
    if pages:
        page_list = " / ".join(f"'{p}'" for p in pages)
        page_instruction = (
            f"\n\n{MULTI_PAGE_PATTERN}\n"
            f"PAGES TO BUILD: {page_list}\n"
            f"Build EVERY listed page as a full <section id='page-NAME' class='page'> with complete content.\n"
            f"Use onclick=\"navigate('page')\" on ALL buttons that change pages.\n"
        )

    quality_notes = orch.get("quality_notes", "")
    color_theme  = orch.get("color_theme", "")
    extra = ""
    if quality_notes: extra += f"\nQUALITY FOCUS: {quality_notes}"
    if color_theme:   extra += f"\nCOLOR THEME: {color_theme}"

    if is_edit:
        task = (
            f"You are EDITING an existing website. The user wants: {prompt}\n\n"
            f"RULES:\n"
            f"1. KEEP 100% of the existing HTML structure, sections, and images.\n"
            f"2. ONLY apply the user's requested change.\n"
            f"3. Output the COMPLETE HTML file with your changes applied.\n"
            f"4. Preserve vanilla HTML structure β€” keep navigate() calls, keep all section ids.\n"
            f"5. Use class NOT className. Vanilla JS only β€” no React, no Babel.\n\n"
            f"Current code:\n{current_code}"
        )
    else:
        task = (
            f"Build a stunning {website_type} website for: {effective_prompt}\n"
            f"{page_instruction}{extra}\n"
            f"{design_colors}"
            f"Requirements: Syne+DM Sans fonts, Tailwind+GSAP+AOS CDN, "
            f"min 8 images using https://source.unsplash.com/WIDTHxHEIGHT/?keyword,keyword&sig=N (free, always works), "
            f"real content NO lorem ipsum, breathtaking hero with hero-content div, bento grid features, "
            f"data-aos='fade-up' on ALL cards and section content.\n"
            f"CRITICAL: Pure vanilla HTML β€” NO React, NO Babel, NO JSX. Use class NOT className.\n"
            f"CRITICAL: Use onclick=\"navigate('page')\" on all nav buttons. Wrap hero text in <div class='hero-content'>.\n"
            f"DO NOT write any <script> init block β€” BuildAI injects it automatically.\n"
            f"Use bg-[#07080f] bg-[#0d0e1a] directly. Output ONLY raw HTML from <!DOCTYPE to </html>."
        )

    # Round 1
    yield make_sse({"type":"status","round":1,"done":False,
                    "message":f"⚑ Round 1 β€” {'Editing' if is_edit else 'Building'} your {website_type}..."})
    try:
        r1 = await primary_caller(builder_system, task, "")
        r1 = emergency_close_tags(r1)
        r1 = await ensure_complete(CONTINUATION_SYSTEM, task, r1, primary_caller)
        r1 = inject_required_scripts(r1, pages)   # ← GUARANTEE navigate() + AOS.init()
        valid, issues = validate_html_structure(r1)
        print(f"[BuildAI] Round 1: {len(r1)} chars, complete={is_complete(r1)}, valid={valid}, issues={issues}")
        yield make_sse({"type":"code","round":1,"done":True,"message":"βœ“ Round 1 β€” foundation built","code":r1,"final":False})
    except Exception as e:
        yield make_sse({"type":"error","round":1,"done":False,"message":str(e)}); return

    await asyncio.sleep(0.5)

    # Round 2 β€” Design elevation with 30s rate-limit retry
    yield make_sse({"type":"status","round":2,"done":False,"message":"🎨 Round 2 β€” Elevating design & animations..."})
    photo_inst = get_photo_instructions(effective_prompt, website_type)
    reviewer_p = REVIEWER_PROMPT.replace("{DESIGN_SKILLS_PLACEHOLDER}", design_skills).replace("{PHOTO_SYSTEM}", photo_inst)
    r2 = r1
    for _attempt in range(2):   # up to 2 attempts with 30s wait
        try:
            r2_raw = await call_gemini(reviewer_p,
                f"Elevate to award-winning quality. Keep all images. Vanilla HTML only. Brief: {effective_prompt}", r1)
            r2_raw = emergency_close_tags(r2_raw)
            r2_raw = await ensure_complete(CONTINUATION_SYSTEM, task, r2_raw, call_gemini)
            r2_raw = inject_required_scripts(r2_raw, pages)   # ← GUARANTEE scripts
            valid2, issues2 = validate_html_structure(r2_raw)
            print(f"[BuildAI] Round 2: {len(r2_raw)} chars, complete={is_complete(r2_raw)}, valid={valid2}, issues={issues2}")
            if valid2 and len(r2_raw) >= len(r1) * 0.8:
                r2 = r2_raw
                yield make_sse({"type":"code","round":2,"done":True,"message":"βœ“ Round 2 β€” design elevated","code":r2,"final":False})
            else:
                reason = f"validation failed: {issues2}" if not valid2 else f"too short"
                print(f"[BuildAI] Round 2 rejected ({reason}) β€” keeping Round 1")
                r2 = r1
                yield make_sse({"type":"code","round":2,"done":True,"message":"βœ“ Round 2 β€” keeping Round 1","code":r2,"final":False})
            break
        except Exception as e:
            err = str(e)
            if _attempt == 0 and any(x in err for x in ['429','rate','limit','quota','402']):
                print(f"[BuildAI] Round 2 rate limited β€” waiting 30s before retry...")
                yield make_sse({"type":"status","round":2,"done":False,"message":"⏳ Rate limited β€” retrying in 30s..."})
                await asyncio.sleep(30)
            else:
                print(f"[BuildAI] Round 2 failed: {e} β€” keeping Round 1")
                r2 = r1
                yield make_sse({"type":"code","round":2,"done":True,"message":"βœ“ Round 2 β€” keeping Round 1 (API limit)","code":r2,"final":False,"partial_build":True})
                break

    await asyncio.sleep(0.5)

    if r2 is r1:
        print("[BuildAI] Skipping Round 3 β€” Round 2 didn't improve")
        yield make_sse({"type":"code","round":3,"done":True,"message":"πŸŽ‰ Website ready!","code":r1,"final":True,"partial_build":True,"files":split_into_files(r1, effective_prompt[:30])})
        return

    # Round 3 β€” QA & final polish with 30s retry
    yield make_sse({"type":"status","round":3,"done":False,"message":"✨ Round 3 β€” QA & final polish..."})
    polisher_p = POLISHER_PROMPT.replace("{PHOTO_SYSTEM}", photo_inst)
    for _attempt in range(2):
        try:
            r3 = await call_mistral(polisher_p,
                f"Final polish for {website_type}. Fix all bugs. Keep all images. Vanilla HTML. Brief: {effective_prompt}", r2)
            r3 = emergency_close_tags(r3)
            r3 = await ensure_complete(CONTINUATION_SYSTEM, task, r3, call_mistral)
            r3 = inject_required_scripts(r3, pages)   # ← GUARANTEE scripts in final output
            valid3, issues3 = validate_html_structure(r3)
            print(f"[BuildAI] Round 3: {len(r3)} chars, complete={is_complete(r3)}, valid={valid3}, issues={issues3}")
            if valid3 and len(r3) >= len(r2) * 0.8:
                yield make_sse({"type":"code","round":3,"done":True,"message":"πŸŽ‰ Website ready!","code":r3,"final":True,"files":split_into_files(r3, effective_prompt[:30])})
            else:
                print(f"[BuildAI] Round 3 rejected β€” returning Round 2")
                yield make_sse({"type":"code","round":3,"done":True,"message":"πŸŽ‰ Website ready!","code":r2,"final":True,"files":split_into_files(r2, effective_prompt[:30])})
            break
        except Exception as e:
            err = str(e)
            if _attempt == 0 and any(x in err for x in ['429','rate','limit','quota','402']):
                print(f"[BuildAI] Round 3 rate limited β€” waiting 30s before retry...")
                yield make_sse({"type":"status","round":3,"done":False,"message":"⏳ Rate limited β€” retrying in 30s..."})
                await asyncio.sleep(30)
            else:
                print(f"[BuildAI] Round 3 failed: {e} β€” returning Round 2")
                yield make_sse({"type":"code","round":3,"done":True,"message":"πŸŽ‰ Website ready!","code":r2,"final":True,"files":split_into_files(r2, effective_prompt[:30])})
                break


def make_sse(data: dict) -> str:
    """Serialize SSE data with proper JSON encoding β€” no manual string manipulation."""
    return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"