File size: 92,370 Bytes
7bdbd56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import warnings
warnings.filterwarnings("ignore", message="The 'tuples' format for chatbot messages is deprecated")

# Ensure we're using Gradio 4.x
import gradio as gr
print(f"Gradio version: {gr.__version__}")
import json
import zipfile
import io
import os
from datetime import datetime
from dotenv import load_dotenv
import requests
from bs4 import BeautifulSoup
import tempfile
from pathlib import Path
from support_docs import create_support_docs, export_conversation_to_markdown

# Simple URL content fetching using requests and BeautifulSoup
def get_grounding_context_simple(urls):
    """Fetch grounding context using enhanced HTTP requests"""
    if not urls:
        return ""
    
    context_parts = []
    for i, url in enumerate(urls, 1):
        if url and url.strip():
            # Use enhanced URL extraction for any URLs within the URL text
            extracted_urls = extract_urls_from_text(url.strip())
            target_url = extracted_urls[0] if extracted_urls else url.strip()
            
            content = enhanced_fetch_url_content(target_url)
            context_parts.append(f"Context from URL {i} ({target_url}):\n{content}")
    
    if context_parts:
        return "\n\n" + "\n\n".join(context_parts) + "\n\n"
    return ""


# Load environment variables from .env file
load_dotenv()

# Utility functions
import re

def extract_urls_from_text(text):
    """Extract URLs from text using regex with enhanced validation"""
    url_pattern = r'https?://[^\s<>"{}|\\^`\[\]"]+'
    urls = re.findall(url_pattern, text)
    
    # Basic URL validation and cleanup
    validated_urls = []
    for url in urls:
        # Remove trailing punctuation that might be captured
        url = url.rstrip('.,!?;:')
        # Basic domain validation
        if '.' in url and len(url) > 10:
            validated_urls.append(url)
    
    return validated_urls

def validate_url_domain(url):
    """Basic URL domain validation"""
    try:
        from urllib.parse import urlparse
        parsed = urlparse(url)
        # Check for valid domain structure
        if parsed.netloc and '.' in parsed.netloc:
            return True
    except:
        pass
    return False

def enhanced_fetch_url_content(url, enable_search_validation=False):
    """Enhanced URL content fetching with optional search validation"""
    if not validate_url_domain(url):
        return f"Invalid URL format: {url}"
    
    try:
        # Enhanced headers for better compatibility
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'Connection': 'keep-alive'
        }
        
        response = requests.get(url, timeout=15, headers=headers)
        response.raise_for_status()
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Enhanced content cleaning
        for element in soup(["script", "style", "nav", "header", "footer", "aside", "form", "button"]):
            element.decompose()
        
        # Extract main content preferentially
        main_content = soup.find('main') or soup.find('article') or soup.find('div', class_=lambda x: bool(x and 'content' in x.lower())) or soup
        text = main_content.get_text()
        
        # Enhanced text cleaning
        lines = (line.strip() for line in text.splitlines())
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        text = ' '.join(chunk for chunk in chunks if chunk and len(chunk) > 2)
        
        # Smart truncation - try to end at sentence boundaries
        if len(text) > 4000:
            truncated = text[:4000]
            last_period = truncated.rfind('.')
            if last_period > 3000:  # If we can find a reasonable sentence break
                text = truncated[:last_period + 1]
            else:
                text = truncated + "..."
        
        return text if text.strip() else "No readable content found at this URL"
        
    except requests.exceptions.Timeout:
        return f"Timeout error fetching {{url}} (15s limit exceeded)"
    except requests.exceptions.RequestException as e:
        return f"Error fetching {{url}}: {{str(e)}}"
    except Exception as e:
        return f"Error processing content from {{url}}: {{str(e)}}"

# Template for generated space app (based on mvp_simple.py)
SPACE_TEMPLATE = '''import gradio as gr
import tempfile
import os
import requests
import json
import re
from bs4 import BeautifulSoup
from datetime import datetime
import urllib.parse


# Configuration
SPACE_NAME = "{name}"
SPACE_DESCRIPTION = "{description}"
SYSTEM_PROMPT = """{system_prompt}"""
MODEL = "{model}"
GROUNDING_URLS = {grounding_urls}
# Get access code from environment variable for security
# If SPACE_ACCESS_CODE is not set, no access control is applied
ACCESS_CODE = os.environ.get("SPACE_ACCESS_CODE")
ENABLE_DYNAMIC_URLS = {enable_dynamic_urls}

# Get API key from environment - customizable variable name with validation
API_KEY = os.environ.get("{api_key_var}")
if API_KEY:
    API_KEY = API_KEY.strip()  # Remove any whitespace
    if not API_KEY:  # Check if empty after stripping
        API_KEY = None
        
# API Key validation and logging
def validate_api_key():
    """Validate API key configuration with detailed logging"""
    if not API_KEY:
        print(f"⚠️  API KEY CONFIGURATION ERROR:")
        print(f"   Variable name: {api_key_var}")
        print(f"   Status: Not set or empty")
        print(f"   Action needed: Set '{api_key_var}' in HuggingFace Space secrets")
        print(f"   Expected format: sk-or-xxxxxxxxxx")
        return False
    elif not API_KEY.startswith('sk-or-'):
        print(f"⚠️  API KEY FORMAT WARNING:")
        print(f"   Variable name: {api_key_var}")
        print(f"   Current value: {{API_KEY[:10]}}..." if len(API_KEY) > 10 else API_KEY)
        print(f"   Expected format: sk-or-xxxxxxxxxx")
        print(f"   Note: OpenRouter keys should start with 'sk-or-'")
        return True  # Still try to use it
    else:
        print(f"✅ API Key configured successfully")
        print(f"   Variable: {api_key_var}")
        print(f"   Format: Valid OpenRouter key")
        return True

# Validate on startup
try:
    API_KEY_VALID = validate_api_key()
except NameError:
    # During template generation, API_KEY might not be defined yet
    API_KEY_VALID = False

def validate_url_domain(url):
    """Basic URL domain validation"""
    try:
        from urllib.parse import urlparse
        parsed = urlparse(url)
        # Check for valid domain structure
        if parsed.netloc and '.' in parsed.netloc:
            return True
    except:
        pass
    return False

def fetch_url_content(url):
    """Enhanced URL content fetching with improved compatibility and error handling"""
    if not validate_url_domain(url):
        return f"Invalid URL format: {{url}}"
    
    try:
        # Enhanced headers for better compatibility
        headers = {{
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'Connection': 'keep-alive'
        }}
        
        response = requests.get(url, timeout=15, headers=headers)
        response.raise_for_status()
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Enhanced content cleaning
        for element in soup(["script", "style", "nav", "header", "footer", "aside", "form", "button"]):
            element.decompose()
        
        # Extract main content preferentially
        main_content = soup.find('main') or soup.find('article') or soup.find('div', class_=lambda x: bool(x and 'content' in x.lower())) or soup
        text = main_content.get_text()
        
        # Enhanced text cleaning
        lines = (line.strip() for line in text.splitlines())
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        text = ' '.join(chunk for chunk in chunks if chunk and len(chunk) > 2)
        
        # Smart truncation - try to end at sentence boundaries
        if len(text) > 4000:
            truncated = text[:4000]
            last_period = truncated.rfind('.')
            if last_period > 3000:  # If we can find a reasonable sentence break
                text = truncated[:last_period + 1]
            else:
                text = truncated + "..."
        
        return text if text.strip() else "No readable content found at this URL"
        
    except requests.exceptions.Timeout:
        return f"Timeout error fetching {{url}} (15s limit exceeded)"
    except requests.exceptions.RequestException as e:
        return f"Error fetching {{url}}: {{str(e)}}"
    except Exception as e:
        return f"Error processing content from {{url}}: {{str(e)}}"

def extract_urls_from_text(text):
    """Extract URLs from text using regex with enhanced validation"""
    import re
    url_pattern = r'https?://[^\\s<>"{{}}|\\\\^`\\[\\]"]+'
    urls = re.findall(url_pattern, text)
    
    # Basic URL validation and cleanup
    validated_urls = []
    for url in urls:
        # Remove trailing punctuation that might be captured
        url = url.rstrip('.,!?;:')
        # Basic domain validation
        if '.' in url and len(url) > 10:
            validated_urls.append(url)
    
    return validated_urls

# Global cache for URL content to avoid re-crawling in generated spaces
_url_content_cache = {{}}

def get_grounding_context():
    """Fetch context from grounding URLs with caching"""
    if not GROUNDING_URLS:
        return ""
    
    # Create cache key from URLs
    cache_key = tuple(sorted([url for url in GROUNDING_URLS if url and url.strip()]))
    
    # Check cache first
    if cache_key in _url_content_cache:
        return _url_content_cache[cache_key]
    
    context_parts = []
    for i, url in enumerate(GROUNDING_URLS, 1):
        if url.strip():
            content = fetch_url_content(url.strip())
            # Add priority indicators
            priority_label = "PRIMARY" if i <= 2 else "SECONDARY"
            context_parts.append(f"[{{priority_label}}] Context from URL {{i}} ({{url}}):\\n{{content}}")
    
    if context_parts:
        result = "\\n\\n" + "\\n\\n".join(context_parts) + "\\n\\n"
    else:
        result = ""
    
    # Cache the result
    _url_content_cache[cache_key] = result
    return result

def export_conversation_to_markdown(conversation_history):
    """Export conversation history to markdown format"""
    if not conversation_history:
        return "No conversation to export."
    
    markdown_content = f"""# Conversation Export
Generated on: {{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}}

---

"""
    
    message_pair_count = 0
    for i, message in enumerate(conversation_history):
        if isinstance(message, dict):
            role = message.get('role', 'unknown')
            content = message.get('content', '')
            
            if role == 'user':
                message_pair_count += 1
                markdown_content += f"## User Message {{message_pair_count}}\\n\\n{{content}}\\n\\n"
            elif role == 'assistant':
                markdown_content += f"## Assistant Response {{message_pair_count}}\\n\\n{{content}}\\n\\n---\\n\\n"
        elif isinstance(message, (list, tuple)) and len(message) >= 2:
            # Handle legacy tuple format: ["user msg", "assistant msg"]
            message_pair_count += 1
            user_msg, assistant_msg = message[0], message[1]
            if user_msg:
                markdown_content += f"## User Message {{message_pair_count}}\\n\\n{{user_msg}}\\n\\n"
            if assistant_msg:
                markdown_content += f"## Assistant Response {{message_pair_count}}\\n\\n{{assistant_msg}}\\n\\n---\\n\\n"
    
    return markdown_content


def generate_response(message, history):
    """Generate response using OpenRouter API"""
    
    # Enhanced API key validation with helpful messages
    if not API_KEY:
        error_msg = f"🔑 **API Key Required**\\n\\n"
        error_msg += f"Please configure your OpenRouter API key:\\n"
        error_msg += f"1. Go to Settings (⚙️) in your HuggingFace Space\\n"
        error_msg += f"2. Click 'Variables and secrets'\\n"
        error_msg += f"3. Add secret: **{api_key_var}**\\n"
        error_msg += f"4. Value: Your OpenRouter API key (starts with `sk-or-`)\\n\\n"
        error_msg += f"Get your API key at: https://openrouter.ai/keys"
        print(f"❌ API request failed: No API key configured for {api_key_var}")
        return error_msg
    
    # Get grounding context
    grounding_context = get_grounding_context()
    
        
    # If dynamic URLs are enabled, check message for URLs to fetch
    if ENABLE_DYNAMIC_URLS:
        urls_in_message = extract_urls_from_text(message)
        if urls_in_message:
            # Fetch content from URLs mentioned in the message
            dynamic_context_parts = []
            for url in urls_in_message[:3]:  # Limit to 3 URLs per message
                content = fetch_url_content(url)
                dynamic_context_parts.append(f"\\n\\nDynamic context from {{url}}:\\n{{content}}")
            if dynamic_context_parts:
                grounding_context += "\\n".join(dynamic_context_parts)
    
    # Build enhanced system prompt with grounding context
    enhanced_system_prompt = SYSTEM_PROMPT + grounding_context
    
    # Build messages array for the API
    messages = [{{"role": "system", "content": enhanced_system_prompt}}]
    
    # Add conversation history - handle both modern messages format and legacy tuples
    for chat in history:
        if isinstance(chat, dict):
            # Modern format: {{"role": "user", "content": "..."}} or {{"role": "assistant", "content": "..."}}
            messages.append(chat)
        elif isinstance(chat, (list, tuple)) and len(chat) >= 2:
            # Legacy format: ["user msg", "assistant msg"] or ("user msg", "assistant msg")
            user_msg, assistant_msg = chat[0], chat[1]
            if user_msg:
                messages.append({{"role": "user", "content": user_msg}})
            if assistant_msg:
                messages.append({{"role": "assistant", "content": assistant_msg}})
    
    # Add current message
    messages.append({{"role": "user", "content": message}})
    
    # Make API request with enhanced error handling
    try:
        print(f"🔄 Making API request to OpenRouter...")
        print(f"   Model: {{MODEL}}")
        print(f"   Messages: {{len(messages)}} in conversation")
        
        response = requests.post(
            url="https://openrouter.ai/api/v1/chat/completions",
            headers={{
                "Authorization": f"Bearer {{API_KEY}}",
                "Content-Type": "application/json",
                "HTTP-Referer": "https://huggingface.co",  # Required by some providers
                "X-Title": "HuggingFace Space"  # Helpful for tracking
            }},
            json={{
                "model": MODEL,
                "messages": messages,
                "temperature": {temperature},
                "max_tokens": {max_tokens}
            }},
            timeout=30
        )
        
        print(f"📡 API Response: {{response.status_code}}")
        
        if response.status_code == 200:
            try:
                result = response.json()
                
                # Enhanced validation of API response structure
                if 'choices' not in result or not result['choices']:
                    print(f"⚠️  API response missing choices: {{result}}")
                    return "API Error: No response choices available"
                elif 'message' not in result['choices'][0]:
                    print(f"⚠️  API response missing message: {{result}}")
                    return "API Error: No message in response"
                elif 'content' not in result['choices'][0]['message']:
                    print(f"⚠️  API response missing content: {{result}}")
                    return "API Error: No content in message"
                else:
                    content = result['choices'][0]['message']['content']
                    
                    # Check for empty content
                    if not content or content.strip() == "":
                        print(f"⚠️  API returned empty content")
                        return "API Error: Empty response content"
                    
                    print(f"✅ API request successful")
                    return content
                    
            except (KeyError, IndexError, json.JSONDecodeError) as e:
                print(f"❌ Failed to parse API response: {{str(e)}}")
                return f"API Error: Failed to parse response - {{str(e)}}"
        elif response.status_code == 401:
            error_msg = f"🔐 **Authentication Error**\\n\\n"
            error_msg += f"Your API key appears to be invalid or expired.\\n\\n"
            error_msg += f"**Troubleshooting:**\\n"
            error_msg += f"1. Check that your **{api_key_var}** secret is set correctly\\n"
            error_msg += f"2. Verify your API key at: https://openrouter.ai/keys\\n"
            error_msg += f"3. Ensure your key starts with `sk-or-`\\n"
            error_msg += f"4. Check that you have credits on your OpenRouter account"
            print(f"❌ API authentication failed: {{response.status_code}} - {{response.text[:200]}}")
            return error_msg
        elif response.status_code == 429:
            error_msg = f"⏱️ **Rate Limit Exceeded**\\n\\n"
            error_msg += f"Too many requests. Please wait a moment and try again.\\n\\n"
            error_msg += f"**Troubleshooting:**\\n"
            error_msg += f"1. Wait 30-60 seconds before trying again\\n"
            error_msg += f"2. Check your OpenRouter usage limits\\n"
            error_msg += f"3. Consider upgrading your OpenRouter plan"
            print(f"❌ Rate limit exceeded: {{response.status_code}}")
            return error_msg
        elif response.status_code == 400:
            try:
                error_data = response.json()
                error_message = error_data.get('error', {{}}).get('message', 'Unknown error')
            except:
                error_message = response.text
            
            error_msg = f"⚠️ **Request Error**\\n\\n"
            error_msg += f"The API request was invalid:\\n"
            error_msg += f"`{{error_message}}`\\n\\n"
            if "model" in error_message.lower():
                error_msg += f"**Model Issue:** The model `{{MODEL}}` may not be available.\\n"
                error_msg += f"Try switching to a different model in your Space configuration."
            print(f"❌ Bad request: {{response.status_code}} - {{error_message}}")
            return error_msg
        else:
            error_msg = f"🚫 **API Error {{response.status_code}}**\\n\\n"
            error_msg += f"An unexpected error occurred. Please try again.\\n\\n"
            error_msg += f"If this persists, check:\\n"
            error_msg += f"1. OpenRouter service status\\n"
            error_msg += f"2. Your API key and credits\\n"
            error_msg += f"3. The model availability"
            print(f"❌ API error: {{response.status_code}} - {{response.text[:200]}}")
            return error_msg
            
    except requests.exceptions.Timeout:
        error_msg = f"⏰ **Request Timeout**\\n\\n"
        error_msg += f"The API request took too long (30s limit).\\n\\n"
        error_msg += f"**Troubleshooting:**\\n"
        error_msg += f"1. Try again with a shorter message\\n"
        error_msg += f"2. Check your internet connection\\n"
        error_msg += f"3. Try a different model"
        print(f"❌ Request timeout after 30 seconds")
        return error_msg
    except requests.exceptions.ConnectionError:
        error_msg = f"🌐 **Connection Error**\\n\\n"
        error_msg += f"Could not connect to OpenRouter API.\\n\\n"
        error_msg += f"**Troubleshooting:**\\n"
        error_msg += f"1. Check your internet connection\\n"
        error_msg += f"2. Check OpenRouter service status\\n"
        error_msg += f"3. Try again in a few moments"
        print(f"❌ Connection error to OpenRouter API")
        return error_msg
    except Exception as e:
        error_msg = f"❌ **Unexpected Error**\\n\\n"
        error_msg += f"An unexpected error occurred:\\n"
        error_msg += f"`{{str(e)}}`\\n\\n"
        error_msg += f"Please try again or contact support if this persists."
        print(f"❌ Unexpected error: {{str(e)}}")
        return error_msg

# Access code verification
access_granted = gr.State(False)
_access_granted_global = False  # Global fallback

def verify_access_code(code):
    \"\"\"Verify the access code\"\"\"
    global _access_granted_global
    if ACCESS_CODE is None:
        _access_granted_global = True
        return gr.update(visible=False), gr.update(visible=True), gr.update(value=True)
    
    if code == ACCESS_CODE:
        _access_granted_global = True
        return gr.update(visible=False), gr.update(visible=True), gr.update(value=True)
    else:
        _access_granted_global = False
        return gr.update(visible=True, value="❌ Incorrect access code. Please try again."), gr.update(visible=False), gr.update(value=False)

def protected_generate_response(message, history):
    \"\"\"Protected response function that checks access\"\"\"
    # Check if access is granted via the global variable
    if ACCESS_CODE is not None and not _access_granted_global:
        return "Please enter the access code to continue."
    return generate_response(message, history)

# Global variable to store chat history for export
chat_history_store = []

def store_and_generate_response(message, history):
    \"\"\"Wrapper function that stores history and generates response\"\"\"
    global chat_history_store
    
    # Generate response using the protected function
    response = protected_generate_response(message, history)
    
    # Convert current history to the format we need for export
    # history comes in as [["user1", "bot1"], ["user2", "bot2"], ...]
    chat_history_store = []
    if history:
        for exchange in history:
            if isinstance(exchange, (list, tuple)) and len(exchange) >= 2:
                chat_history_store.append({{"role": "user", "content": exchange[0]}})
                chat_history_store.append({{"role": "assistant", "content": exchange[1]}})
    
    # Add the current exchange
    chat_history_store.append({{"role": "user", "content": message}})
    chat_history_store.append({{"role": "assistant", "content": response}})
    
    return response

def export_current_conversation():
    \"\"\"Export the current conversation\"\"\"
    if not chat_history_store:
        return gr.update(visible=False)
    
    markdown_content = export_conversation_to_markdown(chat_history_store)
    
    # Save to temporary file
    with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
        f.write(markdown_content)
        temp_file = f.name
    
    return gr.update(value=temp_file, visible=True)

def export_conversation(history):
    \"\"\"Export conversation to markdown file\"\"\"
    if not history:
        return gr.update(visible=False)
    
    markdown_content = export_conversation_to_markdown(history)
    
    # Save to temporary file
    with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
        f.write(markdown_content)
        temp_file = f.name
    
    return gr.update(value=temp_file, visible=True)

# Configuration status display
def get_configuration_status():
    \"\"\"Generate a configuration status message for display\"\"\"
    status_parts = []
    
    if API_KEY_VALID:
        status_parts.append("✅ **API Key:** Configured and valid")
    else:
        status_parts.append("❌ **API Key:** Not configured - Set `{api_key_var}` in Space secrets")
    
    status_parts.append(f"🤖 **Model:** {{MODEL}}")
    status_parts.append(f"🌡️ **Temperature:** {temperature}")
    status_parts.append(f"📝 **Max Tokens:** {max_tokens}")
    
    # URL Grounding details
    if GROUNDING_URLS:
        status_parts.append(f"🔗 **URL Grounding:** {{len(GROUNDING_URLS)}} URLs configured")
        # Show first few URLs as examples
        for i, url in enumerate(GROUNDING_URLS[:3], 1):
            priority_label = "Primary" if i <= 2 else "Secondary"
            status_parts.append(f"  - [{{priority_label}}] {{url}}")
        if len(GROUNDING_URLS) > 3:
            status_parts.append(f"  - ... and {{len(GROUNDING_URLS) - 3}} more URLs")
    else:
        status_parts.append("🔗 **URL Grounding:** No URLs configured")
    
    if ENABLE_DYNAMIC_URLS:
        status_parts.append("🔄 **Dynamic URLs:** Enabled")
    else:
        status_parts.append("🔄 **Dynamic URLs:** Disabled")
    
    if ACCESS_CODE is not None:
        status_parts.append("🔐 **Access Control:** Enabled")
    else:
        status_parts.append("🌐 **Access:** Public Chatbot")
    
    # System Prompt (add at the end)
    status_parts.append("")  # Empty line for spacing
    status_parts.append("**System Prompt:**")
    status_parts.append(f"{{SYSTEM_PROMPT}}")
    
    return "\\n".join(status_parts)

# Create interface with access code protection
with gr.Blocks(title=SPACE_NAME) as demo:
    gr.Markdown(f"# {{SPACE_NAME}}")
    gr.Markdown(SPACE_DESCRIPTION)
    
    # Access code section (shown only if ACCESS_CODE is set)
    with gr.Column(visible=(ACCESS_CODE is not None)) as access_section:
        gr.Markdown("### 🔐 Access Required")
        gr.Markdown("Please enter the access code provided by your instructor:")
        
        access_input = gr.Textbox(
            label="Access Code",
            placeholder="Enter access code...",
            type="password"
        )
        access_btn = gr.Button("Submit", variant="primary")
        access_error = gr.Markdown(visible=False)
    
    # Main chat interface (hidden until access granted)
    with gr.Column(visible=(ACCESS_CODE is None)) as chat_section:
        chat_interface = gr.ChatInterface(
            fn=store_and_generate_response,  # Use wrapper function to store history
            title="",  # Title already shown above
            description="",  # Description already shown above
            examples={examples},
            type="messages"  # Use modern message format for better compatibility
        )
        
        # Export functionality
        with gr.Row():
            export_btn = gr.Button("📥 Export Conversation", variant="secondary", size="sm")
            export_file = gr.File(label="Download Conversation", visible=False)
        
        # Connect export functionality
        export_btn.click(
            export_current_conversation,
            outputs=[export_file]
        )
        
        # Configuration status (always visible)
        with gr.Accordion("📊 Configuration Status", open=not API_KEY_VALID):
            gr.Markdown(get_configuration_status())
    
    # Connect access verification
    if ACCESS_CODE is not None:
        access_btn.click(
            verify_access_code,
            inputs=[access_input],
            outputs=[access_error, chat_section, access_granted]
        )
        access_input.submit(
            verify_access_code,
            inputs=[access_input],
            outputs=[access_error, chat_section, access_granted]
        )

if __name__ == "__main__":
    demo.launch()
'''

# Available models - Updated with valid OpenRouter model IDs
MODELS = [
    "google/gemini-2.0-flash-001",      # Fast, reliable, general tasks
    "google/gemma-3-27b-it",            # High-performance open model
    "anthropic/claude-3.5-haiku",       # Complex reasoning and analysis
    "openai/gpt-4o-mini-search-preview", # Balanced performance and cost with search
    "openai/gpt-4.1-nano",              # Lightweight OpenAI model
    "nvidia/llama-3.1-nemotron-70b-instruct", # Large open-source model
    "mistralai/devstral-small"           # Coding-focused model
]


def get_grounding_context(urls):
    """Fetch context from grounding URLs"""
    if not urls:
        return ""
    
    context_parts = []
    for i, url in enumerate(urls, 1):
        if url and url.strip():
            content = enhanced_fetch_url_content(url.strip())
            # Add priority indicators
            priority_label = "PRIMARY" if i <= 2 else "SECONDARY"
            context_parts.append(f"[{priority_label}] Context from URL {i} ({url}):\n{content}")
    
    if context_parts:
        return "\n\n" + "\n\n".join(context_parts) + "\n\n"
    return ""

def create_readme(config):
    """Generate README with deployment instructions and proper HF Spaces YAML header"""
    # Ensure short_description is a proper string and within HF's 60-character limit
    description = config.get('description', '') or 'AI chat interface'
    if len(description) > 60:
        short_desc = description[:57] + '...'  # 57 + 3 = 60 characters total
    else:
        short_desc = description
    
    return f"""---
title: {config['name']}
emoji: 🤖
colorFrom: blue
colorTo: red
sdk: gradio
sdk_version: 5.38.0
app_file: app.py
pinned: false
license: mit
short_description: "{short_desc}"
---

# {config['name']}

{config['description']}

## Quick Deploy to HuggingFace Spaces

### Step 1: Create the Space
1. Go to https://huggingface.co/spaces
2. Click "Create new Space"
3. Choose a name for your Space
4. Select **Gradio** as the SDK
5. Set visibility (Public/Private)
6. Click "Create Space"

### Step 2: Upload Files
1. In your new Space, click "Files" tab
2. Upload these files from the zip:
   - `app.py`
   - `requirements.txt`
3. Wait for "Building" to complete

### Step 3: Add API Key
1. Go to Settings (gear icon) 
2. Click "Variables and secrets"
3. Click "New secret"
4. Name: `{config['api_key_var']}`
5. Value: Your OpenRouter API key
6. Click "Add"

{f'''### Step 4: Configure Access Control
Your Space is configured with access code protection. Students will need to enter the access code to use the chatbot.

1. Go to Settings (gear icon) 
2. Click "Variables and secrets"
3. Click "New secret"
4. Name: `SPACE_ACCESS_CODE`
5. Value: `{config['access_code']}`
6. Click "Add"

**Important**: The access code is now stored securely as an environment variable and is not visible in your app code.

To disable access protection:
1. Go to Settings → Variables and secrets
2. Delete the `SPACE_ACCESS_CODE` secret
3. The Space will rebuild automatically with no access protection

''' if config['access_code'] else ''}

### Step {4 if not config['access_code'] else 5}: Get Your API Key
1. Go to https://openrouter.ai/keys
2. Sign up/login if needed
3. Click "Create Key"
4. Copy the key (starts with `sk-or-`)

### Step {5 if not config['access_code'] else 6}: Test Your Space
- Go back to "App" tab
- Your Space should be running!
- Try the example prompts or ask a question

## Configuration

- **Model**: {config['model']}
- **Temperature**: {config['temperature']}
- **Max Tokens**: {config['max_tokens']}
- **API Key Variable**: {config['api_key_var']}"""
    
    # Add optional configuration items
    if config['access_code']:
        readme_content += f"""
- **Access Code**: {config['access_code']} (Students need this to access the chatbot)"""
    
    if config.get('enable_dynamic_urls'):
        readme_content += """
- **Dynamic URL Fetching**: Enabled (Assistant can fetch URLs mentioned in conversations)"""
    
    readme_content += f"""

## Customization

To modify your Space:
1. Edit `app.py` in your Space
2. Update configuration variables at the top
3. Changes deploy automatically

## Troubleshooting

- **"Please set your {config['api_key_var']}"**: Add the secret in Space settings
- **Error 401**: Invalid API key or no credits
- **Error 429**: Rate limit - wait and try again
- **Build failed**: Check requirements.txt formatting

## More Help

- HuggingFace Spaces: https://huggingface.co/docs/hub/spaces
- OpenRouter Docs: https://openrouter.ai/docs
- Gradio Docs: https://gradio.app/docs

---

Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} with Chat U/I Helper
"""
    
    return readme_content

def create_requirements():
    """Generate requirements.txt with latest versions"""
    return "gradio>=5.38.0\nrequests>=2.32.3\nbeautifulsoup4>=4.12.3\npython-dotenv>=1.0.0"

def generate_zip(name, description, system_prompt, model, api_key_var, temperature, max_tokens, examples_text, access_code_field="", enable_dynamic_urls=False, url1="", url2="", url3="", url4="", url5="", url6="", url7="", url8="", url9="", url10=""):
    """Generate deployable zip file"""
    
    # Process examples
    if examples_text and examples_text.strip():
        examples_list = [ex.strip() for ex in examples_text.split('\n') if ex.strip()]
        examples_python = repr(examples_list)  # Convert to Python literal representation
    else:
        examples_python = repr([
            "Hello! How can you help me?",
            "Tell me something interesting",
            "What can you do?"
        ])
    
    # Process grounding URLs
    grounding_urls = []
    for url in [url1, url2, url3, url4, url5, url6, url7, url8, url9, url10]:
        if url and url.strip():
            grounding_urls.append(url.strip())
    
    # Use the provided system prompt directly
    
    # Create config
    config = {
        'name': name,
        'description': description,
        'system_prompt': system_prompt,
        'model': model,
        'api_key_var': api_key_var,
        'temperature': temperature,
        'max_tokens': int(max_tokens),
        'examples': examples_python,
        'grounding_urls': json.dumps(grounding_urls),
        'enable_dynamic_urls': enable_dynamic_urls
    }
    
    # Generate files
    app_content = SPACE_TEMPLATE.format(**config)
    # Pass empty access_code to README since user will configure it in HF Spaces
    readme_config = config.copy()
    readme_config['access_code'] = ""  # Always empty since user configures in HF Spaces
    readme_content = create_readme(readme_config)
    requirements_content = create_requirements()
    
    # Create zip file with clean naming
    filename = f"{name.lower().replace(' ', '_').replace('-', '_')}.zip"
    
    # Create zip in memory and save to disk
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        zip_file.writestr('app.py', app_content)
        zip_file.writestr('requirements.txt', requirements_content)
        zip_file.writestr('README.md', readme_content)
        zip_file.writestr('config.json', json.dumps(config, indent=2))
    
    # Write zip to file
    zip_buffer.seek(0)
    with open(filename, 'wb') as f:
        f.write(zip_buffer.getvalue())
    
    return filename

# Define callback functions outside the interface

def update_sandbox_preview(config_data):
    """Update the sandbox preview with generated content"""
    if not config_data:
        return "Generate a space configuration to see preview here.", "<div style='text-align: center; padding: 50px; color: #666;'>No preview available</div>"
    
    # Create preview info
    preview_text = f"""**Space Configuration:**
- **Name:** {config_data.get('name', 'N/A')}
- **Model:** {config_data.get('model', 'N/A')}
- **Temperature:** {config_data.get('temperature', 'N/A')}
- **Max Tokens:** {config_data.get('max_tokens', 'N/A')}
- **Dynamic URLs:** {'✅ Enabled' if config_data.get('enable_dynamic_urls') else '❌ Disabled'}

**System Prompt Preview:**
> {config_data.get('system_prompt', 'No system prompt configured')[:500]}{'...' if len(config_data.get('system_prompt', '')) > 500 else ''}

**Deployment Package:** `{config_data.get('filename', 'Not generated')}`"""
    
    # Create a basic HTML preview of the chat interface
    preview_html = f"""
    <div style="border: 1px solid #ddd; border-radius: 8px; padding: 20px; background: white;">
        <h3 style="margin-top: 0; color: #333;">{config_data.get('name', 'Chat Interface')}</h3>
        <p style="color: #666; margin-bottom: 20px;">{config_data.get('description', 'A customizable AI chat interface')}</p>
        
        <div style="border: 1px solid #ccc; border-radius: 4px; background: white; min-height: 200px; padding: 15px; margin-bottom: 15px;">
            <div style="color: #888; text-align: center; padding: 50px 0;">Chat Interface Preview</div>
            <div style="background: #f0f8ff; padding: 10px; border-radius: 4px; margin-bottom: 10px; border-left: 3px solid #0066cc;">
                <strong>Assistant:</strong> Hello! I'm ready to help you. How can I assist you today?
            </div>
        </div>
        
        <div style="border: 1px solid #ccc; border-radius: 4px; padding: 10px; background: white;">
            <input type="text" placeholder="Type your message here..." style="width: 70%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-right: 10px;">
            <button style="padding: 8px 15px; background: #0066cc; color: white; border: none; border-radius: 4px; cursor: pointer;">Send</button>
        </div>
        
        <div style="margin-top: 15px; padding: 10px; background: white; border: 1px solid #e0e0e0; border-radius: 4px; font-size: 12px; color: #666;">
            <strong>Configuration:</strong> Model: {config_data.get('model', 'N/A')} | Temperature: {config_data.get('temperature', 'N/A')} | Max Tokens: {config_data.get('max_tokens', 'N/A')}
        </div>
    </div>
    """
    
    return preview_text, preview_html

def on_preview_combined(name, description, system_prompt, model, temperature, max_tokens, examples_text, enable_dynamic_urls, url1="", url2="", url3="", url4="", url5="", url6="", url7="", url8="", url9="", url10=""):
    """Generate configuration and return preview updates"""
    if not name or not name.strip():
        return (
            {},
            gr.update(value="**Error:** Please provide a Space Title to preview", visible=True),
            gr.update(visible=False),
            gr.update(value="Configuration will appear here after preview generation."),
            *[gr.update() for _ in range(10)],  # 10 URL updates
            gr.update(),  # preview_add_url_btn
            gr.update(),  # preview_remove_url_btn
            2,           # preview_url_count
            *[gr.update(visible=False) for _ in range(3)]  # 3 example button updates
        )
    
    try:
        # Use the system prompt directly (template selector already updates it)
        if not system_prompt or not system_prompt.strip():
            return (
                {},
                gr.update(value="**Error:** Please provide a System Prompt for the assistant", visible=True),
                gr.update(visible=False),
                gr.update(value="Configuration will appear here after preview generation."),
                *[gr.update() for _ in range(10)],  # 10 URL updates
                gr.update(),  # preview_add_url_btn
                gr.update(),  # preview_remove_url_btn
                2,           # preview_url_count
                *[gr.update(visible=False) for _ in range(3)]  # 3 example button updates
            )
        
        final_system_prompt = system_prompt.strip()
        
        # Process examples like the deployment package
        if examples_text and examples_text.strip():
            examples_list = [ex.strip() for ex in examples_text.split('\n') if ex.strip()]
        else:
            examples_list = [
                "Hello! How can you help me?",
                "Tell me something interesting", 
                "What can you do?"
            ]
        
        # Create configuration for preview
        config_data = {
            'name': name,
            'description': description,
            'system_prompt': final_system_prompt,
            'model': model,
            'temperature': temperature,
            'max_tokens': max_tokens,
            'enable_dynamic_urls': enable_dynamic_urls,
            'url1': url1,
            'url2': url2,
            'url3': url3,
            'url4': url4,
            'url5': url5,
            'url6': url6,
            'url7': url7,
            'url8': url8,
            'url9': url9,
            'url10': url10,
            'examples_text': examples_text,
            'examples_list': examples_list,  # Processed examples for preview
            'preview_ready': True
        }
        
        # Generate preview displays with example prompts
        examples_preview = "\n".join([f"• {ex}" for ex in examples_list[:3]])  # Show first 3 examples
        
        preview_text = f"""**{name}** is ready to test. Use the example prompts below or type your own message."""
        config_display = f"""> **Configuration**:
- **Name:** {name}
- **Description:** {description or 'No description provided'}
- **Model:** {model}
- **Temperature:** {temperature}
- **Max Response Tokens:** {max_tokens}

**System Prompt:**
{final_system_prompt}

**Example Prompts:**
{examples_text if examples_text and examples_text.strip() else 'No example prompts configured'}
"""
        
        # Show success notification
        gr.Info(f"✅ Preview generated successfully for '{name}'! Switch to Preview tab.")

        # Determine how many URLs are configured
        all_urls = [url1, url2, url3, url4, url5, url6, url7, url8, url9, url10]
        url_count = 2  # Start with 2 (always visible)
        for i, url in enumerate(all_urls[2:], start=3):  # Check urls 3-10
            if url and url.strip():
                url_count = i
            else:
                break
        
        # Create URL updates for all preview URLs
        url_updates = []
        for i in range(1, 11):  # URLs 1-10
            url_value = all_urls[i-1] if i <= len(all_urls) else ""
            if i <= 2:  # URLs 1-2 are always visible
                url_updates.append(gr.update(value=url_value))
            else:  # URLs 3-10
                url_updates.append(gr.update(value=url_value, visible=(i <= url_count)))
        
        # Update button states
        secondary_count = url_count - 2  # Number of secondary URLs
        if url_count >= 10:
            preview_add_btn_update = gr.update(value="Max Secondary URLs (8/8)", interactive=False)
        else:
            preview_add_btn_update = gr.update(value=f"+ Add Secondary URLs ({secondary_count}/8)", interactive=True)
        
        preview_remove_btn_update = gr.update(visible=(url_count > 2))
        
        # Update example buttons
        example_btn_updates = []
        for i in range(3):
            if i < len(examples_list):
                # Add click icon and truncate text nicely
                btn_text = f"💬 {examples_list[i][:45]}{'...' if len(examples_list[i]) > 45 else ''}"
                example_btn_updates.append(gr.update(value=btn_text, visible=True))
            else:
                example_btn_updates.append(gr.update(visible=False))
        
        return (
            config_data,
            gr.update(value=preview_text, visible=True),
            gr.update(visible=True),
            gr.update(value=config_display),
            *url_updates,  # Unpack all 10 URL updates
            preview_add_btn_update,
            preview_remove_btn_update,
            url_count,
            *example_btn_updates  # Add example button updates
        )
        
    except Exception as e:
        return (
            {},
            gr.update(value=f"**Error:** {str(e)}", visible=True),
            gr.update(visible=False),
            gr.update(value="Configuration will appear here after preview generation."),
            *[gr.update() for _ in range(10)],  # 10 URL updates
            gr.update(),  # preview_add_url_btn
            gr.update(),  # preview_remove_url_btn
            2,           # preview_url_count
            *[gr.update(visible=False) for _ in range(3)]  # 3 example button updates
        )

def update_preview_display(config_data):
    """Update preview display based on config data"""
    if not config_data or not config_data.get('preview_ready'):
        return (
            gr.update(value="**Status:** Configure your space in the Configuration tab and click 'Preview Deployment Package' to see your assistant here.", visible=True),
            gr.update(visible=False),
            gr.update(value="Configuration will appear here after preview generation.")
        )
    
    # Generate example prompts display
    examples_list = config_data.get('examples_list', [])
    examples_preview = "\n".join([f"• {ex}" for ex in examples_list[:3]])  # Show first 3 examples
    
    preview_text = f"""**{config_data['name']}** is ready to test. Use the example prompts below or type your own message."""
    
    config_display = f"""### Current Configuration

**Space Details:**
- **Name:** {config_data['name']}
- **Description:** {config_data.get('description', 'No description provided')}

**Model Settings:**
- **Model:** {config_data['model']}
- **Temperature:** {config_data['temperature']}
- **Max Response Tokens:** {config_data['max_tokens']}

**Features:**
- **Dynamic URL Fetching:** {'✅ Enabled' if config_data['enable_dynamic_urls'] else '❌ Disabled'}

**System Prompt:**
{config_data['system_prompt']}

**Example Prompts:**
{config_data.get('examples_text', 'No example prompts configured') if config_data.get('examples_text', '').strip() else 'No example prompts configured'}
"""
    
    return (
        gr.update(value=preview_text, visible=True),
        gr.update(visible=True),
        gr.update(value=config_display)
    )

def preview_chat_response(message, history, config_data, url1="", url2="", url3="", url4="", url5="", url6="", url7="", url8="", url9="", url10=""):
    """Generate response for preview chat using actual OpenRouter API"""
    if not config_data or not message:
        return "", history
    
    # Get API key from environment
    api_key = os.environ.get("OPENROUTER_API_KEY")
    
    if not api_key:
        response = f"""🔑 **API Key Required for Preview**

To test your assistant with real API responses, please:

1. Get your OpenRouter API key from: https://openrouter.ai/keys
2. Set it as an environment variable: `export OPENROUTER_API_KEY=your_key_here`
3. Or add it to your `.env` file: `OPENROUTER_API_KEY=your_key_here`

**Your Configuration:**
- **Name:** {config_data.get('name', 'your assistant')}
- **Model:** {config_data.get('model', 'unknown model')}
- **Temperature:** {config_data.get('temperature', 0.7)}
- **Max Tokens:** {config_data.get('max_tokens', 500)}

**System Prompt Preview:**
{config_data.get('system_prompt', '')[:200]}{'...' if len(config_data.get('system_prompt', '')) > 200 else ''}

Once you set your API key, you'll be able to test real conversations in this preview."""
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": response})
        return "", history
    
    try:
        # Get grounding context from URLs - prioritize config_data URLs, fallback to preview tab URLs
        config_urls = [
            config_data.get('url1', ''),
            config_data.get('url2', ''),
            config_data.get('url3', ''),
            config_data.get('url4', ''),
            config_data.get('url5', ''),
            config_data.get('url6', ''),
            config_data.get('url7', ''),
            config_data.get('url8', ''),
            config_data.get('url9', ''),
            config_data.get('url10', '')
        ]
        # Use config URLs if available, otherwise use preview tab URLs
        grounding_urls = config_urls if any(url for url in config_urls if url) else [url1, url2, url3, url4, url5, url6, url7, url8, url9, url10]
        grounding_context = get_cached_grounding_context([url for url in grounding_urls if url and url.strip()])
        
                
        # If dynamic URLs are enabled, check message for URLs to fetch
        dynamic_context = ""
        if config_data.get('enable_dynamic_urls'):
            urls_in_message = extract_urls_from_text(message)
            if urls_in_message:
                dynamic_context_parts = []
                for url in urls_in_message[:3]:  # Increased limit to 3 URLs with enhanced processing
                    content = enhanced_fetch_url_content(url)
                    dynamic_context_parts.append(f"\n\nDynamic context from {url}:\n{content}")
                if dynamic_context_parts:
                    dynamic_context = "\n".join(dynamic_context_parts)
        
        # Build enhanced system prompt with all contexts
        enhanced_system_prompt = config_data.get('system_prompt', '') + grounding_context + dynamic_context
        
        # Build messages array for the API
        messages = [{"role": "system", "content": enhanced_system_prompt}]
        
        # Add conversation history - handle both formats for backwards compatibility
        for chat in history:
            if isinstance(chat, dict):
                # New format: {"role": "user", "content": "..."}
                messages.append(chat)
            elif isinstance(chat, list) and len(chat) >= 2:
                # Legacy format: [user_msg, assistant_msg]
                user_msg, assistant_msg = chat[0], chat[1]
                if user_msg:
                    messages.append({"role": "user", "content": user_msg})
                if assistant_msg:
                    messages.append({"role": "assistant", "content": assistant_msg})
        
        # Add current message
        messages.append({"role": "user", "content": message})
        
        # Debug: Log the request being sent
        request_payload = {
            "model": config_data.get('model', 'google/gemini-2.0-flash-001'),
            "messages": messages,
            "temperature": config_data.get('temperature', 0.7),
            "max_tokens": config_data.get('max_tokens', 500),
            "tools": None  # Explicitly disable tool/function calling
        }
        
        # Make API request to OpenRouter
        response = requests.post(
            url="https://openrouter.ai/api/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            },
            json=request_payload,
            timeout=30
        )
        
        if response.status_code == 200:
            try:
                response_data = response.json()
                
                # Check if response has expected structure
                if 'choices' not in response_data or not response_data['choices']:
                    assistant_response = f"[Preview Debug] No choices in API response. Response: {response_data}"
                elif 'message' not in response_data['choices'][0]:
                    assistant_response = f"[Preview Debug] No message in first choice. Response: {response_data}"
                elif 'content' not in response_data['choices'][0]['message']:
                    assistant_response = f"[Preview Debug] No content in message. Response: {response_data}"
                else:
                    assistant_content = response_data['choices'][0]['message']['content']
                    
                    # Debug: Check if content is empty
                    if not assistant_content or assistant_content.strip() == "":
                        assistant_response = f"[Preview Debug] Empty content from API. Messages sent: {len(messages)} messages, last user message: '{message}', model: {request_payload['model']}"
                    else:
                        # Use the content directly - no preview indicator needed
                        assistant_response = assistant_content
                        
            except (KeyError, IndexError, json.JSONDecodeError) as e:
                assistant_response = f"[Preview Error] Failed to parse API response: {str(e)}. Raw response: {response.text[:500]}"
        else:
            assistant_response = f"[Preview Error] API Error: {response.status_code} - {response.text[:500]}"
            
    except Exception as e:
        assistant_response = f"[Preview Error] {str(e)}"
    
    # Return in the new messages format for Gradio 5.x
    history.append({"role": "user", "content": message})
    history.append({"role": "assistant", "content": assistant_response})
    return "", history

def clear_preview_chat():
    """Clear preview chat"""
    return "", []

def set_example_prompt(example_text):
    """Set example prompt in the text input"""
    return example_text

def export_preview_conversation(history, config_data=None):
    """Export preview conversation to markdown"""
    if not history:
        return gr.update(visible=False)
    
    markdown_content = export_conversation_to_markdown(history, config_data)
    
    # Save to temporary file
    import tempfile
    with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
        f.write(markdown_content)
        temp_file = f.name
    
    return gr.update(value=temp_file, visible=True)

def on_generate(name, description, system_prompt, model, api_key_var, temperature, max_tokens, examples_text, access_code, enable_dynamic_urls, url1, url2, url3, url4, url5, url6, url7, url8, url9, url10):
    if not name or not name.strip():
        return gr.update(value="Error: Please provide a Space Title", visible=True), gr.update(visible=False), {}
    
    
    try:
        # Use the system prompt directly (template selector already updates it)
        if not system_prompt or not system_prompt.strip():
            return gr.update(value="Error: Please provide a System Prompt for the assistant", visible=True), gr.update(visible=False), {}
        
        final_system_prompt = system_prompt.strip()
        
        filename = generate_zip(name, description, final_system_prompt, model, api_key_var, temperature, max_tokens, examples_text, access_code, enable_dynamic_urls, url1, url2, url3, url4, url5, url6, url7, url8, url9, url10)
        
        success_msg = f"""**Deployment package ready!**

**File**: `{filename}`

**What's included:**
- `app.py` - Ready-to-deploy chat interface (Gradio 5.38.0)
- `requirements.txt` - Latest dependencies  
- `README.md` - HuggingFace Spaces configuration & instructions
- `config.json` - Configuration backup

**Next steps:**
1. Download the zip file below
2. Go to https://huggingface.co/spaces and create a new Space
3. Upload ALL files from the zip to your Space (including README.md)
4. Set your `{api_key_var}` secret in Space settings

**Your Space will be live in minutes!**"""
        
        # Update sandbox preview
        config_data = {
            'name': name,
            'description': description,
            'system_prompt': final_system_prompt,
            'model': model,
            'temperature': temperature,
            'max_tokens': max_tokens,
            'enable_dynamic_urls': enable_dynamic_urls,
            'filename': filename
        }
        
        return gr.update(value=success_msg, visible=True), gr.update(value=filename, visible=True), config_data
        
    except Exception as e:
        return gr.update(value=f"Error: {str(e)}", visible=True), gr.update(visible=False), {}

# Global cache for URL content to avoid re-crawling
url_content_cache = {}

def get_cached_grounding_context(urls):
    """Get grounding context with caching to avoid re-crawling same URLs"""
    if not urls:
        return ""
    
    # Filter valid URLs
    valid_urls = [url for url in urls if url and url.strip()]
    if not valid_urls:
        return ""
    
    # Create cache key from sorted URLs
    cache_key = tuple(sorted(valid_urls))
    
    # Check if we already have this content cached
    if cache_key in url_content_cache:
        return url_content_cache[cache_key]
    
    # If not cached, fetch using simple HTTP requests
    grounding_context = get_grounding_context_simple(valid_urls)
    
    # Cache the result
    url_content_cache[cache_key] = grounding_context
    
    return grounding_context


def respond(message, chat_history, url1="", url2="", url3="", url4="", url5="", url6="", url7="", url8="", url9="", url10=""):
    # Make actual API request to OpenRouter
    import os
    import requests
    
    # Get API key from environment
    api_key = os.environ.get("OPENROUTER_API_KEY")
    
    if not api_key:
        response = "Please set your OPENROUTER_API_KEY in the Space settings to use the chat support."
        chat_history.append({"role": "user", "content": message})
        chat_history.append({"role": "assistant", "content": response})
        return "", chat_history
    
    # Get grounding context from URLs using cached approach
    grounding_urls = [url1, url2, url3, url4, url5, url6, url7, url8, url9, url10]
    grounding_context = get_cached_grounding_context(grounding_urls)
    
    # Build enhanced system prompt with grounding context
    base_system_prompt = """You are an expert assistant specializing in Gradio configurations for HuggingFace Spaces. You have deep knowledge of:
- Gradio interface components and layouts
- HuggingFace Spaces configuration (YAML frontmatter, secrets, environment variables)
- Deployment best practices for Gradio apps on HuggingFace
- Space settings, SDK versions, and hardware requirements
- Troubleshooting common Gradio and HuggingFace Spaces issues
- Integration with various APIs and models through Gradio interfaces

Provide specific, technical guidance focused on Gradio implementation details and HuggingFace Spaces deployment. Include code examples when relevant. Keep responses concise and actionable."""
    
    enhanced_system_prompt = base_system_prompt + grounding_context
    
    # Build conversation history for API
    messages = [{
        "role": "system", 
        "content": enhanced_system_prompt
    }]
    
    # Add conversation history - Support both new messages format and legacy tuple format
    for chat in chat_history:
        if isinstance(chat, dict):
            # New format: {"role": "user", "content": "..."}
            messages.append(chat)
        elif isinstance(chat, (list, tuple)) and len(chat) >= 2:
            # Legacy format: ("user msg", "bot msg")
            user_msg, assistant_msg = chat[0], chat[1]
            if user_msg:
                messages.append({"role": "user", "content": user_msg})
            if assistant_msg:
                messages.append({"role": "assistant", "content": assistant_msg})
    
    # Add current message
    messages.append({"role": "user", "content": message})
    
    try:
        # Make API request to OpenRouter
        response = requests.post(
            url="https://openrouter.ai/api/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            },
            json={
                "model": "google/gemini-2.0-flash-001",
                "messages": messages,
                "temperature": 0.7,
                "max_tokens": 500
            }
        )
        
        if response.status_code == 200:
            assistant_response = response.json()['choices'][0]['message']['content']
        else:
            assistant_response = f"Error: {response.status_code} - {response.text}"
            
    except Exception as e:
        assistant_response = f"Error: {str(e)}"
    
    chat_history.append({"role": "user", "content": message})
    chat_history.append({"role": "assistant", "content": assistant_response})
    return "", chat_history

def clear_chat():
    return "", []



def add_urls(count):
    """Show additional URL fields"""
    new_count = min(count + 1, 10)
    
    # Create visibility updates for all URL fields (3-10)
    url_updates = []
    for i in range(3, 11):  # URLs 3-10
        if i <= new_count:
            url_updates.append(gr.update(visible=True))
        else:
            url_updates.append(gr.update(visible=False))
    
    # Update button states  
    secondary_count = new_count - 2  # Number of secondary URLs
    if new_count >= 10:
        add_btn_update = gr.update(value="Max Secondary URLs (8/8)", interactive=False)
    else:
        add_btn_update = gr.update(value=f"+ Add Secondary URLs ({secondary_count}/8)")
    
    remove_btn_update = gr.update(visible=True)
    
    return (*url_updates, add_btn_update, remove_btn_update, new_count)

def remove_urls(count):
    """Hide URL fields"""
    new_count = max(count - 1, 4)
    
    # Create visibility updates for all URL fields (3-10)
    url_updates = []
    for i in range(3, 11):  # URLs 3-10
        if i <= new_count:
            url_updates.append(gr.update(visible=True))
        else:
            url_updates.append(gr.update(visible=False, value=""))
    
    # Update button states
    secondary_count = new_count - 2  # Number of secondary URLs
    add_btn_update = gr.update(value=f"+ Add Secondary URLs ({secondary_count}/8)", interactive=True)
    
    if new_count <= 4:
        remove_btn_update = gr.update(visible=False)
    else:
        remove_btn_update = gr.update(visible=True)
    
    return (*url_updates, add_btn_update, remove_btn_update, new_count)




def toggle_template(template_choice, current_prompt, cached_custom_prompt):
    """Toggle between different assistant templates"""
    # If we're switching away from "None", cache the current custom prompt
    if template_choice != "None" and current_prompt and current_prompt.strip():
        # Check if the current prompt is not a template prompt
        research_prompt = "You are a research aid specializing in academic literature search and analysis. Your expertise spans discovering peer-reviewed sources, assessing research methodologies, synthesizing findings across studies, and delivering properly formatted citations. When responding, anchor claims in specific sources from provided URL contexts, differentiate between direct evidence and interpretive analysis, and note any limitations or contradictory results. Employ clear, accessible language that demystifies complex research, and propose connected research directions when appropriate. Your purpose is to serve as an informed research tool supporting users through initial concept development, exploratory investigation, information collection, and source compilation."
        socratic_prompt = "You are a pedagogically-minded academic assistant designed for introductory courses. Your approach follows constructivist learning principles: build on students' prior knowledge, scaffold complex concepts through graduated questioning, and use Socratic dialogue to guide discovery. Provide concise, evidence-based explanations that connect theory to lived experiences. Each response should model critical thinking by acknowledging multiple perspectives, identifying assumptions, and revealing conceptual relationships. Conclude with open-ended questions that promote higher-order thinking—analysis, synthesis, or evaluation—rather than recall."
        
        # Only cache if it's not one of the template prompts
        if current_prompt != research_prompt and current_prompt != socratic_prompt:
            cached_custom_prompt = current_prompt
    
    if template_choice == "Research Template":
        research_prompt = "You are a research aid specializing in academic literature search and analysis. Your expertise spans discovering peer-reviewed sources, assessing research methodologies, synthesizing findings across studies, and delivering properly formatted citations. When responding, anchor claims in specific sources from provided URL contexts, differentiate between direct evidence and interpretive analysis, and note any limitations or contradictory results. Employ clear, accessible language that demystifies complex research, and propose connected research directions when appropriate. Your purpose is to serve as an informed research tool supporting users through initial concept development, exploratory investigation, information collection, and source compilation."
        return (
            gr.update(value=research_prompt),  # Update main system prompt
            gr.update(value=True),  # Enable dynamic URL fetching for research template
            cached_custom_prompt  # Return the cached prompt
        )
    elif template_choice == "Socratic Template":
        socratic_prompt = "You are a pedagogically-minded academic assistant designed for introductory courses. Your approach follows constructivist learning principles: build on students' prior knowledge, scaffold complex concepts through graduated questioning, and use Socratic dialogue to guide discovery. Provide concise, evidence-based explanations that connect theory to lived experiences. Each response should model critical thinking by acknowledging multiple perspectives, identifying assumptions, and revealing conceptual relationships. Conclude with open-ended questions that promote higher-order thinking—analysis, synthesis, or evaluation—rather than recall."
        return (
            gr.update(value=socratic_prompt),  # Update main system prompt
            gr.update(value=False),  # Socratic template doesn't need dynamic URLs by default
            cached_custom_prompt  # Return the cached prompt
        )
    else:  # "None" or any other value
        # Restore the cached custom prompt if we have one
        prompt_value = cached_custom_prompt if cached_custom_prompt else ""
        return (
            gr.update(value=prompt_value),  # Restore cached prompt or clear
            gr.update(value=False),  # Disable dynamic URL setting
            cached_custom_prompt  # Return the cached prompt
        )


# Create Gradio interface with proper tab structure and fixed configuration
with gr.Blocks(
    title="Chat U/I Helper",
    css="""
        /* Custom CSS to fix styling issues */
        .gradio-container {
            max-width: 1200px !important;
            margin: 0 auto;
        }
        
        /* Fix tab styling */
        .tab-nav {
            border-bottom: 1px solid #e0e0e0;
        }
        
        /* Fix button styling */
        .btn {
            border-radius: 6px;
        }
        
        /* Fix chat interface styling */
        .chat-interface {
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }
        
        /* Hide gradio footer to avoid manifest issues */
        .gradio-footer {
            display: none !important;
        }
        
        /* Fix accordion styling */
        .accordion {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
        }
    """,
    theme="default",
    head="""
        <style>
            /* Additional head styles to prevent manifest issues */
            .gradio-app { 
                background: #ffffff;
            }
        </style>
    """,
    js="""
        function() {
            // Prevent manifest.json requests and other common errors
            if (typeof window !== 'undefined') {
                // Override fetch to handle manifest.json requests
                const originalFetch = window.fetch;
                window.fetch = function(url, options) {
                    // Handle both string URLs and URL objects
                    const urlString = typeof url === 'string' ? url : url.toString();
                    
                    if (urlString.includes('manifest.json')) {
                        return Promise.resolve(new Response('{}', { 
                            status: 200,
                            headers: { 'Content-Type': 'application/json' }
                        }));
                    }
                    
                    // Handle favicon requests
                    if (urlString.includes('favicon.ico')) {
                        return Promise.resolve(new Response('', { status: 204 }));
                    }
                    
                    return originalFetch.apply(this, arguments);
                };
                
                // Prevent postMessage origin errors
                window.addEventListener('message', function(event) {
                    try {
                        if (event.origin && event.origin !== window.location.origin) {
                            event.stopImmediatePropagation();
                            return false;
                        }
                    } catch (e) {
                        // Silently ignore origin check errors
                    }
                }, true);
                
                // Prevent console errors from missing resources
                window.addEventListener('error', function(e) {
                    if (e.target && e.target.src) {
                        const src = e.target.src;
                        if (src.includes('manifest.json') || src.includes('favicon.ico')) {
                            e.preventDefault();
                            return false;
                        }
                    }
                }, true);
                
                // Override console.error to filter out known harmless errors
                const originalConsoleError = console.error;
                console.error = function(...args) {
                    const message = args.join(' ');
                    if (message.includes('manifest.json') || 
                        message.includes('favicon.ico') ||
                        message.includes('postMessage') ||
                        message.includes('target origin')) {
                        return; // Suppress these specific errors
                    }
                    originalConsoleError.apply(console, arguments);
                };
            }
        }
    """
) as demo:
    # Global state for cross-tab functionality
    sandbox_state = gr.State({})
    preview_config_state = gr.State({})
    
    # Global status components that will be defined later
    preview_status = None
    preview_chat_section = None 
    config_display = None
    
    with gr.Tabs():
        with gr.Tab("Configuration"):
            gr.Markdown("# Spaces Configuration")
            gr.Markdown("Convert custom assistants from HuggingChat into chat interfaces with HuggingFace Spaces. Configure and download everything needed to deploy a simple HF space using Gradio.")
    
            with gr.Column():
                name = gr.Textbox(
                    label="Space Title",
                    placeholder="My Course Helper",
                    value="My Custom Space"
                )
                
                description = gr.Textbox(
                    label="Space Description", 
                    placeholder="A customizable AI chat interface for...",
                    lines=2,
                    value="",
                    max_lines=2,
                    max_length=57
                )
                
                model = gr.Dropdown(
                    label="Model",
                    choices=MODELS,
                    value=MODELS[0],
                    info="Choose based on the context and purposes of your space"
                )
                
                api_key_var = gr.Textbox(
                    label="API Key Configuration (Required)",
                    value="OPENROUTER_API_KEY",
                    info="Set this secret in HuggingFace Space Settings → Variables and secrets with your OpenRouter API key",
                    interactive=False
                )
                
                access_code = gr.Textbox(
                    label="Space Access Code (Optional)",
                    value="SPACE_ACCESS_CODE",
                    info="Set this secret in HuggingFace Space Settings → Variables and secrets to require an access code.",
                    interactive=False
                )
                
                with gr.Accordion("Assistant Configuration", open=True):
                    gr.Markdown("Define the system prompt and assistant settings. You can use pre-configured templates or custom fields.")

                    # Template selection - moved before system prompt
                    gr.Markdown("**Choose a Template:** Start with a pre-configured assistant personality or create your own custom prompt. Templates provide tested prompts for common educational use cases.")
                    
                    with gr.Row():
                        template_selector = gr.Radio(
                            label="Assistant Template",
                            choices=["None", "Research Template", "Socratic Template"],
                            value="None",
                            info="Select a template to auto-fill the system prompt, or choose 'None' for custom"
                        )
                    
                    # Main system prompt field - now after template selector
                    system_prompt = gr.Textbox(
                        label="System Prompt",
                        placeholder="You are a helpful assistant that...",
                        lines=4,
                        value="",
                        info="Define the assistant's role, purpose, and behavior. This will be auto-filled if you select a template."
                    )
                    
            
                    
                                        
                    
                    examples_text = gr.Textbox(
                        label="Example Prompts (one per line)",
                        placeholder="Can you analyze this research paper: https://example.com/paper.pdf\nWhat are the latest findings on climate change adaptation?\nHelp me fact-check claims about renewable energy efficiency",
                        lines=3,
                        info="These will appear as clickable examples in the chat interface"
                    )
                    
                    enable_dynamic_urls = gr.Checkbox(
                        label="Enable Dynamic URL Fetching",
                        value=True,  # Enabled by default
                        info="Allow the assistant to fetch additional URLs mentioned in conversations"
                    )
                
                with gr.Accordion("URL Grounding", open=True):
                    gr.Markdown("Add URLs to provide context. Content will be fetched and added to the system prompt. You can add up to 10 URLs total (2 primary + 8 secondary).")
                    
                    # Primary URLs section
                    gr.Markdown("### 🎯 Primary URLs (Always Processed)")
                    gr.Markdown("These URLs are processed first and given highest priority for context.")
                    
                    url1 = gr.Textbox(
                        label="Primary URL 1",
                        placeholder="https://syllabus.edu/course (most important source)",
                        info="Main reference document, syllabus, or primary source"
                    )
                    
                    url2 = gr.Textbox(
                        label="Primary URL 2", 
                        placeholder="https://textbook.com/chapter (core material)",
                        info="Secondary reference, textbook chapter, or key resource"
                    )
                    
                    # Secondary URLs section
                    gr.Markdown("### 📚 Secondary URLs (Additional Context)")
                    gr.Markdown("Additional sources for supplementary context and enhanced responses.")
                    
                    url3 = gr.Textbox(
                        label="Secondary URL 1",
                        placeholder="https://example.com/supplementary", 
                        info="Additional reference or supplementary material",
                        visible=True
                    )
                    
                    url4 = gr.Textbox(
                        label="Secondary URL 2",
                        placeholder="https://example.com/resources",
                        info="Extra context or supporting documentation",
                        visible=True
                    )
                    
                    url5 = gr.Textbox(
                        label="Secondary URL 3",
                        placeholder="https://example.com/guidelines",
                        info="Additional guidelines or reference material",
                        visible=False
                    )
                    
                    url6 = gr.Textbox(
                        label="Secondary URL 4",
                        placeholder="https://example.com/examples",
                        info="Examples, case studies, or additional sources",
                        visible=False
                    )
                    
                    url7 = gr.Textbox(
                        label="Secondary URL 5",
                        placeholder="https://example.com/research",
                        info="Research papers or academic sources",
                        visible=False
                    )
                    
                    url8 = gr.Textbox(
                        label="Secondary URL 6",
                        placeholder="https://example.com/documentation",
                        info="Technical documentation or specifications",
                        visible=False
                    )
                    
                    url9 = gr.Textbox(
                        label="Secondary URL 7",
                        placeholder="https://example.com/articles",
                        info="Articles, blog posts, or news sources",
                        visible=False
                    )
                    
                    url10 = gr.Textbox(
                        label="Secondary URL 8",
                        placeholder="https://example.com/misc",
                        info="Miscellaneous sources or background material",
                        visible=False
                    )
                    
                    # URL management buttons
                    with gr.Row():
                        add_url_btn = gr.Button("+ Add Secondary URLs (2/8)", size="sm")
                        remove_url_btn = gr.Button("- Remove Secondary URLs", size="sm", visible=True)
                    url_count = gr.State(4)  # Track number of visible URLs
                
                with gr.Accordion("Advanced Settings", open=False):
                    with gr.Row():
                        temperature = gr.Slider(
                            label="Temperature",
                            minimum=0,
                            maximum=2,
                            value=0.7,
                            step=0.1,
                            info="Higher = more creative, Lower = more focused"
                        )
                        
                        max_tokens = gr.Slider(
                            label="Max Response Tokens",
                            minimum=50,
                            maximum=4096,
                            value=750,
                            step=50
                        )
                
                with gr.Row():
                    preview_btn = gr.Button("Preview Deployment Package", variant="secondary")
                    generate_btn = gr.Button("Generate Deployment Package", variant="primary")
                
                status = gr.Markdown(visible=False)
                download_file = gr.File(label="Download your zip package", visible=False)
            
            # State variable to cache custom system prompt
            custom_prompt_cache = gr.State("")
            
            # Connect the template selector
            template_selector.change(
                toggle_template,
                inputs=[template_selector, system_prompt, custom_prompt_cache],
                outputs=[system_prompt, enable_dynamic_urls, custom_prompt_cache]
            )
            
            # Web search checkbox is now just for enabling/disabling the feature
            # No additional UI elements needed since we rely on model capabilities
            
            
            
            # Connect the URL management buttons
            add_url_btn.click(
                add_urls,
                inputs=[url_count],
                outputs=[url3, url4, url5, url6, url7, url8, url9, url10, add_url_btn, remove_url_btn, url_count]
            )
            
            remove_url_btn.click(
                remove_urls,
                inputs=[url_count],
                outputs=[url3, url4, url5, url6, url7, url8, url9, url10, add_url_btn, remove_url_btn, url_count]
            )
            
                        
            
            # Connect the generate button
            generate_btn.click(
                on_generate,
                inputs=[name, description, system_prompt, model, api_key_var, temperature, max_tokens, examples_text, access_code, enable_dynamic_urls, url1, url2, url3, url4, url5, url6, url7, url8, url9, url10],
                outputs=[status, download_file, sandbox_state]
            )
            
        
        with gr.Tab("Preview"):
            gr.Markdown("# Sandbox Preview")
            gr.Markdown("Test your assistant before deployment.")
            
            with gr.Column():
                # Preview status - assign to global variable
                preview_status_comp = gr.Markdown("**Status:** Configure your space in the Configuration tab and click 'Preview Deployment Package' to see your assistant here.", visible=True)
                
                # Simulated chat interface for preview using ChatInterface
                with gr.Column(visible=False) as preview_chat_section_comp:
                    preview_chatbot = gr.Chatbot(
                        value=[],
                        label="Preview Chat Interface", 
                        height=400,
                        type="messages"
                    )
                    # Example prompt buttons
                    with gr.Row():
                        preview_example_btn1 = gr.Button("", visible=False, size="sm", variant="secondary")
                        preview_example_btn2 = gr.Button("", visible=False, size="sm", variant="secondary")
                        preview_example_btn3 = gr.Button("", visible=False, size="sm", variant="secondary")
                    
                    preview_msg = gr.Textbox(
                        label="Test your assistant",
                        placeholder="Type a message to test your assistant...",
                        lines=2
                    )
                    
                    # URL context fields for preview testing
                    with gr.Accordion("Test URL Context (Optional)", open=False):
                        gr.Markdown("Test URL context grounding in the preview. Uses same priority system: 2 primary + 8 secondary URLs.")
                        
                        # Primary URLs for preview testing
                        gr.Markdown("**🎯 Primary URLs**")
                        with gr.Row():
                            preview_url1 = gr.Textbox(
                                label="Primary URL 1",
                                placeholder="https://syllabus.edu/course",
                                scale=1
                            )
                            preview_url2 = gr.Textbox(
                                label="Primary URL 2", 
                                placeholder="https://textbook.com/chapter",
                                scale=1
                            )
                        
                        # Secondary URLs for preview testing
                        gr.Markdown("**📚 Secondary URLs**")
                        with gr.Row():
                            preview_url3 = gr.Textbox(
                                label="Secondary URL 1",
                                placeholder="https://example.com/supplementary",
                                scale=1,
                                visible=True
                            )
                            preview_url4 = gr.Textbox(
                                label="Secondary URL 2",
                                placeholder="https://example.com/resources",
                                scale=1,
                                visible=True
                            )
                        
                        with gr.Row():
                            preview_url5 = gr.Textbox(
                                label="Secondary URL 3",
                                placeholder="https://example.com/guidelines",
                                scale=1,
                                visible=False
                            )
                            preview_url6 = gr.Textbox(
                                label="Secondary URL 4",
                                placeholder="https://example.com/examples",
                                scale=1,
                                visible=False
                            )
                        
                        with gr.Row():
                            preview_url7 = gr.Textbox(
                                label="Secondary URL 5",
                                placeholder="https://example.com/research",
                                scale=1,
                                visible=False
                            )
                            preview_url8 = gr.Textbox(
                                label="Secondary URL 6",
                                placeholder="https://example.com/documentation",
                                scale=1,
                                visible=False
                            )
                        
                        with gr.Row():
                            preview_url9 = gr.Textbox(
                                label="Secondary URL 7",
                                placeholder="https://example.com/articles",
                                scale=1,
                                visible=False
                            )
                            preview_url10 = gr.Textbox(
                                label="Secondary URL 8",
                                placeholder="https://example.com/misc",
                                scale=1,
                                visible=False
                            )
                        
                        # URL management for preview
                        with gr.Row():
                            preview_add_url_btn = gr.Button("+ Add Secondary URLs (2/8)", size="sm")
                            preview_remove_url_btn = gr.Button("- Remove Secondary URLs", size="sm", visible=True)
                        preview_url_count = gr.State(4)
                    
                    with gr.Row():
                        preview_send = gr.Button("Send", variant="primary")
                        preview_clear = gr.Button("Clear")
                        preview_export_btn = gr.Button("Export Conversation", variant="secondary")
                    
                    # Export functionality
                    export_file = gr.File(label="Download Conversation", visible=False)
                
                # Configuration display - assign to global variable
                config_display_comp = gr.Markdown("Configuration will appear here after preview generation.")
                
            
            
            # Connect preview chat functionality
            preview_send.click(
                preview_chat_response,
                inputs=[preview_msg, preview_chatbot, preview_config_state, preview_url1, preview_url2, preview_url3, preview_url4, preview_url5, preview_url6, preview_url7, preview_url8, preview_url9, preview_url10],
                outputs=[preview_msg, preview_chatbot]
            )
            
            preview_msg.submit(
                preview_chat_response,
                inputs=[preview_msg, preview_chatbot, preview_config_state, preview_url1, preview_url2, preview_url3, preview_url4, preview_url5, preview_url6, preview_url7, preview_url8, preview_url9, preview_url10],
                outputs=[preview_msg, preview_chatbot]
            )
            
            preview_clear.click(
                clear_preview_chat,
                outputs=[preview_msg, preview_chatbot]
            )
            
            preview_export_btn.click(
                export_preview_conversation,
                inputs=[preview_chatbot],
                outputs=[export_file]
            )
            
            # Connect preview URL management buttons
            preview_add_url_btn.click(
                add_urls,
                inputs=[preview_url_count],
                outputs=[preview_url3, preview_url4, preview_url5, preview_url6, preview_url7, preview_url8, preview_url9, preview_url10, preview_add_url_btn, preview_remove_url_btn, preview_url_count]
            )
            
            preview_remove_url_btn.click(
                remove_urls,
                inputs=[preview_url_count],
                outputs=[preview_url3, preview_url4, preview_url5, preview_url6, preview_url7, preview_url8, preview_url9, preview_url10, preview_add_url_btn, preview_remove_url_btn, preview_url_count]
            )
            
            # Connect example buttons to populate text input
            # Need to get the example text from the state
            def get_example_text(config_data, index):
                if config_data and config_data.get('examples_list'):
                    examples = config_data['examples_list']
                    if index < len(examples):
                        return examples[index]
                return ""
            
            preview_example_btn1.click(
                lambda config_data: get_example_text(config_data, 0),
                inputs=[preview_config_state],
                outputs=[preview_msg]
            )
            
            preview_example_btn2.click(
                lambda config_data: get_example_text(config_data, 1),
                inputs=[preview_config_state],
                outputs=[preview_msg]
            )
            
            preview_example_btn3.click(
                lambda config_data: get_example_text(config_data, 2),
                inputs=[preview_config_state],
                outputs=[preview_msg]
            )
        
        with gr.Tab("Support"):
            create_support_docs()
    
    # Connect cross-tab functionality after all components are defined
    preview_btn.click(
        on_preview_combined,
        inputs=[name, description, system_prompt, model, temperature, max_tokens, examples_text, enable_dynamic_urls, url1, url2, url3, url4, url5, url6, url7, url8, url9, url10],
        outputs=[preview_config_state, preview_status_comp, preview_chat_section_comp, config_display_comp, preview_url1, preview_url2, preview_url3, preview_url4, preview_url5, preview_url6, preview_url7, preview_url8, preview_url9, preview_url10, preview_add_url_btn, preview_remove_url_btn, preview_url_count, preview_example_btn1, preview_example_btn2, preview_example_btn3]
    )

if __name__ == "__main__":
    # Use default Gradio launch settings for HuggingFace Spaces compatibility
    demo.launch(share=True)