File size: 122,404 Bytes
7729ae4
 
 
 
 
716d90b
dd66d31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
 
716d90b
7729ae4
 
 
 
 
 
 
2556849
 
 
 
 
 
 
7729ae4
 
 
2556849
7729ae4
 
 
2556849
7729ae4
 
 
 
2556849
7729ae4
2556849
7729ae4
 
 
 
2556849
 
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2556849
7729ae4
 
 
716d90b
 
 
 
 
 
 
 
 
7729ae4
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
 
 
 
 
 
363d801
 
 
 
 
 
 
 
 
 
 
 
 
49fa060
 
 
 
4c0ca4e
49fa060
 
4c0ca4e
 
49fa060
77486d0
49fa060
 
 
77486d0
49fa060
77486d0
49fa060
77486d0
49fa060
 
77486d0
4c0ca4e
49fa060
 
 
 
716d90b
7729ae4
 
 
 
716d90b
 
 
7729ae4
716d90b
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
 
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
 
 
 
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
7729ae4
716d90b
 
 
 
7729ae4
716d90b
 
 
 
7729ae4
716d90b
 
7729ae4
716d90b
 
7729ae4
716d90b
 
7729ae4
 
dd66d31
 
7729ae4
 
 
 
dd66d31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
dd66d31
 
 
 
 
 
 
 
 
7729ae4
 
 
 
dd66d31
7729ae4
 
dd66d31
7729ae4
dd66d31
7729ae4
716d90b
7729ae4
 
 
dd66d31
 
 
 
7729ae4
dd66d31
7729ae4
 
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b44ef7
716d90b
 
 
 
 
 
7729ae4
 
dd66d31
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
 
 
7729ae4
 
 
 
 
716d90b
 
 
 
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03f7fc8
7729ae4
03f7fc8
7729ae4
 
 
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03f7fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e19b8b
03f7fc8
 
 
 
 
 
 
 
716d90b
03f7fc8
 
 
 
 
 
 
 
 
716d90b
03f7fc8
 
 
 
716d90b
03f7fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
1e19b8b
03f7fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd66d31
03f7fc8
 
 
1e19b8b
03f7fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd66d31
03f7fc8
 
 
 
1e19b8b
03f7fc8
 
 
 
 
 
 
 
 
 
 
 
 
dd66d31
03f7fc8
 
 
 
 
 
1e19b8b
03f7fc8
 
 
 
1e19b8b
03f7fc8
 
 
 
1e19b8b
03f7fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
 
03f7fc8
 
 
 
 
 
716d90b
03f7fc8
 
 
 
 
 
 
 
716d90b
03f7fc8
 
 
 
dd66d31
03f7fc8
 
 
 
1e19b8b
03f7fc8
 
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
 
 
 
 
 
 
 
 
7729ae4
 
 
 
716d90b
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
 
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
 
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
 
7729ae4
 
 
 
 
 
 
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd66d31
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd66d31
716d90b
 
 
 
 
 
 
 
 
 
7729ae4
 
 
 
 
 
 
 
 
 
 
 
716d90b
7729ae4
716d90b
7729ae4
 
716d90b
7729ae4
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
 
 
 
 
03f7fc8
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
7729ae4
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef21fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
ef21fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
ef21fb6
 
 
 
 
 
 
 
 
 
 
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd66d31
716d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef21fb6
716d90b
ef21fb6
716d90b
 
ef21fb6
716d90b
 
 
ef21fb6
 
 
 
 
7d2f575
 
 
 
 
 
 
9f88210
7d2f575
9f88210
7d2f575
 
 
 
 
 
dd66d31
7d2f575
 
1e19b8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d2f575
1e19b8b
 
 
 
 
 
 
 
7d2f575
 
dd66d31
7d2f575
 
 
 
b64ae95
 
 
1e19b8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b64ae95
1e19b8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716d90b
 
 
7729ae4
 
 
 
 
 
 
 
 
716d90b
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd66d31
7729ae4
 
 
1e19b8b
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b44ef7
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b44ef7
7729ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef21fb6
7729ae4
 
 
 
1b44ef7
7729ae4
 
 
 
 
 
 
 
1e19b8b
 
7729ae4
 
 
 
1b44ef7
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
import streamlit as st
from datetime import datetime, date
import copy
import json
import requests
import os
# --- Hugging Face Hub integration ---
try:
    from huggingface_hub import HfApi, hf_hub_download
    HF_HUB_AVAILABLE = True
except ImportError:
    HF_HUB_AVAILABLE = False

HF_REPO_ID = "AIB-Research/bibliPrompt"
HF_JSON_FILENAME = "prompt_templates_data_v3.json"
HF_TOKEN = os.environ.get("HF_TOKEN", None)

# --- Save to Hugging Face Space ---
def save_to_hf_space(json_path, repo_id=HF_REPO_ID, token=HF_TOKEN):
    if not HF_HUB_AVAILABLE:
        st.warning("huggingface_hub n'est pas installé. Sauvegarde sur HF désactivée.")
        return False
    try:
        api = HfApi()
        api.upload_file(
            path_or_fileobj=json_path,
            path_in_repo=HF_JSON_FILENAME,
            repo_id=repo_id,
            repo_type="space",
            token=token
        )
        st.toast("💾 Données sauvegardées sur Hugging Face Space!", icon="🤗")
        return True
    except Exception as e:
        st.warning(f"Erreur lors de la sauvegarde sur Hugging Face: {e}")
        return False

# --- Load from Hugging Face Space ---
def load_from_hf_space(repo_id=HF_REPO_ID, token=HF_TOKEN):
    if not HF_HUB_AVAILABLE:
        st.warning("huggingface_hub n'est pas installé. Chargement depuis HF désactivé.")
        return None
    try:
        local_path = hf_hub_download(
            repo_id=repo_id,
            filename=HF_JSON_FILENAME,
            repo_type="space",
            token=token
        )
        with open(local_path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception as e:
        st.warning(f"Erreur lors du chargement depuis Hugging Face: {e}")
        return None

# --- PAGE CONFIGURATION (MUST BE THE FIRST STREAMLIT COMMAND) ---
# Fixed deployment issue
st.set_page_config(layout="wide", page_title="🛠️ Le laboratoire des Prompts IA", initial_sidebar_state="collapsed" )

# --- CUSTOM CSS FOR SIDEBAR TOGGLE TEXT ---
st.markdown("""
    <style>
        /* Cible le bouton spécifique que vous avez identifié */
        button[data-testid="stBaseButton-headerNoPadding"]::after {
            content: " Menu";
            margin-left: 8px;
            font-size: 0.9em;
            vertical-align: middle;
            color: inherit;
            font-weight: normal;
            display: inline-flex;
            align-items: center;
        }
        div[data-testid="stCodeBlock"] pre,
        pre.st-emotion-cache-1nqbjoj {
            max-height: 520px !important;
            overflow-y: auto !important;
            font-size: 0.875em !important;
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
        }
        div[data-testid="stCodeBlock"] > div:first-child {
            max-height: 520px !important;
            overflow-y: auto !important;
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
        }
        pre.st-emotion-cache-1nqbjoj > div[style*="background-color: transparent;"] {
            height: auto !important;
            max-height: 100% !important;
            overflow-y: auto !important;
        }
        button[data-testid="stCodeCopyButton"] {
            opacity: 0.85 !important;
            visibility: visible !important;
            background-color: #f0f2f6 !important;
            border: 1px solid #cccccc !important;
            border-radius: 4px !important;
            padding: 3px 5px !important;
            transition: opacity 0.15s ease-in-out, background-color 0.15s ease-in-out;
        }
        button[data-testid="stCodeCopyButton"]:hover {
            opacity: 1 !important;
            background-color: #e6e8eb !important;
            border-color: #b0b0b0 !important;
        }
        button[data-testid="stCodeCopyButton"] svg {
            transform: scale(1.2);
            vertical-align: middle;
        }
        section[data-testid="stSidebar"] {
            width: 31.5rem !important;
            min-width: 31.5rem !important;
            max-width: 31.5rem !important;
        }
        section[data-testid="stSidebar"][aria-expanded="false"] {
            width: 0rem !important;
            min-width: 0rem !important;
            max-width: 0rem !important;
            overflow: hidden !important;
        }
        [data-testid="stMainBlockContainer"] {
            padding-top: 3rem !important;
        }
        .css-1d391kg, .css-18e3th9 {
            padding-top: 3rem !important;
        }
        h1[data-testid="stHeading"]:first-of-type {
            margin-top: -2rem !important;
            padding-top: 0rem !important;
        }
        h1:contains("Bienvenue dans votre laboratoire") {
            margin-top: -2rem !important;
            padding-top: 0rem !important;
        }
        @media (max-width: 768px) {
            .main .block-container {
                max-width: 100vw !important;
                width: 100vw !important;
            }
        }
        div[data-testid="stExpander"] div[data-testid="stCodeBlock"] { 
            margin-top: 0.1rem !important; 
            margin-bottom: 0.15rem !important; 
            padding-top: 0.1rem !important; 
            padding-bottom: 0.1rem !important; 
        } 
        div[data-testid="stExpander"] div[data-testid="stCodeBlock"] pre { 
            padding-top: 0.2rem !important; 
            padding-bottom: 0.2rem !important; 
            line-height: 1.1 !important; 
            font-size: 0.85em !important; 
            margin: 0 !important; 
        }
        div[data-testid="stExpander"] {
            width: 100% !important;
            max-width: 100% !important;
            overflow: visible !important;
        }
        div[data-testid="stExpander"] > div:first-child {
            overflow: visible !important;
        }
        div[data-testid="stExpander"] .streamlit-expanderContent {
            width: 100% !important;
            max-width: 100% !important;
            overflow: visible !important;
            position: relative !important;
            transform: translateZ(0) !important;
        }
        .main .block-container {
            overflow-x: hidden !important;
            overflow-y: auto !important;
        }
        div[data-testid="stExpander"] form {
            max-width: 100% !important;
            overflow-x: hidden !important;
        }
        div[data-testid="stExpander"] div[data-testid="column"] {
            min-width: 0 !important;
            overflow: hidden !important;
        }
    </style>
""", unsafe_allow_html=True)

# --- Initial Data Structure & Constants ---
CURRENT_YEAR = datetime.now().year

# Variable de contrôle pour la section de paramétrage - changez à True pour réactiver
SHOW_CONFIG_SECTION = True
GIST_DATA_FILENAME = "prompt_templates_data_v3.json"
LOCAL_DATA_FILENAME = "prompt_templates_data_v3.json"

# --- Function to load prompt templates from files ---
def load_prompt_template(filename):
    """Load prompt template from file, with fallback to basic template if file not found."""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        st.warning(f"Fichier de template '{filename}' non trouvé. Utilisation d'un template de base.")
        return "# MISSION\nVous êtes un assistant IA. Veuillez traiter la demande suivante: {problematique}"
    except Exception as e:
        st.error(f"Erreur lors du chargement du template '{filename}': {e}")
        return "# MISSION\nVous êtes un assistant IA. Veuillez traiter la demande suivante: {problematique}"

# Load prompt templates from external files
META_PROMPT_FOR_EXTERNAL_LLM_TEMPLATE = load_prompt_template("AIBprompt_creation_template.md")
META_PROMPT_FOR_LLM_AMELIORATION_TEMPLATE = load_prompt_template("AIBprompt_improvement_template.md")

ASSISTANT_FORM_VARIABLES = [
    {"name": "problematique", "label": "Décrivez le besoin ou la tâche que le prompt cible doit résoudre :", "type": "text_area", "default": "", "height": 100},
    {"name": "doc_source", "label": "Quel(s) types de document(s) sont nécessaire pour la réalisation de votre besoin ? (e.g. PDF, e-mail, texte brut -laisser vide si non pertinent-) :", "type": "text_input", "default": ""},
    {"name": "elements_specifiques_a_extraire", "label": "Quelles sont les informations spécifiques que vous souhaitez identifier / générer ? (e.g. l'ensemble des ID clients, les clauses du contrat) :", "type": "text_area", "default": "", "height": 100},
    {"name": "format_sortie_desire", "label": "Optionnel : sous quel format voulez vous que le prompt produise une réponse ? (e.g. un texte de deux pages, une liste à puces) :", "type": "text_area", "default": "", "height": 75},
    {"name": "public_cible_reponse", "label": "Optionnel : pour quel public cible s'adressera le résultat du prompt ? (e.g. des profils techniques, le grand public) :", "type": "text_input", "default": ""},
]

def get_default_dates():
    now_iso = datetime.now().isoformat()
    return now_iso, now_iso

INITIAL_PROMPT_TEMPLATES = {
    "Propositions commerciales": {}, "Ateliers métiers": {}, "Project Management": {}
}
for family, use_cases in INITIAL_PROMPT_TEMPLATES.items(): # Initial cleanup
    if isinstance(use_cases, dict):
        for uc_name, uc_config in use_cases.items():
            if "is_favorite" in uc_config: # pragma: no cover
                del uc_config["is_favorite"]

# --- Utility Functions (User's original versions, with height fix in _postprocess_after_loading) ---
def parse_default_value(value_str, var_type):
    if not value_str:
        if var_type == "number_input": return 0.0
        if var_type == "date_input": return datetime.now().date()
        return ""
    if var_type == "number_input":
        try: return float(value_str)
        except ValueError: return 0.0
    elif var_type == "date_input":
        try: return datetime.strptime(value_str, "%Y-%m-%d").date()
        except (ValueError, TypeError):
            return value_str if isinstance(value_str, date) else datetime.now().date()
    return value_str

def _preprocess_for_saving(data_to_save):
    processed_data = copy.deepcopy(data_to_save)
    for family_name in list(processed_data.keys()):
        use_cases_in_family = processed_data[family_name]
        if not isinstance(use_cases_in_family, dict): # pragma: no cover
            st.error(f"Données corrompues (famille non-dict): '{family_name}'. Suppression.")
            del processed_data[family_name]
            continue
        for use_case_name in list(use_cases_in_family.keys()):
            config = use_cases_in_family[use_case_name]
            if not isinstance(config, dict): # pragma: no cover
                st.error(f"Données corrompues (cas d'usage non-dict): '{use_case_name}' dans '{family_name}'. Suppression.")
                del processed_data[family_name][use_case_name]
                continue
            if not isinstance(config.get("variables"), list):
                config["variables"] = []
            for var_info in config.get("variables", []):
                if isinstance(var_info, dict):
                    if var_info.get("type") == "date_input" and isinstance(var_info.get("default"), date):
                        var_info["default"] = var_info["default"].strftime("%Y-%m-%d")
                    if var_info.get("type") == "number_input":
                        if "default" in var_info and var_info["default"] is not None:
                            var_info["default"] = float(var_info["default"])
                        if "min_value" in var_info and var_info["min_value"] is not None:
                            var_info["min_value"] = float(var_info["min_value"])
                        if "max_value" in var_info and var_info["max_value"] is not None:
                            var_info["max_value"] = float(var_info["max_value"])
                        if "step" in var_info and var_info["step"] is not None:
                            var_info["step"] = float(var_info["step"])
                        else: 
                            var_info["step"] = 1.0
                    # Ensure height for text_area is an int if it exists (it should be already from other functions)
                    if var_info.get("type") == "text_area":
                        if "height" in var_info and var_info["height"] is not None:
                            try:
                                var_info["height"] = int(var_info["height"])
                            except (ValueError, TypeError): # pragma: no cover
                                var_info["height"] = 100 # Should not happen if data is clean

            config.setdefault("tags", [])
            if "is_favorite" in config: # pragma: no cover
                del config["is_favorite"]
            config.setdefault("usage_count", 0)
            config.setdefault("created_at", datetime.now().isoformat())
            config.setdefault("updated_at", datetime.now().isoformat())
    return processed_data

def _postprocess_after_loading(loaded_data): # User's trusted version + height fix
    processed_data = copy.deepcopy(loaded_data)
    now_iso = datetime.now().isoformat()
    for family_name in list(processed_data.keys()):
        use_cases_in_family = processed_data[family_name]
        if not isinstance(use_cases_in_family, dict): # pragma: no cover
            st.warning(f"Données corrompues (famille non-dict): '{family_name}'. Ignorée.")
            del processed_data[family_name]
            continue
        for use_case_name in list(use_cases_in_family.keys()):
            config = use_cases_in_family[use_case_name]
            if not isinstance(config, dict): # pragma: no cover
                st.warning(f"Données corrompues (cas d'usage non-dict): '{use_case_name}' dans '{family_name}'. Ignoré.")
                del processed_data[family_name][use_case_name]
                continue
            if not isinstance(config.get("variables"), list):
                config["variables"] = []
            for var_info in config.get("variables", []):
                if isinstance(var_info, dict):
                    if var_info.get("type") == "date_input" and isinstance(var_info.get("default"), str):
                        try:
                            var_info["default"] = datetime.strptime(var_info["default"], "%Y-%m-%d").date()
                        except ValueError:
                            var_info["default"] = datetime.now().date()
                    if var_info.get("type") == "number_input":
                        if "default" in var_info and var_info["default"] is not None:
                            var_info["default"] = float(var_info["default"])
                        else: 
                            var_info["default"] = 0.0
                        if "min_value" in var_info and var_info["min_value"] is not None:
                            var_info["min_value"] = float(var_info["min_value"])
                        if "max_value" in var_info and var_info["max_value"] is not None:
                            var_info["max_value"] = float(var_info["max_value"])
                        if "step" in var_info and var_info["step"] is not None:
                            var_info["step"] = float(var_info["step"])
                        else: 
                            var_info["step"] = 1.0

                    # --- ADDED ROBUST HEIGHT VALIDATION ---
                    if var_info.get("type") == "text_area":
                        height_val = var_info.get("height")
                        if height_val is not None:
                            try:
                                h = int(height_val)
                                if h >= 68:
                                    var_info["height"] = h
                                else:
                                    var_info["height"] = 68 # Set to minimum if too small
                                    # st.warning(f"Hauteur pour '{var_info.get('name', 'N/A')}' ajustée à 68px (minimum).")
                            except (ValueError, TypeError):
                                var_info["height"] = 100 # Default if invalid
                        # If height_val was None, 'height' key might not be in var_info, or it's None.
                        # The st.text_area widget call will handle None by using its internal default.
                        # Or we can explicitly set a default:
                        # else:
                        #     var_info["height"] = 100 # Default if not present

            config.setdefault("tags", [])
            if "is_favorite" in config: # pragma: no cover
                del config["is_favorite"]
            config.setdefault("usage_count", 0)
            config.setdefault("created_at", now_iso)
            config.setdefault("updated_at", now_iso)
            if not isinstance(config.get("tags"), list): config["tags"] = []
    return processed_data

# --- NEW: Simplified function to prepare newly injected use case config ---
def _prepare_newly_injected_use_case_config(uc_config_from_json):
    prepared_config = copy.deepcopy(uc_config_from_json)
    now_iso_created, now_iso_updated = get_default_dates()

    prepared_config["created_at"] = now_iso_created
    prepared_config["updated_at"] = now_iso_updated
    prepared_config["usage_count"] = 0 

    if "template" not in prepared_config or not isinstance(prepared_config["template"], str): # pragma: no cover
        prepared_config["template"] = "" 
        st.warning(f"Cas d'usage injecté '{uc_config_from_json.get('name', 'INCONNU')}' sans template valide. Template initialisé à vide.")

    # Ensure description field exists
    if "description" not in prepared_config or not isinstance(prepared_config["description"], str):
        prepared_config["description"] = ""

    if not isinstance(prepared_config.get("variables"), list):
        prepared_config["variables"] = []

    for var_info in prepared_config.get("variables", []): # Ensure height is valid for text_area
        if isinstance(var_info, dict) and var_info.get("type") == "text_area":
            height_val = var_info.get("height")
            if height_val is not None:
                try:
                    h = int(height_val)
                    if h >= 68: var_info["height"] = h
                    else: var_info["height"] = 68 
                except (ValueError, TypeError):
                    var_info["height"] = 100 # Default if invalid type
            # If 'height' key is missing, it's fine; widget will use its default.

    if not isinstance(prepared_config.get("tags"), list):
        prepared_config["tags"] = []
    else:
        prepared_config["tags"] = sorted(list(set(str(tag).strip() for tag in prepared_config["tags"] if str(tag).strip())))

    if "is_favorite" in prepared_config: # pragma: no cover
        del prepared_config["is_favorite"]

    # Ajout pour la gestion des notes
    # if "ratings" not in prepared_config or not isinstance(prepared_config["ratings"], list):
    #     prepared_config["ratings"] = []
    # if "average_rating" not in prepared_config:
    #     prepared_config["average_rating"] = 0.0
    return prepared_config

# --- Gist Interaction Functions (User's original versions) ---
def get_local_file_content():
    try:
        if os.path.exists(LOCAL_DATA_FILENAME):
            with open(LOCAL_DATA_FILENAME, 'r', encoding='utf-8') as f:
                content = f.read()
                return content if content.strip() else "{}"
        else:
            st.info(f"Fichier '{LOCAL_DATA_FILENAME}' non trouvé. Initialisation.")
            return "{}"
    except Exception as e: # pragma: no cover
        st.error(f"Erreur de lecture du fichier local: {e}")
        return None 

def save_to_local_file(new_content_json_string):
    try:
        with open(LOCAL_DATA_FILENAME, 'w', encoding='utf-8') as f:
            f.write(new_content_json_string)
        return True
    except Exception as e: # pragma: no cover
        st.error(f"Erreur de sauvegarde du fichier local: {e}")
        return False

# --- Unified save/load functions ---
def save_editable_prompts_to_local_and_hf():
    if 'editable_prompts' in st.session_state:
        data_to_save = _preprocess_for_saving(st.session_state.editable_prompts)
        try:
            json_string = json.dumps(data_to_save, indent=4, ensure_ascii=False)
            local_ok = save_to_local_file(json_string)
            hf_ok = False
            # Save to HF Space if possible
            with open(LOCAL_DATA_FILENAME, 'w', encoding='utf-8') as f:
                f.write(json_string)
            if HF_HUB_AVAILABLE:
                hf_ok = save_to_hf_space(LOCAL_DATA_FILENAME)
            if local_ok and hf_ok:
                st.toast("💾 Données sauvegardées localement et sur Hugging Face!", icon="💾")
            elif local_ok:
                st.toast("💾 Données sauvegardées localement!", icon="💾")
            elif hf_ok:
                st.toast("💾 Données sauvegardées sur Hugging Face!", icon="🤗")
            else:
                st.warning("Sauvegarde échouée.")
        except Exception as e: # pragma: no cover
            st.error(f"Erreur préparation données pour sauvegarde: {e}")

def load_editable_prompts_from_local_or_hf():
    # Try HF first, fallback to local
    raw_content = None
    if HF_HUB_AVAILABLE:
        raw_content = load_from_hf_space()
    if not raw_content:
        raw_content = get_local_file_content()
    if raw_content: 
        try:
            loaded_data = json.loads(raw_content)
            if not loaded_data or not isinstance(loaded_data, dict): 
                raise ValueError("Contenu fichier vide ou mal structuré.")
            return _postprocess_after_loading(loaded_data)
        except (json.JSONDecodeError, TypeError, ValueError) as e: 
            st.info(f"Erreur chargement fichier ('{str(e)[:50]}...'). Initialisation avec modèles par défaut.")
    else: 
        st.info("Fichier vide ou inaccessible. Initialisation avec modèles par défaut.")
    initial_data = copy.deepcopy(INITIAL_PROMPT_TEMPLATES)
    if raw_content is None or raw_content == "{}":
        data_to_save_init = _preprocess_for_saving(initial_data) 
        try:
            json_string_init = json.dumps(data_to_save_init, indent=4, ensure_ascii=False)
            save_to_local_file(json_string_init)
            if HF_HUB_AVAILABLE:
                save_to_hf_space(LOCAL_DATA_FILENAME)
            st.info("Modèles par défaut sauvegardés pour initialisation.")
        except Exception as e: # pragma: no cover
            st.error(f"Erreur sauvegarde initiale: {e}")
    return initial_data

# --- ACCESS CODE VERIFICATION ---
# Initialize access control session state
if 'access_granted' not in st.session_state:
    st.session_state.access_granted = False
if 'access_code_input' not in st.session_state:
    st.session_state.access_code_input = ""

# Access code popup
if not st.session_state.access_granted:
    # Simple CSS for background styling
    st.markdown("""
    <style>
    .stApp {
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        backdrop-filter: blur(10px);
    }
    .access-container {
        background: white;
        padding: 0.6rem;
        border-radius: 20px;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        margin: 0.5rem auto;
        max-width: 500px;
        text-align: center;
    }
    </style>
    """, unsafe_allow_html=True)
    
    # No vertical spacing to align at top
    
    # Create the access form
    with st.container():
        st.markdown("""
        <div class="access-container">
            <h1 style="color: #333; margin-bottom: 1rem;">🔐 Accès Sécurisé</h1>
            <p style="color: #666; font-size: 1.1rem; margin-bottom: 2rem;">
                Veuillez entrer le code d'accès pour utiliser l'application
            </p>
        </div>
        """, unsafe_allow_html=True)
        
        # Center the form elements
        col1, col2, col3 = st.columns([1, 2, 1])
        with col2:
            access_code = st.text_input(
                "Code d'accès", 
                placeholder="Entrez le code d'accès...",
                key="access_code_input_field"
            )
            
            if st.button("✅ Valider", use_container_width=True, type="primary"):
                if access_code == "SUPPORT":
                    st.session_state.access_granted = True
                    st.rerun()
                else:
                    st.error("❌ Code d'accès incorrect")
            
            st.markdown("""
                <p style="font-style: italic; color: #666; font-size: 0.9rem; margin-top: 1.5rem; text-align: center;">
                    Pour demander un accès, contactez votre référent métier ou l'administrateur de l'application : 
                    <a href="mailto:arthur.causse@aibuilders.ai" style="color: #0066cc;">arthur.causse@aibuilders.ai</a>
                </p>
            """, unsafe_allow_html=True)
    
    # Stop execution here if access not granted
    st.stop()

# --- Session State Initialization ---
if 'editable_prompts' not in st.session_state:
    st.session_state.editable_prompts = load_editable_prompts_from_local_or_hf()
if 'view_mode' not in st.session_state:
    st.session_state.view_mode = "accueil" # Nouvelle vue par défaut

if 'library_selected_family_for_display' not in st.session_state:
    available_families = list(st.session_state.editable_prompts.keys())
    st.session_state.library_selected_family_for_display = available_families[0] if available_families else None
    
if 'family_selector_edition' not in st.session_state:
    available_families = list(st.session_state.editable_prompts.keys())
    st.session_state.family_selector_edition = available_families[0] if available_families else None
if 'use_case_selector_edition' not in st.session_state:  st.session_state.use_case_selector_edition = None 
if 'editing_variable_info' not in st.session_state: st.session_state.editing_variable_info = None
if 'show_create_new_use_case_form' not in st.session_state: st.session_state.show_create_new_use_case_form = False
if 'force_select_family_name' not in st.session_state: st.session_state.force_select_family_name = None
if 'force_select_use_case_name' not in st.session_state: st.session_state.force_select_use_case_name = None
if 'confirming_delete_details' not in st.session_state: st.session_state.confirming_delete_details = None
if 'confirming_delete_family_name' not in st.session_state: st.session_state.confirming_delete_family_name = None
if 'library_search_term' not in st.session_state: st.session_state.library_search_term = ""
if 'library_selected_tags' not in st.session_state: st.session_state.library_selected_tags = []
# Track previous filter values for change detection
if 'previous_search_term' not in st.session_state: st.session_state.previous_search_term = ""
if 'previous_selected_tags' not in st.session_state: st.session_state.previous_selected_tags = []
if 'variable_type_to_create' not in st.session_state: st.session_state.variable_type_to_create = None
if 'active_generated_prompt' not in st.session_state: st.session_state.active_generated_prompt = ""
if 'duplicating_use_case_details' not in st.session_state: st.session_state.duplicating_use_case_details = None
if 'go_to_config_section' not in st.session_state: st.session_state.go_to_config_section = False

# Generator session state variables
if 'generator_selected_family' not in st.session_state: st.session_state.generator_selected_family = None
if 'generator_selected_use_case' not in st.session_state: st.session_state.generator_selected_use_case = None

if 'injection_selected_family' not in st.session_state:
    st.session_state.injection_selected_family = None
if 'injection_json_text' not in st.session_state:
    st.session_state.injection_json_text = ""

if 'assistant_form_values' not in st.session_state:
    st.session_state.assistant_form_values = {var['name']: var['default'] for var in ASSISTANT_FORM_VARIABLES}
if 'generated_meta_prompt_for_llm' not in st.session_state: 
    st.session_state.generated_meta_prompt_for_llm = ""

# NOUVELLES CLÉS POUR L'ASSISTANT UNIFIÉ
if 'assistant_mode' not in st.session_state:
    st.session_state.assistant_mode = "creation"  # Modes possibles: "creation", "amelioration"
if 'assistant_existing_prompt_value' not in st.session_state:
    st.session_state.assistant_existing_prompt_value = ""

# --- Sidebar Navigation with Tabs ---
st.sidebar.header("Menu Principal")
tab_bibliotheque, tab_edition_generation, tab_injection = st.sidebar.tabs([
    "📚 Bibliothèque",
    "✍️ Édition",
    "💡 Assistant" 
])

# --- Tab: Bibliothèque (Sidebar content) ---
with tab_bibliotheque:
    st.subheader("Explorer la Bibliothèque de Prompts")
    search_col, filter_tag_col = st.columns(2)
    with search_col:
        st.session_state.library_search_term = st.text_input(
            "🔍 Rechercher par mot-clé:",
            value=st.session_state.get("library_search_term", ""),
            placeholder="Nom, template, variable..."
        )

    all_tags_list = sorted(list(set(tag for family in st.session_state.editable_prompts.values() for uc in family.values() for tag in uc.get("tags", []))))
    with filter_tag_col:
        st.session_state.library_selected_tags = st.multiselect(
            "🏷️ Filtrer par Tags:",
            options=all_tags_list,
            default=st.session_state.get("library_selected_tags", [])
        )
    
    # Detect filter changes and auto-redirect to global search results
    current_search_term = st.session_state.get("library_search_term", "").strip()
    current_selected_tags = st.session_state.get("library_selected_tags", [])
    
    # Check if filters have changed
    search_changed = current_search_term != st.session_state.get("previous_search_term", "")
    tags_changed = current_selected_tags != st.session_state.get("previous_selected_tags", [])
    
    # If filters changed and we have active filters, redirect to global search
    if (search_changed or tags_changed) and (current_search_term or current_selected_tags):
        # Update previous values
        st.session_state.previous_search_term = current_search_term
        st.session_state.previous_selected_tags = current_selected_tags.copy()
        # Redirect to global search page
        if st.session_state.view_mode != "select_family_for_library":
            st.session_state.view_mode = "select_family_for_library"
            st.rerun()
    # Update previous values even when filters are cleared
    elif not current_search_term and not current_selected_tags:
        st.session_state.previous_search_term = current_search_term
        st.session_state.previous_selected_tags = current_selected_tags.copy()
    
    st.markdown("---")

    if not st.session_state.editable_prompts or not any(st.session_state.editable_prompts.values()):
        st.info("La bibliothèque est vide. Ajoutez des prompts via l'onglet 'Édition'.")
    else:
        sorted_families_bib = sorted(list(st.session_state.editable_prompts.keys()))

        if not st.session_state.get('library_selected_family_for_display') or \
           st.session_state.library_selected_family_for_display not in sorted_families_bib:
            st.session_state.library_selected_family_for_display = sorted_families_bib[0] if sorted_families_bib else None

        st.write("Sélectionner un métier à afficher :")
        for family_name_bib in sorted_families_bib:
            button_key = f"lib_family_btn_{family_name_bib.replace(' ', '_').replace('&', '_')}"
            is_selected_family = (st.session_state.library_selected_family_for_display == family_name_bib)
            if st.button(
                family_name_bib,
                key=button_key,
                use_container_width=True, 
                type="primary" if is_selected_family else "secondary"
            ):
                if st.session_state.library_selected_family_for_display != family_name_bib:
                    st.session_state.library_selected_family_for_display = family_name_bib
                    st.session_state.view_mode = "library" 
                    st.rerun() 
        st.markdown("---")

# --- Tab: Édition (Sidebar content) ---
with tab_edition_generation:
    st.subheader("Explorateur de Prompts")
    available_families = list(st.session_state.editable_prompts.keys())
    default_family_idx_edit = 0
    current_family_for_edit = st.session_state.get('family_selector_edition')

    if st.session_state.force_select_family_name and st.session_state.force_select_family_name in available_families:
        current_family_for_edit = st.session_state.force_select_family_name
        st.session_state.family_selector_edition = current_family_for_edit 
    elif current_family_for_edit and current_family_for_edit in available_families:
        pass 
    elif available_families:
        current_family_for_edit = available_families[0]
        st.session_state.family_selector_edition = current_family_for_edit 
    else:
        current_family_for_edit = None
        st.session_state.family_selector_edition = None 

    if current_family_for_edit and current_family_for_edit in available_families:
        default_family_idx_edit = available_families.index(current_family_for_edit)
    elif available_families: 
        default_family_idx_edit = 0
        current_family_for_edit = available_families[0]
        st.session_state.family_selector_edition = current_family_for_edit
    else: 
        default_family_idx_edit = 0 

    if not available_families:
        st.info("Aucune famille de métier de cas d'usage. Créez-en une via les options ci-dessous.")
    else:
        prev_family_selection_edit = st.session_state.get('family_selector_edition') 
        selected_family_ui_edit = st.selectbox(
            "Métier :",
            options=available_families,
            index=default_family_idx_edit, 
            key='family_selectbox_widget_edit',
            help="Sélectionnez une métier pour voir ses cas d'usage."
        )
        if st.session_state.family_selector_edition != selected_family_ui_edit :
             st.session_state.family_selector_edition = selected_family_ui_edit

        if prev_family_selection_edit != selected_family_ui_edit:
            st.session_state.use_case_selector_edition = None
            st.session_state.force_select_use_case_name = None 
            st.session_state.view_mode = "generator"
            st.session_state.active_generated_prompt = ""
            st.session_state.variable_type_to_create = None 
            st.session_state.editing_variable_info = None   
            st.rerun()

    current_selected_family_for_edit_logic = st.session_state.get('family_selector_edition')
    use_cases_in_current_family_edit_options = []
    if current_selected_family_for_edit_logic and current_selected_family_for_edit_logic in st.session_state.editable_prompts:
        use_cases_in_current_family_edit_options = sorted(list(st.session_state.editable_prompts[current_selected_family_for_edit_logic].keys()))

    if use_cases_in_current_family_edit_options:
        default_uc_idx_edit = 0
        current_uc_for_edit = st.session_state.get('use_case_selector_edition')

        if st.session_state.force_select_use_case_name and st.session_state.force_select_use_case_name in use_cases_in_current_family_edit_options:
            current_uc_for_edit = st.session_state.force_select_use_case_name
        elif current_uc_for_edit and current_uc_for_edit in use_cases_in_current_family_edit_options:
            pass 
        elif use_cases_in_current_family_edit_options:
            current_uc_for_edit = use_cases_in_current_family_edit_options[0]

        st.session_state.use_case_selector_edition = current_uc_for_edit 

        if current_uc_for_edit and current_uc_for_edit in use_cases_in_current_family_edit_options: 
            default_uc_idx_edit = use_cases_in_current_family_edit_options.index(current_uc_for_edit)

        prev_uc_selection_edit = st.session_state.get('use_case_selector_edition') 
        selected_use_case_ui_edit = st.radio(
            "Cas d'usage :",
            options=use_cases_in_current_family_edit_options,
            index=default_uc_idx_edit,
            key='use_case_radio_widget_edit',
            help="Sélectionnez un cas d'usage pour générer un prompt ou le paramétrer."
        )
        if st.session_state.use_case_selector_edition != selected_use_case_ui_edit:
            st.session_state.use_case_selector_edition = selected_use_case_ui_edit

        if prev_uc_selection_edit != selected_use_case_ui_edit:
            st.session_state.view_mode = "generator"
            st.session_state.active_generated_prompt = ""
            st.session_state.variable_type_to_create = None 
            st.session_state.editing_variable_info = None   
            st.rerun()

    elif current_selected_family_for_edit_logic: 
        st.info(f"Aucun cas d'usage dans '{current_selected_family_for_edit_logic}'. Créez-en un.")
        st.session_state.use_case_selector_edition = None 

    if st.session_state.force_select_family_name: st.session_state.force_select_family_name = None
    if st.session_state.force_select_use_case_name: st.session_state.force_select_use_case_name = None
    st.markdown("---")

    with st.expander("🗂️ Gérer les familles de prompts par métier", expanded=False):
        with st.form("new_family_form_sidebar", clear_on_submit=True):
            new_family_name = st.text_input("Nom du nouveau métier:", key="new_fam_name_sidebar")
            submitted_new_family = st.form_submit_button("➕ Créer métier")
            if submitted_new_family and new_family_name.strip():
                if new_family_name.strip() in st.session_state.editable_prompts:
                    st.error(f"Le métier '{new_family_name.strip()}' existe déjà.")
                else:
                    st.session_state.editable_prompts[new_family_name.strip()] = {}
                    save_editable_prompts_to_local_and_hf()
                    st.success(f"Métier '{new_family_name.strip()}' créée.")
                    st.session_state.force_select_family_name = new_family_name.strip() 
                    st.session_state.use_case_selector_edition = None 
                    st.session_state.view_mode = "generator"
                    st.rerun()
            elif submitted_new_family:
                st.error("Le nom du métier ne peut pas être vide.")

        if available_families and current_selected_family_for_edit_logic :
            st.markdown("---")
            with st.form("rename_family_form_sidebar"):
                st.write(f"Renommer le métier : **{current_selected_family_for_edit_logic}**")
                renamed_family_name_input = st.text_input("Nouveau nom :", value=current_selected_family_for_edit_logic, key="ren_fam_name_sidebar")
                submitted_rename_family = st.form_submit_button("✏️ Renommer")
                if submitted_rename_family and renamed_family_name_input.strip():
                    renamed_family_name = renamed_family_name_input.strip()
                    if renamed_family_name == current_selected_family_for_edit_logic:
                        st.info("Le nouveau nom est identique à l'ancien.")
                    elif renamed_family_name in st.session_state.editable_prompts:
                        st.error(f"Un métier nommé '{renamed_family_name}' existe déjà.")
                    else:
                        st.session_state.editable_prompts[renamed_family_name] = st.session_state.editable_prompts.pop(current_selected_family_for_edit_logic)
                        save_editable_prompts_to_local_and_hf()
                        st.success(f"Métier '{current_selected_family_for_edit_logic}' renommé en '{renamed_family_name}'.")
                        st.session_state.force_select_family_name = renamed_family_name 
                        if st.session_state.library_selected_family_for_display == current_selected_family_for_edit_logic:
                           st.session_state.library_selected_family_for_display = renamed_family_name
                        st.session_state.view_mode = "generator"
                        st.rerun()
                elif submitted_rename_family:
                    st.error("Le nouveau nom du métier ne peut pas être vide.")

            st.markdown("---")
            st.write(f"Supprimer le métier : **{current_selected_family_for_edit_logic}**")
            if st.session_state.confirming_delete_family_name == current_selected_family_for_edit_logic:
                st.warning(f"Supprimer '{current_selected_family_for_edit_logic}' et tous ses cas d'usage ? Action irréversible.")

                _text_confirm_delete = f"Oui, supprimer définitivement '{current_selected_family_for_edit_logic}'"
                if st.button(_text_confirm_delete, type="primary", key=f"confirm_del_fam_sb_{current_selected_family_for_edit_logic}", use_container_width=True):
                    deleted_fam_name = current_selected_family_for_edit_logic 
                    del st.session_state.editable_prompts[current_selected_family_for_edit_logic]
                    save_editable_prompts_to_local_and_hf()
                    st.success(f"Métier '{deleted_fam_name}' supprimée.")
                    st.session_state.confirming_delete_family_name = None
                    st.session_state.family_selector_edition = None 
                    st.session_state.use_case_selector_edition = None
                    if st.session_state.library_selected_family_for_display == deleted_fam_name:
                        st.session_state.library_selected_family_for_display = None
                    st.session_state.view_mode = "library" 
                    st.rerun()

                if st.button("Non, annuler la suppression", key=f"cancel_del_fam_sb_{current_selected_family_for_edit_logic}", use_container_width=True):
                    st.session_state.confirming_delete_family_name = None
                    st.session_state.view_mode = "generator"
                    st.rerun()
            else:
                if st.button(f"🗑️ Supprimer le métier Sélectionnée", key=f"del_fam_btn_sb_{current_selected_family_for_edit_logic}"):
                    st.session_state.confirming_delete_family_name = current_selected_family_for_edit_logic
                    st.session_state.view_mode = "generator"
                    st.rerun()
        elif not available_families:
            st.caption("Créez un métier pour pouvoir le gérer.")
        else: 
            st.caption("Sélectionnez un métier (ci-dessus) pour le gérer.")

    st.markdown("---")

    with st.expander("➕ Créer un Cas d'Usage", expanded=st.session_state.get('show_create_new_use_case_form', False)):
        if not available_families:
            st.caption("Veuillez d'abord créer une famille de métier pour y ajouter des cas d'usage.")
        else: 
            if st.button("Afficher/Masquer Formulaire de Création de Cas d'Usage", key="toggle_create_uc_form_in_exp"):
                st.session_state.show_create_new_use_case_form = not st.session_state.get('show_create_new_use_case_form', False)
                st.rerun() 

            if st.session_state.get('show_create_new_use_case_form', False): 
                with st.form("new_use_case_form_in_exp", clear_on_submit=True):
                    default_create_family_idx_tab = 0
                    if current_selected_family_for_edit_logic and current_selected_family_for_edit_logic in available_families:
                        default_create_family_idx_tab = available_families.index(current_selected_family_for_edit_logic)

                    uc_parent_family = st.selectbox(
                        "Métier parent du nouveau cas d'usage:",
                        options=available_families,
                        index=default_create_family_idx_tab,
                        key="new_uc_parent_fam_in_exp"
                    )
                    uc_name_input = st.text_input("Nom du Nouveau Cas d'Usage:", key="new_uc_name_in_exp")
                    uc_description_input = st.text_area("Description du cas d'usage:", height=100, key="new_uc_desc_in_exp", value="") 
                    uc_template_input = st.text_area("Template Initial du Cas d'Usage:", height=150, key="new_uc_template_in_exp", value="Nouveau prompt...")
                    submitted_new_uc = st.form_submit_button("Créer Cas d'Usage")

                    if submitted_new_uc:
                        parent_family_val = uc_parent_family 
                        uc_name_val = uc_name_input.strip()
                        uc_template_val = uc_template_input 
                        uc_description_val = uc_description_input.strip()

                        if not uc_name_val: 
                            st.error("Le nom du cas d'usage ne peut pas être vide.")
                        elif uc_name_val in st.session_state.editable_prompts.get(parent_family_val, {}):
                            st.error(f"Le cas d'usage '{uc_name_val}' existe déjà dans le métier '{parent_family_val}'.")
                        else:
                            now_iso_create, now_iso_update = get_default_dates()
                            st.session_state.editable_prompts[parent_family_val][uc_name_val] = {
                                "description": uc_description_val,
                                "template": uc_template_val or "Nouveau prompt...",
                                "variables": [], "tags": [],
                                "usage_count": 0, "created_at": now_iso_create, "updated_at": now_iso_update
                            }
                            save_editable_prompts_to_local_and_hf()
                            st.success(f"Cas d'usage '{uc_name_val}' créé avec succès dans '{parent_family_val}'.")
                            st.session_state.show_create_new_use_case_form = False 
                            st.session_state.force_select_family_name = parent_family_val
                            st.session_state.force_select_use_case_name = uc_name_val
                            st.session_state.view_mode = "generator"
                            st.session_state.active_generated_prompt = "" 
                            st.rerun()

# --- Tab: Injection (Sidebar content) ---
with tab_injection:
    st.subheader("Assistant & Injection")
    st.markdown("Utilisez l'assistant pour préparer un prompt système ou injectez des cas d'usage en format JSON.")
    # MODIFICATION DU BOUTON EXISTANT
    if st.button("✨ Assistant Prompt Système", key="start_assistant_unified_btn", use_container_width=True): # Nom du bouton mis à jour
        st.session_state.view_mode = "assistant_creation" 
        # Réinitialiser au mode "creation" par défaut et vider les champs des deux modes potentiels
        st.session_state.assistant_mode = "creation" 
        st.session_state.assistant_form_values = {var['name']: var['default'] for var in ASSISTANT_FORM_VARIABLES}
        st.session_state.assistant_existing_prompt_value = "" 
        st.session_state.generated_meta_prompt_for_llm = "" # Le méta-prompt généré est commun
        st.rerun()
    
    if st.button("💉 Injecter JSON Manuellement", key="start_manual_injection_btn", use_container_width=True):
        st.session_state.view_mode = "inject_manual" 
        st.session_state.injection_selected_family = None 
        st.session_state.injection_json_text = "" 
        st.session_state.generated_meta_prompt_for_llm = "" # Aussi réinitialiser ici
        st.rerun()

# --- Main Display Area ---
# Handle force selection after injection
if st.session_state.get('force_select_family_name'):
    st.session_state.family_selector_edition = st.session_state.force_select_family_name
    st.session_state.force_select_family_name = None
    
if st.session_state.get('force_select_use_case_name'):
    st.session_state.use_case_selector_edition = st.session_state.force_select_use_case_name
    st.session_state.force_select_use_case_name = None

library_family_to_display = st.session_state.get('library_selected_family_for_display')

# NOUVELLE SECTION POUR LA PAGE D'ACCUEIL
if st.session_state.view_mode == "accueil":
    st.header("Bienvenue dans votre laboratoire des prompts IA ! 💡")
    st.caption(f"Créé par le pôle Data / IA")
    st.markdown("""
        Vous êtes au bon endroit pour maîtriser l'art de "parler" aux Intelligences Artificielles (IA) et obtenir d'elles exactement ce dont vous avez besoin !

        **Qu'est-ce qu'un "prompt" ?**
        Imaginez donner des instructions à un assistant virtuel intelligent, mais qui a besoin de consignes claires. Un "prompt", c'est simplement cette instruction, cette question ou cette consigne que vous formulez à l'IA.
        Plus votre instruction est bien pensée, plus l'IA vous fournira une réponse utile et pertinente.

        **Que pouvez-vous faire avec cette application ?**

        Cet outil est conçu pour vous simplifier la vie, que vous soyez novice ou plus expérimenté :

        * **Découvrir et utiliser des modèles d'instructions prêts à l'emploi** : Explorez une collection de "prompts" déjà conçus pour diverses tâches (comme rédiger un email, résumer un document, analyser une situation, etc.). Vous pourrez les utiliser tels quels ou les adapter facilement.
        * **Créer vos propres instructions sur mesure** : Vous avez une idée précise en tête ? Notre assistant vous guide pas à pas pour construire le "prompt" parfait, même si vous n'avez aucune connaissance technique. L'objectif est de transformer votre besoin en une instruction claire pour l'IA.
        * **Organiser et améliorer vos instructions** : Conservez vos meilleurs "prompts", modifiez-les et perfectionnez-les au fil du temps.

        En bref, cet outil vous aide à formuler les meilleures demandes possibles aux IA pour qu'elles deviennent de véritables alliées dans votre travail ou vos projets.
    """)

    cols_accueil = st.columns(2)
    with cols_accueil[0]:
        if st.button("📚 Je souhaite utiliser / modifier un prompt existant", use_container_width=True, type="primary"):
            st.session_state.view_mode = "select_family_for_library"
            st.rerun()
    with cols_accueil[1]:
        if st.button("✨ Je souhaite créer un prompt à partir de mon besoin", use_container_width=True, type="primary"):
            st.session_state.view_mode = "assistant_creation"
            # Réinitialiser les valeurs du formulaire de l'assistant et le prompt généré
            st.session_state.assistant_form_values = {var['name']: var['default'] for var in ASSISTANT_FORM_VARIABLES}
            st.session_state.generated_meta_prompt_for_llm = ""
            st.rerun()

elif st.session_state.view_mode == "select_family_for_library":
    if st.button("⬅️ Retour à l'accueil", key="back_to_accueil_from_select_family"):
        st.session_state.view_mode = "accueil"
        st.rerun()
    
    # Check if global filters are active
    search_term_lib = st.session_state.get("library_search_term", "").strip().lower()
    selected_tags_lib = st.session_state.get("library_selected_tags", [])
    has_active_filters = bool(search_term_lib or selected_tags_lib)
    
    if has_active_filters:
        st.header("📚 Résultats de recherche dans tous les métiers")
        if search_term_lib and selected_tags_lib:
            st.markdown(f"Recherche: **{search_term_lib}** | Tags: **{', '.join(selected_tags_lib)}**")
        elif search_term_lib:
            st.markdown(f"Recherche: **{search_term_lib}**")
        elif selected_tags_lib:
            st.markdown(f"Tags: **{', '.join(selected_tags_lib)}**")
        st.markdown("---")
        
        # Global filtering across all families
        global_filtered_results = {}
        for family_name, use_cases in st.session_state.editable_prompts.items():
            family_filtered_use_cases = {}
            for uc_name, uc_config in use_cases.items():
                match_search = True
                if search_term_lib:
                    match_search = (search_term_lib in uc_name.lower() or
                                    search_term_lib in uc_config.get("template", "").lower() or
                                    any(search_term_lib in var.get("name","").lower() or search_term_lib in var.get("label","").lower() 
                                        for var in uc_config.get("variables", [])) or
                                    any(search_term_lib in tag.lower() for tag in uc_config.get("tags", [])))
                match_tags = True
                if selected_tags_lib: 
                    match_tags = all(tag in uc_config.get("tags", []) for tag in selected_tags_lib)
                
                if match_search and match_tags:
                    family_filtered_use_cases[uc_name] = uc_config
            
            if family_filtered_use_cases:
                global_filtered_results[family_name] = family_filtered_use_cases
        
        if not global_filtered_results:
            st.info("Aucun prompt ne correspond à vos critères de recherche dans tous les métiers.")
        else:
            # Display results grouped by family
            for family_name, filtered_use_cases in sorted(global_filtered_results.items()):
                st.subheader(f"🔹 {family_name}")
                sorted_use_cases = sorted(filtered_use_cases.keys())
                for uc_name in sorted_use_cases:
                    uc_config = filtered_use_cases[uc_name]
                    exp_title = f"{uc_name}"
                    if uc_config.get("usage_count", 0) > 0: 
                        exp_title += f" (Utilisé {uc_config.get('usage_count')} fois)"
                    
                    with st.expander(exp_title, expanded=False):
                        # Display tags in the same format as standard library view
                        tags_display = uc_config.get("tags", [])
                        if tags_display: 
                            st.markdown(f"**Tags :** {', '.join([f'`{tag}`' for tag in tags_display])}")
                        
                        # Display creation and modification dates
                        created_at_str = uc_config.get('created_at', get_default_dates()[0])
                        updated_at_str = uc_config.get('updated_at', get_default_dates()[1])
                        st.caption(f"Créé le : {datetime.fromisoformat(created_at_str).strftime('%d/%m/%Y %H:%M')} | Modifié le : {datetime.fromisoformat(updated_at_str).strftime('%d/%m/%Y %H:%M')}")

                        # Three buttons in columns - same format as standard library view
                        col_btn_lib1, col_btn_lib2, col_btn_lib3 = st.columns(3)
                        with col_btn_lib1:
                            if st.button(f"✍️ Utiliser ce prompt", key=f"global_lib_use_{family_name.replace(' ', '_')}_{uc_name.replace(' ', '_')}", use_container_width=True):
                                st.session_state.view_mode = "generator"
                                st.session_state.generator_selected_family = family_name
                                st.session_state.generator_selected_use_case = uc_name
                                st.session_state.active_generated_prompt = ""
                                st.rerun()
                        with col_btn_lib2:
                            if st.button(f"📋 Dupliquer ce prompt", key=f"global_lib_duplicate_{family_name.replace(' ', '_')}_{uc_name.replace(' ', '_')}", use_container_width=True):
                                st.session_state.duplicating_use_case_details = {
                                    "family": family_name,
                                    "use_case": uc_name
                                }
                                st.rerun()
                        with col_btn_lib3:
                            if st.button(f"🗑️ Supprimer ce prompt", key=f"global_lib_delete_{family_name.replace(' ', '_')}_{uc_name.replace(' ', '_')}", use_container_width=True):
                                st.session_state.confirming_delete_details = {
                                    "family": family_name,
                                    "use_case": uc_name
                                }
                                st.rerun()
                st.markdown("---")
        
        # Clear filters option
        if st.button("🗑️ Effacer les filtres", type="secondary"):
            st.session_state.library_search_term = ""
            st.session_state.library_selected_tags = []
            st.rerun()
    
    else:
        st.header("📚 Explorer les prompts par métier")
        st.markdown("Cliquez sur le nom d'un métier pour afficher les prompts associés.")
        st.markdown("---")

        available_families = list(st.session_state.editable_prompts.keys())

        if not available_families:
            st.info("Aucun métier de prompts n'a été créé pour le moment.")
            st.markdown("Vous pouvez en créer via l'onglet **Édition** dans le menu latéral (accessible via l'icône Menu en haut à gauche).")
            st.markdown("---")

        else:
            sorted_families = sorted(available_families)
            
            # Vous pouvez ajuster le nombre de colonnes si vous avez beaucoup de familles
            num_cols = 3 
            cols = st.columns(num_cols)
            for i, family_name in enumerate(sorted_families):
                with cols[i % num_cols]:
                    if st.button(f"{family_name}", key=f"select_family_for_lib_btn_{family_name}", use_container_width=True, help=f"Voir les prompts du métier '{family_name}'"):
                        st.session_state.library_selected_family_for_display = family_name
                        st.session_state.view_mode = "library" # Redirige vers la bibliothèque avec la famille sélectionnée
                        st.rerun()
            
            st.markdown("---")

elif st.session_state.view_mode == "library":
    if st.button("⬅️ Retour à la sélection des métiers", key="back_to_select_family_from_library"):
        st.session_state.view_mode = "select_family_for_library"
        st.rerun()
    if not library_family_to_display:
        st.info("Veuillez sélectionner un métier dans la barre latérale (onglet Bibliothèque) pour afficher les prompts.")
        available_families_main_display = list(st.session_state.editable_prompts.keys())
        if available_families_main_display:
            st.session_state.library_selected_family_for_display = available_families_main_display[0]
            st.rerun()
        elif not any(st.session_state.editable_prompts.values()): 
             st.warning("Aucun métier de cas d'usage n'est configurée. Créez-en via l'onglet 'Édition'.")
    elif library_family_to_display in st.session_state.editable_prompts:
        st.header(f"Bibliothèque - métier : {library_family_to_display}")
        use_cases_in_family_display = st.session_state.editable_prompts[library_family_to_display]
        filtered_use_cases = {}
        search_term_lib = st.session_state.get("library_search_term", "").strip().lower()
        selected_tags_lib = st.session_state.get("library_selected_tags", [])
        if use_cases_in_family_display:
            for uc_name, uc_config in use_cases_in_family_display.items():
                match_search = True
                if search_term_lib:
                    match_search = (search_term_lib in uc_name.lower() or
                                    search_term_lib in uc_config.get("template", "").lower() or
                                    any(search_term_lib in var.get("name","").lower() or search_term_lib in var.get("label","").lower() 
                                        for var in uc_config.get("variables", [])) or
                                    any(search_term_lib in tag.lower() for tag in uc_config.get("tags", [])))
                match_tags = True
                if selected_tags_lib: match_tags = all(tag in uc_config.get("tags", []) for tag in selected_tags_lib)
                if match_search and match_tags: filtered_use_cases[uc_name] = uc_config
        if not filtered_use_cases:
            if not use_cases_in_family_display: st.info(f"Le métier '{library_family_to_display}' ne contient actuellement aucun prompt.")
            else: st.info("Aucun prompt ne correspond à vos critères de recherche/filtre dans cette métier.")
        else:
            # Gestion de la duplication de cas d'usage
            if st.session_state.duplicating_use_case_details and \
               st.session_state.duplicating_use_case_details["family"] == library_family_to_display:
                
                original_uc_name_for_dup = st.session_state.duplicating_use_case_details["use_case"]
                original_family_name_for_dup = st.session_state.duplicating_use_case_details["family"]
                
                st.markdown(f"### 📋 Dupliquer '{original_uc_name_for_dup}' (depuis: {original_family_name_for_dup})")
                
                form_key_duplicate = f"form_duplicate_lib_{original_family_name_for_dup.replace(' ','_')}_{original_uc_name_for_dup.replace(' ','_')}"
                with st.form(key=form_key_duplicate):
                    available_families_list = list(st.session_state.editable_prompts.keys())
                    try:
                        default_family_idx = available_families_list.index(original_family_name_for_dup)
                    except ValueError:
                        default_family_idx = 0
                    
                    selected_target_family_for_duplicate = st.selectbox(
                        "Choisir la famille de destination pour la copie :",
                        options=available_families_list,
                        index=default_family_idx,
                        key=f"target_family_dup_select_{form_key_duplicate}"
                    )
                    
                    suggested_new_name_base = f"{original_uc_name_for_dup} (copie)"
                    suggested_new_name = suggested_new_name_base
                    temp_copy_count = 1
                    while suggested_new_name in st.session_state.editable_prompts.get(selected_target_family_for_duplicate, {}):
                        suggested_new_name = f"{suggested_new_name_base} {temp_copy_count}"
                        temp_copy_count += 1
                    
                    new_duplicated_uc_name_input = st.text_input(
                        "Nouveau nom pour le cas d'usage dupliqué:",
                        value=suggested_new_name,
                        key=f"new_dup_name_input_{form_key_duplicate}"
                    )
                    
                    submitted_duplicate_form = st.form_submit_button("✅ Confirmer la Duplication", use_container_width=True)
                    
                    if submitted_duplicate_form:
                        new_uc_name_val_from_form = new_duplicated_uc_name_input.strip()
                        target_family_on_submit = selected_target_family_for_duplicate
                        
                        if not new_uc_name_val_from_form:
                            st.error("Le nom du nouveau cas d'usage ne peut pas être vide.")
                        elif new_uc_name_val_from_form in st.session_state.editable_prompts.get(target_family_on_submit, {}):
                            st.error(f"Un cas d'usage nommé '{new_uc_name_val_from_form}' existe déjà dans la famille '{target_family_on_submit}'.")
                        else:
                            current_prompt_config = st.session_state.editable_prompts[original_family_name_for_dup][original_uc_name_for_dup]
                            st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form] = copy.deepcopy(current_prompt_config)
                            now_iso_dup_create, now_iso_dup_update = get_default_dates()
                            st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["created_at"] = now_iso_dup_create
                            st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["updated_at"] = now_iso_dup_update
                            st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["usage_count"] = 0
                            save_editable_prompts_to_local_and_hf()
                            st.success(f"Cas d'usage '{original_uc_name_for_dup}' dupliqué en '{new_uc_name_val_from_form}' dans la famille '{target_family_on_submit}'.")
                            
                            st.session_state.duplicating_use_case_details = None
                            if target_family_on_submit != library_family_to_display:
                                st.session_state.library_selected_family_for_display = target_family_on_submit
                            st.rerun()
                
                cancel_key_duplicate = f"cancel_dup_process_lib_{original_family_name_for_dup.replace(' ','_')}_{original_uc_name_for_dup.replace(' ','_')}"
                if st.button("❌ Annuler la Duplication", key=cancel_key_duplicate, use_container_width=True):
                    st.session_state.duplicating_use_case_details = None
                    st.rerun()
                
                st.markdown("---")
            
            # Gestion de la suppression de cas d'usage
            if st.session_state.confirming_delete_details and \
               st.session_state.confirming_delete_details["family"] == library_family_to_display:
                
                details = st.session_state.confirming_delete_details
                st.warning(f"⚠️ Supprimer '{details['use_case']}' de '{details['family']}' ? Action irréversible.")
                
                c1_del_uc, c2_del_uc, _ = st.columns([1,1,3])
                if c1_del_uc.button(f"Oui, supprimer '{details['use_case']}'", key=f"del_yes_lib_{details['family']}_{details['use_case']}", type="primary"):
                    deleted_uc_name_for_msg = details['use_case']
                    deleted_uc_fam_for_msg = details['family']
                    del st.session_state.editable_prompts[details["family"]][details["use_case"]]
                    save_editable_prompts_to_local_and_hf()
                    st.success(f"'{deleted_uc_name_for_msg}' supprimé de '{deleted_uc_fam_for_msg}'.")
                    st.session_state.confirming_delete_details = None
                    st.rerun()
                
                if c2_del_uc.button("Non, annuler", key=f"del_no_lib_{details['family']}_{details['use_case']}"):
                    st.session_state.confirming_delete_details = None
                    st.rerun()
                
                st.markdown("---")
            
            sorted_use_cases_display = sorted(list(filtered_use_cases.keys()))
            for use_case_name_display in sorted_use_cases_display:
                prompt_config_display = filtered_use_cases[use_case_name_display]
                template_display = prompt_config_display.get("template", "_Template non défini._")
                exp_title = f"{use_case_name_display}"
                if prompt_config_display.get("usage_count", 0) > 0: exp_title += f" (Utilisé {prompt_config_display.get('usage_count')} fois)"
                with st.expander(exp_title, expanded=False):
                    
                    tags_display = prompt_config_display.get("tags", [])
                    if tags_display: st.markdown(f"**Tags :** {', '.join([f'`{tag}`' for tag in tags_display])}")
                    created_at_str = prompt_config_display.get('created_at', get_default_dates()[0])
                    updated_at_str = prompt_config_display.get('updated_at', get_default_dates()[1])
                    st.caption(f"Créé le : {datetime.fromisoformat(created_at_str).strftime('%d/%m/%Y %H:%M')} | Modifié le : {datetime.fromisoformat(updated_at_str).strftime('%d/%m/%Y %H:%M')}")

                    col_btn_lib1, col_btn_lib2, col_btn_lib3 = st.columns(3)
                    with col_btn_lib1:
                        if st.button(f"✍️ Utiliser ce prompt", key=f"main_lib_use_{library_family_to_display.replace(' ', '_')}_{use_case_name_display.replace(' ', '_')}", use_container_width=True):
                            st.session_state.view_mode = "generator"; st.session_state.generator_selected_family = library_family_to_display; st.session_state.generator_selected_use_case = use_case_name_display; st.session_state.active_generated_prompt = ""; st.rerun()
                    with col_btn_lib2:
                        if st.button(f"📋 Dupliquer ce prompt", key=f"main_lib_duplicate_{library_family_to_display.replace(' ', '_')}_{use_case_name_display.replace(' ', '_')}", use_container_width=True):
                            st.session_state.duplicating_use_case_details = {
                                "family": library_family_to_display,
                                "use_case": use_case_name_display
                            }
                            st.rerun()
                    with col_btn_lib3:
                        if st.button(f"🗑️ Supprimer ce prompt", key=f"main_lib_delete_{library_family_to_display.replace(' ', '_')}_{use_case_name_display.replace(' ', '_')}", use_container_width=True):
                            st.session_state.confirming_delete_details = {
                                "family": library_family_to_display,
                                "use_case": use_case_name_display
                            }
                            st.rerun()
    else: 
        st.info("Aucun métier n'est actuellement sélectionnée dans la bibliothèque ou le métier sélectionné n'existe plus.")
        available_families_check = list(st.session_state.editable_prompts.keys())
        if not available_families_check : st.warning("La bibliothèque est entièrement vide. Veuillez créer des métiers et des prompts.")


elif st.session_state.view_mode == "generator":
    generator_family = st.session_state.get('generator_selected_family')
    generator_use_case = st.session_state.get('generator_selected_use_case')
    
    if st.button(f"⬅️ Retour à la bibliothèque ({generator_family or 'Métier'})", key="back_to_library_from_generator"):
        if generator_family:
            st.session_state.library_selected_family_for_display = generator_family
        st.session_state.view_mode = "library"
        st.rerun()
    
    if not generator_family or not generator_use_case:
        st.info("Sélection de prompt invalide. Retournez à la bibliothèque pour choisir un prompt.")
    elif generator_family not in st.session_state.editable_prompts or generator_use_case not in st.session_state.editable_prompts[generator_family]:
        st.warning("Le prompt sélectionné n'existe plus. Retournez à la bibliothèque pour en choisir un autre.")
    else:
        # Bandeau image pour "Générateur de Prompt"
        st.image("BandeauGener.png", use_container_width=True)
        
        current_prompt_config = st.session_state.editable_prompts[generator_family][generator_use_case]
        st.header(f"{generator_use_case}")
        created_at_str_gen = current_prompt_config.get('created_at', get_default_dates()[0])
        updated_at_str_gen = current_prompt_config.get('updated_at', get_default_dates()[1])
        st.caption(f"Métier : {generator_family} | Utilisé {current_prompt_config.get('usage_count', 0)} fois. Créé le : {datetime.fromisoformat(created_at_str_gen).strftime('%d/%m/%Y')}, Modifié le : {datetime.fromisoformat(updated_at_str_gen).strftime('%d/%m/%Y')}")
        # Afficher la description si elle existe
        description = current_prompt_config.get("description", "").strip()
        if description:
            st.markdown(f"*{description}*")
        gen_form_values = {}
        with st.form(key=f"gen_form_{generator_family}_{generator_use_case}"):
            st.markdown("**Remplissez le formulaire ci-dessous pour ajouter du contexte à votre prompt :**")
            if not current_prompt_config.get("variables"):
                st.info("Ce cas d'usage n'a pas de variables configurées pour la génération.")
            
            variables_for_form = current_prompt_config.get("variables", [])
            if not isinstance(variables_for_form, list):
                variables_for_form = []
            
            # Simplified layout to prevent glitch - removed dynamic columns
            for var_info in variables_for_form:
                widget_key = f"gen_input_{generator_family}_{generator_use_case}_{var_info['name']}"
                field_default = var_info.get("default")
                var_type = var_info.get("type")
                
                if var_type == "text_input":
                    gen_form_values[var_info["name"]] = st.text_input(
                        var_info["label"], 
                        value=str(field_default or ""), 
                        key=widget_key
                    )
                elif var_type == "selectbox":
                    opts = var_info.get("options", [])
                    idx = 0
                    if opts:
                        try:
                            idx = opts.index(field_default) if field_default in opts else 0
                        except ValueError:
                            idx = 0
                    gen_form_values[var_info["name"]] = st.selectbox(
                        var_info["label"], 
                        options=opts, 
                        index=idx, 
                        key=widget_key
                    )
                elif var_type == "date_input":
                    val_date = field_default if isinstance(field_default, date) else datetime.now().date()
                    gen_form_values[var_info["name"]] = st.date_input(
                        var_info["label"], 
                        value=val_date, 
                        key=widget_key
                    )
                elif var_type == "number_input":
                    current_value_default_gen = var_info.get("default")
                    min_val_config_gen = var_info.get("min_value")
                    max_val_config_gen = var_info.get("max_value")
                    step_config_gen = var_info.get("step")
                    val_num_gen = float(current_value_default_gen) if isinstance(current_value_default_gen, (int, float)) else 0.0
                    min_val_gen = float(min_val_config_gen) if min_val_config_gen is not None else None
                    max_val_gen = float(max_val_config_gen) if max_val_config_gen is not None else None
                    step_val_gen = float(step_config_gen) if step_config_gen is not None else 1.0
                    if min_val_gen is not None and val_num_gen < min_val_gen:
                        val_num_gen = min_val_gen
                    if max_val_gen is not None and val_num_gen > max_val_gen:
                        val_num_gen = max_val_gen
                    gen_form_values[var_info["name"]] = st.number_input(
                        var_info["label"], 
                        value=val_num_gen, 
                        min_value=min_val_gen,
                        max_value=max_val_gen, 
                        step=step_val_gen, 
                        key=widget_key, 
                        format="%.2f"
                    )
                elif var_type == "text_area":
                    height_val = var_info.get("height")
                    final_height = None
                    if height_val is not None:
                        try:
                            h = int(height_val)
                            if h >= 68:
                                final_height = h
                            else:
                                final_height = 68
                        except (ValueError, TypeError):
                            final_height = None
                    else:
                        final_height = None
                    gen_form_values[var_info["name"]] = st.text_area(
                        var_info["label"], 
                        value=str(field_default or ""), 
                        height=final_height, 
                        key=widget_key
                    )
            
            if st.form_submit_button("🚀 Générer Prompt"):
                processed_values_for_template = {}
                for k, v_val in gen_form_values.items():
                    if v_val is None:
                        continue
                    
                    if isinstance(v_val, date):
                        processed_values_for_template[k] = v_val.strftime("%d/%m/%Y")
                    elif isinstance(v_val, float):
                        if v_val.is_integer():
                            processed_values_for_template[k] = str(int(v_val))
                        else:
                            processed_values_for_template[k] = f"{v_val:.2f}"
                    else:
                        processed_values_for_template[k] = str(v_val)
                
                final_vals_for_prompt = processed_values_for_template
                
                try:
                    prompt_template_content = current_prompt_config.get("template", "")
                    processed_template = prompt_template_content
                    
                    sorted_vars_for_formatting = sorted(final_vals_for_prompt.items(), key=lambda item: len(item[0]), reverse=True)
                    
                    for var_name, var_value in sorted_vars_for_formatting:
                        placeholder_streamlit = f"{{{var_name}}}"
                        processed_template = processed_template.replace(placeholder_streamlit, str(var_value))
                    
                    formatted_template_content = processed_template.replace("{{", "{").replace("}}", "}")
                    
                    use_case_title = generator_use_case
                    generated_prompt = f"Sujet : {use_case_title}\n{formatted_template_content}"
                    st.session_state.active_generated_prompt = generated_prompt
                    st.success("Prompt généré avec succès!")
                    st.balloons()
                    current_prompt_config["usage_count"] = current_prompt_config.get("usage_count", 0) + 1
                    current_prompt_config["updated_at"] = datetime.now().isoformat()
                    save_editable_prompts_to_local_and_hf()
                    
                except Exception as e:
                    st.error(f"Erreur inattendue lors de la génération du prompt : {e}")
                    st.session_state.active_generated_prompt = f"ERREUR INATTENDUE - TEMPLATE ORIGINAL :\n---\n{prompt_template_content}"
        
        st.markdown("---")
        if st.session_state.active_generated_prompt:
            st.subheader("✅ Prompt Généré (éditable):")
            edited_prompt_value = st.text_area(
                "Prompt:", 
                value=st.session_state.active_generated_prompt, 
                height=200, 
                key=f"editable_generated_prompt_output_{generator_family}_{generator_use_case}", 
                label_visibility="collapsed"
            )
            # Removed session state update to prevent auto-restart loop
            
            st.caption("Prompt généré (pour relecture et copie manuelle) - Utilisez l'icône de copie en haut à droite du bloc :")
            
            if st.session_state.active_generated_prompt:
                st.code(st.session_state.active_generated_prompt, language='markdown', line_numbers=False)
            else:
                st.markdown("*Aucun prompt généré à afficher.*")
        
        # ⚙️ Paramétrage du Prompt - Configuration Feature (Generator Mode) - COMMENTED OUT TO TEST GLITCH
        # should_expand_config = SHOW_CONFIG_SECTION and st.session_state.get('go_to_config_section', False)
        # if SHOW_CONFIG_SECTION:
        #     with st.expander(f"⚙️ Paramétrage du Prompt: {generator_use_case}", expanded=should_expand_config):
        #         st.subheader("Template du Prompt")
                safe_family_key_part = str(generator_family).replace(' ', '_').replace('.', '_').replace('{', '_').replace('}', '_').replace('(', '_').replace(')', '_')
                safe_uc_key_part = str(generator_use_case).replace(' ', '_').replace('.', '_').replace('{', '_').replace('}', '_').replace('(', '_').replace(')', '_')
                template_text_area_key = f"template_text_area_{safe_family_key_part}_{safe_uc_key_part}"; new_tpl = st.text_area("Template:", value=current_prompt_config.get('template', ''), height=200, key=template_text_area_key)
                new_desc = st.text_area("Description (aide pour l'utilisateur):", value=current_prompt_config.get('description', ''), height=100, key=f"desc_text_area_{safe_family_key_part}_{safe_uc_key_part}")
                st.markdown("##### Variables disponibles à insérer :"); variables_config = current_prompt_config.get('variables', [])
                if not variables_config: st.caption("Aucune variable définie pour ce prompt. Ajoutez-en ci-dessous.")
                else:
                    for var_info in variables_config:
                        if 'name' in var_info:
                            st.code(f"{{{var_info['name']}}}", language=None)
                    st.caption("Survolez une variable ci-dessus et cliquez sur l'icône qui apparaît pour la copier.")
                save_template_button_key = f"save_template_button_{safe_family_key_part}_{safe_uc_key_part}"
                if st.button("Sauvegarder Template & Description", key=save_template_button_key): 
                    current_prompt_config['template'] = new_tpl
                    current_prompt_config['description'] = new_desc
                    current_prompt_config["updated_at"] = datetime.now().isoformat()
                    save_editable_prompts_to_local_and_hf()
                    st.success("Template et Description sauvegardés!"); 
                    st.rerun()
                # --- TEMPORARILY COMMENTED OUT FOR GLITCH TESTING ---
                # st.markdown("---"); st.subheader("Variables du Prompt"); current_variables_list = current_prompt_config.get('variables', [])
                # if not current_variables_list: st.info("Aucune variable définie.")
                # else: pass 
                # for idx, var_data in enumerate(list(current_variables_list)): 
                #     var_id_for_key = var_data.get('name', f"varidx{idx}").replace(" ", "_"); action_key_prefix = f"var_action_{generator_family.replace(' ','_')}_{generator_use_case.replace(' ','_')}_{var_id_for_key}"
                #     col_info, col_up, col_down, col_edit, col_delete = st.columns([3, 0.5, 0.5, 0.8, 0.8])
                #     with col_info: st.markdown(f"**{idx + 1}. {var_data.get('name', 'N/A')}** ({var_data.get('label', 'N/A')})\n*Type: `{var_data.get('type', 'N/A')}`*")
                #     with col_up:
                #         disable_up_button = (idx == 0)
                #         if st.button("↑", key=f"{action_key_prefix}_up", help="Monter cette variable", disabled=disable_up_button, use_container_width=True): current_variables_list[idx], current_variables_list[idx-1] = current_variables_list[idx-1], current_variables_list[idx]; current_prompt_config["variables"] = current_variables_list; current_prompt_config["updated_at"] = datetime.now().isoformat(); save_editable_prompts_to_local_and_hf(); st.session_state.editing_variable_info = None; st.session_state.variable_type_to_create = None; st.rerun()
                #     with col_down:
                #         disable_down_button = (idx == len(current_variables_list) - 1)
                #         if st.button("↓", key=f"{action_key_prefix}_down", help="Descendre cette variable", disabled=disable_down_button, use_container_width=True): current_variables_list[idx], current_variables_list[idx+1] = current_variables_list[idx+1], current_variables_list[idx]; current_prompt_config["variables"] = current_variables_list; current_prompt_config["updated_at"] = datetime.now().isoformat(); save_editable_prompts_to_local_and_hf(); st.session_state.editing_variable_info = None; st.session_state.variable_type_to_create = None; st.rerun()
                #     with col_edit:
                #         if st.button("Modifier", key=f"{action_key_prefix}_edit", use_container_width=True): st.session_state.editing_variable_info = { "family": generator_family, "use_case": generator_use_case, "index": idx, "data": copy.deepcopy(var_data) }; st.session_state.variable_type_to_create = var_data.get('type'); st.rerun()
                #     with col_delete:
                #         if st.button("Suppr.", key=f"{action_key_prefix}_delete", type="secondary", use_container_width=True): variable_name_to_delete = current_variables_list.pop(idx).get('name', 'Variable inconnue'); current_prompt_config["variables"] = current_variables_list; current_prompt_config["updated_at"] = datetime.now().isoformat(); save_editable_prompts_to_local_and_hf(); st.success(f"Variable '{variable_name_to_delete}' supprimée."); st.session_state.editing_variable_info = None; st.session_state.variable_type_to_create = None; st.rerun()
                # --- TEMPORARILY COMMENTED OUT FOR GLITCH TESTING ---
                # st.markdown("---"); st.subheader("Ajouter une Variable"); is_editing_var = False; variable_data_for_form = {"name": "", "label": "", "type": "", "options": "", "default": ""} 
                # if st.session_state.editing_variable_info and st.session_state.editing_variable_info.get("family") == generator_family and st.session_state.editing_variable_info.get("use_case") == generator_use_case:
                #     edit_var_idx = st.session_state.editing_variable_info["index"]
                #     if edit_var_idx < len(current_prompt_config.get('variables',[])):
                #         is_editing_var = True; current_editing_data_snapshot = current_prompt_config['variables'][edit_var_idx]; variable_data_for_form.update(copy.deepcopy(current_editing_data_snapshot))
                #         if isinstance(variable_data_for_form.get("options"), list): variable_data_for_form["options"] = ", ".join(map(str, variable_data_for_form["options"]))
                #         raw_def_edit_form = variable_data_for_form.get("default")
                #         if isinstance(raw_def_edit_form, date): variable_data_for_form["default"] = raw_def_edit_form.strftime("%Y-%m-%d")
                #         elif raw_def_edit_form is not None: variable_data_for_form["default"] = str(raw_def_edit_form)
                #         else: variable_data_for_form["default"] = "" 
                #     else: st.session_state.editing_variable_info = None; st.session_state.variable_type_to_create = None; st.warning("La variable que vous tentiez de modifier n'existe plus. Annulation de l'édition."); st.rerun() # pragma: no cover
                # if not is_editing_var and st.session_state.variable_type_to_create is None:
                #     st.markdown("##### 1. Choisissez le type de variable à créer :"); variable_types_map = { "Zone de texte (courte)": "text_input", "Liste choix": "selectbox", "Date": "date_input", "Nombre": "number_input", "Zone de texte (longue)": "text_area" }; num_type_buttons = len(variable_types_map); cols_type_buttons = st.columns(min(num_type_buttons, 5)); button_idx = 0
                #     for btn_label, type_val in variable_types_map.items():
                #         if cols_type_buttons[button_idx % len(cols_type_buttons)].button(btn_label, key=f"btn_type_{type_val}_{generator_use_case.replace(' ','_')}", use_container_width=True): st.session_state.variable_type_to_create = type_val; st.rerun()
                #         button_idx += 1
                #     st.markdown("---")
                # if st.session_state.variable_type_to_create:
                #     current_type_for_form = st.session_state.variable_type_to_create
                #     variable_types_map_display = { 
                #         "text_input": "Zone de texte (courte)", "selectbox": "Liste choix", 
                #         "date_input": "Date", "number_input": "Nombre", "text_area": "Zone de texte (longue)"
                #     }
                #     readable_type = variable_types_map_display.get(current_type_for_form, "Type Inconnu")
                #     form_title = f"Modifier Variable : {variable_data_for_form.get('name','N/A')} ({readable_type})" if is_editing_var else f"Nouvelle Variable : {readable_type}"
                #     st.markdown(f"##### 2. Configurez la variable")

                #     form_key_suffix = f"_edit_{st.session_state.editing_variable_info['index']}" if is_editing_var and st.session_state.editing_variable_info else "_create"
                #     form_var_specific_key = f"form_var_{current_type_for_form}_{generator_use_case.replace(' ','_')}{form_key_suffix}"

                #     with st.form(key=form_var_specific_key, clear_on_submit=(not is_editing_var)): 
                #         st.subheader(form_title)
                #         var_name_input_form = st.text_input(
                #             "Nom technique (ex : nom_client. Sans espaces, accents ou caractères spéciaux)", 
                #             value=variable_data_for_form.get("name", ""), 
                #             key=f"{form_var_specific_key}_name",
                #             disabled=is_editing_var 
                #         )
                #         var_label_input_form = st.text_input(
                #             "Label pour l'utilisateur (description affichée)", 
                #             value=variable_data_for_form.get("label", ""), 
                #             key=f"{form_var_specific_key}_label"
                #         )
                #         var_options_str_input_form = ""
                #         if current_type_for_form == "selectbox":
                #             var_options_str_input_form = st.text_input(
                #                 "Options (séparées par une virgule)", 
                #                 value=variable_data_for_form.get("options", ""), 
                #                 key=f"{form_var_specific_key}_options"
                #             )
                #         date_hint = " (Format AAAA-MM-JJ)" if current_type_for_form == "date_input" else ""
                #         var_default_val_str_input_form = st.text_input(
                #             f"Valeur par défaut{date_hint}", 
                #             value=str(variable_data_for_form.get("default", "")), 
                #             key=f"{form_var_specific_key}_default"
                #         )

                #         min_val_input_form, max_val_input_form, step_val_input_form, height_val_input_form = None, None, None, None
                #         if current_type_for_form == "number_input": 
                #             num_cols_var_form = st.columns(3)
                #             min_val_edit_default = variable_data_for_form.get("min_value")
                #             max_val_edit_default = variable_data_for_form.get("max_value")
                #             step_val_edit_default = variable_data_for_form.get("step", 1.0) 
                #             min_val_input_form = num_cols_var_form[0].number_input("Valeur minimale (optionnel)", value=float(min_val_edit_default) if min_val_edit_default is not None else None, format="%g", key=f"{form_var_specific_key}_min")
                #             max_val_input_form = num_cols_var_form[1].number_input("Valeur maximale (optionnel)", value=float(max_val_edit_default) if max_val_edit_default is not None else None, format="%g", key=f"{form_var_specific_key}_max")
                #             step_val_input_form = num_cols_var_form[2].number_input("Pas (incrément)", value=float(step_val_edit_default), format="%g", min_value=1e-9, key=f"{form_var_specific_key}_step") 
                #         if current_type_for_form == "text_area": 
                #             height_val_input_form = st.number_input("Hauteur de la zone de texte (pixels)", value=int(variable_data_for_form.get("height", 100)), min_value=68, step=25, key=f"{form_var_specific_key}_height")

                #         submit_button_label_form = "Sauvegarder Modifications" if is_editing_var else "Ajouter Variable"
                #         submitted_specific_var_form = st.form_submit_button(submit_button_label_form)

                #         if submitted_specific_var_form:
                #             var_name_val_submit = var_name_input_form.strip()
                #             if not var_name_val_submit or not var_label_input_form.strip(): st.error("Le nom technique et le label de la variable sont requis.")
                #             elif not var_name_val_submit.isidentifier(): st.error("Nom technique invalide. Utilisez lettres, chiffres, underscores. Ne pas commencer par un chiffre. Ne pas utiliser de mot-clé Python.")
                #             elif current_type_for_form == "selectbox" and not [opt.strip() for opt in var_options_str_input_form.split(',') if opt.strip()]: st.error("Pour une variable de type 'Liste choix', au moins une option est requise.")
                #             else:
                #                 new_var_data_to_submit = { "name": var_name_val_submit, "label": var_label_input_form.strip(), "type": current_type_for_form }; parsed_def_val_submit = parse_default_value(var_default_val_str_input_form.strip(), current_type_for_form)
                #                 if current_type_for_form == "selectbox":
                #                     options_list_submit = [opt.strip() for opt in var_options_str_input_form.split(',') if opt.strip()]; new_var_data_to_submit["options"] = options_list_submit
                #                     if options_list_submit: 
                #                         if parsed_def_val_submit not in options_list_submit: st.warning(f"La valeur par défaut '{parsed_def_val_submit}' n'est pas dans la liste d'options. La première option '{options_list_submit[0]}' sera utilisée comme défaut."); new_var_data_to_submit["default"] = options_list_submit[0]
                #                         else: new_var_data_to_submit["default"] = parsed_def_val_submit
                #                     else: new_var_data_to_submit["default"] = "" 
                #                 else: new_var_data_to_submit["default"] = parsed_def_val_submit
                #                 if current_type_for_form == "number_input": 
                #                     if min_val_input_form is not None: new_var_data_to_submit["min_value"] = float(min_val_input_form)
                #                     if max_val_input_form is not None: new_var_data_to_submit["max_value"] = float(max_val_input_form)
                #                     if step_val_input_form is not None: new_var_data_to_submit["step"] = float(step_val_input_form)
                #                     else: new_var_data_to_submit["step"] = 1.0 
                #                 if current_type_for_form == "text_area" and height_val_input_form is not None: 
                #                     new_var_data_to_submit["height"] = int(height_val_input_form)

                #                 can_proceed_with_save = True; target_vars_list = current_prompt_config.get('variables', [])
                #                 if is_editing_var:
                #                     idx_to_edit_submit_form = st.session_state.editing_variable_info["index"]; target_vars_list[idx_to_edit_submit_form] = new_var_data_to_submit; st.success(f"Variable '{var_name_val_submit}' mise à jour avec succès."); st.session_state.editing_variable_info = None; st.session_state.variable_type_to_create = None 
                #                 else: 
                #                     existing_var_names_in_uc = [v['name'] for v in target_vars_list]
                #                     if var_name_val_submit in existing_var_names_in_uc: st.error(f"Une variable avec le nom technique '{var_name_val_submit}' existe déjà pour ce cas d'usage."); can_proceed_with_save = False 
                #                     else: target_vars_list.append(new_var_data_to_submit); st.success(f"Variable '{var_name_val_submit}' ajoutée avec succès.")
                #                 if can_proceed_with_save:
                #                     current_prompt_config["variables"] = target_vars_list; current_prompt_config["updated_at"] = datetime.now().isoformat(); save_editable_prompts_to_local_and_hf()
                #                     if not is_editing_var: st.session_state.variable_type_to_create = None
                #                     st.rerun()
                    
                #     cancel_button_label_form = "Annuler Modification" if is_editing_var else "Changer de Type / Annuler Création"
                #     cancel_btn_key = f"cancel_var_action_btn_{form_var_specific_key}_outside" 

                #     if st.button(cancel_button_label_form, key=cancel_btn_key, help="Réinitialise le formulaire de variable."):
                #         st.session_state.variable_type_to_create = None 
                #         if is_editing_var: 
                #             st.session_state.editing_variable_info = None 
                #         st.rerun()
                st.markdown("---"); st.subheader("🏷️ Tags"); current_tags_str = ", ".join(current_prompt_config.get("tags", []))
                new_tags_str_input = st.text_input("Tags (séparés par des virgules):", value=current_tags_str, key=f"tags_input_{generator_family}_{generator_use_case}")
                if st.button("Sauvegarder Tags", key=f"save_tags_btn_{generator_family}_{generator_use_case}"): current_prompt_config["tags"] = sorted(list(set(t.strip() for t in new_tags_str_input.split(',') if t.strip()))); current_prompt_config["updated_at"] = datetime.now().isoformat(); save_editable_prompts_to_local_and_hf(); st.success("Tags sauvegardés!"); st.rerun()

                st.markdown("---")
                st.subheader("Actions sur le Cas d'Usage")

                if st.session_state.duplicating_use_case_details and \
                   st.session_state.duplicating_use_case_details["family"] == generator_family and \
                   st.session_state.duplicating_use_case_details["use_case"] == generator_use_case:

                     original_uc_name_for_dup_form = st.session_state.duplicating_use_case_details["use_case"]
                     original_family_name_for_dup = st.session_state.duplicating_use_case_details["family"]
                     st.markdown(f"#### Dupliquer '{original_uc_name_for_dup_form}' (depuis: {original_family_name_for_dup})")

                     form_key_duplicate = f"form_duplicate_name_{original_family_name_for_dup.replace(' ','_')}_{original_uc_name_for_dup_form.replace(' ','_')}"
                     with st.form(key=form_key_duplicate):
                         available_families_list = list(st.session_state.editable_prompts.keys())
                         try:
                             default_family_idx = available_families_list.index(original_family_name_for_dup)
                         except ValueError: 
                             default_family_idx = 0

                         selected_target_family_for_duplicate = st.selectbox(
                             "Choisir la famille de destination pour la copie :",
                             options=available_families_list,
                             index=default_family_idx,
                             key=f"target_family_dup_select_{form_key_duplicate}"
                         )

                         suggested_new_name_base = f"{original_uc_name_for_dup_form} (copie)"
                         suggested_new_name = suggested_new_name_base
                         temp_copy_count = 1
                         while suggested_new_name in st.session_state.editable_prompts.get(selected_target_family_for_duplicate, {}):
                             suggested_new_name = f"{suggested_new_name_base} {temp_copy_count}"
                             temp_copy_count += 1

                         new_duplicated_uc_name_input = st.text_input(
                             "Nouveau nom pour le cas d'usage dupliqué:",
                             value=suggested_new_name,
                             key=f"new_dup_name_input_{form_key_duplicate}"
                         )

                         submitted_duplicate_form = st.form_submit_button("✅ Confirmer la Duplication", use_container_width=True)

                         if submitted_duplicate_form:
                             new_uc_name_val_from_form = new_duplicated_uc_name_input.strip()
                             target_family_on_submit = selected_target_family_for_duplicate

                             if not new_uc_name_val_from_form:
                                 st.error("Le nom du nouveau cas d'usage ne peut pas être vide.")
                             elif new_uc_name_val_from_form in st.session_state.editable_prompts.get(target_family_on_submit, {}):
                                 st.error(f"Un cas d'usage nommé '{new_uc_name_val_from_form}' existe déjà dans la famille '{target_family_on_submit}'.")
                             else:
                                 st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form] = copy.deepcopy(current_prompt_config)
                                 now_iso_dup_create, now_iso_dup_update = get_default_dates()
                                 st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["created_at"] = now_iso_dup_create
                                 st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["updated_at"] = now_iso_dup_update
                                 st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["usage_count"] = 0
                                 save_editable_prompts_to_local_and_hf()
                                 st.success(f"Cas d'usage '{original_uc_name_for_dup_form}' dupliqué en '{new_uc_name_val_from_form}' dans la famille '{target_family_on_submit}'.")

                                 st.session_state.duplicating_use_case_details = None
                                 st.session_state.force_select_family_name = target_family_on_submit
                                 st.session_state.force_select_use_case_name = new_uc_name_val_from_form
                                 st.session_state.active_generated_prompt = ""
                                 st.session_state.variable_type_to_create = None
                                 st.session_state.editing_variable_info = None
                                 st.session_state.go_to_config_section = True
                                 st.rerun()

                     cancel_key_duplicate = f"cancel_dup_process_{original_family_name_for_dup.replace(' ','_')}_{original_uc_name_for_dup_form.replace(' ','_')}"
                     if st.button("❌ Annuler la Duplication", key=cancel_key_duplicate, use_container_width=True):
                         st.session_state.duplicating_use_case_details = None
                         st.rerun()
                else: 
                     action_cols_manage = st.columns(2)
                     with action_cols_manage[0]: 
                         dup_key_init = f"initiate_dup_uc_btn_{generator_family.replace(' ','_')}_{generator_use_case.replace(' ','_')}"
                         if st.button("🔄 Dupliquer ce Cas d'Usage", key=dup_key_init, use_container_width=True):
                             st.session_state.duplicating_use_case_details = {
                                 "family": generator_family,
                                 "use_case": generator_use_case
                             }
                             st.session_state.go_to_config_section = True
                             st.rerun()

                     with action_cols_manage[1]: 
                         del_uc_key_exp_main = f"del_uc_btn_exp_main_{generator_family.replace(' ','_')}_{generator_use_case.replace(' ','_')}"
                         is_confirming_this_uc_delete_main = bool(st.session_state.confirming_delete_details and \
                                                             st.session_state.confirming_delete_details.get("family") == generator_family and \
                                                             st.session_state.confirming_delete_details.get("use_case") == generator_use_case)
                         if st.button("🗑️ Supprimer Cas d'Usage", key=del_uc_key_exp_main, type="secondary", disabled=is_confirming_this_uc_delete_main, use_container_width=True):
                             st.session_state.confirming_delete_details = {"family": generator_family, "use_case": generator_use_case}
                             st.rerun()
            
            if st.session_state.get('go_to_config_section'):
                st.session_state.go_to_config_section = False
elif st.session_state.view_mode == "inject_manual": 
    if st.button("⬅️ Retour à l'accueil", key="back_to_accueil_from_inject"):
        st.session_state.view_mode = "accueil"
        st.rerun()
    st.header("💉 Injection Manuelle de Cas d'Usage JSON")
    st.markdown("""Collez ici un ou plusieurs cas d'usage au format JSON. Le JSON doit être un dictionnaire où chaque clé est le nom du nouveau cas d'usage, et la valeur est sa configuration.""")
    st.caption("Exemple de structure pour un cas d'usage :")
    json_example_string = """{
  "Nom de Mon Nouveau Cas d'Usage": {
    "description": "Ce prompt vous aide à réaliser une tâche spécifique. N'oubliez pas d'ajouter le document nécessaire à votre conversation avec l'IA.",
    "template": "Ceci est le {variable_exemple} pour mon prompt.",
    "variables": [
      {
        "name": "variable_exemple",
        "label": "Variable d'Exemple",
        "type": "text_input",
        "default": "texte par défaut"
      }
    ],
    "tags": ["nouveau", "exemple"]
  }
}"""
    st.code(json_example_string, language="json")
    available_families_for_injection = list(st.session_state.editable_prompts.keys())
    if not available_families_for_injection: 
        st.warning("Aucun métier n'existe. Veuillez d'abord créer un métier via l'onglet 'Édition'.")
    else:
        selected_family_for_injection = st.selectbox("Choisissez le métier de destination pour l'injection :", options=[""] + available_families_for_injection, index=0, key="injection_family_selector")
        st.session_state.injection_selected_family = selected_family_for_injection if selected_family_for_injection else None
        if st.session_state.injection_selected_family:
            st.subheader(f"Injecter dans le métier : {st.session_state.injection_selected_family}")
            st.session_state.injection_json_text = st.text_area("Collez le JSON des cas d'usage ici :", value=st.session_state.get("injection_json_text", ""), height=300, key="injection_json_input")
            if st.button("➕ Injecter les Cas d'Usage", key="submit_injection_btn"):
                if not st.session_state.injection_json_text.strip(): 
                    st.error("La zone de texte JSON est vide.")
                else:
                    try:
                        injected_data = json.loads(st.session_state.injection_json_text)
                        if not isinstance(injected_data, dict): 
                            st.error("Le JSON fourni doit être un dictionnaire (objet JSON).")
                        else:
                            target_family_name = st.session_state.injection_selected_family
                            if target_family_name not in st.session_state.editable_prompts: 
                                st.error(f"Le métier de destination '{target_family_name}' n'existe plus ou n'a pas été correctement sélectionnée.") 
                            else:
                                family_prompts = st.session_state.editable_prompts[target_family_name]
                                successful_injections = []
                                failed_injections = []
                                first_new_uc_name = None
                                for uc_name, uc_config_json in injected_data.items():
                                    uc_name_stripped = uc_name.strip()
                                    if not uc_name_stripped: 
                                        failed_injections.append(f"Nom de cas d'usage vide ignoré.")
                                        continue
                                    if not isinstance(uc_config_json, dict) or "template" not in uc_config_json: 
                                        failed_injections.append(f"'{uc_name_stripped}': Configuration invalide ou template manquant.")
                                        continue
                                    if uc_name_stripped in family_prompts: 
                                        st.warning(f"Le cas d'usage '{uc_name_stripped}' existe déjà dans le métier '{target_family_name}'. Il a été ignoré.")
                                        failed_injections.append(f"'{uc_name_stripped}': Existe déjà, ignoré.")
                                        continue

                                    prepared_uc_config = _prepare_newly_injected_use_case_config(uc_config_json)

                                    if not prepared_uc_config.get("template"): 
                                        failed_injections.append(f"'{uc_name_stripped}': Template invalide après traitement.")
                                        continue
                                    family_prompts[uc_name_stripped] = prepared_uc_config
                                    successful_injections.append(uc_name_stripped)
                                    if first_new_uc_name is None: 
                                        first_new_uc_name = uc_name_stripped
                                if successful_injections:
                                    save_editable_prompts_to_local_and_hf()
                                    st.success(f"{len(successful_injections)} cas d'usage injectés avec succès dans '{target_family_name}': {', '.join(successful_injections)}")
                                    st.session_state.injection_json_text = "" 
                                    if first_new_uc_name: 
                                        st.session_state.view_mode = "generator"
                                        st.session_state.force_select_family_name = target_family_name
                                        st.session_state.force_select_use_case_name = first_new_uc_name
                                        st.session_state.go_to_config_section = True
                                        st.session_state.active_generated_prompt = "" # <--- AJOUTEZ CETTE LIGNE ICI
                                        st.rerun()
                                if failed_injections:
                                    for fail_msg in failed_injections: 
                                        st.error(f"Échec d'injection : {fail_msg}")
                                if not successful_injections and not failed_injections: 
                                    st.info("Aucun cas d'usage n'a été trouvé dans le JSON fourni ou tous étaient vides/invalides.")
                    except json.JSONDecodeError as e: 
                        st.error(f"Erreur de parsing JSON : {e}")
                    except Exception as e: 
                        st.error(f"Une erreur inattendue est survenue lors de l'injection : {e}") # pragma: no cover
        else: 
            st.info("Veuillez sélectionner un métier de destination pour commencer l'injection.")

elif st.session_state.view_mode == "assistant_creation": # Cette vue gère maintenant les deux modes
    if st.button("⬅️ Retour à l'accueil", key="back_to_accueil_from_assistant_unified"):
        st.session_state.view_mode = "accueil"
        st.rerun()
    st.header("✨ Assistant Prompt Système")

    # S'assurer que assistant_mode a une valeur initiale valide si elle n'est pas déjà définie
    if 'assistant_mode' not in st.session_state:
        st.session_state.assistant_mode = "creation"

    mode_options_labels = {
        "creation": "🆕 Créer un nouveau prompt système",
        "amelioration": "🚀 Améliorer un prompt existant"
    }
    
    # Utiliser l'index pour que st.radio se souvienne de la sélection via st.session_state.assistant_mode
    current_mode_index = 0 if st.session_state.assistant_mode == "creation" else 1

    selected_mode_key = st.radio(
        "Que souhaitez-vous faire ?",
        options=list(mode_options_labels.keys()),
        format_func=lambda key: mode_options_labels[key],
        index=current_mode_index,
        key="assistant_mode_radio_selector" # Clé unique pour le widget radio
    )

    # Si le mode sélectionné via le radio a changé, mettre à jour st.session_state et rerun pour rafraîchir le formulaire
    if selected_mode_key != st.session_state.assistant_mode:
        st.session_state.assistant_mode = selected_mode_key
        st.session_state.generated_meta_prompt_for_llm = "" # Vider le prompt généré car le mode a changé
        # Optionnel: vider les valeurs des formulaires lors du changement de mode pour éviter confusion
        # st.session_state.assistant_form_values = {var['name']: var['default'] for var in ASSISTANT_FORM_VARIABLES}
        # st.session_state.assistant_existing_prompt_value = ""
        st.rerun()

    if st.session_state.assistant_mode == "creation":
        st.markdown("Décrivez votre besoin pour que l'assistant génère une instruction détaillée. Vous donnerez cette instruction à votre LLM qui, en retour, produira les éléments de votre cas d'usage (prompt système, variables, etc.).")
        with st.form(key="assistant_creation_form_std"):
            # Initialiser current_form_input_values avec les valeurs de session_state ou les valeurs par défaut
            # pour que les champs du formulaire soient pré-remplis correctement.
            temp_form_values = {}
            for var_info in ASSISTANT_FORM_VARIABLES:
                field_key = f"assistant_form_{var_info['name']}"
                # Utilise la valeur de session_state pour ce champ ou la valeur par défaut si non trouvée
                value_for_widget = st.session_state.assistant_form_values.get(var_info['name'], var_info['default'])

                if var_info["type"] == "text_input":
                    temp_form_values[var_info["name"]] = st.text_input(
                        var_info["label"], value=value_for_widget, key=field_key
                    )
                elif var_info["type"] == "text_area":
                    temp_form_values[var_info["name"]] = st.text_area(
                        var_info["label"], value=value_for_widget, height=var_info.get("height", 100), key=field_key
                    )
                elif var_info["type"] == "number_input": # Assurez-vous que ce cas est géré si vous l'avez
                    try:
                        num_value_for_widget = float(value_for_widget if value_for_widget else var_info["default"])
                    except (ValueError, TypeError):
                        num_value_for_widget = float(var_info["default"])
                    temp_form_values[var_info["name"]] = st.number_input(
                         var_info["label"],
                         value=num_value_for_widget,
                         min_value=float(var_info.get("min_value")) if var_info.get("min_value") is not None else None,
                         max_value=float(var_info.get("max_value")) if var_info.get("max_value") is not None else None,
                         step=float(var_info.get("step", 1.0)),
                         key=field_key,
                         format="%g" # ou un autre format si nécessaire
                    )
            submitted_assistant_form = st.form_submit_button("📝 Générer l'instruction de création")

            if submitted_assistant_form:
                st.session_state.assistant_form_values = temp_form_values.copy() # Sauvegarde les valeurs actuelles du formulaire
                try:
                    # Vérifier si tous les champs requis pour ce template sont remplis (si nécessaire)
                    populated_meta_prompt = META_PROMPT_FOR_EXTERNAL_LLM_TEMPLATE.format(**st.session_state.assistant_form_values)
                    st.session_state.generated_meta_prompt_for_llm = populated_meta_prompt
                    st.success("Instruction de création générée !")
                except KeyError as e: 
                    st.error(f"Erreur lors de la construction de l'instruction. Clé de formatage manquante : {e}.")
                    st.session_state.generated_meta_prompt_for_llm = ""
                except Exception as e: 
                    st.error(f"Une erreur inattendue est survenue : {e}")
                    st.session_state.generated_meta_prompt_for_llm = ""

    elif st.session_state.assistant_mode == "amelioration":
        st.markdown("Collez votre prompt existant. L'assistant générera une instruction pour votre LLM afin de transformer votre prompt en un cas d'usage structuré et améliorable pour cette application.")
        with st.form(key="assistant_amelioration_form_unified"):
            # Utilise la valeur de session_state pour ce champ
            prompt_existant_input_val = st.text_area(
                "Collez votre prompt existant ici :",
                value=st.session_state.assistant_existing_prompt_value, 
                height=300,
                key="assistant_form_prompt_existant_unified"
            )
            submitted_assistant_amelioration_form = st.form_submit_button("📝 Générer l'instruction d'amélioration")

            if submitted_assistant_amelioration_form:
                st.session_state.assistant_existing_prompt_value = prompt_existant_input_val # Sauvegarde la valeur soumise
                if not prompt_existant_input_val.strip():
                    st.error("Veuillez coller un prompt existant dans la zone de texte.")
                    st.session_state.generated_meta_prompt_for_llm = ""
                else:
                    try:
                        populated_meta_prompt_amelioration = META_PROMPT_FOR_LLM_AMELIORATION_TEMPLATE.format(
                            prompt_existant=prompt_existant_input_val # Utiliser la valeur actuelle du champ
                        )
                        st.session_state.generated_meta_prompt_for_llm = populated_meta_prompt_amelioration
                        st.success("Instruction d'amélioration générée !")
                    except KeyError as e: 
                        st.error(f"Erreur lors de la construction de l'instruction. Clé de formatage manquante : {e}.")
                        st.session_state.generated_meta_prompt_for_llm = ""
                    except Exception as e: 
                        st.error(f"Une erreur inattendue est survenue : {e}")
                        st.session_state.generated_meta_prompt_for_llm = ""

    # Affichage commun du méta-prompt généré (qu'il vienne de la création ou de l'amélioration)
    if st.session_state.generated_meta_prompt_for_llm:
        st.subheader("📋 Instruction Générée (à coller dans votre LLM) :")

        st.code(st.session_state.generated_meta_prompt_for_llm, language='markdown', line_numbers=True)
        st.caption("<span style='color:gray; font-size:0.9em;'>Utilisez l'icône en haut à droite du bloc de code pour copier l'instruction.</span>", unsafe_allow_html=True)
        st.markdown("---")
        st.info("Une fois que votre LLM externe a généré le JSON basé sur cette instruction, copiez ce JSON et utilisez le bouton \"💉 Injecter JSON Manuellement\" (disponible aussi dans l'onglet Assistant du menu) pour l'ajouter à votre atelier.")
        if st.button("💉 Injecter JSON Manuellement", key="prepare_inject_from_assistant_unified_btn", use_container_width=True, type="primary"):
            st.session_state.view_mode = "inject_manual"
            st.session_state.injection_selected_family = None
            st.session_state.injection_json_text = ""
            st.toast("Collez le JSON généré par le LLM et sélectionnez un métier de destination.", icon="💡")
            st.rerun()   
    if not any(st.session_state.editable_prompts.values()): # pragma: no cover
        st.warning("Aucun groupement de cas d'usage métier n'est configurée. Veuillez en créer une via l'onglet 'Édition' ou vérifier votre Gist.")
    elif st.session_state.view_mode not in ["library", "generator", "inject_manual", "assistant_creation"]: # pragma: no cover
        st.session_state.view_mode = "library" if list(st.session_state.editable_prompts.keys()) else "generator"
        st.rerun()

# --- Sidebar Footer ---
st.sidebar.markdown("---")
st.sidebar.info(f"Générateur v3.3.6 - © {CURRENT_YEAR} AIBuilders (démo)")