File size: 58,994 Bytes
2ae5792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import os
import gradio as gr
from huggingface_hub import InferenceClient
import torch
import re
import warnings
import time
import json
import asyncio # Import asyncio for asynchronous operations
# Removed specific transformers imports that might not be strictly necessary for InferenceClient
# from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig, BitsAndBytesConfig
from sentence_transformers import SentenceTransformer, util, CrossEncoder
import gspread
# Removed google.auth.default as service account from dict is used
# from google.auth import default
from tqdm import tqdm
from ddgs import DDGS
import spacy
from datetime import date, timedelta, datetime
from dateutil.relativedelta import relativedelta # Corrected import
import traceback
import base64
import dateparser
from dateparser.search import search_dates
import pytz
# Removed userdata as secrets are accessed via environment variables in Spaces
# from google.colab import userdata
import os # Ensure os is imported for environment variables
from datasets import Dataset, DatasetDict, concatenate_datasets, load_dataset
from huggingface_hub import HfApi, login # Import login for initial auth

import faiss
import numpy as np
import pickle


# --- SQL Logging Imports and Connection Placeholder (Removed for HF Space) ---
# Removed SQL related code as per user's request to use HF Datasets
# ---

# Define the dataset name (replace with your actual Hugging Face username and desired dataset name)
# Ensure this dataset is set to private on the Hugging Face Hub
dataset_name = "Futuresony/Logs_Conversation" # REPLACE WITH YOUR ACTUAL DATASET NAME

# Global variable to store the dataset
conversation_dataset = None

# Initialize HfApi for pushing - Use token from environment variable
# No need to re-initialize HfApi with token here as login handles it
# hf_api = HfApi(token=HF_TOKEN)


# Suppress warnings
warnings.filterwarnings("ignore", category=UserWarning)

# Define global variables and load secrets from environment variables for HF Spaces
# HF_TOKEN is now accessed via os.environ or handled by huggingface_hub login
HF_TOKEN = os.getenv("HF_TOKEN") # Access HF_TOKEN from environment variable
# Add a print statement to check if HF_TOKEN is loaded
print(f"HF_TOKEN loaded: {'Yes' if HF_TOKEN else 'No'}")

SHEET_ID = "19ipxC2vHYhpXCefpxpIkpeYdI43a1Ku2kYwecgUULIw"
# GOOGLE_BASE64_CREDENTIALS is now accessed via os.environ
GOOGLE_BASE64_CREDENTIALS = os.getenv("GOOGLE_BASE64_CREDENTIALS")


# SECRET_API_KEY is now accessed via os.environ
SECRET_API_KEY = os.getenv("APP_API_KEY")
# Add a print statement to check if SECRET_API_KEY is loaded
print(f"SECRET_API_KEY loaded: {'Yes' if SECRET_API_KEY else 'No'}")

if not SECRET_API_KEY:
    print("Warning: APP_API_KEY secret not set. API key validation will fail.")
elif not SECRET_API_KEY.startswith("fs_"):
    print("Warning: APP_API_KEY secret does not start with 'fs_'. Please check your secret.")

# Authenticate with Hugging Face Hub using the token from environment variable
try:
    print("Attempting to authenticate with Hugging Face Hub...")
    # login() automatically looks for HF_TOKEN in environment variables
    login(add_to_git_credential=True)
    print("Hugging Face Hub authentication successful.")
except Exception as e:
    print(f"Hugging Face Hub authentication failed: {e}")
    print(traceback.format_exc())


# Initialize InferenceClient for primary model (LLaMA-3.3-70B-Instruct)
primary_client = InferenceClient("meta-llama/Llama-3.3-70B-Instruct", token=HF_TOKEN)
print("Primary model (LLaMA-3.3-70B-Instruct) client initialized.")

# Initialize InferenceClient for fallback model (Gemma-2-9b-it)
fallback_client = InferenceClient("google/gemma-2-9b-it", token=HF_TOKEN)
print("Fallback model (Gemma-2-9b-it) client initialized.")


# Load spacy model for sentence splitting
nlp = None
try:
    nlp = spacy.load("en_core_web_sm")
    print("SpaCy model 'en_core_web_sm' loaded.")
except OSError:
    print("SpaCy model 'en_core_web_sm' not found. Downloading...")
    try:
        import subprocess
        subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"], check=True)
        nlp = spacy.load("en_core_web_sm")
        print("SpaCy model 'en_core_web_sm' downloaded and loaded.")
    except Exception as e:
        print(f"Failed to download or load SpaCy model: {e}")

# Load SentenceTransformer for RAG/business info retrieval and semantic detection
embedder = None
try:
    print("Attempting to load Sentence Transformer (sentence-transformers/paraphrase-MiniLM-L6-v2)...")
    embedder = SentenceTransformer("sentence-transformers/paraphrase-MiniLM-L6-v2")
    print("Sentence Transformer loaded.")
except Exception as e:
     print(f"Error loading Sentence Transformer: {e}")

# Load a Cross-Encoder model for re-ranking retrieved documents
reranker = None
try:
    print("Attempting to load Cross-Encoder Reranker (cross-encoder/ms-marco-MiniLM-L6-v2)...")
    reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L6-v2')
    print("Cross-Encoder Reranker loaded.")
except Exception as e:
    print(f"Error loading Cross-Encoder Reranker: {e}")
    print("Please ensure the model identifier 'cross-encoder/ms-marco-MiniLM-L6-v2' is correct and accessible on Hugging Face Hub.")
    print(traceback.format_exc())
    reranker = None

# Google Sheets Authentication
gc = None
def authenticate_google_sheets():
    """Authenticates with Google Sheets using base64 encoded credentials."""
    global gc
    print("Authenticating Google Account...")
    if not GOOGLE_BASE64_CREDENTIALS:
        print("Error: GOOGLE_BASE64_CREDENTIALS secret not found.")
        return False
    try:
        credentials_json = base64.b64decode(GOOGLE_BASE64_CREDENTIALS).decode('utf-8')
        credentials = json.loads(credentials_json)
        gc = gspread.service_account_from_dict(credentials)
        print("Google Sheets authentication successful via service account.")
        return True
    except Exception as e:
        print(f"Google Sheets authentication failed: {e}")
        print(traceback.format_exc())
        print("Please ensure your GOOGLE_BASE64_CREDENTIALS secret is correctly set and contains valid service account credentials.")
        return False

# Google Sheets Data Loading and Embedding for RAG
data = []
descriptions_for_embedding = []
embeddings = torch.tensor([]) # This will store embeddings for RAG data
business_info_available = False

def load_business_info():
    """Loads business information from Google Sheet and creates embeddings."""
    global data, descriptions_for_embedding, embeddings, business_info_available
    business_info_available = False
    if gc is None:
        print("Skipping Google Sheet loading: Google Sheets client not authenticated.")
        return
    if not SHEET_ID:
         print("Error: SHEET_ID not set.")
         return
    try:
        sheet = gc.open_by_key(SHEET_ID).sheet1
        print(f"Successfully opened Google Sheet with ID: {SHEET_ID}")
        data_records = sheet.get_all_records()
        if not data_records:
            print(f"Warning: No data records found in Google Sheet with ID: {SHEET_ID}")
            data = []
            descriptions_for_embedding = []
        else:
            filtered_data = [row for row in data_records if row.get('Service') and row.get('Description')]
            if not filtered_data:
                print("Warning: Filtered data is empty after checking for 'Service' and 'Description'.")
                data = []
                descriptions_for_embedding = []
            else:
                data = filtered_data
                descriptions_for_embedding = [f"Service: {row['Service']}. Description: {row['Description']}" for row in data]
                if descriptions_for_embedding and embedder is not None:
                    print("Encoding descriptions for RAG...")
                    try:
                        embeddings = embedder.encode(descriptions_for_embedding, convert_to_tensor=True)
                        print("Encoding complete. RAG embeddings created.")
                        business_info_available = True
                    except Exception as e:
                        print(f"Error during description encoding for RAG: {e}")
                        embeddings = torch.tensor([])
                        business_info_available = False
                else:
                    print("Skipping encoding descriptions for RAG: No descriptions found or embedder not available.")
                    embeddings = torch.tensor([])
                    business_info_available = False
        print(f"Loaded {len(descriptions_for_embedding)} entries from Google Sheet for embedding/RAG.")
        if not business_info_available:
            print("Business information retrieval (RAG) is NOT available.")
        else:
            print("Business information retrieval (RAG) is available.")
    except gspread.exceptions.SpreadsheetNotFound:
        print(f"Error: Google Sheet with ID '{SHEET_ID}' not found.")
        print("Please check the SHEET_ID and ensure your authenticated Google Account has access to this sheet.")
        business_info_available = False
    except Exception as e:
        print(f"An error occurred while accessing the Google Sheet: {e}")
        print(traceback.format_exc())
        business_info_available = False

# Business Info Retrieval (RAG) function - Reusing the existing one
def retrieve_business_info(query: str, top_n: int = 3) -> list:
    """
    Retrieves relevant business information from loaded data based on a query.
    """
    global data, embeddings
    if not business_info_available or embedder is None or not descriptions_for_embedding or not data or embeddings.numel() == 0:
        print("Business information retrieval is not available or RAG data is empty.")
        return []
    try:
        query_embedding = embedder.encode(query, convert_to_tensor=True)
        # Ensure both tensors are on the same device for cosine similarity calculation
        if query_embedding.device != embeddings.device:
             query_embedding = query_embedding.to(embeddings.device)

        cosine_scores = util.cos_sim(query_embedding, embeddings)[0]
        top_results_indices = torch.topk(cosine_scores, k=min(top_n, len(data)))[1].tolist()
        top_results = [data[i] for i in top_results_indices]
        if reranker is not None and top_results:
            print("Re-ranking top results...")
            rerank_pairs = [(query, descriptions_for_embedding[i]) for i in top_results_indices]
            rerank_scores = reranker.predict(rerank_pairs)
            reranked_indices = sorted(range(len(rerank_scores)), key=lambda i: rerank_scores[i], reverse=True)
            reranked_results = [top_results[i] for i in reranked_indices]
            print("Re-ranking complete.")
            return reranked_results
        else:
            return top_results
    except Exception as e:
        print(f"Error during business information retrieval: {e}")
        print(traceback.format_exc())
        return []


# Function to perform DuckDuckGo Search and return results with URLs
async def perform_duckduckgo_search(query: str, max_results: int = 5):
    """
    Performs a search using DuckDuckGo asynchronously and returns a list of dictionaries.
    """
    print(f"Executing Tool: perform_duckduckgo_search with query='{query}')")
    search_results_list = []
    try:
        await asyncio.sleep(1) # Simulate async operation
        with DDGS() as ddgs:
            search_query = query.strip()
            if not search_query or len(search_query.split()) < 2:
                 print(f"Skipping search for short query: '{search_query}'")
                 return []
            print(f"Sending search query to DuckDuckGo: '{search_query}'")
            # DDGS text method is not inherently async, but we can run it in a thread
            # to make the chat function awaitable.
            loop = asyncio.get_event_loop()
            results_generator = await loop.run_in_executor(None, lambda: list(ddgs.text(search_query, max_results=max_results)))
            results_found = False
            for r in results_generator:
                search_results_list.append(r)
                results_found = True
            print(f"Raw results from DuckDuckGo: {search_results_list}")
            if not results_found and max_results > 0:
                 print(f"DuckDuckGo search for '{search_query}' returned no results.")
            elif results_found:
                 print(f"DuckDuckGo search for '{search_query}' completed. Found {len(search_results_list)} results.")
    except Exception as e:
        print(f"Error during Duckduckgo search for '{search_query if 'search_query' in locals() else query}': {e}")
        print(traceback.format_exc())
        return f"An error occurred during web search: {e}" # Return error message on failure
    return search_results_list

# Define the new semantic date/time detection and calculation function using dateparser
async def perform_date_calculation(query: str) -> str or None:
    """
    Analyzes query for date/time information using dateparser asynchronously.
    """
    print(f"Executing Tool: perform_date_calculation with query='{query}') using dateparser.search_dates")
    try:
        await asyncio.sleep(0.1) # Simulate async operation
        eafrica_tz = pytz.timezone('Africa/Dar_es_Salaam')
        now = datetime.now(eafrica_tz)
    except pytz.UnknownTimeZoneError:
        print("Error: Unknown timezone 'Africa/Dar_es_Salaam'. Using default system time.")
        now = datetime.now()
    try:
        # dateparser.search_dates is not inherently async, run in thread
        loop = asyncio.get_event_loop()
        found = await loop.run_in_executor(None, lambda: search_dates(
            query,
            settings={
                "PREFER_DATES_FROM": "future",
                "RELATIVE_BASE": now
            },
            languages=['sw', 'en']
        ))

        if not found:
            print("dateparser.search_dates could not parse any date/time.")
            return None
        text_snippet, parsed = found[0]
        print(f"dateparser.search_dates found: text='{text_snippet}', parsed='{parsed}'")
        is_swahili = any(swahili_phrase in query.lower() for swahili_phrase in ['tarehe', 'siku', 'saa', 'muda', 'leo', 'kesho', 'jana', 'ngapi', 'gani', 'mwezi', 'mwaka', 'habari', 'mambo', 'shikamoo', 'karibu', 'asante'])

        if is_swahili:
            query_lower = query.lower().strip()
            if query_lower in ['habari', 'mambo', 'habari gani']:
                 return "Nzuri! Habari zako?"
            elif query_lower in ['shikamoo']:
                 return "Marahaba!"
            elif query_lower in ['asante']:
                 return "Karibu!"
            elif query_lower in ['karibu']:
                 return "Asante!"

        if now.tzinfo is not None and parsed.tzinfo is None:
            parsed = now.tzinfo.localize(parsed)
        elif now.tzinfo is None and parsed.tzinfo is not None:
             parsed = parsed.replace(tzinfo=None)

        if parsed.date() == now.date():
             if abs((parsed - now).total_seconds()) < 60 or parsed.time() == datetime.min.time():
                 print("Query parsed to today's date and time is close to 'now' or midnight, returning current time/date.")
                 if is_swahili:
                     return f"Kwa saa za Afrika Mashariki (Tanzania), tarehe ya leo ni {now.strftime('%A, %d %B %Y')} na saa ni {now.strftime('%H:%M:%S')}."
                 else:
                     return f"In East Africa (Tanzania), the current date is {now.strftime('%A, %d %B %Y')} and the time is {now.strftime('%H:%M:%S')}."
             else:
                  print(f"Query parsed to a specific time today: {parsed.strftime('%H:%M:%S')}")
                  if is_swahili:
                       return f"Hiyo inafanyika leo, {parsed.strftime('%A, %d %B %Y')}, saa {parsed.strftime('%H:%M:%S')} saa za Afrika Mashariki."
                  else:
                       return f"That falls on today, {parsed.strftime('%A, %d %B %Y')}, at {parsed.strftime('%H:%M:%S')} East Africa Time."
        else:
            print(f"Query parsed to a specific date: {parsed.strftime('%A, %d %B %Y')} at {parsed.strftime('%H:%M:%S')}")
            time_str = parsed.strftime('%H:%M:%S')
            date_str = parsed.strftime('%A, %d %B %Y')
            if parsed.tzinfo:
                 tz_name = parsed.tzinfo.tzname(parsed) or 'UTC'
                 if is_swahili:
                     return f"Hiyo inafanyika tarehe {date_str} saa {time_str} {tz_name}."
                 else:
                      return f"That falls on {date_str} at {time_str} {tz_name}."
            else:
                 if is_swahili:
                      return f"Hiyo inafanyika tarehe {date_str} saa {time_str}."
                 else:
                      return f"That falls on {date_str} at {time_str}."
    except Exception as e:
        print(f"Error during dateparser.search_dates execution: {e}")
        print(traceback.format_exc())
        return f"An error occurred while parsing date/time: {e}" # Return error message on failure

# Function to determine if a query requires a tool or can be answered directly
# Modified to include complexity check for routing to primary vs fallback
def determine_tool_usage(query: str) -> tuple[str, str]:
    """
    Analyzes the query to determine if a specific tool is needed and its complexity.
    Returns a tuple: (tool_name, complexity_level)
    Complexity levels: 'simple' (fallback), 'complex' (primary)
    """
    query_lower = query.lower()

    swahili_conversational_phrases = ['habari', 'mambo', 'shikamoo', 'karibu', 'asante', 'habari gani']
    if any(swahili_phrase in query_lower for swahili_phrase in swahili_conversational_phrases):
        print(f"Detected a Swahili conversational phrase: '{query}'. Using 'date_calculation' tool and 'simple' complexity.")
        return "date_calculation", "simple" # Simple conversational queries routed to fallback

    # Check for business info retrieval first
    if business_info_available:
         # Use a simple LLM call to check if the query is business-related
         messages_business_check = [{"role": "user", "content": f"Does the following query ask about a specific person, service, offering, or description that is likely to be found *only* within a specific business's internal knowledge base, and not general knowledge? For example, questions about 'Salum' or 'Jackson Kisanga' are likely business-related, while questions about 'the current president of the USA' or 'who won the Ballon d'Or' are general knowledge. Answer only 'yes' or 'no'. Query: {query}"}]
         try:
             business_check_response = primary_client.chat_completion( # Use primary client for this check
                 messages=messages_business_check,
                 max_tokens=10,
                 temperature=0.1
             ).choices[0].message.content.strip().lower()
             if business_check_response == "yes":
                 print(f"Detected as specific business info query based on LLM check: '{query}'. Using 'business_info_retrieval' tool and 'simple' complexity.")
                 # Business info RAG is handled by the fallback model
                 return "business_info_retrieval", "simple"
             else:
                 print(f"LLM check indicates not a specific business info query: '{query}')")
         except Exception as e:
             print(f"Error during LLM call for business info check for query '{query}': {e}")
             print(traceback.format_exc())
             print(f"Proceeding without business info check for query '{query}' due to error.")

    # Check for date/time calculation
    # We don't pre-calculate here, just check if the tool might be relevant
    date_time_keywords = ['date', 'time', 'when', 'what day', 'what time', 'leo', 'kesho', 'jana', 'muda', 'saa', 'tarehe', 'siku']
    if any(keyword in query_lower for keyword in date_time_keywords):
         print(f"Detected date/time keywords in query: '{query}'. Suggesting 'date_calculation' tool.")
         # We still need to determine complexity for the final generation
         messages_complexity = [{"role": "user", "content": f"Is the following query simple or complex? A simple query is a basic question, a greeting, or a question that can be answered with a short, direct response. A complex query requires detailed understanding, multiple steps, or external information synthesis. Respond ONLY with 'simple' or 'complex'. Query: {query}"}]
         try:
             complexity_response = primary_client.chat_completion(
                  messages=messages_complexity,
                  max_tokens=10,
                  temperature=0.1
             ).choices[0].message.content.strip().lower()
             print(f"Determined complexity for date/time query '{query}': '{complexity_response}'")
             return "date_calculation", complexity_response # Use date_calculation tool, complexity from LLM
         except Exception as e:
             print(f"Error determining complexity for date/time query '{query}': {e}. Defaulting to 'simple'.")
             return "date_calculation", "simple" # Default to simple on error


    # Check if web search is needed for general knowledge or current info
    messages_tool_determination_search = [{"role": "user", "content": f"Does the following query require searching the web for current or general knowledge information (e.g., news, facts, definitions, current events)? Respond ONLY with 'duckduckgo_search' or 'none'. Query: {query}"}]
    try:
        search_determination_response = primary_client.chat_completion( # Use primary client for this check
            messages=messages_tool_determination_search,
            max_tokens=20,
            temperature=0.1,
            top_p=0.9
        ).choices[0].message.content or ""
        response_lower = search_determination_response.strip().lower()
        if "duckduckgo_search" in response_lower:
            print(f"Model-determined tool for '{query}': 'duckduckgo_search'. Using 'complex' complexity.")
            # Web search queries are generally more complex and routed to primary
            return "duckduckgo_search", "complex"
        else:
            print(f"Model-determined tool for '{query}': 'none' (for search).")
    except Exception as e:
        print(f"Error during LLM call for search tool determination for query '{query}': {e}")
        print(traceback.format_exc())
        print(f"Proceeding without search tool check for query '{query}' due to error.")

    # If no specific tool is determined, route based on query complexity
    messages_complexity = [{"role": "user", "content": f"Is the following query simple or complex? A simple query is a basic question, a greeting, or a question that can be answered with a short, direct response. A complex query requires detailed understanding, multiple steps, or external information synthesis. Respond ONLY with 'simple' or 'complex'. Query: {query}"}]
    try:
        complexity_response = primary_client.chat_completion( # Use primary client for complexity check
             messages=messages_complexity,
             max_tokens=10,
             temperature=0.1
        ).choices[0].message.content.strip().lower()

        if "complex" in complexity_response:
             print(f"Determined query complexity for '{query}': 'complex'. Using 'none' tool.")
             return "none", "complex" # No tool, complex query routed to primary
        else:
             print(f"Determined query complexity for '{query}': 'simple'. Using 'none' tool.")
             return "none", "simple" # No tool, simple query routed to fallback

    except Exception as e:
        print(f"Error during LLM call for complexity determination for query '{query}': {e}")
        print(traceback.format_exc())
        print(f"Defaulting query '{query}' to 'complex' due to error.")
        return "none", "complex" # Default to complex on error


# Function to summarize chat history
def summarize_chat_history(chat_history: list[dict]) -> str:
    """
    Summarizes the provided chat history using the LLM.
    Uses the primary client for summarization.
    """
    print("\n--- Summarizing chat history ---")
    if not chat_history:
        print("Chat history is empty, no summarization needed.")
        return ""

    history_text = "\n".join([f"{msg['role']}: {msg['content']}" for msg in chat_history])

    prompt_for_summary = f"""
Please provide a concise summary of the following conversation history.
Conversation History:
{history_text}

Summary:
"""
    try:
        messages_summary = [{"role": "user", "content": prompt_for_summary}]
        summary_response = primary_client.chat_completion( # Use primary client
            messages=messages_summary,
            max_tokens=200, # Adjust based on desired summary length
            temperature=0.3,
            top_p=0.9
        ).choices[0].message.content or ""
        print("Chat history summarization successful using primary client.")
        return summary_response.strip()
    except Exception as e:
        print(f"Error during LLM call for chat history summarization (primary client): {e}")
        print(traceback.format_exc())
        return "Unable to summarize previous conversation."


# Function to generate text using the LLM, incorporating tool results if available
# Modified to use primary or fallback client based on complexity
def generate_text(prompt: str, tool_results: dict = None, chat_history: list[dict] = None, complexity_level: str = 'complex') -> str:
    """
    Generates text using the configured LLM (primary or fallback), optionally incorporating tool results and chat history.
    Implements conversation summarization and windowing for long histories.
    """
    persona_instructions = """You are absa_ai, an AI developed on August 7, 2025, by the absa team. Your knowledge about business data comes from the company's internal Google Sheet.
You are a friendly and helpful chatbot. Respond to greetings appropriately (e.g., "Hello!", "Hi there!", "Habari!"). If the user uses Swahili greetings or simple conversational phrases, respond in Swahili. Otherwise, respond in English unless the query is clearly in Swahili. Handle conversational flow and ask follow-up questions when appropriate.
If the user asks a question about other companies or general knowledge, answer their question. However, subtly remind them that your primary expertise and purpose are related to Absa-specific information.
"""
    messages = [{"role": "user", "content": persona_instructions}]

    # --- Conversation Summarization and Windowing ---
    SUMMARY_THRESHOLD = 10 # Summarize after 10 turns (5 user/assistant pairs)
    HISTORY_WINDOW_SIZE = 4 # Keep the last 4 turns (2 user/assistant pairs)

    if chat_history:
        print(f"Current chat history length: {len(chat_history)}")
        if len(chat_history) > SUMMARY_THRESHOLD:
            print("Chat history exceeds threshold, summarizing older turns.")
            history_to_summarize = chat_history[:-HISTORY_WINDOW_SIZE]
            summary = summarize_chat_history(history_to_summarize) # summarize_chat_history uses primary client
            if summary:
                messages.append({"role": "assistant", "content": f"Summary of previous conversation: {summary}"})
                print("Added summary to messages.")
            recent_history = chat_history[-HISTORY_WINDOW_SIZE:]
            print(f"Including last {len(recent_history)} turns from history.")
            for message_dict in recent_history:
                 role = message_dict.get("role")
                 content = message_dict.get("content")
                 if role in ["user", "assistant"] and content is not None:
                     messages.append({"role": role, "content": content})
        else:
            print("Including full chat history in LLM prompt.")
            for message_dict in chat_history:
                role = message_dict.get("role")
                content = message_dict.get("content")
                if role in ["user", "assistant"] and content is not None:
                    messages.append({"role": role, "content": content})


    current_user_content = prompt
    if tool_results and any(tool_results.values()):
        current_user_content += "\n\nTool Results:\n"
        for question, results in tool_results.items():
            if results is not None and results != "none": # Only include if results are not None or "none"
                current_user_content += f"--- Results for: {question} ---\n"
                if isinstance(results, list):
                    if not results: # Handle empty list case
                        current_user_content += "No results found.\n\n"
                    else:
                        for i, result in enumerate(results):
                            if isinstance(result, dict) and 'Service' in result and 'Description' in result:
                                current_user_content += f"Business Info {i+1}:\nService: {result.get('Service', 'N/A')}\nDescription: {result.get('Description', 'N/A')}\n\n"
                            elif isinstance(result, dict) and 'url' in result:
                                current_user_content += f"Search Result {i+1}:\nTitle: {result.get('title', 'N/A')}\nURL: {result.get('url', 'N/A')}\nSnippet: {result.get('body', 'N/A')}\n\n"
                            else:
                                current_user_content += f"{result}\n\n"
                elif isinstance(results, dict):
                    if not results: # Handle empty dict case
                         current_user_content += "No results found.\n\n"
                    else:
                        for key, value in results.items():
                            current_user_content += f"{key}: {value}\n"
                        current_user_content += "\n"
                else: # Handle string results (like date calculation or error messages)
                    current_user_content += f"{results}\n\n"

        current_user_content += "Based on the provided tool results and the conversation history, answer the user's latest query. If a question was answered by a tool, use the tool's result directly in your response. If a tool returned an error or no results, acknowledge that and try to answer based on your general knowledge or other tool results. Maintain the language of the original query if possible, especially for simple greetings or direct questions answered by tools."
        print("Added tool results and instruction to final prompt.")
    else:
         current_user_content += "Based on the conversation history, answer the user's latest query."
         print("No tool results to add to final prompt, relying on conversation history.")

    messages.append({"role": "user", "content": current_user_content})

    generation_config = {
        "temperature": 0.7,
        "max_new_tokens": 500,
        "top_p": 0.95,
        "top_k": 50,
        "do_sample": True,
    }

    try:
        if complexity_level == 'complex':
            print("Using primary client for generation.")
            response = primary_client.chat_completion(
                messages=messages,
                max_tokens=generation_config.get("max_new_tokens", 512),
                temperature=generation_config.get("temperature", 0.7),
                top_p=generation_config.get("top_p", 0.95)
            ).choices[0].message.content or ""
            print("LLM generation successful using primary client.")
        else: # complexity_level == 'simple' or fallback needed
            print("Using fallback client for generation.")
            # Use fallback_client for chat completion with Gemma
            response = fallback_client.chat_completion(
                messages=messages,
                max_tokens=generation_config.get("max_new_tokens", 512),
                temperature=generation_config.get("temperature", 0.7),
                top_p=generation_config.get("top_p", 0.95)
            ).choices[0].message.content or ""
            print("LLM generation successful using fallback client.")


        return response.strip()
    except Exception as e:
        print(f"Error during final LLM generation (primary or fallback): {e}")
        print(traceback.format_exc())
        return "An error occurred while generating the final response."

# Function to log conversation data to the Hugging Face Dataset and push
def log_conversation(user_query: str, model_response: str, tool_details: dict = None, user_id: str = None):
    """
    Logs conversation data (query, response, timestamp, optional details) to the Hugging Face Dataset
    and pushes the changes to the Hub.
    """
    global conversation_dataset # Access the global dataset variable
    global dataset_name # Access the dataset name

    print("\n--- Attempting to log conversation to Hugging Face Dataset ---")

    if conversation_dataset is None:
        print("Warning: Hugging Face dataset not loaded or created. Skipping conversation logging.")
        return

    try:
        timestamp = datetime.now().isoformat()
        # Ensure tool_details is a JSON string or None
        tool_details_json = json.dumps(tool_details) if tool_details is not None else None
        # Handle potential None values for user_id
        user_id_val = user_id if user_id is not None else "anonymous"

        # Create a dictionary for the new log entry
        new_log_entry = {
            'timestamp': timestamp,
            'user_id': user_id_val,
            'user_query': user_query,
            'model_response': model_response,
            'tool_details': tool_details_json
        }

        # Append the new log entry to the 'train' split of the dataset
        new_row_dataset = Dataset.from_dict({key: [value] for key, value in new_log_entry.items()})

        # Check if the 'train' split exists before concatenating
        if 'train' in conversation_dataset:
             conversation_dataset['train'] = concatenate_datasets([conversation_dataset['train'], new_row_dataset])
        else:
             # If 'train' doesn't exist (e.g., first log entry), create it
             # Need to define the schema here as well if creating from scratch
             log_schema = {
                 'timestamp': 'string',
                 'user_id': 'string',
                 'user_query': 'string',
                 'model_response': 'string',
                 'tool_details': 'string'
             }
             conversation_dataset = DatasetDict({'train': new_dataset.cast(log_schema)}) # Use new_dataset with schema


        print("Conversation data successfully added to the dataset object.")

        # --- Pushing to the Hugging Face Hub ---
        print(f"Attempting to push dataset to {dataset_name}...")
        # Use the push_to_hub method of the DatasetDict
        # Use commit_message for clarity
        conversation_dataset.push_to_hub(dataset_name, token=HF_TOKEN, commit_message=f"Add conversation log: {timestamp}")
        print(f"Successfully pushed dataset to {dataset_name}.")


    except Exception as e:
        print(f"An unexpected error occurred during Hugging Face Dataset logging and pushing: {e}")
        print(traceback.format_exc())


# Need to import concatenate_datasets
from datasets import concatenate_datasets
from huggingface_hub import HfApi # Ensure HfApi is imported

# --- Caching Implementation ---
# Define the path for the FAISS index file
FAISS_INDEX_FILE = "cache.index"
# Define the path for the metadata file (query text, response, timestamp)
CACHE_METADATA_FILE = "cache_metadata.pkl"

# Global variables for FAISS index and metadata
faiss_index = None
cache_metadata = {}

# Dimension of the embeddings (should match your embedder model output dimension)
# For 'sentence-transformers/paraphrase-MiniLM-L6-v2', the dimension is 384
EMBEDDING_DIM = 384

CACHE_SIMILARITY_THRESHOLD = 0.9 # Cosine similarity threshold for cache hit
CACHE_EXPIRATION_DAYS = 7 # Cache entries expire after 7 days


def initialize_cache():
    """Initializes or loads the FAISS index and cache metadata."""
    global faiss_index, cache_metadata
    print("\n--- Initializing Cache ---")
    if os.path.exists(FAISS_INDEX_FILE) and os.path.exists(CACHE_METADATA_FILE):
        print("Loading existing cache...")
        try:
            faiss_index = faiss.read_index(FAISS_INDEX_FILE)
            with open(CACHE_METADATA_FILE, 'rb') as f:
                cache_metadata = pickle.load(f)
            print(f"Cache loaded successfully. Current cache size: {faiss_index.ntotal}")
            # Clean up expired entries on load
            cleanup_expired_cache_entries()
        except Exception as e:
            print(f"Error loading cache files: {e}. Initializing new cache.")
            print(traceback.format_exc())
            faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM) # Using L2 distance
            cache_metadata = {}
            save_cache() # Save empty cache
    else:
        print("No existing cache found. Initializing new cache.")
        faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM) # Using L2 distance
        cache_metadata = {}
        save_cache() # Save empty cache

def save_cache():
    """Saves the FAISS index and cache metadata to files."""
    global faiss_index, cache_metadata
    if faiss_index is None:
        print("Warning: FAISS index not initialized. Cannot save cache.")
        return
    print("Saving cache...")
    try:
        faiss.write_index(faiss_index, FAISS_INDEX_FILE)
        with open(CACHE_METADATA_FILE, 'wb') as f:
            pickle.dump(cache_metadata, f)
        print("Cache saved successfully.")
    except Exception as e:
        print(f"Error saving cache files: {e}")
        print(traceback.format_exc())

def get_query_embedding(query: str):
    """Generates an embedding for the given query."""
    if embedder is None:
        print("Warning: Embedder not available. Cannot generate query embedding for caching.")
        return None
    try:
        return embedder.encode(query, convert_to_tensor=False) # Return numpy array for FAISS
    except Exception as e:
        print(f"Error generating embedding for query '{query}': {e}")
        print(traceback.format_exc())
        return None

def add_to_cache(query: str, response: str):
    """Adds the query, response, and timestamp to the cache."""
    global faiss_index, cache_metadata
    if embedder is None or faiss_index is None:
        print("Warning: Embedder or FAISS index not available. Cannot add query to cache.")
        return

    try:
        query_embedding = get_query_embedding(query)
        if query_embedding is None:
            return

        # Add the embedding to the FAISS index
        faiss_index.add(np.array([query_embedding])) # Add expects a numpy array of shape (n, dim)

        # Store metadata (query, response, timestamp) keyed by the FAISS index ID
        # The last added embedding gets the index faiss_index.ntotal - 1
        cache_id = faiss_index.ntotal - 1
        now = datetime.now()
        cache_metadata[cache_id] = {
            'query': query, # Store original query for debugging/verification
            'response': response,
            'timestamp': now,
            'count': 1 # Initialize count
        }
        print(f"Added query and response to cache with ID {cache_id}.")
        save_cache() # Save cache after adding
        print(f"Current cache size: {faiss_index.ntotal}")

    except Exception as e:
        print(f"Error adding query to cache: {e}")
        print(traceback.format_exc())


def check_cache(query: str):
    """Checks the cache for a similar query and returns the cached response if found and not expired."""
    global faiss_index, cache_metadata
    if faiss_index is None or embedder is None or faiss_index.ntotal == 0:
        print("Cache is empty or not available. Skipping cache check.")
        return None

    try:
        query_embedding = get_query_embedding(query)
        if query_embedding is None:
            return None

        # Search the FAISS index for similar embeddings
        # D is distances, I is indices of the nearest neighbors
        D, I = faiss_index.search(np.array([query_embedding]), 1) # Search for the 1 nearest neighbor

        if I[0][0] != -1 and D[0][0] <= (1 - CACHE_SIMILARITY_THRESHOLD): # Check if a neighbor was found and distance is within threshold
            cached_id = I[0][0]
            print(f"Found potential cache hit with ID {cached_id} and distance {D[0][0]:.4f}.")

            if cached_id in cache_metadata:
                cached_data = cache_metadata[cached_id]
                now = datetime.now()
                # Check for expiration
                if (now - cached_data['timestamp']).days <= CACHE_EXPIRATION_DAYS:
                    print(f"Cache hit! Returning cached response for query: '{query}'")
                    # Update timestamp and count on cache hit
                    cache_metadata[cached_id]['timestamp'] = now
                    cache_metadata[cached_id]['count'] += 1
                    save_cache() # Save cache after updating metadata
                    return cached_data['response']
                else:
                    print(f"Cache entry with ID {cached_id} found but expired.")
                    # We could remove the expired entry here, but it's handled by cleanup_expired_cache_entries
            else:
                 print(f"Cache ID {cached_id} found in index but not in metadata. Cache inconsistency.")

        print(f"No suitable cache entry found for query: '{query}'")
        return None

    except Exception as e:
        print(f"Error during cache check: {e}")
        print(traceback.format_exc())
        return None

def cleanup_expired_cache_entries():
    """Removes expired entries from the cache and rebuilds the FAISS index if necessary."""
    global faiss_index, cache_metadata
    if faiss_index is None or faiss_index.ntotal == 0:
        print("Cache is empty or not initialized. No expired entries to clean.")
        return

    print("Cleaning up expired cache entries...")
    now = datetime.now()
    expired_ids = [
        cache_id for cache_id, cached_data in cache_metadata.items()
        if (now - cached_data['timestamp']).days > CACHE_EXPIRATION_DAYS
    ]

    if expired_ids:
        print(f"Found {len(expired_ids)} expired cache entries.")
        # Remove from metadata
        for cache_id in expired_ids:
            del cache_metadata[cache_id]

        # Rebuild FAISS index with non-expired entries
        if cache_metadata:
            print("Rebuilding FAISS index with non-expired entries...")
            try:
                # Get embeddings for non-expired entries
                non_expired_embeddings = []
                non_expired_metadata_list = sorted(cache_metadata.items()) # Sort by ID to maintain order
                for cache_id, cached_data in non_expired_metadata_list:
                    # Need to retrieve original query to re-embed
                    original_query = cached_data.get('query')
                    if original_query and embedder:
                         try:
                             non_expired_embeddings.append(embedder.encode(original_query, convert_to_tensor=False).tolist())
                         except Exception as e:
                             print(f"Error re-embedding query '{original_query}': {e}. Skipping.")


                if non_expired_embeddings:
                    print(f"Re-embedding {len(non_expired_embeddings)} non-expired queries.")
                    faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM)
                    faiss_index.add(np.array(non_expired_embeddings))
                    print(f"FAISS index rebuilt. New size: {faiss_index.ntotal}")
                else:
                     print("No non-expired entries to rebuild FAISS index. Clearing index.")
                     faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM)
                     cache_metadata = {} # Clear metadata if index is cleared

            except Exception as e:
                print(f"Error rebuilding FAISS index: {e}")
                print(traceback.format_exc())
                # On error, it might be safer to clear the cache to avoid inconsistencies
                print("Clearing cache due to rebuild error.")
                faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM)
                cache_metadata = {}

        else:
            print("All cache entries expired. Clearing FAISS index and metadata.")
            faiss_index = faiss.IndexFlatL2(EMBEDDING_DIM)
            cache_metadata = {}

        save_cache() # Save after cleanup
    else:
        print("No expired cache entries found.")


# Main chat function with query breakdown and tool execution per question
async def chat(query: str, chat_history: list[dict], api_key: str):
    """
    Processes user queries by breaking down multi-part queries, determining and
    executing appropriate tools for each question asynchronously, and synthesizing results
    using the LLM. Incorporates caching for repeated questions and routes
    to primary or fallback model based on complexity.
    """
    print(f"\n--- chat function received new query ---")
    print(f"  query: {query}")
    print(f"  Validating against SECRET_API_KEY: {'Yes' if SECRET_API_KEY else 'No'}")
    print(f"  chat_history: {chat_history}")
    print(f"  api_key from UI received: {'Yes' if api_key else 'No'}")


    if not SECRET_API_KEY:
        print("Error: APP_API_KEY secret not set in Hugging Face Space Secrets.")
        # Log failure before returning
        log_conversation(
             user_query=query,
             model_response="API key validation failed: Application not configured correctly. APP_API_KEY secret is missing.",
             tool_details={"validation_status": "failed", "reason": "secret_not_set"},
             user_id="unknown"
        )
        return "API key validation failed: Application not configured correctly. APP_API_KEY secret is missing."

    if api_key != SECRET_API_KEY:
        print("Error: API key from UI does not match SECRET_API_KEY.")
        # Log failure before returning
        log_conversation(
            user_query=query,
            model_response="API key validation failed: Invalid API key provided.",
            tool_details={"validation_status": "failed", "reason": "invalid_api_key"},
            user_id="unknown"
        )
        return "API key validation failed: Invalid API key provided."

    # --- Cache Check ---
    cached_response = check_cache(query)
    if cached_response:
        print(f"Returning cached response for query: '{query}'")
        # Log the cached response
        try:
            user_id_to_log = "anonymous"
            if chat_history:
                 for turn in chat_history:
                     if turn.get("role") == "user" and "user_id:" in turn.get("content", "").lower():
                          match = re.search(r"user_id:\s*(\S+)", turn.get("content", ""), re.IGNORECASE)
                          if match:
                               user_id_to_log = match.group(1)
                               break

            log_conversation(
                user_query=query,
                model_response=cached_response,
                tool_details={"cache_status": "hit"},
                user_id=user_id_to_log
            )
        except Exception as e:
            print(f"Error during logging of cached response: {e}")
            print(traceback.format_exc())

        return cached_response

    print("\n--- Breaking down query ---")
    # Use the primary client for query breakdown as it's generally better at understanding complex queries
    prompt_for_question_breakdown = f"""
Analyze the following query and list each distinct question found within it.
Present each question on a new line, starting with a hyphen.
Query: {query}
"""
    try:
        messages_question_breakdown = primary_client.chat_completion( # Use primary client
            messages=[{"role": "user", "content": prompt_for_question_breakdown}],
            max_tokens=100,
            temperature=0.1,
            top_p=0.9
        ).choices[0].message.content or ""
        individual_questions = [line.strip() for line in messages_question_breakdown.split('\n') if line.strip()]
        cleaned_questions = [re.sub(r'^[-*]?\s*', '', q) for q in individual_questions if not q.strip().lower().startswith('note:')]
        print("Individual questions identified:")
        for q in cleaned_questions:
            print(f"- {q}")
    except Exception as e:
        print(f"Error during LLM call for question breakdown (primary client): {e}")
        print(traceback.format_exc())
        print(f"Proceeding with original query as a single question due to breakdown error.")
        cleaned_questions = [query]

    print("\n--- Determining tools and complexity per question ---")
    determined_tools_and_complexity = {}
    for question in cleaned_questions:
        print(f"\nAnalyzing question for tool determination and complexity: '{question}'")
        tool, complexity = determine_tool_usage(question) # determine_tool_usage uses primary client for checks
        determined_tools_and_complexity[question] = {"tool": tool, "complexity": complexity}
        print(f"Determined tool and complexity for '{question}': Tool='{tool}', Complexity='{complexity}'")

    print("\nSummary of determined tools and complexity per question:")
    for question, details in determined_tools_and_complexity.items():
        print(f"'{question}': Tool='{details['tool']}', Complexity='{details['complexity']}'")

    print("\n--- Executing tools asynchronously and collecting results ---")
    tool_results = {}
    tasks = []
    questions_to_process = []

    for question, details in determined_tools_and_complexity.items():
        tool = details['tool']
        print(f"\nQueueing tool '{tool}' for question: '{question}')")
        questions_to_process.append(question)
        if tool == "date_calculation":
            tasks.append(perform_date_calculation(question))
        elif tool == "duckduckgo_search":
            tasks.append(perform_duckduckgo_search(question))
        elif tool == "business_info_retrieval":
            # Business info retrieval is synchronous, run it directly or wrap in run_in_executor
            # For simplicity and to leverage async, we'll wrap it.
            loop = asyncio.get_event_loop()
            tasks.append(loop.run_in_executor(None, retrieve_business_info, question))
        elif tool == "none":
             print(f"Skipping tool execution for question: '{question}' as tool is 'none'. LLM will handle.")
             tasks.append(asyncio.Future()) # Add a placeholder future
             tasks[-1].set_result("none") # Set result immediately to indicate no tool used

    # Run all tasks concurrently
    try:
        results = await asyncio.gather(*tasks, return_exceptions=True)
        print("\n--- Asynchronous Tool Execution Results ---")
        for i, question in enumerate(questions_to_process):
            result = results[i]
            if isinstance(result, Exception):
                print(f"Error executing tool for question '{question}': {result}")
                tool_results[question] = f"An error occurred while fetching information for this part of your query: {result}" # Error message for the user
            else:
                print(f"Result for question '{question}': {result}")
                tool_results[question] = result
        print("\n-----------------------------------------")
    except Exception as e:
        print(f"An error occurred during asynchronous tool execution: {e}")
        print(traceback.format_exc())
        # If gathering fails completely, set error for all
        for question in questions_to_process:
             tool_results[question] = f"An error occurred while fetching information for this part of your query: {e}"


    print("\n--- Collected Tool Results ---")
    if tool_results:
        for question, result in tool_results.items():
            print(f"\nQuestion: {question}")
            print(f"Result: {result}")
    else:
        print("No tool results were collected.")
    print("\n--------------------------")

    print("\n--- Generating final response ---")

    # Determine the overall complexity to choose the final generation model
    # If any question was determined as 'complex', use the primary model
    overall_complexity = 'simple'
    for details in determined_tools_and_complexity.values():
        if details['complexity'] == 'complex':
            overall_complexity = 'complex'
            break
    print(f"Overall query complexity determined as: '{overall_complexity}'")


    final_response = generate_text(query, tool_results, chat_history, complexity_level=overall_complexity)
    print("\n--- Final Response from LLM ---")
    print(final_response)
    print("\n----------------------------")

    # --- Add response to cache ---
    # We add the entire query and final response to the cache, not individual questions.
    add_to_cache(query, final_response)

    try:
        user_id_to_log = "anonymous"
        if chat_history:
             for turn in chat_history:
                 if turn.get("role") == "user" and "user_id:" in turn.get("content", "").lower():
                      match = re.search(r"user_id:\s*(\S+)", turn.get("content", ""), re.IGNORECASE)
                      if match:
                           user_id_to_log = match.group(1)
                           break

        logged_tool_details = {}
        for question, details in determined_tools_and_complexity.items():
            logged_tool_details[question] = {
                 "tool_used": details['tool'],
                 "complexity": details['complexity'],
                 "raw_output": tool_results.get(question)
            }
        logged_tool_details["cache_status"] = "miss" # Log cache miss when generating a new response
        logged_tool_details["model_used_for_generation"] = "primary" if overall_complexity == 'complex' else "fallback"


        # Call the logging function (currently logs to Hugging Face Dataset)
        log_conversation(
            user_query=query,
            model_response=final_response,
            tool_details=logged_tool_details,
            user_id=user_id_to_log
        )
    except Exception as e:
        print(f"Error during conversation logging after response generation: {e}")
        print(traceback.format_exc())

    return final_response

# Keep the Gradio interface setup as is for now
if __name__ == "__main__":
    # Load/Create Hugging Face Dataset on startup
    try:
        # Attempt to load the existing dataset
        print(f"Attempting to load dataset from {dataset_name} on startup...")
        # Use load_dataset for loading directly from the Hub
        conversation_dataset = load_dataset(dataset_name, token=HF_TOKEN)
        print(f"Successfully loaded existing dataset from {dataset_name} on startup.")
        print(conversation_dataset)

    except Exception as e:
        print(f"Dataset not found or failed to load from {dataset_name} on startup: {e}")
        print("Creating a new dataset object on startup...")

        # Define the schema for conversation logs
        # Using 'string' as the data type for simplicity, tool_details will be JSON string
        log_schema = {
            'timestamp': 'string',
            'user_id': 'string',
            'user_query': 'string',
            'model_response': 'string',
            'tool_details': 'string' # Store JSON string here
        }

        # Create an empty dataset with the defined schema
        empty_data = {col: [] for col in log_schema.keys()}
        new_dataset = Dataset.from_dict(empty_data)

        # Wrap the dataset in a DatasetDict
        conversation_dataset = DatasetDict({'train': new_dataset})

        print(f"Created a new empty dataset object with schema: {log_schema}")
        print(conversation_dataset)


    authenticate_google_sheets()
    load_business_info() # This will also create RAG embeddings if data is loaded

    if nlp is None:
        print("Warning: SpaCy model not loaded. Sentence splitting may not work correctly.")
    if embedder is None:
        print("Warning: Sentence Transformer (embedder) not loaded. RAG will not be available.")
    if reranker is None:
        print("Warning: Cross-Encoder Reranker not loaded. Re-ranking of RAG results will not be performed.")
    if not business_info_available:
        print("Warning: Business information (Google Sheet data) not loaded successfully. "
              "RAG will not be available. Please ensure the GOOGLE_BASE64_CREDENTIALS secret is set correctly.")


    DESCRIPTION = """
    # LLM with Tools (DuckDuckGo Search, Date Calculation, Business Info RAG, Hugging Face Dataset Logging) and Two-Tier Model System
    Ask me anything! I can perform web searches, calculate dates, retrieve business information using RAG, and conversation data will be logged to a Hugging Face Dataset. I use a primary LLaMA-70B model for complex queries and a fallback Gemma-2-9b-it model for simpler ones and RAG synthesis.
    """

    demo = gr.ChatInterface(
        fn=chat,
        stop_btn=None,
        examples=[
            ["Hello there! How are you doing?"],
            ["What is the current time in East Africa?"],
            ["Tell me about the 'Project Management' service from Absa."],
            ["Search the web for the latest news on AI."],
            ["Habari!"],
            ["What is the date next Tuesday?"],
            ["What is the time in East Africa and search for latest AI news"],
            ["Who is Jackson Kisanga?"], # Example for business info retrieval
            ["What is the weather like in London?"], # Example for web search
            ["Tell me a joke."], # Example for simple query
        ],
        cache_examples=False,
        type="messages",
        description=DESCRIPTION,
        fill_height=True,
        additional_inputs=[
            gr.Textbox(label="API Key", type="password", placeholder="Enter your API key (starts with fs_)", interactive=True)
        ],
        additional_inputs_accordion="API Key (Required)"
    )

    try:
        # Initialize the cache before launching the demo
        initialize_cache()
        demo.launch(debug=True, show_error=True)
    except Exception as e:
        print(f"Error launching Gradio interface: {e}")
        print(traceback.format_exc())
        print("Please check the console output for more details on the error.")