File size: 68,960 Bytes
9d6015f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f41653d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d6015f
f41653d
9d6015f
f41653d
f266ceb
 
 
 
f41653d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d6015f
 
f41653d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4b0135
 
 
 
 
 
 
f41653d
 
 
 
 
 
 
 
 
 
 
b4b0135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f41653d
 
cd9e047
 
 
25899d8
cd9e047
 
 
25899d8
 
 
 
 
 
 
 
 
 
 
 
 
cd9e047
 
 
 
 
 
 
 
f41653d
 
 
9d6015f
f41653d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d6015f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f266ceb
 
 
 
 
 
 
 
 
 
 
 
aaaba76
 
 
f266ceb
aaaba76
 
 
f266ceb
aaaba76
f266ceb
 
 
aaaba76
 
 
f266ceb
 
 
 
 
aaaba76
f266ceb
 
 
 
aaaba76
f266ceb
 
 
 
 
 
 
 
 
 
 
 
 
9d6015f
 
f41653d
 
9d6015f
 
 
 
 
 
 
 
f41653d
 
9d6015f
f41653d
cd9e047
f41653d
 
 
 
9d6015f
f41653d
 
 
 
 
 
 
aaaba76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f41653d
aaaba76
 
f41653d
 
 
9d6015f
 
 
 
 
 
 
 
 
 
 
 
 
 
f41653d
9d6015f
 
f41653d
 
cd9e047
f41653d
 
 
9d6015f
 
 
f41653d
9d6015f
f41653d
 
 
 
 
 
 
 
 
 
 
aaaba76
 
 
 
 
 
 
 
 
f41653d
aaaba76
 
 
 
 
 
 
 
 
 
 
 
28f9d0d
aaaba76
 
 
 
 
 
 
 
 
 
 
 
28f9d0d
9d6015f
28f9d0d
9d6015f
f41653d
 
 
 
9d6015f
f41653d
 
 
 
 
 
 
 
 
 
 
 
 
9d6015f
 
 
cd9e047
f41653d
f266ceb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f41653d
 
 
 
 
 
 
5c130f4
 
 
 
 
 
 
 
 
f41653d
 
 
9d6015f
 
 
 
5c130f4
9d6015f
 
5c130f4
9d6015f
 
 
5c130f4
9d6015f
 
cd9e047
5c130f4
9d6015f
f41653d
 
 
 
 
 
 
 
9d6015f
 
f41653d
9d6015f
 
f41653d
 
 
aaaba76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f41653d
 
 
 
aaaba76
f266ceb
 
aaaba76
f266ceb
 
 
f41653d
f266ceb
 
 
9d6015f
f266ceb
 
 
6648afb
 
 
 
 
 
f266ceb
9d6015f
 
 
 
 
 
 
6648afb
f266ceb
 
 
 
9d6015f
 
 
 
 
 
 
 
 
f41653d
9d6015f
f41653d
 
 
cd9e047
f41653d
 
 
9d6015f
f41653d
9d6015f
 
f41653d
 
 
 
 
 
 
 
9d6015f
 
 
f41653d
 
 
 
 
9d6015f
 
 
 
 
 
 
 
 
 
 
 
 
f41653d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd9e047
f41653d
 
 
 
 
 
 
 
 
 
 
cd9e047
f41653d
 
 
 
 
 
 
 
 
 
cd9e047
f41653d
 
 
 
 
cd9e047
f41653d
 
 
 
 
 
ffafd0f
1f8f6e9
f41653d
 
 
 
 
 
 
 
 
2eb5a6d
 
 
 
 
18aa80e
 
2eb5a6d
 
 
 
 
f41653d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf45da8
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
# # app.py - MasterLLM v2.0 with Bedrock Fallback System
# """
# MasterLLM Pipeline Orchestrator v2.0
# - Bedrock (priority) + Gemini (fallback) for pipeline generation
# - Bedrock LangChain (priority) + CrewAI (fallback) for execution
# - MongoDB session management
# - Complete REST API
# - Gradio UI with fancy displays
# """
# import os
# import json
# import uuid
# from datetime import datetime
# from typing import List, Optional

# import gradio as gr
# from fastapi import FastAPI
# from fastapi.middleware.cors import CORSMiddleware
# from contextlib import asynccontextmanager
# import asyncio

# # Import our new services
# from services.pipeline_generator import generate_pipeline, format_pipeline_for_display
# from services.pipeline_executor import execute_pipeline_streaming
# from services.session_manager import session_manager
# from api_routes import router as api_router


# # ========================
# # BACKGROUND CLEANUP TASK
# # ========================

# async def periodic_cleanup():
#     """Cleanup old sessions every hour"""
#     while True:
#         await asyncio.sleep(3600)  # Run every hour
#         try:
#             removed = session_manager.cleanup_old_sessions(max_age_hours=24)
#             if removed > 0:
#                 print(f"🧹 Cleaned up {removed} inactive sessions")
#         except Exception as e:
#             print(f"⚠️  Cleanup error: {e}")


# @asynccontextmanager
# async def lifespan(app: FastAPI):
#     """Manage application lifecycle"""
#     # Startup
#     print("πŸš€ Starting MasterLLM v2.0...")
#     task = asyncio.create_task(periodic_cleanup())
#     yield
#     # Shutdown
#     task.cancel()
#     session_manager.close()
#     print("πŸ›‘ MasterLLM shut down gracefully")


# # ========================
# # FASTAPI APP
# # ========================

# app = FastAPI(
#     title="MasterLLM v2.0 - AI Pipeline Orchestrator",
#     description="Bedrock + Gemini fallback system with MongoDB sessions",
#     version="2.0.0",
#     lifespan=lifespan
# )

# # CORS Configuration
# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=[os.getenv("FRONTEND_ORIGIN", "http://localhost:3000")],
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )

# # Mount API routes
# app.include_router(api_router)


# # ========================
# # CONVERSATION STATE
# # ========================

# class ConversationState:
#     INITIAL = "initial"
#     PIPELINE_PROPOSED = "pipeline_proposed"
#     PIPELINE_APPROVED = "pipeline_approved"
#     EXECUTING = "executing"
#     COMPLETED = "completed"
#     ERROR = "error"


# # ========================
# # GRADIO UI HANDLERS
# # ========================

# def create_new_session():
#     """Create a new session"""
#     return session_manager.create_session()


# def handle_file_upload(file_path, session_id):
#     """Handle file upload"""
#     if not file_path:
#         return None, json.dumps({
#             "status": "error",
#             "message": "No file uploaded"
#         }, indent=2), session_id
    
#     if not session_id:
#         session_id = create_new_session()
    
#     file_name = os.path.basename(file_path)
    
#     # Update session
#     session_manager.update_session(session_id, {
#         "current_file": file_path,
#         "state": ConversationState.INITIAL
#     })
    
#     # Add system message
#     session_manager.add_message(
#         session_id,
#         "system",
#         f"File uploaded: {file_name}"
#     )
    
#     status = {
#         "status": "success",
#         "message": f"File '{file_name}' uploaded successfully",
#         "file_info": {
#             "name": file_name,
#             "path": file_path,
#             "size_bytes": os.path.getsize(file_path) if os.path.exists(file_path) else 0
#         },
#         "next_action": "πŸ’¬ Now tell me what you'd like to do with this document"
#     }
    
#     return file_path, json.dumps(status, indent=2), session_id


# def format_chat_history(history, new_user_msg, new_assistant_msg):
#     """
#     Convert chat history to new Gradio format (list of dicts with role/content)
#     Handles both old format (tuples) and new format (dicts)
#     """
#     messages = []
    
#     # Handle existing history - could be in old or new format
#     if history:
#         # Check if already in new format (list of dicts with 'role' and 'content')
#         if isinstance(history[0], dict) and 'role' in history[0]:
#             # Already in new format, just copy it
#             messages = list(history)
#         else:
#             # Old format (list of tuples), convert it
#             for item in history:
#                 if isinstance(item, (list, tuple)) and len(item) == 2:
#                     user_msg, bot_msg = item
#                     messages.append({"role": "user", "content": user_msg})
#                     messages.append({"role": "assistant", "content": bot_msg})
    
#     # Add new messages
#     messages.append({"role": "user", "content": new_user_msg})
#     messages.append({"role": "assistant", "content": new_assistant_msg})
    
#     return messages


# def chatbot_response_streaming(message: str, history: List, session_id: str, file_path: str = None):
#     """
#     Handle chat messages with streaming updates
#     Uses Bedrock (priority) β†’ Gemini (fallback) for both generation and execution
#     """
#     # Get or create session
#     session = session_manager.get_session(session_id)
#     if not session:
#         session_id = create_new_session()
#         session = session_manager.get_session(session_id)
    
#     # Update file path if provided
#     if file_path:
#         session_manager.update_session(session_id, {"current_file": file_path})
#         session = session_manager.get_session(session_id)
    
#     # Add user message to session
#     session_manager.add_message(session_id, "user", message)
    
#     current_state = session.get("state", ConversationState.INITIAL)
    
#     # ========================
#     # STATE: INITIAL - Generate Pipeline
#     # ========================
#     if current_state == ConversationState.INITIAL:
#         # Check if file is uploaded
#         if not session.get("current_file"):
#             response = {
#                 "status": "error",
#                 "message": "Please upload a document first",
#                 "action": "πŸ“ Click 'Upload Document' to begin"
#             }
#             response_text = f"```json\n{json.dumps(response, indent=2)}\n```"
#             session_manager.add_message(session_id, "assistant", response_text)
#             yield format_chat_history(history, message, response_text)
#             return
        
#         try:
#             # Generate pipeline using Bedrock β†’ Gemini fallback
#             yield format_chat_history(history, message, "πŸ€– Generating pipeline with AI...\n⏳ Trying Bedrock first...")
            
#             pipeline = generate_pipeline(
#                 user_input=message,
#                 file_path=session.get("current_file"),
#                 prefer_bedrock=True
#             )
            
#             # Save proposed pipeline to session
#             session_manager.update_session(session_id, {
#                 "proposed_pipeline": pipeline,
#                 "state": ConversationState.PIPELINE_PROPOSED
#             })
            
#             # Format for display
#             formatted_display = format_pipeline_for_display(pipeline)
            
#             # Create response with both fancy display and JSON
#             response_text = formatted_display + f"\n\n```json\n{json.dumps(pipeline, indent=2)}\n```"
            
#             session_manager.add_message(session_id, "assistant", response_text)
#             yield format_chat_history(history, message, response_text)
#             return
            
#         except Exception as e:
#             error_response = {
#                 "status": "error",
#                 "message": "Failed to generate pipeline",
#                 "error": str(e),
#                 "action": "Please try rephrasing your request"
#             }
#             response_text = f"```json\n{json.dumps(error_response, indent=2)}\n```"
#             session_manager.add_message(session_id, "assistant", response_text)
#             yield format_chat_history(history, message, response_text)
#             return
    
#     # ========================
#     # STATE: PIPELINE_PROPOSED - Handle Approval/Rejection
#     # ========================
#     elif current_state == ConversationState.PIPELINE_PROPOSED:
#         user_input = message.lower().strip()
        
#         # APPROVE - Execute the pipeline
#         if "approve" in user_input or "yes" in user_input:
#             session_manager.update_session(session_id, {"state": ConversationState.EXECUTING})
            
#             plan = session.get("proposed_pipeline", {})
            
#             # Initial status
#             initial_status = {
#                 "status": "executing",
#                 "message": "πŸš€ Starting pipeline execution...",
#                 "pipeline": plan.get("pipeline_name", "unknown"),
#                 "executor": "Attempting Bedrock LangChain first",
#                 "steps": []
#             }
#             accumulated_response = f"```json\n{json.dumps(initial_status, indent=2)}\n```"
#             yield format_chat_history(history, message, accumulated_response)
            
#             steps_completed = []
#             final_payload = None
#             executor_used = "unknown"
            
#             try:
#                 # Execute pipeline with Bedrock β†’ CrewAI fallback
#                 for event in execute_pipeline_streaming(
#                     pipeline=plan,
#                     file_path=session.get("current_file"),
#                     session_id=session_id,
#                     prefer_bedrock=True
#                 ):
#                     event_type = event.get("type")
                    
#                     # Info events (fallback notifications, etc.)
#                     if event_type == "info":
#                         info_status = {
#                             "status": "info",
#                             "message": event.get("message"),
#                             "executor": event.get("executor", "unknown")
#                         }
#                         accumulated_response = f"```json\n{json.dumps(info_status, indent=2)}\n```"
#                         yield format_chat_history(history, message, accumulated_response)
                    
#                     # Step updates
#                     elif event_type == "step":
#                         step_info = {
#                             "step": event.get("step", 0),
#                             "tool": event.get("tool", "processing"),
#                             "status": event.get("status", "running"),
#                             "executor": event.get("executor", "unknown")
#                         }
                        
#                         # Add observation if available (tool output)
#                         if "observation" in event:
#                             step_info["observation"] = event.get("observation")
                        
#                         # Add tool input if available
#                         if "input" in event:
#                             step_info["input"] = event.get("input")
                        
#                         steps_completed.append(step_info)
#                         executor_used = event.get("executor", executor_used)
                        
#                         # Create more informative status message
#                         status_message = f"πŸ“ Step {event.get('step', 0)}: {event.get('tool', 'processing')}"
#                         if event.get('status') == 'completed' and 'observation' in event:
#                             obs_preview = str(event.get('observation'))[:100]
#                             status_message += f" βœ…\n   Output: {obs_preview}..."
#                         elif event.get('status') == 'executing':
#                             status_message += " ⏳"
                        
#                         progress_status = {
#                             "status": "executing",
#                             "message": status_message,
#                             "pipeline": plan.get("pipeline_name", ""),
#                             "executor": executor_used,
#                             "current_step": step_info,
#                             "steps_completed": steps_completed
#                         }
#                         accumulated_response = f"```json\n{json.dumps(progress_status, indent=2)}\n```"
#                         yield format_chat_history(history, message, accumulated_response)

                    
#                     # Final result
#                     elif event_type == "final":
#                         final_payload = event.get("data")
#                         executor_used = event.get("executor", executor_used)
                    
#                     # Error
#                     elif event_type == "error":
#                         error_result = {
#                             "status": "failed",
#                             "error": event.get("error"),
#                             "steps_completed": steps_completed,
#                             "executor": event.get("executor", "unknown")
#                         }
#                         final_response = f"```json\n{json.dumps(error_result, indent=2)}\n```"
#                         session_manager.update_session(session_id, {"state": ConversationState.INITIAL})
#                         session_manager.add_message(session_id, "assistant", final_response)
#                         yield format_chat_history(history, message, final_response)
#                         return
                
#                 # Process final result
#                 if final_payload:
#                     session_manager.update_session(session_id, {
#                         "pipeline_result": final_payload,
#                         "state": ConversationState.INITIAL
#                     })
                    
#                     # Save execution to MongoDB
#                     session_manager.save_pipeline_execution(
#                         session_id=session_id,
#                         pipeline=plan,
#                         result=final_payload,
#                         file_path=session.get("current_file"),
#                         executor=executor_used
#                     )
                    
#                     # Format final response
#                     final_display = {
#                         "status": "completed",
#                         "executor": executor_used,
#                         "pipeline": plan.get("pipeline_name"),
#                         "result": final_payload,
#                         "summary": {
#                             "total_steps": len(steps_completed),
#                             "completed_successfully": len([s for s in steps_completed if s.get("status") == "completed"])
#                         }
#                     }
#                     final_response = f"```json\n{json.dumps(final_display, indent=2)}\n```"
#                 else:
#                     final_response = f"```json\n{json.dumps({'status': 'completed', 'steps': steps_completed, 'executor': executor_used}, indent=2)}\n```"
#                     session_manager.update_session(session_id, {"state": ConversationState.INITIAL})
                
#                 session_manager.add_message(session_id, "assistant", final_response)
#                 yield format_chat_history(history, message, final_response)
#                 return
                
#             except Exception as e:
#                 error_result = {
#                     "error": str(e),
#                     "status": "failed",
#                     "message": "Pipeline execution failed",
#                     "steps_completed": steps_completed
#                 }
#                 final_response = f"```json\n{json.dumps(error_result, indent=2)}\n```"
#                 session_manager.update_session(session_id, {"state": ConversationState.INITIAL})
#                 session_manager.add_message(session_id, "assistant", final_response)
#                 yield format_chat_history(history, message, final_response)
#                 return
        
#         # REJECT - Cancel the pipeline
#         elif "reject" in user_input or "no" in user_input:
#             session_manager.update_session(session_id, {
#                 "state": ConversationState.INITIAL,
#                 "proposed_pipeline": None
#             })
#             response_data = {
#                 "status": "rejected",
#                 "message": "Pipeline rejected by user",
#                 "action": "πŸ’¬ Please provide a new instruction"
#             }
#             response = f"```json\n{json.dumps(response_data, indent=2)}\n```"
#             session_manager.add_message(session_id, "assistant", response)
#             yield format_chat_history(history, message, response)
#             return
        
#         # EDIT - Request modifications
#         elif "edit" in user_input or "modify" in user_input:
#             current_pipeline = session.get("proposed_pipeline", {})
#             edit_help = {
#                 "status": "edit_mode",
#                 "message": "To modify the plan, describe your changes",
#                 "current_plan": current_pipeline,
#                 "examples": [
#                     "Add summarization at the end",
#                     "Remove table extraction",
#                     "Only process pages 1-3",
#                     "Translate to French instead of Spanish"
#                 ],
#                 "action": "Describe your changes, or say 'approve' to run as-is"
#             }
#             response = f"```json\n{json.dumps(edit_help, indent=2)}\n```"
#             session_manager.add_message(session_id, "assistant", response)
#             yield format_chat_history(history, message, response)
#             return
        
#         # Try to modify pipeline based on user input
#         else:
#             if len(message.strip()) > 5:
#                 try:
#                     original_plan = session.get("proposed_pipeline", {})
#                     edit_context = f"Original: {original_plan.get('pipeline_name')}. User wants: {message}"
                    
#                     # Generate new pipeline with modification
#                     new_pipeline = generate_pipeline(
#                         user_input=edit_context,
#                         file_path=session.get("current_file"),
#                         prefer_bedrock=True
#                     )
                    
#                     session_manager.update_session(session_id, {
#                         "proposed_pipeline": new_pipeline,
#                         "state": ConversationState.PIPELINE_PROPOSED
#                     })
                    
#                     formatted = format_pipeline_for_display(new_pipeline)
#                     response = formatted + f"\n\n```json\n{json.dumps(new_pipeline, indent=2)}\n```"
#                     session_manager.add_message(session_id, "assistant", response)
#                     yield format_chat_history(history, message, response)
#                     return
                    
#                 except Exception as e:
#                     error_response = {
#                         "status": "edit_failed",
#                         "error": str(e),
#                         "message": "Could not modify the plan",
#                         "action": "Try 'approve' to run as-is, or 'reject' to start over"
#                     }
#                     response = f"```json\n{json.dumps(error_response, indent=2)}\n```"
#                     session_manager.add_message(session_id, "assistant", response)
#                     yield format_chat_history(history, message, response)
#                     return
            
#             # Default waiting message
#             response_data = {
#                 "status": "waiting_for_confirmation",
#                 "message": "Please type 'approve', 'reject', or describe changes",
#                 "hint": "You can also say 'edit' for modification hints"
#             }
#             response = f"```json\n{json.dumps(response_data, indent=2)}\n```"
#             session_manager.add_message(session_id, "assistant", response)
#             yield format_chat_history(history, message, response)
#             return
    
#     # Default fallback
#     response = json.dumps({"status": "ready", "message": "Ready for your next instruction"}, indent=2)
#     session_manager.add_message(session_id, "assistant", response)
#     yield format_chat_history(history, message, response)


# # ========================
# # GRADIO UI
# # ========================

# # Simple Blocks initialization for HF Spaces compatibility (older Gradio version)
# with gr.Blocks(title="MasterLLM v2.0 - AI Pipeline Orchestrator") as demo:
#     gr.Markdown("""
#     # πŸ€– MasterLLM v2.0 - AI Pipeline Orchestrator
    
#     **πŸ† Bedrock Priority** with Gemini Fallback | **πŸ’Ύ MongoDB Sessions** | **πŸ“‘ Complete REST API**
    
#     Upload a document, describe what you want, and watch AI orchestrate the perfect pipeline!
#     """)
    
#     # State management
#     session_id_state = gr.State(value=create_new_session())
#     file_state = gr.State(value=None)
    
#     with gr.Row():
#         with gr.Column(scale=3):
#             # Chat interface - Gradio auto-detects format from data structure
#             chatbot = gr.Chatbot(label="Chat")
            
#             # Text input
#             msg = gr.Textbox(
#                 placeholder="πŸ’¬ Type your instruction... (e.g., 'extract text from pages 1-5 and summarize')",
#                 label="Your Message",
#                 lines=2,
#                 max_lines=4,
#             )
            
#             with gr.Row():
#                 submit_btn = gr.Button("πŸš€ Send", variant="primary", scale=2)
#                 clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", scale=1)
        
#         with gr.Column(scale=1):
#             # File upload section
#             gr.Markdown("### πŸ“ Upload Document")
#             file_upload = gr.File(
#                 label="PDF or Image",
#                 file_types=[".pdf", ".png", ".jpg", ".jpeg", ".gif", ".bmp"],
#                 type="filepath",
#             )
            
#             upload_status = gr.Textbox(
#                 label="πŸ“Š Upload Status",
#                 interactive=False,
#                 lines=10,
#                 max_lines=15,
#             )
            
#             # Session info
#             gr.Markdown("### πŸ”— Session Info")
#             session_display = gr.Textbox(
#                 label="Session ID",
#                 interactive=False,
#                 value=lambda: session_id_state.value[:8] + "...",
#             )
            
#             # Examples
#             gr.Markdown("### πŸ’‘ Example Pipelines")
#             gr.Examples(
#                 examples=[
#                     "extract text from pages 1-5",
#                     "extract text and summarize",
#                     "extract text, tables, and translate to Spanish",
#                     "get tables from pages 2-4 and summarize",
#                     "text-classify-ner from entire document",
#                     "describe images and summarize findings",
#                     "extract text, detect signatures and stamps",
#                 ],
#                 inputs=msg,
#             )
            
#             # System info
#             gr.Markdown("""
#             ### ℹ️ System Features
#             - βœ… **Bedrock** (Claude 3.5 Sonnet) priority
#             - βœ… **Gemini** (gemini-2.0-flash) fallback
#             - βœ… **MongoDB** session persistence
#             - βœ… **Streaming** real-time updates
#             - βœ… **Component-level** JSON output
#             - βœ… **REST API** for integration
            
#             ### πŸ“Š Pipeline Flow:
#             1. **Upload** your document
#             2. **Describe** what you want
#             3. **Review** AI-generated pipeline
#             4. **Approve** to execute
#             5. **Watch** streaming updates
#             6. **Get** complete JSON results
#             """)
    
#     # Event handlers
#     file_upload.upload(
#         fn=handle_file_upload,
#         inputs=[file_upload, session_id_state],
#         outputs=[file_state, upload_status, session_id_state],
#     )
    
#     msg.submit(
#         fn=chatbot_response_streaming,
#         inputs=[msg, chatbot, session_id_state, file_state],
#         outputs=[chatbot],
#     ).then(
#         lambda: "",
#         outputs=msg,
#     )
    
#     submit_btn.click(
#         fn=chatbot_response_streaming,
#         inputs=[msg, chatbot, session_id_state, file_state],
#         outputs=[chatbot],
#     ).then(
#         lambda: "",
#         outputs=msg,
#     )
    
#     clear_btn.click(
#         fn=lambda: ([], create_new_session(), None, None, "", ""),
#         outputs=[chatbot, session_id_state, file_state, file_upload, msg, upload_status],
#     )

# # Mount Gradio on FastAPI
# app = gr.mount_gradio_app(app, demo, path="/")


# # ========================
# # LAUNCH
# # ========================

# if __name__ == "__main__":
#     import uvicorn
#     port = int(os.getenv("PORT", 7860))
#     print(f"""
#     ╔════════════════════════════════════════════════════════════╗
#     β•‘                                                            β•‘
#     β•‘           πŸš€ MasterLLM v2.0 Starting...                   β•‘
#     β•‘                                                            β•‘
#     β•‘  🌐 Gradio UI:  http://localhost:{port}                      β•‘
#     β•‘  πŸ“‘ REST API:   http://localhost:{port}/api/v1                β•‘
#     β•‘  πŸ“š API Docs:   http://localhost:{port}/docs                  β•‘
#     β•‘                                                            β•‘
#     β•‘  πŸ† Bedrock:    Priority (Claude 3.5 Sonnet)             β•‘
#     β•‘  πŸ”„ Gemini:     Fallback (gemini-2.0-flash)              β•‘
#     β•‘  πŸ’Ύ MongoDB:    Session management                         β•‘
#     β•‘                                                            β•‘
#     β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
#     """)
    
#     uvicorn.run(app, host="0.0.0.0", port=port)

# app.py - MasterLLM v2.0 with Bedrock Fallback System
"""
MasterLLM Pipeline Orchestrator v2.0
- Bedrock (priority) + Gemini (fallback) for pipeline generation
- Bedrock LangChain (priority) + CrewAI (fallback) for execution
- MongoDB session management
- Complete REST API
- Gradio UI with fancy displays
"""
import os
import json
import uuid
from datetime import datetime
from typing import List, Optional

import gradio as gr
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import asyncio

# Import our new services
from services.pipeline_generator import generate_pipeline, format_pipeline_for_display
from services.pipeline_executor import execute_pipeline_streaming
from services.session_manager import session_manager
from services.intent_classifier import intent_classifier
from api_routes import router as api_router
from api_routes_v2 import router as api_router_v2

# V3 Architecture managers
from services.pipeline_manager import get_pipeline_manager
from services.workflow_manager import get_workflow_manager


# ========================
# BACKGROUND CLEANUP TASK
# ========================

async def periodic_cleanup():
    """Cleanup old sessions every hour"""
    while True:
        await asyncio.sleep(3600)  # Run every hour
        try:
            removed = session_manager.cleanup_old_sessions(max_age_hours=24)
            if removed > 0:
                print(f"🧹 Cleaned up {removed} inactive sessions")
        except Exception as e:
            print(f"⚠️  Cleanup error: {e}")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage application lifecycle"""
    # Startup
    print("πŸš€ Starting MasterLLM v2.0...")
    task = asyncio.create_task(periodic_cleanup())
    yield
    # Shutdown
    task.cancel()
    session_manager.close()
    print("πŸ›‘ MasterLLM shut down gracefully")


# ========================
# FASTAPI APP
# ========================

app = FastAPI(
    title="MasterLLM v2.0 - AI Pipeline Orchestrator",
    description="Bedrock + Gemini fallback system with MongoDB sessions",
    version="2.0.0",
    lifespan=lifespan
)

# CORS Configuration
app.add_middleware(
    CORSMiddleware,
    allow_origins=[os.getenv("FRONTEND_ORIGIN", "http://localhost:3000")],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Mount API routes
app.include_router(api_router)  # V1 API (legacy)
app.include_router(api_router_v2)  # V2 API (enhanced with intent classification)


# ========================
# CONVERSATION STATE
# ========================

class ConversationState:
    INITIAL = "initial"
    PIPELINE_PROPOSED = "pipeline_proposed"
    PIPELINE_APPROVED = "pipeline_approved"
    EXECUTING = "executing"
    COMPLETED = "completed"
    ERROR = "error"


# ========================
# GRADIO UI HANDLERS
# ========================

def create_new_session():
    """Create a new session"""
    return session_manager.create_session()


def handle_file_upload(file_path, session_id):
    """
    Handle file upload with V3 architecture integration
    - Uploads file to S3
    - Creates record in files collection
    - Generates presigned URL
    - Stores file metadata in MongoDB
    """
    if not file_path:
        return None, json.dumps({
            "status": "error",
            "message": "No file uploaded"
        }, indent=2), session_id
    
    if not session_id:
        session_id = create_new_session()
    
    file_name = os.path.basename(file_path)
    
    try:
        # V3: Upload to S3 and create file record
        from services.s3_manager import get_s3_manager
        from services.schemas import FileSchema, schema_to_dict
        from datetime import datetime
        
        s3 = get_s3_manager()
        file_id = str(uuid.uuid4())
        file_size = os.path.getsize(file_path) if os.path.exists(file_path) else 0
        
        # Determine MIME type
        mime_type = "application/pdf"
        if file_path.lower().endswith(('.png', '.jpg', '.jpeg')):
            mime_type = "image/jpeg"
        elif file_path.lower().endswith('.gif'):
            mime_type = "image/gif"
        
        # Upload to S3
        s3_key = f"sessions/{session_id}/files/{file_id}_{file_name}"
        with open(file_path, 'rb') as f:
            s3_result = s3.upload_file(
                key=s3_key,
                file_obj=f,
                content_type=mime_type,
                add_prefix=False
            )
        
        # Generate presigned URL (7-day max)
        presigned = s3.generate_presigned_url(
            s3_key,
            expires_in=604800,  # 7 days
            add_prefix=False
        )
        
        # Create file record in MongoDB
        mongodb_uri = os.getenv("MONGODB_URI")
        mongodb_db = os.getenv("MONGODB_DB", "masterllm")
        from pymongo import MongoClient
        
        mongo_client = MongoClient(mongodb_uri)
        files_collection = mongo_client[mongodb_db]["files"]
        
        file_record = FileSchema(
            file_id=file_id,
            session_id=session_id,
            uploaded_at=datetime.utcnow(),
            file_name=file_name,
            file_size=file_size,
            mime_type=mime_type,
            s3_bucket=s3.bucket_name,
            s3_key=s3_key,
            presigned_url=presigned["presigned_url"],
            presigned_expires_at=presigned["presigned_expires_at"]
        )
        
        files_collection.insert_one(schema_to_dict(file_record))
        
        print(f"βœ… File uploaded to S3 and recorded: {file_id}")
        
        # Update session with file reference
        session_manager.update_session(session_id, {
            "current_file": file_path,  # Keep local path for backward compatibility
            "current_file_id": file_id,  # V3: file_id reference
            "state": ConversationState.INITIAL
        })
        
        # Add system message with file info
        session_manager.add_message(
            session_id,
            "system",
            f"File uploaded: {file_name}",
            file_data={"file_id": file_id, "file_name": file_name}
        )
        
        status = {
            "status": "success",
            "message": f"File '{file_name}' uploaded successfully",
            "file_info": {
                "file_id": file_id,
                "name": file_name,
                "size_bytes": file_size,
                "s3_key": s3_key,
                "presigned_url": presigned["presigned_url"],
                "expires_at": presigned["presigned_expires_at"]
            },
            "next_action": "πŸ’¬ Now tell me what you'd like to do with this document"
        }
        
        return file_path, json.dumps(status, indent=2), session_id
        
    except Exception as e:
        # Fallback to old behavior if V3 integration fails
        print(f"⚠️ File upload V3 integration failed: {e}")
        print(f"   Falling back to local file path")
        
        # Update session with local path only
        session_manager.update_session(session_id, {
            "current_file": file_path,
            "state": ConversationState.INITIAL
        })
        
        # Add system message
        session_manager.add_message(
            session_id,
            "system",
            f"File uploaded: {file_name}"
        )
        
        status = {
            "status": "partial_success",
            "message": f"File '{file_name}' uploaded locally (S3 upload failed)",
            "file_info": {
                "name": file_name,
                "path": file_path,
                "size_bytes": os.path.getsize(file_path) if os.path.exists(file_path) else 0
            },
            "warning": str(e),
            "next_action": "πŸ’¬ Now tell me what you'd like to do with this document"
        }
        
        return file_path, json.dumps(status, indent=2), session_id



def format_chat_history(history, new_user_msg, new_assistant_msg):
    """
    Convert chat history to new Gradio format (list of dicts with role/content)
    Handles both old format (tuples) and new format (dicts)
    """
    messages = []
    
    # Handle existing history - could be in old or new format
    if history:
        # Check if already in new format (list of dicts with 'role' and 'content')
        if isinstance(history[0], dict) and 'role' in history[0]:
            # Already in new format, just copy it
            messages = list(history)
        else:
            # Old format (list of tuples), convert it
            for item in history:
                if isinstance(item, (list, tuple)) and len(item) == 2:
                    user_msg, bot_msg = item
                    messages.append({"role": "user", "content": user_msg})
                    messages.append({"role": "assistant", "content": bot_msg})
    
    # Add new messages
    messages.append({"role": "user", "content": new_user_msg})
    messages.append({"role": "assistant", "content": new_assistant_msg})
    
    return messages


def chatbot_response_streaming(message: str, history: List, session_id: str, file_path: str = None):
    """
    Handle chat messages with streaming updates
    Uses intent classification + Bedrock (priority) β†’ Gemini (fallback) for both generation and execution
    """
    # Get or create session
    session = session_manager.get_session(session_id)
    if not session:
        session_id = create_new_session()
        session = session_manager.get_session(session_id)
    
    # Update file path if provided
    if file_path:
        session_manager.update_session(session_id, {"current_file": file_path})
        session = session_manager.get_session(session_id)
    
    # Add user message to session
    session_manager.add_message(session_id, "user", message)
    
    current_state = session.get("state", ConversationState.INITIAL)
    
    # ========================
    # CLASSIFY USER INTENT
    # ========================
    intent_data = intent_classifier.classify_intent(message)
    
    # ========================
    # HANDLE CASUAL CHAT & QUESTIONS
    # ========================
    if intent_data["intent"] in ["casual_chat", "question"] and current_state == ConversationState.INITIAL:
        friendly_response = intent_classifier.get_friendly_response(intent_data["intent"], message)
        session_manager.add_message(session_id, "assistant", friendly_response)
        yield format_chat_history(history, message, friendly_response)
        return
    
    # ========================
    # HANDLE UNCLEAR INTENT
    # ========================
    if intent_data["intent"] == "unclear" and current_state == ConversationState.INITIAL:
        friendly_response = intent_classifier.get_friendly_response("unclear", message)
        session_manager.add_message(session_id, "assistant", friendly_response)
        yield format_chat_history(history, message, friendly_response)
        return
    
    # ========================
    # HANDLE WORKFLOW SAVE REQUEST (V3)
    # ========================
    pending_workflow = session.get("pending_workflow_save")
    if pending_workflow and any(phrase in message.lower() for phrase in ["save", "yes", "sure", "ok"]):
        try:
            from services.s3_manager import get_s3_manager
            
            pipeline_mgr = get_pipeline_manager()
            workflow_mgr = get_workflow_manager()
            s3 = get_s3_manager()
            
            # V3: Get full pipeline document from S3 using pipeline_id
            pipeline_id = pending_workflow.get("pipeline_id")
            pipeline_doc = pipeline_mgr.get_full_pipeline_document(pipeline_id)
            
            if pipeline_doc and pipeline_doc.get("definition"):
                # Extract definition from pipeline document
                pipeline_def = pipeline_doc["definition"]
                
                # Save as workflow with source tracking
                workflow_id = workflow_mgr.save_workflow(
                    session_id=session_id,
                    pipeline_definition=pipeline_def,
                    user_message=message,
                    source_pipeline_id=pipeline_id,
                    pipeline_status=pipeline_doc.get("status", "unknown")
                )
                
                # Clear pending
                session_manager.update_session(session_id, {"pending_workflow_save": None})
                
                response = f"βœ… **Workflow Saved!**\n\nWorkflow ID: `{workflow_id}`\nName: {pending_workflow['pipeline_name']}\nSource Pipeline: `{pipeline_id[:8]}...`\n\nYou can now reuse this workflow anytime!\n\nWhat else can I help you with?"
                session_manager.add_message(session_id, "assistant", response)
                yield format_chat_history(history, message, response)
                return
            else:
                # Pipeline document not found
                session_manager.update_session(session_id, {"pending_workflow_save": None})
                response = "⚠️ Sorry, I couldn't find the pipeline to save. The workflow save request has expired.\n\nWhat else can I help you with?"
                session_manager.add_message(session_id, "assistant", response)
                yield format_chat_history(history, message, response)
                return
                
        except Exception as e:
            session_manager.update_session(session_id, {"pending_workflow_save": None})
            response = f"❌ Failed to save workflow: {str(e)}\n\nWhat would you like to do next?"
            session_manager.add_message(session_id, "assistant", response)
            yield format_chat_history(history, message, response)
            return
    
    # ========================
    # STATE: INITIAL - Generate Pipeline ONLY if intent requires it
    # ========================
    if current_state == ConversationState.INITIAL:
        # Only generate pipeline if user explicitly requested it
        if not intent_data.get("requires_pipeline", False):
            # Not a pipeline request - give friendly response
            friendly_response = "I'm here to help process documents! Please tell me what you'd like to do with your document.\n\nFor example:\n- 'extract text and summarize'\n- 'get tables from pages 2-5'\n- 'translate to Spanish'\n\nType 'help' to see all capabilities!"
            session_manager.add_message(session_id, "assistant", friendly_response)
            yield format_chat_history(history, message, friendly_response)
            return
        
        # Check if file is uploaded
        if not session.get("current_file"):
            response_text = "πŸ“ Please upload a document first before I can process it!\n\nClick the 'Upload Document' button to get started."
            session_manager.add_message(session_id, "assistant", response_text)
            yield format_chat_history(history, message, response_text)
            return
        
        try:
            # Generate pipeline using Bedrock β†’ Gemini fallback
            yield format_chat_history(history, message, "πŸ€– Analyzing your request and creating a pipeline...\n⏳ This will take just a moment...")
            
            pipeline = generate_pipeline(
                user_input=message,
                file_path=session.get("current_file"),
                prefer_bedrock=True
            )
            
            # V3: Create pipeline_id and upload to S3
            pipeline_id = str(uuid.uuid4())
            
            # Build initial pipeline document
            pipeline_doc = {
                "pipeline_id": pipeline_id,
                "session_id": session_id,
                "pipeline_name": pipeline.get("pipeline_name"),
                "status": "proposed",
                "created_at": datetime.utcnow().isoformat() + "Z",
                "created_by_message": message,
                "definition": pipeline,
                "execution": None,
                "results": None
            }
            
            # Upload to S3
            from services.s3_manager import get_s3_manager
            s3 = get_s3_manager()
            pipeline_s3_key = f"sessions/{session_id}/pipelines/{pipeline_id}.json"
            s3.upload_json(pipeline_s3_key, pipeline_doc, add_prefix=False)
            
            # Create metadata in MongoDB
            from services.pipeline_manager import get_pipeline_manager
            pipeline_mgr = get_pipeline_manager()
            pipeline_mgr.create_pipeline_metadata(
                pipeline_id=pipeline_id,
                session_id=session_id,
                pipeline_name=pipeline.get("pipeline_name"),
                s3_key=pipeline_s3_key,
                status="proposed",
                created_by_message=message
            )
            
            # Update session with reference only (not full pipeline)
            session_manager.update_session(session_id, {
                "current_pipeline_id": pipeline_id,
                "current_pipeline_s3_key": pipeline_s3_key,
                "state": ConversationState.PIPELINE_PROPOSED
            })
            
            # Create user-friendly display
            pipeline_name = pipeline.get("pipeline_name", "Document Processing")
            steps_list = pipeline.get("pipeline_steps", [])
            steps_summary = "\n".join([f"  {i+1}. **{step.get('tool', 'Unknown')}**" for i, step in enumerate(steps_list)])
            
            friendly_display = f"""🎯 **Pipeline Created: {pipeline_name}**

Here's what I'll do:
{steps_summary}

**Ready to proceed?**
- Type **'approve'** or **'yes'** to execute
- Type **'reject'** or **'no'** to cancel
- Describe changes to modify the plan"""
            
            # Add technical details in collapsible format
            response_text = friendly_display + f"\n\n<details>\n<summary>πŸ“Š Technical Details (for developers)</summary>\n\n```json\n{json.dumps(pipeline, indent=2)}\n```\n</details>"
            
            session_manager.add_message(session_id, "assistant", response_text)
            yield format_chat_history(history, message, response_text)
            return
            
        except Exception as e:
            error_response = f"❌ **Oops!** I encountered an error while creating the pipeline:\n\n{str(e)}\n\nPlease try rephrasing your request or type 'help' for examples."
            session_manager.add_message(session_id, "assistant", error_response)
            yield format_chat_history(history, message, error_response)
            return

    
    # ========================
    # STATE: PIPELINE_PROPOSED - Handle Approval/Rejection
    # ========================
    elif current_state == ConversationState.PIPELINE_PROPOSED:
        user_input = message.lower().strip()
        
        # APPROVE - Execute the pipeline
        if "approve" in user_input or "yes" in user_input:
            session_manager.update_session(session_id, {"state": ConversationState.EXECUTING})
            
            # V3: Get pipeline references from session
            pipeline_s3_key = session.get("current_pipeline_s3_key")
            pipeline_id = session.get("current_pipeline_id")
            
            # Download pipeline from S3
            from services.s3_manager import get_s3_manager
            s3 = get_s3_manager()
            from services.pipeline_manager import get_pipeline_manager
            pipeline_mgr = get_pipeline_manager()
            
            if pipeline_s3_key:
                try:
                    pipeline_doc = s3.download_json(pipeline_s3_key, add_prefix=False)
                    plan = pipeline_doc["definition"]
                except Exception as e:
                    print(f"⚠️ Failed to download pipeline from S3: {e}")
                    plan = {}
                    pipeline_id = session_id
            else:
                # Fallback for old sessions without S3 storage
                plan = session.get("proposed_pipeline", {})
                pipeline_id = session_id
            
            # Update pipeline status to executing
            if pipeline_s3_key and pipeline_doc:
                pipeline_doc["status"] = "executing"
                pipeline_doc["execution"] = {
                    "started_at": datetime.utcnow().isoformat() + "Z",
                    "executor": "unknown",
                    "components_status": []
                }
                s3.upload_json(pipeline_s3_key, pipeline_doc, add_prefix=False)
                pipeline_mgr.update_pipeline_status(pipeline_id, "executing")
            
            execution_id = pipeline_id
            
            # Initial status - User-friendly
            initial_message = f"βœ… **Approved!** Starting execution of: **{plan.get('pipeline_name', 'pipeline')}**\n\nπŸš€ Processing... please wait...\n_(Using {plan.get('_generator', 'AI')} - {plan.get('_model', 'model')})_"
            yield format_chat_history(history, message, initial_message)
            
            steps_completed = []
            final_payload = None
            executor_used = "unknown"
            progress_messages = []
            
            try:
                # Execute pipeline with Bedrock β†’ CrewAI fallback
                for event in execute_pipeline_streaming(
                    pipeline=plan,
                    file_path=session.get("current_file"),
                    session_id=session_id,
                    prefer_bedrock=True
                ):
                    event_type = event.get("type")
                    
                    # Info events (fallback notifications, etc.)
                    if event_type == "info":
                        info_message = f"ℹ️ {event.get('message')}\n_(Executor: {event.get('executor', 'unknown')})_"
                        progress_messages.append(info_message)
                        accumulated_response = initial_message + "\n\n" + "\n".join(progress_messages)
                        yield format_chat_history(history, message, accumulated_response)
                    
                    # Component status updates (V3)
                    elif event_type == "component_status":
                        step_info = {
                            "step": event.get("step", 0),
                            "component": event.get("component", "processing"),
                            "status": event.get("status", "running"),
                            "message": event.get("message", ""),
                            "executor": event.get("executor", "unknown")
                        }
                        
                        if "observation" in event:
                            step_info["observation"] = event.get("observation")
                        
                        steps_completed.append(step_info)
                        executor_used = event.get("executor", executor_used)
                        
                        # User-friendly status
                        status_emoji = "βœ…" if event.get('status') == 'completed' else "⏳"
                        component_msg = event.get('message', '')
                        status_line = f"{status_emoji} Step {event.get('step', 0)}: {event.get('component', 'processing')}"
                        if component_msg:
                            status_line += f" - {component_msg}"
                        
                        progress_messages.append(status_line)
                        current_progress = "\n".join(progress_messages[-5:])  # Last 5 steps
                        accumulated = initial_message + "\n\n" + current_progress
                        yield format_chat_history(history, message, accumulated)
                    
                    # Legacy step updates (backwards compatibility)
                    elif event_type == "step":
                        step_info = {
                            "step": event.get("step", 0),
                            "tool": event.get("tool", "processing"),
                            "status": event.get("status", "running"),
                            "executor": event.get("executor", "unknown")
                        }
                        
                        # Add observation if available (tool output)
                        if "observation" in event:
                            step_info["observation"] = event.get("observation")
                        
                        # Add tool input if available
                        if "input" in event:
                            step_info["input"] = event.get("input")
                        
                        steps_completed.append(step_info)
                        executor_used = event.get("executor", executor_used)
                        
                        # Create user-friendly progress message
                        step_num = event.get('step', 0)
                        tool_name = event.get('tool', 'processing')
                        
                        if event.get('status') == 'completed' and 'observation' in event:
                            obs_preview = str(event.get('observation'))[:80]
                            step_message = f"βœ… **Step {step_num}:** {tool_name} - Completed!\n   _Preview: {obs_preview}..._"
                        elif event.get('status') == 'executing':
                            step_message = f"⏳ **Step {step_num}:** {tool_name} - Processing..."
                        else:
                            step_message = f"πŸ“ **Step {step_num}:** {tool_name}"
                        
                        progress_messages.append(step_message)
                        accumulated_response = initial_message + "\n\n" + "\n\n".join(progress_messages)
                        yield format_chat_history(history, message, accumulated_response)


                    
                    # Final result
                    elif event_type == "final":
                        final_payload = event.get("data")
                        executor_used = event.get("executor", executor_used)
                    
                    # Error
                    elif event_type == "error":
                        error_msg = event.get("error", "Unknown error")
                        friendly_error = f"❌ **Pipeline Failed**\n\nError: {error_msg}\n\nCompleted {len(steps_completed)} step(s) before failure.\n\nWhat would you like to do next?"
                        session_manager.update_session(session_id, {"state": ConversationState.INITIAL})
                        session_manager.add_message(session_id, "assistant", friendly_error)
                        yield format_chat_history(history, message, friendly_error)
                        return
                
                # Process final result
                    # V3: Update pipeline document with results in S3
                    if pipeline_s3_key:
                        try:
                            pipeline_doc = s3.download_json(pipeline_s3_key, add_prefix=False)
                            pipeline_doc["status"] = "completed"
                            if pipeline_doc.get("execution"):
                                pipeline_doc["execution"]["completed_at"] = datetime.utcnow().isoformat() + "Z"
                                pipeline_doc["execution"]["executor"] = executor_used
                            pipeline_doc["results"] = {
                                "final_output_url": final_payload.get("final_output_url"),
                                "final_output_expires_at": final_payload.get("final_output_expires_at"),
                                "components_executed": final_payload.get("components_executed"),
                                "last_node_output": final_payload.get("last_node_output"),
                                "workflow_status": "completed"
                            }
                            s3.upload_json(pipeline_s3_key, pipeline_doc, add_prefix=False)
                            
                            # Update MongoDB metadata
                            pipeline_mgr.update_pipeline_status(
                                pipeline_id,
                                "completed",
                                final_output_url=final_payload.get("final_output_url"),
                                final_output_expires_at=final_payload.get("final_output_expires_at")
                            )
                        except Exception as e:
                            print(f"⚠️ Failed to update pipeline document: {e}")
                    
                    # Update session state
                    session_manager.update_session(session_id, {
                        "state": ConversationState.INITIAL
                    })
                    
                    # V3: Store pending workflow save info with pipeline_id
                    session_manager.update_session(session_id, {
                        "pending_workflow_save": {
                            "pipeline_id": pipeline_id,
                            "pipeline_name": plan.get("pipeline_name", "Untitled")
                        }
                    })
                    
                    # REMOVED: Deprecated save_pipeline_execution - now handled by pipeline_manager
                    
                    # Create user-friendly final response with workflow save prompt
                    success_count = len([s for s in steps_completed if s.get("status") == "completed"])
                    
                    # V3: Check if we have S3 final output URL
                    final_output_url = final_payload.get("final_output_url", "")
                    final_output_expires = final_payload.get("final_output_expires_at", "")
                    
                    # Build URL section
                    url_section = ""
                    if final_output_url:
                        url_section = f"\nπŸ“Š **Results Available:**\n- [Download All Outputs]({final_output_url})\n- Expires: {final_output_expires}\n"
                    
                    friendly_final = f"""πŸŽ‰ **Pipeline Completed Successfully!**

**Summary:**
- Pipeline: {plan.get('pipeline_name', 'Document Processing')}
- Total Steps: {len(steps_completed)}
- Successful: {success_count}
- Executor: {executor_used}
{url_section}
πŸ’Ύ **Would you like to save this workflow for future use?**
Type **'save workflow'** or **'yes'** to save it.

βœ… All done! What else can I help you with?

<details>
<summary>πŸ“Š Detailed Results (for developers)</summary>

```json
{json.dumps({"status": "completed", "executor": executor_used, "pipeline": plan.get("pipeline_name"), "result": final_payload, "steps": steps_completed}, indent=2)}
```
</details>"""
                    final_response = friendly_final
                else:
                    final_response = f"βœ… **Pipeline Completed!**\n\nExecuted {len(steps_completed)} steps using {executor_used}.\n\nReady for your next task!"
                    session_manager.update_session(session_id, {"state": ConversationState.INITIAL})
                
                session_manager.add_message(session_id, "assistant", final_response)
                yield format_chat_history(history, message, final_response)
                return
                
            except Exception as e:
                friendly_error = f"❌ **Pipeline Execution Failed**\n\nError: {str(e)}\n\nCompleted {len(steps_completed)} step(s) before failure.\n\n<details>\n<summary>πŸ“‹ Error Details</summary>\n\n```\n{str(e)}\n```\n</details>\n\nWould you like to try again with a different approach?"
                session_manager.update_session(session_id, {"state": ConversationState.INITIAL})
                session_manager.add_message(session_id, "assistant", friendly_error)
                yield format_chat_history(history, message, friendly_error)
                return
        
        # REJECT - Cancel the pipeline
        elif "reject" in user_input or "no" in user_input:
            session_manager.update_session(session_id, {
                "state": ConversationState.INITIAL,
                "proposed_pipeline": None
            })
            friendly_rejection = "πŸ‘ No problem! Pipeline cancelled.\n\nWhat else would you like me to help you with?"
            session_manager.add_message(session_id, "assistant", friendly_rejection)
            yield format_chat_history(history, message, friendly_rejection)
            return
        
        # EDIT - Request modifications
        elif "edit" in user_input or "modify" in user_input:
            current_pipeline = session.get("proposed_pipeline", {})
            friendly_edit_help = f"""πŸ“ **Edit Mode**

Current pipeline: **{current_pipeline.get('pipeline_name', 'Unknown')}**

Describe what you'd like to change. For example:
- "Add summarization at the end"
- "Remove table extraction"
- "Only process pages 1-3"
- "Translate to French instead of Spanish"

Or type 'approve' to run the current plan as-is."""
            session_manager.add_message(session_id, "assistant", friendly_edit_help)
            yield format_chat_history(history, message, friendly_edit_help)
            return
        
        # Try to modify pipeline based on user input
        else:
            if len(message.strip()) > 5:
                try:
                    original_plan = session.get("proposed_pipeline", {})
                    edit_context = f"Original: {original_plan.get('pipeline_name')}. User wants: {message}"
                    
                    # Generate new pipeline with modification
                    new_pipeline = generate_pipeline(
                        user_input=edit_context,
                        file_path=session.get("current_file"),
                        prefer_bedrock=True
                    )
                    
                    session_manager.update_session(session_id, {
                        "proposed_pipeline": new_pipeline,
                        "state": ConversationState.PIPELINE_PROPOSED
                    })
                    
                    formatted = format_pipeline_for_display(new_pipeline)
                    response = formatted + f"\n\n```json\n{json.dumps(new_pipeline, indent=2)}\n```"
                    session_manager.add_message(session_id, "assistant", response)
                    yield format_chat_history(history, message, response)
                    return
                    
                except Exception as e:
                    error_response = {
                        "status": "edit_failed",
                        "error": str(e),
                        "message": "Could not modify the plan",
                        "action": "Try 'approve' to run as-is, or 'reject' to start over"
                    }
                    response = f"```json\n{json.dumps(error_response, indent=2)}\n```"
                    session_manager.add_message(session_id, "assistant", response)
                    yield format_chat_history(history, message, response)
                    return
            
            # Default waiting message
            response_data = {
                "status": "waiting_for_confirmation",
                "message": "Please type 'approve', 'reject', or describe changes",
                "hint": "You can also say 'edit' for modification hints"
            }
            response = f"```json\n{json.dumps(response_data, indent=2)}\n```"
            session_manager.add_message(session_id, "assistant", response)
            yield format_chat_history(history, message, response)
            return
    
    # Default fallback
    response = json.dumps({"status": "ready", "message": "Ready for your next instruction"}, indent=2)
    session_manager.add_message(session_id, "assistant", response)
    yield format_chat_history(history, message, response)


# ========================
# GRADIO UI
# ========================

# Simple Blocks initialization for HF Spaces compatibility (older Gradio version)
with gr.Blocks(title="MasterLLM v2.0 - AI Pipeline Orchestrator") as demo:
    gr.Markdown("""
    # πŸ€– MasterLLM v2.0 - AI Pipeline Orchestrator
    
    **πŸ† Bedrock Priority** with Gemini Fallback | **πŸ’Ύ MongoDB Sessions** | **πŸ“‘ Complete REST API**
    
    Upload a document, describe what you want, and watch AI orchestrate the perfect pipeline!
    """)
    
    # State management
    session_id_state = gr.State(value=create_new_session())
    file_state = gr.State(value=None)
    
    with gr.Row():
        with gr.Column(scale=3):
            # Chat interface - Gradio auto-detects format from data structure
            chatbot = gr.Chatbot(label="Chat")
            
            # Text input
            msg = gr.Textbox(
                placeholder="πŸ’¬ Type your instruction... (e.g., 'extract text from pages 1-5 and summarize')",
                label="Your Message",
                lines=2,
                max_lines=4,
            )
            
            with gr.Row():
                submit_btn = gr.Button("πŸš€ Send", variant="primary", scale=2)
                clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", scale=1)
        
        with gr.Column(scale=1):
            # File upload section
            gr.Markdown("### πŸ“ Upload Document")
            file_upload = gr.File(
                label="PDF or Image",
                file_types=[".pdf", ".png", ".jpg", ".jpeg", ".gif", ".bmp"],
                type="filepath",
            )
            
            upload_status = gr.Textbox(
                label="πŸ“Š Upload Status",
                interactive=False,
                lines=10,
                max_lines=15,
            )
            
            # Session info
            gr.Markdown("### πŸ”— Session Info")
            session_display = gr.Textbox(
                label="Session ID",
                interactive=False,
                value=lambda: session_id_state.value[:8] + "...",
            )
            
            # Examples
            gr.Markdown("### πŸ’‘ Example Pipelines")
            gr.Examples(
                examples=[
                    "extract text from pages 1-5",
                    "extract text and summarize",
                    "extract text, tables, and translate to Spanish",
                    "get tables from pages 2-4 and summarize",
                    "text-classify-ner from entire document",
                    "describe images and summarize findings",
                    "extract text, detect signatures and stamps",
                ],
                inputs=msg,
            )
            
            # System info
            gr.Markdown("""
            ### ℹ️ System Features
            - βœ… **Bedrock** (Claude 3.5 Sonnet) priority
            - βœ… **Gemini** (gemini-2.0-flash) fallback
            - βœ… **MongoDB** session persistence
            - βœ… **Streaming** real-time updates
            - βœ… **Component-level** JSON output
            - βœ… **REST API** for integration
            
            ### πŸ“Š Pipeline Flow:
            1. **Upload** your document
            2. **Describe** what you want
            3. **Review** AI-generated pipeline
            4. **Approve** to execute
            5. **Watch** streaming updates
            6. **Get** complete JSON results
            """)
    
    # Event handlers
    file_upload.upload(
        fn=handle_file_upload,
        inputs=[file_upload, session_id_state],
        outputs=[file_state, upload_status, session_id_state],
    )
    
    msg.submit(
        fn=chatbot_response_streaming,
        inputs=[msg, chatbot, session_id_state, file_state],
        outputs=[chatbot],
    ).then(
        lambda: "",
        outputs=msg,
    )
    
    submit_btn.click(
        fn=chatbot_response_streaming,
        inputs=[msg, chatbot, session_id_state, file_state],
        outputs=[chatbot],
    ).then(
        lambda: "",
        outputs=msg,
    )
    
    clear_btn.click(
        fn=lambda: ([], create_new_session(), None, None, "", ""),
        outputs=[chatbot, session_id_state, file_state, file_upload, msg, upload_status],
    )

# Mount Gradio on FastAPI
app = gr.mount_gradio_app(app, demo, path="/")


# ========================
# LAUNCH
# ========================

if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", 7860))
    print(f"""
    ╔════════════════════════════════════════════════════════════╗
    β•‘                                                            β•‘
    β•‘           πŸš€ MasterLLM v2.0 Starting...                   β•‘
    β•‘                                                            β•‘
    β•‘  🌐 Gradio UI:  http://localhost:{port}                      β•‘
    β•‘  πŸ“‘ REST API:   http://localhost:{port}/api/v1                β•‘
    β•‘  πŸ“š API Docs:   http://localhost:{port}/docs                  β•‘
    β•‘                                                            β•‘
    β•‘  πŸ† Bedrock:    Priority (Claude 3.5 Sonnet)             β•‘
    β•‘  πŸ”„ Gemini:     Fallback (gemini-2.0-flash)              β•‘
    β•‘  πŸ’Ύ MongoDB:    Session management                         β•‘
    β•‘                                                            β•‘
    β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
    """)
    
    uvicorn.run(app, host="0.0.0.0", port=port)