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
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
import os
import pandas as pd
import streamlit as st
import re


# βœ… Fix OpenMP library conflict (common with PyTorch/NumPy)
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'

# --- Visualization imports ---
try:
    import matplotlib.pyplot as plt
    import plotly.express as px
    import plotly.graph_objects as go
    VISUALIZATION_AVAILABLE = True
except ImportError:
    st.warning("πŸ“Š Visualization libraries not available. Install: pip install matplotlib plotly")
    VISUALIZATION_AVAILABLE = False

# --- Modular Imports ---
from db_utils import get_engine, get_db
from llm_utils import get_llm, get_sql_prompt
from chroma_utils import get_chroma_client, get_chroma_collection, get_embedding_model
from pdf_utils import extract_pdf_text, extract_csv_text, extract_excel_text, extract_json_text, extract_docx_text

# --- Voice functionality imports (with error handling) ---
# (No need to import from agents, these are defined locally)
import json
from difflib import SequenceMatcher
from langchain.chains import LLMChain

# === Document Storage Functions ===

def chunk_text(text, chunk_size=800, overlap=100):
    """Split text into overlapping chunks"""
    chunks = []
    start = 0
    while start < len(text):
        end = min(start + chunk_size, len(text))
        chunk = text[start:end]
        chunks.append(chunk)
        start += chunk_size - overlap
    return chunks

def store_document_chunks(filename, text, file_type, chroma_collection, embedding_model):
    """Store document chunks in vector database with metadata"""
    try:
        if not text or not text.strip():
            st.warning(f"No text content found in {filename}")
            return False
        
        # Create chunks based on file type
        if file_type in ['pdf', 'txt', 'docx']:
            # For text documents, use standard chunking
            chunks = chunk_text(text, chunk_size=800, overlap=100)
            chunk_type = "text_chunk"
        elif file_type in ['csv', 'excel']:
            # For structured data, treat entire content as context
            chunks = [text]  # Store the summary as a single chunk
            chunk_type = "data_summary"
        else:
            chunks = chunk_text(text, chunk_size=800, overlap=100)
            chunk_type = "text_chunk"
        
        # Generate embeddings for all chunks
        chunk_embeddings = embedding_model.encode(chunks, convert_to_numpy=True)
        
        # Get existing IDs to avoid conflicts
        existing_data = chroma_collection.get()
        existing_ids = existing_data.get('ids', [])
        
        # Remove existing chunks for this file (if any)
        file_ids_to_remove = [id for id in existing_ids if id.startswith(f"doc_{filename}_")]
        if file_ids_to_remove:
            chroma_collection.delete(ids=file_ids_to_remove)
            st.info(f"Removed {len(file_ids_to_remove)} existing chunks for {filename}")
        
        # Add new chunks
        chunk_ids = []
        chunk_documents = []
        chunk_metadatas = []
        embeddings_list = []
        
        for i, (chunk, embedding) in enumerate(zip(chunks, chunk_embeddings)):
            chunk_id = f"doc_{filename}_{i}"
            chunk_ids.append(chunk_id)
            chunk_documents.append(chunk)
            chunk_metadatas.append({
                "filename": filename,
                "file_type": file_type,
                "chunk_index": i,
                "chunk_type": chunk_type,
                "total_chunks": len(chunks),
                "source": "uploaded_document"
            })
            embeddings_list.append(embedding.tolist())
        
        # Add to ChromaDB
        chroma_collection.add(
            embeddings=embeddings_list,
            documents=chunk_documents,
            metadatas=chunk_metadatas,
            ids=chunk_ids
        )
        
        # st.success(f"βœ… Stored {len(chunks)} chunks from {filename} in vector database")  # Hidden for cleaner UI
        return True
        
    except Exception as e:
        st.error(f"❌ Error storing chunks for {filename}: {str(e)}")
        return False

def create_csv_context(df, filename):
    """Create comprehensive context for CSV data that can be used for queries"""
    try:
        context_parts = []
        
        # Basic info
        context_parts.append(f"Dataset: {filename}")
        context_parts.append(f"Shape: {df.shape[0]} rows Γ— {df.shape[1]} columns")
        
        # Column information with data types and sample values
        context_parts.append("\nColumns and Data Types:")
        for col in df.columns:
            dtype = str(df[col].dtype)
            non_null_count = df[col].count()
            
            # Get sample values (excluding nulls)
            sample_values = df[col].dropna().head(3).tolist()
            sample_str = ", ".join([str(v)[:50] for v in sample_values])
            
            context_parts.append(f"- {col} ({dtype}): {non_null_count}/{len(df)} non-null values")
            if sample_str:
                context_parts.append(f"  Sample values: {sample_str}")
        
        # Summary statistics for numeric columns
        numeric_cols = df.select_dtypes(include=['number']).columns
        if len(numeric_cols) > 0:
            context_parts.append("\nNumeric Column Statistics:")
            for col in numeric_cols[:5]:  # Limit to first 5 numeric columns
                stats = df[col].describe()
                context_parts.append(f"- {col}: min={stats['min']:.2f}, max={stats['max']:.2f}, mean={stats['mean']:.2f}")
        
        # Sample data
        context_parts.append(f"\nSample Data (first 5 rows):")
        context_parts.append(df.head().to_string(index=False))
        
        # Unique values for categorical columns (if small enough)
        categorical_cols = df.select_dtypes(include=['object']).columns
        for col in categorical_cols[:3]:  # Limit to first 3 categorical columns
            unique_vals = df[col].unique()
            if len(unique_vals) <= 10:
                context_parts.append(f"\nUnique values in {col}: {', '.join(map(str, unique_vals))}")
            else:
                context_parts.append(f"\nUnique values in {col}: {len(unique_vals)} unique values")
                context_parts.append(f"Sample values: {', '.join(map(str, unique_vals[:5]))}")
        
        return "\n".join(context_parts)
        
    except Exception as e:
        return f"Error creating CSV context: {str(e)}"

# βœ… Custom CSS for Styling
st.markdown(
    """

    <style>

    /* Background and font styles */

    body {

        background-color: #f4f4f4;

        font-family: 'Arial', sans-serif;

    }

    

    /* Title Styling */

    .title {

        color: #2E86C1;

        text-align: center;

        font-size: 40px;

        font-weight: bold;

    }

    

    /* Text Area Styling */

    .stTextArea > div > textarea {

        border-radius: 10px;

        border: 2px solid #3498db;

        padding: 10px;

        font-size: 16px;

        height: 150px !important;  /* Increased height */

    }



    /* Button Styling */

    .stButton > button {

        background-color: #3498db;

        color: white;

        font-size: 18px;

        border-radius: 10px;

        padding: 10px 20px;

        border: none;

        transition: 0.3s;

    }

    

    .stButton > button:hover {

        background-color: #2980b9;

    }



    /* SQL Query Box */

    .stCode {

        background-color: #1e272e;

        color: #ecf0f1;

        font-size: 16px;

        border-radius: 10px;

    }



    /* Dataframe Table */

    .stDataFrame {

        border-radius: 10px;

        overflow: hidden;

        box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);

    }

    </style>

    """,
    unsafe_allow_html=True
)

# βœ… Streamlit Chat UI with Session History
st.markdown('<h3 class="title">Multi-Model RAG System</h3>', unsafe_allow_html=True)
st.write("       Chat with the agent. Your session history will be preserved below.")

# Initialize session state for chat history
if 'chat_history' not in st.session_state:
    st.session_state['chat_history'] = [] 
# Each item: {'role': 'user'/'agent', 'content': str, 'sql': str or None, 'df': DataFrame or None}

# Initialize session state for voice input
if 'pending_voice_query' not in st.session_state:
    st.session_state['pending_voice_query'] = None

## --- Modular Setup ---
engine = get_engine()
db = get_db(engine)
llm = get_llm()
sql_prompt = get_sql_prompt()

# βœ… Function to Format Schema as Markdown
def format_schema_markdown(schema_info):
    import re
    tables = re.findall(r'CREATE TABLE \"([^\"]+)\" \((.*?)\)', schema_info, re.DOTALL)
    md = '**Database Tables and Columns:**\n'
    for table, cols in tables:
        col_names = re.findall(r'\"([^\"]+)\"', cols)
        md += f'- **{table}**: ' + ', '.join(f'`{col}`' for col in col_names) + '\\n'
    return md

# Helper: Detect if a question is a follow-up
followup_starters = [
    'and ', 'also', 'from which', 'which', 'what about', 'where', 'who', 
    'how many', 'show me those', 'give me those', 'break this down', 'break it down',
    'group by', 'group this', 'filter by', 'filter this', 'sort by', 'order by',
    'can you', 'could you', 'please', 'now', 'then', 'next', 'also show',
    'what if', 'how about', 'instead', 'rather', 'but', 'however', 'compare',
    'vs ', 'versus', 'against', 'difference', 'change this', 'modify this',
    'add ', 'include', 'exclude', 'remove', 'without', 'only', 'just',
    'for the', 'in the', 'during', 'between', 'from the', 'to the'
]

followup_patterns = [
    r'\b(this|that|it|these|those)\b',  # Referential pronouns
    r'\b(same|previous|last|above|before)\b',  # Temporal references
    r'\b(more|less|greater|smaller|higher|lower)\b',  # Comparative terms
    r'\b(details?|breakdown|analysis|summary)\b',  # Analysis requests
    r'\b(why|how|when|where)\s+(did|does|is|are|was|were)\b',  # Question patterns
]

def is_followup_question(q):
    ql = q.strip().lower()
    
    # Check starter words
    if any(ql.startswith(st) for st in followup_starters):
        return True
    
    # Check patterns using regex
    import re
    for pattern in followup_patterns:
        if re.search(pattern, ql):
            return True
    
    # Check if question is very short (likely a follow-up)
    if len(ql.split()) <= 3 and any(word in ql for word in ['what', 'how', 'why', 'where', 'when', 'who']):
        return True
    
    return False

PROMPT_JSONL_PATH = 'prompts.jsonl'
def load_prompt_examples(jsonl_path):
    examples = []
    try:
        with open(jsonl_path, 'r', encoding='utf-8') as f:
            for line in f:
                examples.append(json.loads(line))
    except Exception:
        pass
    return examples

prompt_examples = load_prompt_examples(PROMPT_JSONL_PATH)

# === Utility Functions ===

def extract_llm_content(response):
    """

    Extract text content from various LLM response formats

    """
    if hasattr(response, 'content'):
        return response.content
    elif isinstance(response, dict):
        return response.get('text', response.get('content', str(response)))
    else:
        return str(response)

def fix_duplicate_columns(df):
    """

    Fix duplicate column names in DataFrame by adding suffixes

    """
    if df is None or df.empty:
        return df
    
    # Get column names
    columns = df.columns.tolist()
    
    # Check for duplicates
    seen = {}
    new_columns = []
    
    for col in columns:
        if col in seen:
            seen[col] += 1
            new_columns.append(f"{col}_{seen[col]}")
        else:
            seen[col] = 1
            new_columns.append(col)
    
    # Only rename if there were duplicates
    if len(set(columns)) != len(columns):
        df.columns = new_columns
        
    return df

def build_conversation_context(max_exchanges=3):
    """

    Build enhanced context from recent chat history including results

    """
    if 'chat_history' not in st.session_state or not st.session_state['chat_history']:
        return ""
    
    history = st.session_state['chat_history']
    recent_history = history[-max_exchanges*2:] if len(history) > max_exchanges*2 else history
    
    context_parts = ["Recent conversation context:"]
    
    for i in range(0, len(recent_history), 2):
        if i + 1 < len(recent_history):
            user_msg = recent_history[i]
            agent_msg = recent_history[i + 1]
            
            context_parts.append(f"Q: {user_msg.get('content', '')}")
            
            # Include SQL if available
            if agent_msg.get('sql'):
                context_parts.append(f"SQL: {agent_msg['sql']}")
            
            # Include result summary if available
            if agent_msg.get('df') is not None and hasattr(agent_msg['df'], 'shape'):
                df = agent_msg['df']
                context_parts.append(f"Result: {df.shape[0]} rows returned")
                if df.shape[0] > 0:
                    # Add column names for reference
                    context_parts.append(f"Columns: {', '.join(df.columns.tolist())}")
            
            context_parts.append("---")
    
    return "\n".join(context_parts) if len(context_parts) > 1 else ""

def get_enhanced_context_for_followup(user_query):
    """

    Create enhanced context for follow-up questions

    """
    context_parts = []
    
    # Add conversation context
    conv_context = build_conversation_context(max_exchanges=2)
    if conv_context:
        context_parts.append(conv_context)
    
    # Add last result columns if available for column references
    if 'last_result_df' in st.session_state and st.session_state['last_result_df'] is not None:
        df = st.session_state['last_result_df']
        if hasattr(df, 'columns'):
            context_parts.append(f"Available columns from last result: {', '.join(df.columns.tolist())}")
            
            # Add sample values for categorical columns
            categorical_cols = df.select_dtypes(include=['object']).columns
            if len(categorical_cols) > 0:
                sample_values = []
                for col in categorical_cols[:3]:  # Limit to first 3 categorical columns
                    unique_vals = df[col].unique()[:5]  # First 5 unique values
                    sample_values.append(f"{col}: {', '.join(map(str, unique_vals))}")
                if sample_values:
                    context_parts.append(f"Sample values: {'; '.join(sample_values)}")
    
    # Add last data question
    if 'last_data_question' in st.session_state:
        context_parts.append(f"Last main question: {st.session_state['last_data_question']}")
    
    return "\n\n".join(context_parts) if context_parts else ""

# Initialize ChromaDB and embedding model with persistence
try:
    with st.spinner("πŸ”„ Initializing persistent vector database..."):
        chroma_client = get_chroma_client()
        chroma_collection = get_chroma_collection(chroma_client)
        embedding_model = get_embedding_model()
        
        # Try to initialize from existing JSONL if database is empty
        from chroma_utils import initialize_from_jsonl, check_database_stats
        initialize_from_jsonl(PROMPT_JSONL_PATH)
        
        # Show database statistics
        stats = check_database_stats()
        # Hide vector DB status/info messages unless error or warning
        if stats["status"] != "healthy":
            st.warning(f"⚠️ Database status: {stats['status']}")
            
except Exception as e:
    st.error(f"❌ Vector search initialization failed: {str(e)}")
    chroma_client = None
    chroma_collection = None
    embedding_model = None

# (No need to import run_query_chain; define and use locally)

with st.sidebar:
    st.markdown('---')
    st.markdown('### Upload PDF, CSV, Excel, Word, or JSON files to query their content')
    uploaded_files = st.file_uploader(
        "Upload one or more files (PDF, CSV, Excel, DOCX, JSON)",
        type=["pdf", "csv", "xlsx", "xls", "json", "docx"],
        accept_multiple_files=True
    )
    if 'uploaded_dfs' not in st.session_state:
        st.session_state['uploaded_dfs'] = {}
    if 'uploaded_texts' not in st.session_state:
        st.session_state['uploaded_texts'] = {}
    for uploaded_file in uploaded_files or []:
        filename = uploaded_file.name
        if filename.endswith('.csv'):
            df = pd.read_csv(uploaded_file)
            st.session_state['uploaded_dfs'][filename] = df
            
            # Create comprehensive CSV context for vector storage
            csv_context = create_csv_context(df, filename)
            st.session_state['uploaded_texts'][filename] = csv_context
            
            # Store in vector database
            if chroma_collection is not None and embedding_model is not None:
                store_document_chunks(filename, csv_context, 'csv', chroma_collection, embedding_model)
            
            st.success(f"CSV loaded: {filename} (shape: {df.shape})")
            
        elif filename.endswith(('.xlsx', '.xls')):
            df = pd.read_excel(uploaded_file)
            st.session_state['uploaded_dfs'][filename] = df
            
            # Create comprehensive Excel context for vector storage
            excel_context = create_csv_context(df, filename)  # Same logic as CSV
            st.session_state['uploaded_texts'][filename] = excel_context
            
            # Store in vector database
            if chroma_collection is not None and embedding_model is not None:
                store_document_chunks(filename, excel_context, 'excel', chroma_collection, embedding_model)
            
            st.success(f"Excel loaded: {filename} (shape: {df.shape})")
            
        elif filename.endswith('.json'):
            # Extract text summary for Q&A
            text, error = extract_json_text(uploaded_file)
            if text:
                st.session_state['uploaded_texts'][filename] = text
                
                # Store in vector database
                if chroma_collection is not None and embedding_model is not None:
                    store_document_chunks(filename, text, 'json', chroma_collection, embedding_model)
                
                st.success(f"JSON loaded: {filename} (chars: {len(text)})")
            else:
                st.error(f"JSON error: {error}")
                
        elif filename.endswith('.pdf'):
            text, error = extract_pdf_text(uploaded_file)
            if text:
                st.session_state['uploaded_texts'][filename] = text
                
                # Store in vector database
                if chroma_collection is not None and embedding_model is not None:
                    store_document_chunks(filename, text, 'pdf', chroma_collection, embedding_model)
                
                st.success(f"PDF loaded: {filename} (chars: {len(text)})")
            else:
                st.error(f"PDF error: {error}")
                
        elif filename.endswith('.docx'):
            text, error = extract_docx_text(uploaded_file)
            if text:
                st.session_state['uploaded_texts'][filename] = text
                
                # Store in vector database
                if chroma_collection is not None and embedding_model is not None:
                    store_document_chunks(filename, text, 'docx', chroma_collection, embedding_model)
                
                st.success(f"Word document loaded: {filename} (chars: {len(text)})")
            else:
                st.error(f"DOCX error: {error}")
    
    # Show uploaded DataFrames
    if st.session_state['uploaded_dfs']:
        st.markdown('#### Uploaded DataFrames:')
        for fname, df in st.session_state['uploaded_dfs'].items():
            st.write(f"**{fname}**")
            st.dataframe(df.head())
    # Show uploaded PDF text (first 500 chars)
    if st.session_state['uploaded_texts']:
        st.markdown('#### Uploaded File Text (preview):')
        for fname, text in st.session_state['uploaded_texts'].items():
            st.write(f"**{fname}**: {text[:500]}{'...' if len(text) > 500 else ''}")

    # Vector Database Status
    if chroma_collection is not None:
        with st.expander("πŸ“Š Vector Database Status", expanded=False):
            try:
                # Get collection stats
                collection_data = chroma_collection.get(include=['metadatas'])
                total_items = len(collection_data.get('ids', []))
                
                if total_items > 0:
                    # Count by source type
                    metadatas = collection_data.get('metadatas', [])
                    source_counts = {}
                    doc_counts = {}
                    
                    for meta in metadatas:
                        source = meta.get('source', 'unknown')
                        filename = meta.get('filename', 'unknown')
                        
                        source_counts[source] = source_counts.get(source, 0) + 1
                        if filename != 'unknown':
                            doc_counts[filename] = doc_counts.get(filename, 0) + 1
                    
                    st.write(f"**Total chunks stored:** {total_items}")
                    
                    if doc_counts:
                        st.write("**Documents in vector database:**")
                        for doc, count in doc_counts.items():
                            st.write(f"- {doc}: {count} chunks")
                    
                    if source_counts:
                        st.write("**Content by source:**")
                        for source, count in source_counts.items():
                            if source == 'uploaded_document':
                                st.write(f"- πŸ“„ Uploaded documents: {count} chunks")
                            elif source == 'jsonl_import':
                                st.write(f"- πŸ’Ύ Imported prompts: {count} items")
                            else:
                                st.write(f"- {source}: {count} items")
                    
                    # Add clear documents button
                    col1, col2 = st.columns(2)
                    with col1:
                        if st.button("πŸ—‘οΈ Clear Document Chunks", help="Remove all uploaded document chunks from vector database"):
                            try:
                                # Get all document chunk IDs
                                all_data = chroma_collection.get()
                                doc_ids = [id for id in all_data.get('ids', []) if id.startswith('doc_')]
                                
                                if doc_ids:
                                    chroma_collection.delete(ids=doc_ids)
                                    # st.success(f"Removed {len(doc_ids)} document chunks from vector database")  # Hidden for cleaner UI
                                    st.rerun()
                                else:
                                    st.info("No document chunks to remove")
                            except Exception as e:
                                st.error(f"Error clearing documents: {e}")
                    
                    with col2:
                        if st.button("πŸ”„ Refresh Status", help="Refresh vector database status"):
                            st.rerun()
                else:
                    st.write("No items in vector database yet.")
                    
            except Exception as e:
                st.write(f"Error checking database status: {e}")


# === Local Definition: run_query_chain ===
def run_query_chain(user_query):
    schema_info = db.get_table_info()
    # Check for meta/schema questions
    meta_keywords = [
        'list of tables', 'show tables', 'schema details', 'database schema', 'table names', 'what tables', 'describe schema', 'show schema', 'database structure', 'column', 'columns'
    ]
    if any(kw in user_query.lower() for kw in meta_keywords):
        st.write("[DEBUG] Detected meta/schema question.")
        return None, format_schema_markdown(schema_info)
    # Check for direct table details or table preview requests
    import re
    table_match = re.search(r'(?:give me|show|display|list|fetch|get) (.+?)(?: details)?$', user_query.lower())
    if table_match:
        stopwords = {'me', 'the', 'a', 'an', 'all', 'of', 'my', 'our', 'their', 'this', 'that'}
        table_candidate = table_match.group(1)
        table_candidate = ' '.join([w for w in table_candidate.split() if w not in stopwords]).strip()
        # Remove trailing 'table' or 'data' if present
        for suffix in [' table', ' data']:
            if table_candidate.lower().endswith(suffix):
                table_candidate = table_candidate[: -len(suffix)].strip()
        schema_tables = ['Location', 'Product', 'Sales']
        matched_table = None
        for t in schema_tables:
            if table_candidate.lower() == t.lower():
                matched_table = t
                break
        if matched_table:
            try:
                df = pd.read_sql(f'SELECT * FROM "{matched_table}" LIMIT 10', engine)
                df = fix_duplicate_columns(df)
                st.session_state['last_result_df'] = df
                return f'SELECT * FROM "{matched_table}" LIMIT 10', df
            except Exception as e:
                st.write(f"[DEBUG] SQL Error: {e}")
                return None, f"SQL Error: {e}"
    # --- Enhanced follow-up logic ---
    if 'last_data_question' in st.session_state and is_followup_question(user_query):
        context = st.session_state['last_data_question']
        last_df = st.session_state.get('last_result_df')
        st.write(f"[DEBUG] Follow-up detected. Last context: {context}")
        if last_df is not None and 'Product Name' in last_df.columns:
            product_names = last_df['Product Name'].tolist()
            if product_names:
                in_clause = ', '.join([f'"{p}"' for p in product_names])
                sql = f'SELECT * FROM "Product" WHERE "Product Name" IN ({in_clause})'
                try:
                    df = pd.read_sql(sql, engine)
                    df = fix_duplicate_columns(df)
                    st.session_state['last_result_df'] = df
                    return sql, df
                except Exception as e:
                    st.write(f"[DEBUG] SQL Error (follow-up): {e}")
                    return sql, f"SQL Error: {e}"
        user_query = f"Previous question: {context}\nFollow-up: {user_query}"
    # Check for similar prompt in ChromaDB (semantic search)
    # (You can add semantic search logic here if needed)
    # Check for similar prompt in prompts.jsonl (string similarity)
    best_example, score = None, 0
    for ex in prompt_examples:
        s = SequenceMatcher(None, user_query.lower(), ex['prompt'].lower()).ratio()
        if s > score:
            score = s
            best_example = ex
    if best_example and score > 0.85:
        try:
            df = pd.read_sql(best_example['sql'], engine)
            df = fix_duplicate_columns(df)
            st.session_state['last_result_df'] = df
            return best_example['sql'], df
        except Exception as e:
            st.write(f"[DEBUG] SQL Error (string sim): {e}")
            return best_example['sql'], f"SQL Error: {e}"
    # Enhanced context-aware follow-up handling
    if 'last_data_question' in st.session_state and is_followup_question(user_query):
        st.write(f"[DEBUG] Enhanced follow-up detected")
        
        # Build enhanced context
        enhanced_context = get_enhanced_context_for_followup(user_query)
        if enhanced_context:
            user_query = f"{enhanced_context}\n\nCurrent follow-up question: {user_query}"
        else:
            # Fallback to simple context
            context = st.session_state['last_data_question']
            user_query = f"Previous question: {context}\nFollow-up: {user_query}"
    sql_generation_chain = LLMChain(llm=llm, prompt=sql_prompt)
    generated_sql = sql_generation_chain.invoke({"question": user_query, "schema": schema_info})
    if isinstance(generated_sql, dict):
        for key in ["sql", "text", "output", "result"]:
            if key in generated_sql and isinstance(generated_sql[key], str):
                generated_sql = generated_sql[key]
                break
        else:
            generated_sql = str(generated_sql)
    if isinstance(generated_sql, str) and not generated_sql.strip().lower().startswith("select"):
        for line in generated_sql.splitlines():
            if line.strip().lower().startswith("select"):
                generated_sql = line.strip()
                break
    if not (generated_sql.strip().lower().startswith("select")):
        fallback_query = f"Write a SQL query for: {user_query}"
        generated_sql = sql_generation_chain.invoke({"question": fallback_query, "schema": schema_info})
        if isinstance(generated_sql, dict):
            for key in ["sql", "text", "output", "result"]:
                if key in generated_sql and isinstance(generated_sql[key], str):
                    generated_sql = generated_sql[key]
                    break
            else:
                generated_sql = str(generated_sql)
        if isinstance(generated_sql, str) and not generated_sql.strip().lower().startswith("select"):
            for line in generated_sql.splitlines():
                if line.strip().lower().startswith("select"):
                    generated_sql = line.strip()
                    break
    if not (generated_sql.strip().lower().startswith("select")):
        st.write("[DEBUG] No valid SQL generated.")
        return None, "No SQL query could be generated for your request. Please rephrase or be more specific."
    try:
        df = pd.read_sql(generated_sql, engine)
        # Fix duplicate column names
        df = fix_duplicate_columns(df)
        st.session_state['last_data_question'] = user_query if not is_followup_question(user_query) else st.session_state.get('last_data_question', user_query)
        st.session_state['last_result_df'] = df
        # --- Add new prompt/SQL to prompts.jsonl ---
        with open(PROMPT_JSONL_PATH, "a", encoding="utf-8") as f:
            f.write(json.dumps({"prompt": user_query, "sql": generated_sql}) + "\n")
        return generated_sql, df
    except Exception as e:
        return generated_sql, f"SQL Error: {e}"

def create_data_visualization(df: pd.DataFrame, chart_key: str):
    """

    Create visualization options for DataFrame

    """
    if not VISUALIZATION_AVAILABLE or df.empty:
        return
    
    st.markdown("### πŸ“Š Data Visualization")
    
    # Create visualization options
    col1, col2, col3 = st.columns(3)
    
    with col1:
        show_bar = st.checkbox("πŸ“Š Bar Chart", key=f"bar_{chart_key}")
    with col2:
        show_pie = st.checkbox("πŸ₯§ Pie Chart", key=f"pie_{chart_key}")
    with col3:
        show_line = st.checkbox("πŸ“ˆ Line Chart", key=f"line_{chart_key}")
    
    if show_bar or show_pie or show_line:
        # Get column options for visualization
        numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
        text_cols = df.select_dtypes(include=['object', 'string']).columns.tolist()
        
        col_x, col_y = st.columns(2)
        
        with col_x:
            x_col = st.selectbox(
                "Select X-axis column:",
                options=df.columns.tolist(),
                key=f"x_col_{chart_key}"
            )
        
        with col_y:
            y_col = st.selectbox(
                "Select Y-axis column:",
                options=numeric_cols if numeric_cols else df.columns.tolist(),
                key=f"y_col_{chart_key}"
            )
        
        if x_col and y_col:
            try:
                # Create visualizations based on selection
                if show_bar:
                    st.subheader("πŸ“Š Bar Chart")
                    if len(df) > 20:
                        # For large datasets, aggregate or show top 20
                        plot_df = df.groupby(x_col)[y_col].sum().reset_index().head(20)
                    else:
                        plot_df = df
                    
                    fig_bar = px.bar(plot_df, x=x_col, y=y_col, 
                                   title=f"{y_col} by {x_col}")
                    st.plotly_chart(fig_bar, use_container_width=True)
                
                if show_pie:
                    st.subheader("πŸ₯§ Pie Chart")
                    # Aggregate data for pie chart
                    if len(df) > 10:
                        # Show top 10 categories for pie chart
                        pie_df = df.groupby(x_col)[y_col].sum().reset_index()
                        pie_df = pie_df.nlargest(10, y_col)
                    else:
                        pie_df = df.groupby(x_col)[y_col].sum().reset_index()
                    
                    fig_pie = px.pie(pie_df, values=y_col, names=x_col,
                                   title=f"{y_col} Distribution by {x_col}")
                    st.plotly_chart(fig_pie, use_container_width=True)
                
                if show_line:
                    st.subheader("πŸ“ˆ Line Chart")
                    fig_line = px.line(df, x=x_col, y=y_col,
                                     title=f"{y_col} Trend by {x_col}")
                    st.plotly_chart(fig_line, use_container_width=True)
                    
            except Exception as e:
                st.error(f"Visualization error: {e}")
                st.info("πŸ’‘ Tip: Make sure you select appropriate columns for the chart type")

# === Chat Input Section ===
st.markdown("---")

user_query = None
st.write("🎀 Voice recording functionality has been removed.")
user_query = st.chat_input("πŸ’¬ Ask about your business data or upload files to analyze...", key="main_chat_input")
    # If you want to convert speech to text, send this audio to an ASR model


# Check for pending voice query from session state
if 'pending_voice_query' in st.session_state and st.session_state['pending_voice_query']:
    user_query = st.session_state['pending_voice_query']
    # Clear the pending query to avoid reprocessing
    st.session_state['pending_voice_query'] = None

# Regular text input
text_query = st.chat_input("πŸ’¬ Ask about your business data or upload files to analyze...", key="secondary_chat_input")
if text_query:
    user_query = text_query

# When user submits a query
if user_query:
    generated_sql, df_results = run_query_chain(user_query)
    st.session_state['chat_history'].append({
        'role': 'user',
        'content': user_query,
        'sql': None,
        'df': None
    })
    st.session_state['chat_history'].append({
        'role': 'agent',
        'content': "Here is the generated SQL and results.",
        'sql': generated_sql,
        'df': df_results
    })

# Agent 1 Scope checkbox to show metadata information
agent1_scope = st.checkbox('Agent 1 Scope', help="Show database table information")

if agent1_scope:
    st.subheader("πŸ” Agent 1 Scope - Database Tables")
    
    # Database Schema Section - Just show table names
    schema_info = db.get_table_info()
    
    # Parse schema and display just table names
    tables = re.findall(r'CREATE TABLE \"([^\"]+)\" \((.*?)\)', schema_info, re.DOTALL)
    
    if tables:
        st.markdown("**Available Tables:**")
        table_names = [table_name for table_name, _ in tables]
        
        # Display table names in a simple format
        for i, table_name in enumerate(table_names, 1):
            st.write(f"{i}. **{table_name}**")
    else:
        st.write("No tables found in database")

# Show all prompts in ChromaDB checkbox
show_prompts = st.checkbox("Show Vector DB Prompts", help="Display all prompts stored in vector database")

if show_prompts:
    st.subheader("🧠 Vector Database Prompts")
    if chroma_collection is not None:
        try:
            chroma_data = chroma_collection.get()
            documents = chroma_data.get('documents', [])
            metadatas = chroma_data.get('metadatas', [])
            
            if documents:
                st.write(f"**Total prompts: {len(documents)}**")
                
                for i, doc in enumerate(documents):
                    metadata = metadatas[i] if i < len(metadatas) else {}
                    sql = metadata.get('sql', 'No SQL available')
                    
                    with st.expander(f"Prompt {i+1}: {doc[:50]}{'...' if len(doc) > 50 else ''}", expanded=False):
                        st.write("**Prompt:**")
                        st.write(doc)
                        st.write("**SQL:**")
                        st.code(sql, language='sql')
            else:
                st.info("No prompts found in vector database")
        except Exception as e:
            st.error(f"Error accessing vector DB: {e}")
    else:
        st.warning("Vector database not available")

# Agent 2 Scope checkbox (disabled - not used)
agent2_scope = st.checkbox('Agent 2 Scope', disabled=True, help="Agent 2 functionality - Currently not implemented")

if agent2_scope:
    st.info("🚧 Agent 2 is not yet implemented")

# Agent 3 Scope checkbox (disabled - not used)  
agent3_scope = st.checkbox('Agent 3 Scope', disabled=True, help="Agent 3 functionality - Currently not implemented")

if agent3_scope:
    st.info("🚧 Agent 3 is not yet implemented")

# Display chat history
for msg in st.session_state['chat_history']:
    if msg['role'] == 'user':
        with st.chat_message('user'):
            st.markdown(msg.get('content', ''))
    else:
        with st.chat_message('assistant'):
            sql = msg.get('sql')
            df = msg.get('df')
            response_content = msg.get('content', '')
            
            # If the agent's response is a SQL query, show it and the result
            if sql and isinstance(sql, str) and sql.strip().lower().startswith('select'):
                st.markdown(response_content)
                st.code(sql, language='sql')
                
                if isinstance(df, pd.DataFrame):
                    if df.empty:
                        st.info('No results found for this query.')
                    else:
                        # Fix duplicate column names
                        df = fix_duplicate_columns(df)
                        
                        # Add visualization options above the dataframe
                        if VISUALIZATION_AVAILABLE:
                            create_data_visualization(df, f"viz1_{hash(sql)}")
                        
                        st.subheader("πŸ“‹ Query Results")
                        st.dataframe(df)
                        
                        # --- Save as CSV and View buttons ---
                        col1, col2 = st.columns(2)
                        with col1:
                            csv_filename = "chat_agent_output.csv"
                            st.download_button(
                                label="Download as CSV",
                                data=df.to_csv(index=False).encode('utf-8'),
                                file_name=csv_filename,
                                mime='text/csv',
                                key=f"csv_{sql}"
                            )
                        with col2:
                            view_name = st.text_input(f"Enter view name to save as DB view (for this result):", key=f"view_{sql}")
                            if st.button("Save as View", key=f"btn_view_{sql}") and view_name:
                                safe_view_name = ''.join(c for c in view_name if c.isalnum() or c == '_')
                                create_view_sql = f'''CREATE VIEW IF NOT EXISTS "{safe_view_name}" AS {sql.strip().rstrip(';')};'''
                                try:
                                    engine.execute(create_view_sql)
                                    st.success(f"View '{safe_view_name}' created successfully!")
                                except Exception as ve:
                                    st.error(f"Error creating view: {ve}")
                elif isinstance(df, str) and df.startswith('SQL Error:'):
                    st.error(df)
            # If the agent's response is a plain message (not SQL), show as markdown only
            elif sql and not sql.strip().lower().startswith('select'):
                st.markdown(sql)
            else:
                st.markdown(response_content)
                if isinstance(df, pd.DataFrame):
                    if df.empty:
                        st.info('No results found for this query.')
                    else:
                        # Add visualization options above the dataframe
                        if VISUALIZATION_AVAILABLE:
                            create_data_visualization(df, f"viz2_{hash(msg.get('content', ''))}")
                        
                        st.subheader("πŸ“‹ Query Results")
                        st.dataframe(df)
                        
                        # --- Save as CSV and View buttons ---
                        col1, col2 = st.columns(2)
                        with col1:
                            csv_filename = "chat_agent_output.csv"
                            st.download_button(
                                label="Download as CSV",
                                data=df.to_csv(index=False).encode('utf-8'),
                                file_name=csv_filename,
                                mime='text/csv',
                                key=f"csv_{msg.get('content', '')}"
                            )
                        with col2:
                            view_name = st.text_input(f"Enter view name to save as DB view (for this result):", key=f"view_{msg.get('content', '')}")
                            if st.button("Save as View", key=f"btn_view_{msg.get('content', '')}") and view_name:
                                safe_view_name = ''.join(c for c in view_name if c.isalnum() or c == '_')
                                # Use the last SQL if available
                                sql_to_use = sql if sql else ""
                                create_view_sql = f'''CREATE VIEW IF NOT EXISTS "{safe_view_name}" AS {sql_to_use.strip().rstrip(';')};'''
                                try:
                                    engine.execute(create_view_sql)
                                    st.success(f"View '{safe_view_name}' created successfully!")
                                except Exception as ve:
                                    st.error(f"Error creating view: {ve}")
                elif isinstance(df, str) and df.startswith('SQL Error:'):
                    st.error(df)

# === Prompt Tuning Agent Section ===
from langchain.prompts import PromptTemplate

# Helper: Suggest a better prompt using LLM
prompt_tuning_template = PromptTemplate(
    input_variables=["draft", "schema"],
    template="""

    You are an expert SQL query writer and prompt improvement assistant for a SQLite database. Given the following database schema:

    {schema}



    The user has written this draft prompt/question:

    "{draft}"



    Your job is to:

    - Suggest a clearer, more specific, and effective prompt that will help generate a correct SQL query for SQLite.

    - Use the exact table and column names as shown in the schema (including case, spaces, and special characters).

    - If the draft is already good, return it as is. Otherwise, rewrite it to be more explicit, mentioning relevant tables/columns if possible.

    - If the user's intent requires columns from multiple tables, make sure the improved prompt is clear about the relationship (e.g., join keys) and the aggregation or ranking needed.

    - Only return the improved prompt, no explanations.

    

    Example:

    Draft: top 3 product with highest revenue

    Improved: Show the top 3 products by total revenue, using the "Product Name" from the "Product" table and summing "Revenue (USD)" from the "Sales" table. Join "Product" and "Sales" on "Product ID". Order by total revenue descending and limit to 3 results.

    """
)

def suggest_better_prompt(draft, schema_info):
    chain = LLMChain(llm=llm, prompt=prompt_tuning_template)
    improved = chain.invoke({"draft": draft, "schema": schema_info})
    # Extract string if dict
    if isinstance(improved, dict):
        for key in ["text", "output", "result"]:
            if key in improved and isinstance(improved[key], str):
                improved = improved[key]
                break
        else:
            improved = str(improved)
    return improved.strip()

def generate_sql_for_prompt(prompt, schema_info):
    # --- Patch: Always refer to schema before generating SQL ---
    # If prompt does not mention schema, prepend schema info for LLM context
    schema_hint = f"Refer to this schema for table and column names:\n{schema_info}\n"
    prompt_with_schema = f"{schema_hint}{prompt}" if 'CREATE TABLE' not in prompt else prompt
    sql_chain = LLMChain(llm=llm, prompt=sql_prompt)
    sql = sql_chain.invoke({"question": prompt_with_schema, "schema": schema_info})
    if isinstance(sql, dict):
        for key in ["sql", "text", "output", "result"]:
            if key in sql and isinstance(sql[key], str):
                sql = sql[key]
                break
        else:
            sql = str(sql)
    # Extract SQL if explanation is included
    if isinstance(sql, str) and not sql.strip().lower().startswith("select"):
        for line in sql.splitlines():
            if line.strip().lower().startswith("select"):
                sql = line.strip()
                break
    # --- Patch: Auto-quote all table and column names for SQLite ---
    def auto_quote_sql(sql_str, schema_info):
        import re
        # Find all table and column names from schema
        tables = re.findall(r'CREATE TABLE "([^"]+)" \((.*?)\)', schema_info, re.DOTALL)
        table_names = [t[0] for t in tables]
        col_names = []
        for _, cols in tables:
            col_names += re.findall(r'"([^"]+)"', cols)
        # Quote table names not already quoted
        for t in table_names:
            # Only quote if not already quoted
            sql_str = re.sub(rf'(?<!["])\b{re.escape(t)}\b(?!["])', f'"{t}"', sql_str)
        # Quote column names not already quoted
        for c in col_names:
            # Only quote if not already quoted and not part of a string literal
            sql_str = re.sub(rf'(?<![\.\"])(?<!["])\b{re.escape(c)}\b(?!["])', f'"{c}"', sql_str)
        return sql_str
    sql = auto_quote_sql(sql, schema_info)
    return sql.strip()

def save_prompt_sql_pair(prompt, sql):
    # Save to prompts.jsonl
    with open(PROMPT_JSONL_PATH, "a", encoding="utf-8") as f:
        f.write(json.dumps({"prompt": prompt, "sql": sql}) + "\n")
    
    # Save to ChromaDB (if available)
    if chroma_collection is not None and embedding_model is not None:
        try:
            query_emb = embedding_model.encode([prompt], convert_to_numpy=True)
            existing_ids = chroma_collection.get().get('ids', [])
            next_id = str(len(existing_ids) + 1)
            
            chroma_collection.add(
                embeddings=query_emb,
                documents=[prompt],
                metadatas=[{"sql": sql}],
                ids=[next_id]
            )
        except Exception as e:
            # st.warning(f"Could not save to vector DB: {e}")  # Hidden for cleaner UI
            pass
    else:
        # st.info("Vector DB not available - saved to local file only")  # Hidden for cleaner UI
        pass

# === Streamlit Tabs: Main Agent and Prompt Tuning Agent ===


# === Multi-Agent Integration ===
from langchain.agents import initialize_agent, AgentType, Tool

# --- SQL Query Tool ---
def run_sql_query(sql: str) -> str:
    # Always limit result size for LLM safety
    import re
    sql_lc = sql.lower()
    if sql_lc.startswith("select") and "limit" not in sql_lc:
        # Add LIMIT 20 to queries without a limit
        if ";" in sql:
            sql = re.sub(r';\s*$', '', sql)
        sql += " LIMIT 20"
    try:
        df = pd.read_sql(sql, engine)
        df = fix_duplicate_columns(df)
        return df.to_csv(index=False)
    except Exception as e:
        return f"SQL Error: {e}"

sql_query_tool = Tool(
    name="run_sql_query",
    func=run_sql_query,
    description="Execute a SQL query on the business database and return results as CSV."
)

# --- SQL Generation Tool ---
def generate_sql_tool(question: str) -> str:
    sql = generate_sql_for_prompt(question, db.get_table_info())
    return sql

sql_gen_tool = Tool(
    name="generate_sql",
    func=generate_sql_tool,
    description="Convert a natural language question to an optimized SQL query for the business database."
)

# --- Document Q&A Tool (Enhanced with Vector DB) ---
def ask_document_tool(question: str) -> str:
    """Answer questions using documents stored in vector database"""
    try:
        if chroma_collection is None or embedding_model is None:
            return "Vector database not available. Please check your setup."
        
        # Get question embedding
        question_embedding = embedding_model.encode([question], convert_to_numpy=True)
        
        # Search vector database for relevant document chunks
        try:
            results = chroma_collection.query(
                query_embeddings=question_embedding.tolist(),
                n_results=5,  # Get top 5 most relevant chunks
                include=['documents', 'metadatas', 'distances']
            )
            
            if not results['documents'] or not results['documents'][0]:
                return "No relevant documents found. Please upload some documents first."
            
            # Process results to build context
            contexts = []
            sources = []
            
            for i, (doc, metadata, distance) in enumerate(zip(
                results['documents'][0], 
                results['metadatas'][0], 
                results['distances'][0]
            )):
                if distance < 1.5:  # Only include reasonably relevant chunks
                    file_type = metadata.get('file_type', 'unknown')
                    filename = metadata.get('filename', 'unknown')
                    chunk_type = metadata.get('chunk_type', 'text_chunk')
                    
                    if chunk_type == 'data_summary':
                        contexts.append(f"[Data from {filename}]:\n{doc}")
                    else:
                        contexts.append(f"[Text from {filename}]:\n{doc}")
                    
                    sources.append(f"{filename} ({file_type})")
            
            if not contexts:
                return "No sufficiently relevant content found for your question."
            
            # Build comprehensive prompt
            context_text = "\n\n".join(contexts[:3])  # Use top 3 contexts
            unique_sources = list(set(sources[:3]))
            
            # Different prompts for data vs text questions
            if any('data_summary' in str(meta.get('chunk_type', '')) for meta in results['metadatas'][0][:3]):
                # Data-focused prompt
                prompt = f"""Based on the following data sources, answer the question:



Context from uploaded files:

{context_text}



Question: {question}



Instructions:

- Provide a clear, data-driven answer

- Reference specific data points when relevant

- If the question requires analysis not directly shown in the context, indicate what additional analysis would be needed

- Mention which files the answer is based on



Answer:"""
            else:
                # Text-focused prompt
                prompt = f"""Based on the following document content, answer the question:



Context from uploaded documents:

{context_text}



Question: {question}



Instructions:

- Provide a comprehensive answer based on the context

- Quote relevant parts when helpful

- If the answer is not fully contained in the context, indicate this clearly

- Mention which documents the answer is based on



Answer:"""
            
            # Get LLM response
            answer = llm.invoke(prompt)
            answer_text = extract_llm_content(answer)
            
            # Add source information
            source_info = f"\n\nπŸ“ Sources: {', '.join(unique_sources)}"
            return answer_text + source_info
            
        except Exception as e:
            st.error(f"Error querying vector database: {str(e)}")
            return f"Error searching documents: {str(e)}"
            
    except Exception as e:
        return f"Error in document query: {str(e)}"

document_qa_tool = Tool(
    name="ask_documents",
    func=ask_document_tool,
    description="Answer questions based on uploaded documents (PDF, CSV, Excel, JSON) using semantic search across the vector database."
)

# --- Data Analysis Tool for CSV/Excel ---
def analyze_data_tool(question: str) -> str:
    """Analyze uploaded CSV/Excel data using pandas operations"""
    try:
        uploaded_dfs = st.session_state.get('uploaded_dfs', {})
        if not uploaded_dfs:
            return "No CSV or Excel files uploaded for analysis."
        
        # For now, use the first uploaded DataFrame
        filename = list(uploaded_dfs.keys())[0]
        df = uploaded_dfs[filename]
        
        # Create a prompt to generate pandas code
        columns_info = []
        for col in df.columns:
            dtype = str(df[col].dtype)
            sample_vals = df[col].dropna().head(3).tolist()
            columns_info.append(f"- {col} ({dtype}): sample values {sample_vals}")
        
        columns_str = "\n".join(columns_info)
        
        analysis_prompt = f"""Given a pandas DataFrame called 'df' with the following structure:



Filename: {filename}

Shape: {df.shape}

Columns:

{columns_str}



Question: {question}



Generate Python code using pandas to answer this question. The code should:

1. Use the variable 'df' for the DataFrame

2. Be safe to execute (no file operations, imports, etc.)

3. Return a result that answers the question

4. Handle potential errors gracefully



Provide only the Python code, no explanations:"""

        # Get code from LLM
        code_response = llm.invoke(analysis_prompt)
        code = extract_llm_content(code_response)
        
        # Clean up the code
        code = code.strip()
        if code.startswith('```python'):
            code = code[9:]
        if code.startswith('```'):
            code = code[3:]
        if code.endswith('```'):
            code = code[:-3]
        code = code.strip()
        
        # Execute the code safely
        try:
            # Create a safe execution environment
            safe_globals = {
                'df': df,
                'pd': pd,
                'np': __import__('numpy'),
                'len': len,
                'str': str,
                'int': int,
                'float': float,
                'sum': sum,
                'max': max,
                'min': min,
                'round': round
            }
            
            # Execute the code
            local_vars = {}
            exec(code, safe_globals, local_vars)
            
            # Try to get the result
            if 'result' in local_vars:
                result = local_vars['result']
            else:
                # If no explicit result variable, evaluate the last expression
                lines = code.strip().split('\n')
                last_line = lines[-1].strip()
                if not (last_line.startswith('print') or last_line.startswith('df')):
                    result = eval(last_line, safe_globals, local_vars)
                else:
                    result = "Code executed successfully, but no result to display."
            
            # Format the result
            if hasattr(result, 'to_string'):  # DataFrame or Series
                if len(str(result)) > 2000:  # Truncate if too long
                    result_str = str(result)[:2000] + "...\n(Result truncated)"
                else:
                    result_str = str(result)
            else:
                result_str = str(result)
            
            return f"Analysis of {filename}:\n\n{result_str}\n\nCode used:\n```python\n{code}\n```"
            
        except Exception as e:
            return f"Error executing analysis: {str(e)}\n\nGenerated code:\n```python\n{code}\n```"
            
    except Exception as e:
        return f"Error in data analysis: {str(e)}"

data_analysis_tool = Tool(
    name="analyze_data",
    func=analyze_data_tool,
    description="Analyze uploaded CSV/Excel data using pandas operations. Can perform calculations, filtering, grouping, and statistical analysis."
)

# --- Initialize Multi-Agent ---

# --- Enhanced Multi-Agent with Context-Aware Reasoning ---

from langchain.memory import ConversationBufferMemory
multi_tools = [sql_query_tool, sql_gen_tool, document_qa_tool, data_analysis_tool]
conversation_memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True
)
multi_agent = initialize_agent(
    tools=multi_tools,
    llm=llm,
    agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
    memory=conversation_memory,
    verbose=True
)

# Helper: Analyze sales drop for a product using previous DataFrame
def analyze_sales_drop(product_name=None, product_id=None):
    # Use last DataFrame and question from session state
    last_df = st.session_state.get('last_result_df')
    last_question = st.session_state.get('last_data_question', '')
    if last_df is None:
        return "No previous data available for analysis."
    # Try to detect sales drop by comparing sales over time
    if product_name and 'Product Name' in last_df.columns:
        df_product = last_df[last_df['Product Name'] == product_name]
    elif product_id and 'Product ID' in last_df.columns:
        df_product = last_df[last_df['Product ID'] == product_id]
    else:
        df_product = last_df
    # If sales data available
    if 'Revenue (USD)' in df_product.columns and 'Month' in df_product.columns:
        trend = df_product.groupby('Month')['Revenue (USD)'].sum().sort_index()
        if len(trend) > 1:
            diffs = trend.diff().fillna(0)
            drop_months = [m for m, d in zip(trend.index, diffs) if d < 0]
            if drop_months:
                return f"Sales dropped in months: {', '.join(map(str, drop_months))}. Trend: {trend.to_dict()}"
            else:
                return f"No sales drop detected. Trend: {trend.to_dict()}"
        else:
            return "Not enough data to detect sales trend."
    return "Sales data not available for this product."

tab1, tab2, tab3, tab4 = st.tabs(["SQL Chat Agent", "Prompt Tuning Agent", "PDF Q&A Agent", "Multi-Agent Q&A"])


# --- PDF Q&A Agent Tab ---
with tab3:
    st.markdown("### PDF Q&A Agent")
    st.write("Ask questions about the uploaded PDF. The agent will answer using semantic search and LLM.")
    pdf_files = list(st.session_state.get('uploaded_texts', {}).keys())
    if not pdf_files:
        st.warning("No PDF uploaded. Please upload a PDF in the sidebar.")
    else:
        selected_pdf = st.selectbox("Select PDF to query:", pdf_files)
        pdf_text = st.session_state['uploaded_texts'][selected_pdf]
        user_pdf_question = st.text_input("Ask a question about the PDF:")
        if user_pdf_question:
            def chunk_text(text, chunk_size=800, overlap=100):
                chunks = []
                start = 0
                while start < len(text):
                    end = min(start + chunk_size, len(text))
                    chunk = text[start:end]
                    chunks.append(chunk)
                    start += chunk_size - overlap
                return chunks
            pdf_chunks = chunk_text(pdf_text)
            chunk_embeddings = embedding_model.encode(pdf_chunks, convert_to_numpy=True)
            from numpy import dot
            from numpy.linalg import norm
            q_emb = embedding_model.encode([user_pdf_question], convert_to_numpy=True)[0]
            sims = [dot(q_emb, chunk_emb)/(norm(q_emb)*norm(chunk_emb)) for chunk_emb in chunk_embeddings]
            best_idx = int(max(range(len(sims)), key=lambda i: sims[i]))
            best_chunk = pdf_chunks[best_idx]
            context_prompt = f"Context from PDF:\n{best_chunk}\n\nQuestion: {user_pdf_question}\nAnswer:"
            answer = llm.invoke(context_prompt)
            answer_text = extract_llm_content(answer)
                
            st.markdown("**PDF Q&A Response:**")
            st.write(answer_text)

with tab4:
    st.markdown("### Multi-Agent Q&A")
    st.write("Ask any complex question. The agent will use SQL, prompt tuning, and PDF Q&A tools as needed.")
    user_multi_question = st.text_input("Ask a question across tools (SQL + PDF + Prompt):")
    # multi_agent is already initialized above
    if user_multi_question:
        # Context-aware follow-up detection
        followup_keywords = ["why sales got reduce", "why did sales drop", "reason for sales drop", "sales decrease"]
        matched = any(k in user_multi_question.lower() for k in followup_keywords)
        product_name = None
        product_id = None
        import re
        name_match = re.search(r'product name ([\w\s]+)', user_multi_question.lower())
        id_match = re.search(r'productid (\d+)', user_multi_question.lower())
        if name_match:
            product_name = name_match.group(1).strip()
        if id_match:
            product_id = id_match.group(1).strip()
        if matched:
            analysis = analyze_sales_drop(product_name=product_name, product_id=product_id)
            st.markdown(f"**Sales Drop Analysis:**\n{analysis}")
            st.session_state['chat_history'].append({'role': 'user', 'content': user_multi_question})
            st.session_state['chat_history'].append({'role': 'agent', 'content': analysis})
        else:
            response = multi_agent.run(user_multi_question)
            st.markdown("**Agent Response:**")
            st.write(response)
            st.session_state['chat_history'].append({'role': 'user', 'content': user_multi_question})
            st.session_state['chat_history'].append({'role': 'agent', 'content': response})