File size: 62,881 Bytes
461adca
 
 
 
 
60a364a
461adca
558b73f
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c2542b
461adca
 
 
 
 
 
 
 
 
 
59fabbc
 
461adca
 
 
0c2542b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71df805
 
461adca
71df805
 
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a09e8cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461adca
 
 
 
 
 
 
 
a765e3e
461adca
 
a765e3e
 
461adca
 
 
 
381cd06
 
 
461adca
 
 
381cd06
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39e57fa
 
492b465
39e57fa
 
 
 
461adca
39e57fa
461adca
 
 
 
 
 
 
 
 
 
 
 
39e57fa
 
 
 
 
 
 
 
a765e3e
492b465
 
 
 
 
 
39e57fa
0c2542b
 
 
2ef2be1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59fabbc
 
 
 
 
461adca
39e57fa
461adca
 
59fabbc
558b73f
 
 
 
 
 
 
 
 
 
461adca
 
558b73f
 
 
 
 
 
 
 
a765e3e
558b73f
0c2542b
 
 
 
 
 
2ef2be1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59fabbc
 
 
 
 
461adca
558b73f
461adca
 
 
 
0c2542b
461adca
 
a765e3e
 
461adca
 
 
59fabbc
 
 
 
 
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c2542b
 
 
461adca
 
 
 
 
 
 
 
 
 
 
a765e3e
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59fabbc
 
 
 
 
 
461adca
 
 
 
59fabbc
461adca
 
 
59fabbc
 
 
461adca
 
 
 
 
59fabbc
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558b73f
a765e3e
 
 
461adca
a765e3e
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a765e3e
461adca
a765e3e
461adca
a765e3e
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d814828
 
 
 
 
 
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98f5eca
3e63a13
 
59fabbc
98f5eca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e63a13
 
381cd06
3e63a13
 
 
 
 
98f5eca
3e63a13
 
 
 
 
 
a3e169a
39e57fa
492b465
 
39e57fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a765e3e
39e57fa
a765e3e
 
60a364a
492b465
39e57fa
492b465
 
 
a765e3e
492b465
 
 
 
39e57fa
0c2542b
 
 
2ef2be1
 
 
 
 
 
 
98f5eca
2ef2be1
 
3e63a13
98f5eca
 
 
 
 
 
 
3e63a13
98f5eca
2ef2be1
 
 
 
 
 
 
a3e169a
39e57fa
59fabbc
 
a09e8cb
 
 
59fabbc
 
 
39e57fa
a3e169a
59fabbc
 
 
 
3e63a13
59fabbc
 
 
3e63a13
 
 
 
 
 
461adca
 
381cd06
3e63a13
 
461adca
3e63a13
 
381cd06
3e63a13
 
 
 
 
 
 
 
 
 
 
 
a3e169a
558b73f
 
 
 
 
 
 
 
 
 
 
 
 
 
a765e3e
 
558b73f
 
 
a765e3e
558b73f
0c2542b
 
 
 
 
 
2ef2be1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59fabbc
558b73f
59fabbc
 
a09e8cb
 
 
59fabbc
 
 
558b73f
a3e169a
59fabbc
 
 
 
3e63a13
59fabbc
 
 
3e63a13
 
 
 
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a765e3e
461adca
 
a765e3e
461adca
 
a765e3e
 
 
 
 
 
 
 
 
 
 
 
 
461adca
0c2542b
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59fabbc
 
461adca
59fabbc
a09e8cb
 
461adca
 
59fabbc
461adca
59fabbc
461adca
59fabbc
 
 
 
 
461adca
59fabbc
461adca
 
 
 
 
 
59fabbc
 
 
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a765e3e
 
461adca
 
 
 
 
 
 
 
 
 
 
 
a3e169a
 
461adca
 
 
0c2542b
 
 
461adca
 
 
 
 
 
 
 
 
 
 
a3e169a
 
 
59fabbc
 
 
 
a09e8cb
 
461adca
 
 
 
 
 
59fabbc
 
 
 
 
 
 
 
 
461adca
 
 
59fabbc
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a765e3e
 
 
461adca
 
 
 
 
a765e3e
 
 
461adca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
import os
import sys
import json
import time
import boto3
import httpx
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Any
from anthropic import Anthropic
import openai
from openai import OpenAI
from google import genai
from google.genai import types
from llama_index.core import Settings
from llama_index.llms.openai import OpenAI as LlamaOpenAI
from llama_index.core.llms import ChatMessage
from llama_index.core.storage.docstore import SimpleDocumentStore
from llama_index.retrievers.bm25 import BM25Retriever
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core.retrievers import QueryFusionRetriever
from llama_index.core.workflow import Event, Context, Workflow, StartEvent, StopEvent, step
from llama_index.core.schema import NodeWithScore

from config import (
    AWS_ACCESS_KEY_ID,
    AWS_SECRET_ACCESS_KEY,
    ANTHROPIC_API_KEY,
    OPENAI_API_KEY,
    BUCKET_NAME,
    PREFIX_RETRIEVER,
    LOCAL_DIR,
    SETTINGS,
    MAX_TOKENS_CONFIG,
    MAX_TOKENS_ANALYSIS,
    GENERATION_TEMPERATURE,
    LEGAL_POSITION_SCHEMA,
    REQUIRED_FILES,
    DEBUG_PROMPTS,
    ModelProvider,
    AnalysisModelName,
    DEEPSEEK_API_KEY,
    validate_environment
)
from prompts import SYSTEM_PROMPT, LEGAL_POSITION_PROMPT, PRECEDENT_ANALYSIS_TEMPLATE
from utils import (
    clean_text,
    extract_court_decision_text,
    get_links_html,
    get_links_html_lp,
    extract_json_from_text
)
from embeddings import GeminiEmbedding

# ============ Debug Prompt Logging ============
# DEBUG_PROMPTS is loaded from config (YAML env setting + DEBUG_PROMPTS env var override).
_PROMPT_SEP = "=" * 80


def _log_prompt(provider: str, model: str, system: str, user: str) -> None:
    """Print full system + user prompts when DEBUG_PROMPTS is enabled."""
    if not DEBUG_PROMPTS:
        return
    print(f"\n{_PROMPT_SEP}")
    print(f"[PROMPT DEBUG] Provider: {provider} | Model: {model}")
    print(f"{_PROMPT_SEP}")
    if system:
        print("[PROMPT DEBUG] ── SYSTEM PROMPT ──────────────────────────────────")
        print(system)
    print("[PROMPT DEBUG] ── USER PROMPT ────────────────────────────────────")
    print(user)
    print(f"{_PROMPT_SEP}\n")
# ============ End Debug Prompt Logging ============

# Initialize embedding model and settings BEFORE importing components
# Priority: OpenAI > Gemini > None
embed_model = None
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")

if OPENAI_API_KEY:
    embed_model = OpenAIEmbedding(model_name="text-embedding-3-small")
    print("OpenAI embedding model initialized successfully")
elif GEMINI_API_KEY:
    embed_model = GeminiEmbedding(api_key=GEMINI_API_KEY, model_name="gemini-embedding-001")
    print("Gemini embedding model initialized successfully (alternative to OpenAI)")
else:
    print("Warning: No embedding API key found (OpenAI or Gemini). Search functionality will be disabled.")

if embed_model:
    Settings.embed_model = embed_model

# Set basic LlamaIndex Settings before setting LLM
Settings.chunk_size = SETTINGS["chunk_size"]
Settings.similarity_top_k = SETTINGS["similarity_top_k"]

# Set a default LLM to prevent QueryFusionRetriever from trying to load OpenAI
# Use a mock LLM with minimal initialization to avoid validation issues
# We use DeepSeek but with a gpt-4o-mini model name to pass validation
if DEEPSEEK_API_KEY:
    Settings.llm = LlamaOpenAI(
        api_key=DEEPSEEK_API_KEY,
        api_base="https://api.deepseek.com",
        model="gpt-4o-mini"  # Use a known model name for validation
    )
    print("DeepSeek LLM set as default for LlamaIndex (using gpt-4o-mini model name for compatibility)")
elif OPENAI_API_KEY:
    Settings.llm = LlamaOpenAI(api_key=OPENAI_API_KEY, model="gpt-4o-mini")
    print("OpenAI LLM set as default for LlamaIndex")

# Now we can safely set context_window
Settings.context_window = SETTINGS["context_window"]

# Import components AFTER setting all Settings
from components import search_components

# Initialize S3 client (optional, only if AWS credentials are provided)
s3_client = None
if all([AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY]):
    try:
        s3_client = boto3.client(
            "s3",
            aws_access_key_id=AWS_ACCESS_KEY_ID,
            aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
            region_name="eu-north-1"
        )
        print("AWS S3 client initialized successfully")
    except Exception as e:
        print(f"Warning: Failed to initialize AWS S3 client: {str(e)}")
        s3_client = None
else:
    print("AWS credentials not provided. Will use local files only.")


def download_s3_file(bucket_name: str, s3_key: str, local_path: str) -> None:
    """Download a single file from S3."""
    if not s3_client:
        raise ValueError("S3 client not initialized. Please provide AWS credentials or use local files.")
    try:
        s3_client.download_file(bucket_name, s3_key, str(local_path))
        print(f"Downloaded: {s3_key} -> {local_path}")
    except Exception as e:
        print(f"Error downloading file {s3_key}: {str(e)}", file=sys.stderr)
        raise


def download_s3_folder(bucket_name: str, prefix: str, local_dir: Path) -> None:
    """Download all files from an S3 folder."""
    if not s3_client:
        raise ValueError("S3 client not initialized. Please provide AWS credentials or use local files.")
    try:
        response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
        if 'Contents' not in response:
            raise ValueError(f"No files found in S3 bucket {bucket_name} with prefix {prefix}")

        for obj in response['Contents']:
            s3_key = obj['Key']
            if s3_key.endswith('/'):
                continue
            local_file_path = local_dir / Path(s3_key).relative_to(prefix)
            local_file_path.parent.mkdir(parents=True, exist_ok=True)
            s3_client.download_file(bucket_name, s3_key, str(local_file_path))
            print(f"Downloaded: {s3_key} -> {local_file_path}")
    except Exception as e:
        print(f"Error downloading folder {prefix}: {str(e)}", file=sys.stderr)
        raise


def initialize_components() -> bool:
    """Initialize all necessary components for the application."""
    try:
        # Create local directory if it doesn't exist
        LOCAL_DIR.mkdir(parents=True, exist_ok=True)

        # Download index files from S3 only if S3 client is available and local files don't exist
        missing_files = [f for f in REQUIRED_FILES if not (LOCAL_DIR / f).exists()]
        
        if missing_files:
            if s3_client:
                print("Some required files are missing locally. Attempting to download from S3...")
                download_s3_folder(BUCKET_NAME, PREFIX_RETRIEVER, LOCAL_DIR)
            else:
                print(f"Warning: Missing required files and no S3 client available: {', '.join(missing_files)}")
                print(f"Checking if files exist in {LOCAL_DIR}...")
        else:
            print(f"All required files found locally in {LOCAL_DIR}")

        if not LOCAL_DIR.exists():
            raise FileNotFoundError(f"Directory not found: {LOCAL_DIR}")

        # Check for required files again
        missing_files = [f for f in REQUIRED_FILES if not (LOCAL_DIR / f).exists()]
        if missing_files:
            raise FileNotFoundError(f"Missing required files: {', '.join(missing_files)}")

        # Initialize search components if any embedding model is available
        if embed_model:
            success = search_components.initialize_components(LOCAL_DIR)
            if not success:
                raise RuntimeError("Failed to initialize search components")
            print("Search components initialized successfully")
        else:
            print("Skipping search components initialization (no embedding API key available)")

        return True

    except Exception as e:
        print(f"Error initializing components: {str(e)}", file=sys.stderr)
        return False


def deduplicate_nodes(nodes: list[NodeWithScore], key="doc_id"):
    """Видаляє дублікати з результатів пошуку на основі метаданих."""
    seen = set()
    unique_nodes = []

    for node in nodes:
        value = node.node.metadata.get(key)
        if value and value not in seen:
            seen.add(value)
            unique_nodes.append(node)

    return unique_nodes


def get_text_length_without_spaces(text: str) -> int:
    """Підраховує довжину тексту без пробілів."""
    return len(''.join(text.split()))


def get_available_providers() -> Dict[str, bool]:
    """Get status of all AI providers."""
    # Use os.getenv directly to ensure we get the latest environment state
    # independent of import time
    return {
        "openai": bool(os.getenv("OPENAI_API_KEY", "")),
        "anthropic": bool(os.getenv("ANTHROPIC_API_KEY", "")),
        "gemini": bool(os.getenv("GEMINI_API_KEY", "")),
        "deepseek": bool(os.getenv("DEEPSEEK_API_KEY", ""))
    }


def check_provider_available(provider: str) -> Tuple[bool, str]:
    """
    Check if a provider is available.

    Returns:
        Tuple of (is_available, error_message)
    """
    providers = get_available_providers()
    provider_key = provider.lower()

    if provider_key not in providers:
        return False, f"Unknown provider: {provider}"

    if not providers[provider_key]:
        available = [k.upper() for k, v in providers.items() if v]
        if not available:
            return False, "No AI provider API keys configured. Please set at least one API key."
        return False, f"{provider.upper()} API key not configured. Available providers: {', '.join(available)}"

    return True, ""


def normalize_response_keys(response_dict: Dict[str, Any]) -> Dict[str, Any]:
    """
    Normalize keys in the response dictionary to match the expected format.
    Handles variations like 'text_lp' -> 'text' and 'proceeding_type' -> 'proceeding'.
    """
    if not response_dict:
        return response_dict
    
    # Map common variations to standard keys
    key_mapping = {
        "text_lp": "text",
        "legal_position_text": "text", 
        "lp_text": "text",
        "proceeding_type": "proceeding",
        "type_of_proceeding": "proceeding"
    }
    
    normalized = response_dict.copy()
    for variant, standard in key_mapping.items():
        if variant in normalized and standard not in normalized:
            normalized[standard] = normalized.pop(variant)
            
    return normalized


class RetrieverEvent(Event):
    """Event class for retriever operations."""
    nodes: list[NodeWithScore]


class LLMAnalyzer:
    """Class for handling different LLM providers."""

    def __init__(self, provider: Any, model_name: Any, temperature: float = GENERATION_TEMPERATURE, max_tokens: Optional[int] = None):
        self.provider = provider
        self.model_name = model_name
        self.temperature = temperature
        self.max_tokens = max_tokens

        if provider == ModelProvider.OPENAI:
            if not OPENAI_API_KEY:
                raise ValueError(f"OpenAI API key not configured. Please set OPENAI_API_KEY environment variable to use {provider.value} provider.")
            # Disable HTTP/2 to avoid 421 Misdirected Request on HF Spaces
            self._http_client = httpx.Client(timeout=httpx.Timeout(120.0, connect=30.0), http2=False)
            self.client = openai.OpenAI(api_key=OPENAI_API_KEY, http_client=self._http_client)
        elif provider == ModelProvider.DEEPSEEK:
            if not DEEPSEEK_API_KEY:
                raise ValueError(f"DeepSeek API key not configured. Please set DEEPSEEK_API_KEY environment variable to use {provider.value} provider.")
            # Disable HTTP/2 for consistent connections
            self._http_client = httpx.Client(timeout=httpx.Timeout(120.0, connect=30.0), http2=False)
            self.client = openai.OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com", http_client=self._http_client)
        elif provider == ModelProvider.ANTHROPIC:
            if not ANTHROPIC_API_KEY:
                raise ValueError(f"Anthropic API key not configured. Please set ANTHROPIC_API_KEY environment variable to use {provider.value} provider.")
            self.client = Anthropic(api_key=ANTHROPIC_API_KEY)
        elif provider == ModelProvider.GEMINI:
            if not os.environ.get("GEMINI_API_KEY"):
                raise ValueError(f"Gemini API key not configured. Please set GEMINI_API_KEY environment variable to use {provider.value} provider.")
            # Initialize Gemini client with new API
            self.client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
        else:
            raise ValueError(f"Unsupported provider: {provider}")

    async def analyze(self, prompt: str, response_schema: dict) -> str:
        """Analyze text using selected LLM provider."""
        if self.provider == ModelProvider.OPENAI:
            return await self._analyze_with_openai(prompt, response_schema)
        elif self.provider == ModelProvider.DEEPSEEK:
            return await self._analyze_with_deepseek(prompt)
        elif self.provider == ModelProvider.ANTHROPIC:
            return await self._analyze_with_anthropic(prompt, response_schema)
        else:
            return await self._analyze_with_gemini(prompt, response_schema)

    async def _analyze_with_openai(self, prompt: str, response_schema: dict) -> str:
        """Analyze text using OpenAI."""
        # Determine model name and if it's a reasoning model
        model_val = self.model_name.value if hasattr(self.model_name, "value") else str(self.model_name)
        is_reasoning_model = any(m in model_val.lower() for m in ["gpt-4.1", "gpt-4.5", "gpt-5", "o1", "o3"])
        
        # Use developer role for newer models
        role = "developer" if is_reasoning_model else "system"
        
        messages = [
            ChatMessage(role=role, content=SYSTEM_PROMPT),
            ChatMessage(role="user", content=prompt)
        ]

        response_format = {
            "type": "json_schema",
            "json_schema": {
                "name": "relevant_positions_schema",
                "schema": response_schema
            }
        }

        try:
            completion_params = {
                "model": model_val,
                "messages": [{"role": m.role, "content": m.content} for m in messages],
                "response_format": response_format,
            }
            
            # Reasoning models usually require temperature=1.0 or none
            if not is_reasoning_model:
                completion_params["temperature"] = self.temperature
            
            # Add GPT-5.2 specific parameters
            if "gpt-5" in model_val.lower():
                completion_params["reasoning_effort"] = "medium"
                completion_params["verbosity"] = "medium"
                completion_params["store"] = False

            # Log full prompts in debug mode
            _log_prompt("openai-analyzer", model_val, SYSTEM_PROMPT, prompt)

            # Retry logic for OpenAI analysis
            max_retries = 3
            last_error = None
            response = None
            for attempt in range(max_retries):
                try:
                    print(f"[DEBUG] OpenAI Analysis call attempt {attempt + 1}/{max_retries}")
                    response = self.client.chat.completions.create(**completion_params)
                    break
                except Exception as api_err:
                    last_error = api_err
                    print(f"[ERROR] OpenAI Analysis attempt {attempt + 1} failed: {type(api_err).__name__}: {str(api_err)}")
                    if attempt < max_retries - 1:
                        time.sleep(2 ** attempt)
                    else:
                        raise last_error

            response_text = response.choices[0].message.content
            
            # Verify it's valid JSON
            json_data = extract_json_from_text(response_text)
            return json.dumps(json_data, ensure_ascii=False) if json_data else response_text
        except Exception as e:
            raise RuntimeError(f"Error in OpenAI analysis ({model_val}): {str(e)}")

    async def _analyze_with_deepseek(self, prompt: str) -> str:
        """Analyze text using DeepSeek."""
        model_val = self.model_name.value if hasattr(self.model_name, "value") else str(self.model_name)
        is_reasoning = "reasoner" in model_val.lower()
        
        messages = []
        if is_reasoning:
            # DeepSeek R1 does not support system role, combine with user
            messages.append(ChatMessage(role="user", content=f"{SYSTEM_PROMPT}\n\n{prompt}"))
        else:
            messages.append(ChatMessage(role="system", content=SYSTEM_PROMPT))
            messages.append(ChatMessage(role="user", content=prompt))

        try:
            completion_params = {
                "model": model_val,
                "messages": [{"role": m.role, "content": m.content} for m in messages],
            }
            
            # Use JSON mode and temperature only for non-reasoning models
            if not is_reasoning:
                completion_params["response_format"] = {'type': 'json_object'}
                completion_params["temperature"] = self.temperature

            # Log full prompts in debug mode
            if is_reasoning:
                _log_prompt("deepseek-analyzer", model_val, "", f"{SYSTEM_PROMPT}\n\n{prompt}")
            else:
                _log_prompt("deepseek-analyzer", model_val, SYSTEM_PROMPT, prompt)

            # Retry logic for DeepSeek analysis
            max_retries = 3
            last_error = None
            response = None
            for attempt in range(max_retries):
                try:
                    print(f"[DEBUG] DeepSeek Analysis call attempt {attempt + 1}/{max_retries}")
                    response = self.client.chat.completions.create(**completion_params)
                    break
                except Exception as api_err:
                    last_error = api_err
                    print(f"[ERROR] DeepSeek Analysis attempt {attempt + 1} failed: {type(api_err).__name__}: {str(api_err)}")
                    if attempt < max_retries - 1:
                        time.sleep(2 ** attempt)
                    else:
                        raise last_error

            response_text = response.choices[0].message.content
            
            # Verify and clean JSON
            json_data = extract_json_from_text(response_text)
            return json.dumps(json_data, ensure_ascii=False) if json_data else response_text
        except Exception as e:
            raise RuntimeError(f"Error in DeepSeek analysis ({model_val}): {str(e)}")

    async def _analyze_with_anthropic(self, prompt: str, response_schema: dict) -> str:
        """Analyze text using Anthropic."""
        try:
            _log_prompt("anthropic-analyzer", str(self.model_name), SYSTEM_PROMPT, prompt)
            response = self.client.messages.create(
                model=self.model_name,
                max_tokens=self.max_tokens or MAX_TOKENS_ANALYSIS,
                temperature=self.temperature,
                system=SYSTEM_PROMPT,
                messages=[{"role": "user", "content": prompt}]
            )
            response_text = response.content[0].text
            
            # Extract JSON from potential markdown blocks
            json_data = extract_json_from_text(response_text)
            if json_data:
                return json.dumps(json_data, ensure_ascii=False)
            return response_text
        except Exception as e:
            raise RuntimeError(f"Error in Anthropic analysis: {str(e)}")

    async def _analyze_with_gemini(self, prompt: str, response_schema: dict) -> str:
        """Analyze text using Gemini with new API."""
        try:
            # Форматуємо промпт для отримання відповіді у форматі JSON
            json_instruction = """
            Твоя відповідь повинна бути в форматі JSON:
            {
                "relevant_positions": [
                    {
                        "lp_id": "ID позиції",
                        "source_index": "Порядковий номер позиції у списку",
                        "description": "Детальне обґрунтування релевантності"
                    }
                ]
            }
            """

            formatted_prompt = f"{prompt}\n\n{json_instruction}"

            # Log full prompts in debug mode
            _log_prompt("gemini-analyzer", str(self.model_name), SYSTEM_PROMPT, formatted_prompt)

            # Use new google.genai API
            contents = [
                types.Content(
                    role="user",
                    parts=[
                        types.Part.from_text(text=formatted_prompt),
                    ],
                ),
            ]
            
            generate_content_config = types.GenerateContentConfig(
                temperature=self.temperature,
                max_output_tokens=self.max_tokens or MAX_TOKENS_ANALYSIS,
                system_instruction=[
                    types.Part.from_text(text=SYSTEM_PROMPT),
                ],
            )

            response = self.client.models.generate_content(
                model=self.model_name,
                contents=contents,
                config=generate_content_config,
            )
            response_text = response.text

            if not response_text:
                raise RuntimeError("Empty response from Gemini")

            # Витягуємо JSON з відповіді за допомогою універсальної функції
            json_data = extract_json_from_text(response_text)
            
            if json_data:
                if "relevant_positions" not in json_data:
                    json_data = {
                        "relevant_positions": [
                            {
                                "lp_id": "unknown",
                                "source_index": "1",
                                "description": json.dumps(json_data, ensure_ascii=False)
                            }
                        ]
                    }
                return json.dumps(json_data, ensure_ascii=False)
            else:
                # Якщо JSON не знайдено, створюємо структурований JSON з тексту
                return json.dumps({
                    "relevant_positions": [
                        {
                            "lp_id": "unknown",
                            "source_index": "1",
                            "description": response_text
                        }
                    ]
                }, ensure_ascii=False)

        except Exception as e:
            # Спроба отримати більш детальну інформацію про помилку
            error_details = str(e)
            if hasattr(e, 'response'):
                error_details += f"\nResponse: {e.response}"
            raise RuntimeError(f"Error in Gemini analysis: {error_details}")


class PrecedentAnalysisWorkflow(Workflow):
    """Workflow for analyzing legal precedents."""

    def __init__(self, provider: Any = ModelProvider.OPENAI,
                 model_name: Any = AnalysisModelName.GPT4o_MINI,
                 temperature: float = GENERATION_TEMPERATURE,
                 max_tokens: Optional[int] = None):
        super().__init__()
        self.analyzer = LLMAnalyzer(provider, model_name, temperature, max_tokens)

    @step
    async def analyze(self, ctx: Context, ev: StartEvent) -> StopEvent:
        """Analyze legal precedents."""
        try:
            query = ev.get("query", "")
            question = ev.get("question", "")
            nodes = ev.get("nodes", [])

            if not query:
                return StopEvent(result="Error: No text provided (query)")
            if not nodes:
                return StopEvent(result="Error: No legal positions provided for analysis (nodes)")

            context_parts = []
            for i, node in enumerate(nodes, 1):
                node_text = node.node.text if hasattr(node, 'node') else node.text
                metadata = node.node.metadata if hasattr(node, 'node') else node.metadata
                lp_id = metadata.get('lp_id', f'unknown_{i}')
                context_parts.append(f"Source {i} (ID: {lp_id}):\n{node_text}")

            context_str = "\n\n".join(context_parts)

            response_schema = {
                "type": "object",
                "properties": {
                    "relevant_positions": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "lp_id": {"type": "string"},
                                "source_index": {"type": "string"},
                                "description": {"type": "string"}
                            },
                            "required": ["lp_id", "source_index", "description"]
                        }
                    }
                }
            }

            prompt = PRECEDENT_ANALYSIS_TEMPLATE.format(
                query=query,
                question=question if question else "Загальний аналіз релевантності",
                context_str=context_str
            )

            response_content = await self.analyzer.analyze(prompt, response_schema)

            try:
                # Спроба розпарсити JSON
                parsed_response = json.loads(response_content)

                if "relevant_positions" in parsed_response:
                    response_lines = []
                    for position in parsed_response["relevant_positions"]:
                        position_text = f"* [{position['source_index']}] {position['description']}  "
                        response_lines.append(position_text)

                    response_text = "\n".join(response_lines)
                    return StopEvent(result=response_text)
                else:
                    # Якщо немає relevant_positions, повертаємо весь текст
                    return StopEvent(result=f"* [1] {response_content}")

            except json.JSONDecodeError as e:
                # Якщо не вдалося розпарсити JSON, повертаємо текст як є
                return StopEvent(result=f"* [1] {response_content}")

        except Exception as e:
            return StopEvent(result=f"Error during analysis: {str(e)}")


def generate_legal_position(
        input_text: str,
        input_type: str,
        comment_input: str,
        provider: str,
        model_name: str,
        thinking_enabled: bool = False,
        thinking_type: str = "Adaptive",
        thinking_level: str = "MEDIUM",
        openai_verbosity: str = "medium",
        thinking_budget: int = 10000,
        temperature: float = GENERATION_TEMPERATURE,
        max_tokens: Optional[int] = None,
        custom_system_prompt: Optional[str] = None,
        custom_lp_prompt: Optional[str] = None
) -> Dict:
    """Generate legal position from input text using specified provider and model."""
    try:
        # Check if provider is available
        is_available, error_msg = check_provider_available(provider)
        if not is_available:
            return {
                "title": "Помилка конфігурації",
                "text": error_msg,
                "proceeding": "N/A",
                "category": "Error"
            }

        # Use custom prompts if provided, otherwise use defaults
        system_prompt = custom_system_prompt if custom_system_prompt else SYSTEM_PROMPT
        lp_prompt = custom_lp_prompt if custom_lp_prompt else LEGAL_POSITION_PROMPT

        print(f"[DEBUG] RAW input_text length: {len(input_text) if input_text else 0}")
        print(f"[DEBUG] RAW input_text preview: {input_text[:300] if input_text else 'Empty'}")
        print(f"[DEBUG] Using custom prompts: system={custom_system_prompt is not None}, lp={custom_lp_prompt is not None}")

        input_text = clean_text(input_text)

        print(f"[DEBUG] AFTER CLEAN input_text length: {len(input_text) if input_text else 0}")
        print(f"[DEBUG] AFTER CLEAN input_text preview: {input_text[:300] if input_text else 'Empty'}")

        comment_input = clean_text(comment_input)

        if input_type == "url":
            try:
                extracted = extract_court_decision_text(input_text)
                print(f"[DEBUG] EXTRACTED text length: {len(extracted) if extracted else 0}")
                print(f"[DEBUG] EXTRACTED text preview: {extracted[:300] if extracted else 'Empty'}")

                court_decision_text = clean_text(extracted)

                print(f"[DEBUG] AFTER CLEAN extracted length: {len(court_decision_text) if court_decision_text else 0}")
                print(f"[DEBUG] AFTER CLEAN extracted preview: {court_decision_text[:300] if court_decision_text else 'Empty'}")
            except Exception as e:
                raise Exception(f"Помилка при отриманні тексту за URL: {str(e)}")
        else:
            court_decision_text = input_text

        # Debug: Check what we have before formatting
        print(f"[DEBUG] FINAL court_decision_text length: {len(court_decision_text)}")
        print(f"[DEBUG] FINAL court_decision_text preview: {court_decision_text[:300]}")
        print(f"[DEBUG] comment_input: {comment_input[:100] if comment_input else 'Empty'}")

        # Check if placeholders exist in the prompt, if not - append them to the end
        if "{court_decision_text}" not in lp_prompt:
            print("[WARNING] {court_decision_text} placeholder missing in prompt! Appending to the end.")
            lp_prompt += "\n\n<court_decision>\n{court_decision_text}\n</court_decision>"
        
        if "{comment}" not in lp_prompt:
            lp_prompt += "\n\n<comment>\n{comment}\n</comment>"

        content = lp_prompt.format(
            court_decision_text=court_decision_text,
            comment=comment_input if comment_input else "Коментар відсутній"
        )

        # Debug: Check formatted content
        print(f"[DEBUG] ===== UNIFIED PROMPT FOR ALL PROVIDERS =====")
        print(f"[DEBUG] Formatted content length: {len(content)}")
        print(f"[DEBUG] Content preview (first 500 chars): {content[:500]}")
        print(f"[DEBUG] Provider: {provider}, Model: {model_name}")
        print(f"[DEBUG] ==============================================")

        # Validation check - ensure court_decision_text is not empty
        if not court_decision_text or len(court_decision_text.strip()) < 50:
            print(f"[WARNING] court_decision_text is too short or empty! Length: {len(court_decision_text) if court_decision_text else 0}")
            raise Exception(f"Текст судового рішення занадто короткий або відсутній (довжина: {len(court_decision_text) if court_decision_text else 0} символів). Будь ласка, перевірте вхідні дані.")

        if provider == ModelProvider.OPENAI.value:
            # Diagnostic: test raw httpx connection before using OpenAI SDK
            http_client = None
            response_text = None
            try:
                print(f"[DEBUG] OpenAI pre-flight check...")
                print(f"[DEBUG] openai SDK version: {openai.__version__}")
                print(f"[DEBUG] httpx version: {httpx.__version__}")
                print(f"[DEBUG] OPENAI_API_KEY length: {len(OPENAI_API_KEY) if OPENAI_API_KEY else 0}")
                
                # Quick raw httpx connectivity test to api.openai.com
                try:
                    with httpx.Client(timeout=10.0, http2=False) as test_client:
                        test_resp = test_client.get("https://api.openai.com/v1/models",
                                                     headers={"Authorization": f"Bearer {OPENAI_API_KEY[:20]}...truncated"})
                        print(f"[DEBUG] Raw httpx test -> HTTP {test_resp.status_code}")
                except Exception as pre_err:
                    import traceback
                    print(f"[WARNING] Raw httpx pre-flight failed: {type(pre_err).__name__}: {pre_err}")
                    print(f"[WARNING] Pre-flight traceback: {traceback.format_exc()}")
                
                http_client = httpx.Client(
                    timeout=httpx.Timeout(120.0, connect=30.0),
                    http2=False,
                )
                client = OpenAI(
                    api_key=OPENAI_API_KEY, 
                    http_client=http_client
                )
                print(f"[DEBUG] OpenAI client base_url: {client.base_url}")
                
                # Retry logic for connection errors
                max_retries = 3
                last_error = None
                response = None
                
                print(f"[DEBUG] OpenAI Generation - Model: {model_name}")
                
                # Check for reasoning models (gpt-4.1, gpt-5.2, o1, etc.)
                is_reasoning_model = any(m in model_name.lower() for m in ["gpt-4.1", "gpt-4.5", "gpt-5", "o1", "o3"])
                
                # Use developer role for newer models, system for others
                role = "developer" if is_reasoning_model else "system"
                
                messages = [
                    {"role": role, "content": system_prompt},
                    {"role": "user", "content": content},
                ]
                
                # Parameters for chat completion
                completion_params = {
                    "model": model_name,
                    "messages": messages,
                }
                
                # Set tokens based on model capabilities
                if is_reasoning_model:
                    completion_params["max_completion_tokens"] = max_tokens or MAX_TOKENS_CONFIG["openai"]
                else:
                    completion_params["max_tokens"] = max_tokens or MAX_TOKENS_CONFIG["openai"]
                    completion_params["temperature"] = temperature

                # Handle thinking/reasoning for GPT-5.2 and other reasoning models
                if thinking_enabled and is_reasoning_model:
                    # GPT-5.2 specific parameters
                    if "gpt-5" in model_name.lower():
                        completion_params["reasoning_effort"] = thinking_level.lower()
                        completion_params["verbosity"] = openai_verbosity.lower()
                        completion_params["store"] = False
                    else:
                        # For other reasoning models (gpt-4.1, o1, etc.)
                        completion_params["reasoning_effort"] = thinking_level.lower()

                # Log full prompts in debug mode
                _log_prompt("openai", model_name, system_prompt, content)

                # Execute with retries
                for attempt in range(max_retries):
                    try:
                        print(f"[DEBUG] OpenAI API call attempt {attempt + 1}/{max_retries}")
                        response = client.chat.completions.create(**completion_params)
                        break
                    except Exception as api_err:
                        import traceback
                        last_error = api_err
                        error_type = type(api_err).__name__
                        error_detail = str(api_err)
                        # Walk the full exception chain
                        cause = api_err.__cause__
                        depth = 0
                        while cause and depth < 5:
                            error_detail += f"\n  -> Caused by [{depth}]: {type(cause).__name__}: {cause}"
                            cause = getattr(cause, '__cause__', None) or getattr(cause, '__context__', None)
                            depth += 1
                        print(f"[ERROR] OpenAI API attempt {attempt + 1} failed: {error_type}: {error_detail}")
                        print(f"[ERROR] Full traceback:\n{traceback.format_exc()}")
                        if attempt < max_retries - 1:
                            wait_time = 2 ** attempt  # 1, 2, 4 seconds
                            print(f"[DEBUG] Retrying in {wait_time}s...")
                            time.sleep(wait_time)
                        else:
                            raise last_error

                response_text = response.choices[0].message.content
                print(f"[DEBUG] OpenAI response length: {len(response_text) if response_text else 0}")
                
                json_response = extract_json_from_text(response_text)
                if json_response:
                    json_response = normalize_response_keys(json_response)
                
                if json_response and all(key in json_response for key in ["title", "text", "proceeding", "category"]):
                    return json_response
                else:
                    print(f"[WARNING] Invalid JSON structure from OpenAI. Text: {response_text[:300] if response_text else 'None'}...")
                    raise ValueError("Invalid JSON structure")
            except Exception as e:
                print(f"[ERROR] OpenAI generation/parsing failed: {e}")
                return {
                    "title": "Автоматично сформований заголовок (OpenAI)",
                    "text": response_text.strip() if response_text else f"Помилка при отриманні відповіді: {str(e)}",
                    "proceeding": "Не визначено",
                    "category": "Помилка парсингу"
                }
            finally:
                if http_client:
                    try:
                        http_client.close()
                    except Exception:
                        pass

        if provider == ModelProvider.DEEPSEEK.value:
            # Use custom httpx client with HTTP/2 disabled for consistent connections
            http_client = None
            response_text = None
            try:
                http_client = httpx.Client(
                    timeout=httpx.Timeout(120.0, connect=30.0),
                    http2=False,
                )
                client = OpenAI(
                    api_key=DEEPSEEK_API_KEY, 
                    base_url="https://api.deepseek.com", 
                    http_client=http_client
                )
                
                # Retry logic for DeepSeek
                max_retries = 3
                last_error = None
                response = None
                
                print(f"[DEBUG] DeepSeek Generation - Model: {model_name}")
                
                # Check for reasoning model (DeepSeek R1)
                is_reasoning = "reasoner" in model_name.lower()
                
                messages = []
                if is_reasoning:
                    # R1 does not support system role, combine with user
                    combined_content = f"{system_prompt}\n\n{content}"
                    messages.append({"role": "user", "content": combined_content})
                else:
                    messages.append({"role": "system", "content": system_prompt})
                completion_params = {
                    "model": model_name,
                    "messages": messages,
                    "max_tokens": max_tokens or MAX_TOKENS_CONFIG["deepseek"],
                    "frequency_penalty": 0.0,
                }
                
                if not is_reasoning:
                    completion_params["temperature"] = temperature

                # Log full prompts in debug mode
                if is_reasoning:
                    _log_prompt("deepseek", model_name, "", combined_content)
                else:
                    _log_prompt("deepseek", model_name, system_prompt, content)

                # Execute with retries
                for attempt in range(max_retries):
                    try:
                        print(f"[DEBUG] DeepSeek API call attempt {attempt + 1}/{max_retries}")
                        response = client.chat.completions.create(**completion_params)
                        break
                    except Exception as api_err:
                        last_error = api_err
                        error_type = type(api_err).__name__
                        print(f"[ERROR] DeepSeek API attempt {attempt + 1} failed: {error_type}: {str(api_err)}")
                        if attempt < max_retries - 1:
                            wait_time = 2 ** attempt
                            print(f"[DEBUG] Retrying in {wait_time}s...")
                            time.sleep(wait_time)
                        else:
                            raise last_error

                response_text = response.choices[0].message.content
                print(f"[DEBUG] DeepSeek response length: {len(response_text) if response_text else 0}")
                
                json_response = extract_json_from_text(response_text)
                if json_response:
                    json_response = normalize_response_keys(json_response)
                
                if json_response and all(key in json_response for key in ["title", "text", "proceeding", "category"]):
                    return json_response
                else:
                    print(f"[WARNING] Invalid JSON structure from DeepSeek. Text: {response_text[:300] if response_text else 'None'}...")
                    raise ValueError("Invalid JSON structure")
            except Exception as e:
                print(f"[ERROR] DeepSeek generation/parsing failed: {e}")
                return {
                    "title": "Автоматично сформований заголовок (DeepSeek)",
                    "text": response_text.strip() if response_text else f"Помилка при отриманні відповіді від DeepSeek: {str(e)}",
                    "proceeding": "Не визначено",
                    "category": "Помилка API/Парсингу"
                }
            finally:
                if http_client:
                    try:
                        http_client.close()
                    except Exception:
                        pass

        elif provider == ModelProvider.ANTHROPIC.value:
            client = Anthropic(api_key=ANTHROPIC_API_KEY)

            # Debug: check what we're sending to Anthropic
            print(f"[DEBUG] Sending to Anthropic - content length: {len(content)}")
            print(f"[DEBUG] Content preview: {content[:500]}")
            print(f"[DEBUG] ANTHROPIC_API_KEY set: {bool(ANTHROPIC_API_KEY)}, length: {len(ANTHROPIC_API_KEY) if ANTHROPIC_API_KEY else 0}")

            messages = [{
                "role": "user",
                "content": content
            }]

            # Prepare message creation parameters
            message_params = {
                "model": model_name,
                "max_tokens": max_tokens or MAX_TOKENS_CONFIG["anthropic"],
                "system": system_prompt,
                "messages": messages,
                "temperature": temperature
            }

            # Add thinking config if enabled
            if thinking_enabled and "claude" in model_name.lower():
                # For Claude 4.6 models, we can use Adaptive
                if thinking_type.lower() == "adaptive" and getattr(model_name, "find", lambda x: -1)("-4-6") != -1:
                    message_params["thinking"] = {"type": "adaptive"}
                    message_params["temperature"] = 1.0
                else:
                    # 'Enabled' type works for both 4.5 and 4.6 models
                    message_params["thinking"] = {
                        "type": "enabled",
                        "budget_tokens": max(1024, int(thinking_budget))
                    }
                    message_params["temperature"] = 1.0

            # Log full prompts in debug mode
            _log_prompt("anthropic", model_name, system_prompt, content)

            # Retry logic for connection errors
            max_retries = 3
            last_error = None
            for attempt in range(max_retries):
                try:
                    print(f"[DEBUG] Anthropic API call attempt {attempt + 1}/{max_retries}")
                    response = client.messages.create(**message_params)
                    break
                except Exception as api_err:
                    last_error = api_err
                    error_type = type(api_err).__name__
                    print(f"[ERROR] Anthropic API attempt {attempt + 1} failed: {error_type}: {str(api_err)}")
                    if attempt < max_retries - 1:
                        wait_time = 2 ** attempt  # 1, 2, 4 seconds
                        print(f"[DEBUG] Retrying in {wait_time}s...")
                        time.sleep(wait_time)
                    else:
                        raise Exception(f"Помилка з'єднання з Anthropic API після {max_retries} спроб: {error_type}: {str(api_err)}")

            try:
                # Extract text from response, handling different content block types
                response_text = ""
                thinking_text = ""
                
                for block in response.content:
                    if hasattr(block, 'type'):
                        if block.type == 'thinking':
                            # Separate thinking blocks (if any)
                            thinking_text += getattr(block, 'thinking', '')
                        elif block.type == 'text':
                            response_text += getattr(block, 'text', '')
                    elif hasattr(block, 'text'):
                        # Fallback for simpler response format
                        response_text += block.text
                
                if thinking_text:
                    print(f"[DEBUG] Anthropic thinking block length: {len(thinking_text)}")
                
                print(f"[DEBUG] Anthropic response text length: {len(response_text)}")
                print(f"[DEBUG] Response preview (first 500 chars): {response_text[:500]}")
                
                # Спробуємо розпарсити JSON за допомогою універсальної функції
                json_response = extract_json_from_text(response_text)
                
                if json_response:
                    json_response = normalize_response_keys(json_response)
                    
                    # Validate required fields
                    required = ["title", "text", "proceeding", "category"]
                    missing = [f for f in required if f not in json_response]
                    if missing:
                        print(f"[WARNING] Missing fields in Anthropic JSON: {missing}")
                        for field in missing:
                            if field not in json_response:
                                json_response[field] = "Не вказано"
                    return json_response
                else:
                    print(f"[ERROR] Could not extract JSON from Anthropic response")
                    # Fallback: create structured response from raw text
                    return {
                        "title": "Автоматично згенерований заголовок",
                        "text": response_text.strip(),
                        "proceeding": "Не визначено",
                        "category": "Помилка парсингу JSON"
                    }
            except Exception as e:
                # Скидання помилки для подальшого аналізу
                error_details = str(e)
                if hasattr(e, 'response'):
                    error_details += f"\nResponse: {e.response}"
                raise RuntimeError(f"Error in Anthropic analysis: {error_details}")

        elif provider == ModelProvider.GEMINI.value:
            if not os.environ.get("GEMINI_API_KEY"):
                raise ValueError("Gemini API key not found in environment variables")

            try:
                # Debug: Log input parameters
                print(f"[DEBUG] Gemini Generation:")
                print(f"[DEBUG] Model: {model_name}")
                print(f"[DEBUG] Input text length: {len(input_text)}")
                print(f"[DEBUG] Court decision text length: {len(court_decision_text)}")
                
                # Use new google.genai API
                client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
                
                contents = [
                    types.Content(
                        role="user",
                        parts=[
                            types.Part.from_text(text=content),
                        ],
                    ),
                ]
                
                # Build config based on model version
                config_params = {
                    "temperature": temperature,
                    "max_output_tokens": max_tokens or MAX_TOKENS_CONFIG["gemini"],
                    "system_instruction": [
                        types.Part.from_text(text=system_prompt),
                    ],
                }
                
                # Add thinking config if enabled (only for Gemini 3+ models)
                if thinking_enabled and model_name.startswith("gemini-3"):
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=thinking_level.upper()
                    )
                
                # Only add response_mime_type for models that support it
                # if not model_name.startswith("gemini-3"):
                #     config_params["response_mime_type"] = "application/json"
                
                generate_content_config = types.GenerateContentConfig(**config_params)

                # Log full prompts in debug mode
                _log_prompt("gemini", model_name, system_prompt, content)

                response = client.models.generate_content(
                    model=model_name,
                    contents=contents,
                    config=generate_content_config,
                )
                response_text = response.text

                # Перевіряємо наявність тексту у відповіді
                if not response_text:
                    raise Exception("Пуста відповідь від моделі Gemini")

                print(f"[DEBUG] Gemini response length: {len(response_text)}")
                print(f"[DEBUG] Gemini response preview: {response_text[:300]}...")

                # Спробуємо розпарсити JSON за допомогою універсальної функції
                json_response = extract_json_from_text(response_text)
                
                if json_response:
                    json_response = normalize_response_keys(json_response)
                    
                    # Перевіряємо наявність всіх необхідних полів
                    required_fields = ["title", "text", "proceeding", "category"]
                    if all(field in json_response for field in required_fields):
                        return json_response
                    else:
                        missing_fields = [field for field in required_fields if field not in json_response]
                        print(f"[WARNING] Gemini response missing fields: {missing_fields}")
                        # Fallback for missing fields
                        for field in required_fields:
                            if field not in json_response:
                                json_response[field] = "Не визначено"
                        return json_response
                else:
                    print(f"[ERROR] Could not extract JSON from Gemini response: {response_text[:300]}...")
                    return {
                        "title": "Автоматично сформований заголовок",
                        "text": response_text.strip(),
                        "proceeding": "Не визначено",
                        "category": "Помилка парсингу"
                    }

            except Exception as e:
                print(f"Error in Gemini generation: {str(e)}")
                return {
                    "title": "Error in Gemini generation",
                    "text": str(e),
                    "proceeding": "Error",
                    "category": "Error"
                }

    except Exception as e:
        print(f"Error in generate_legal_position: {str(e)}")
        return {
            "title": "Error",
            "text": str(e),
            "proceeding": "Unknown",
            "category": "Error"
        }


async def search_with_ai_action(legal_position_json: Dict) -> Tuple[str, Optional[List[NodeWithScore]]]:
    """Search for relevant legal positions based on input."""
    try:
        if not embed_model:
            return "Помилка: пошук недоступний без налаштованого embedding API ключа (OpenAI або Gemini)", None

        retriever = search_components.get_retriever()
        if not retriever:
            return "Помилка: компоненти пошуку не ініціалізовано", None

        query_text = (
            f"{legal_position_json['title']}: "
            f"{legal_position_json['text']}: "
            f"{legal_position_json['proceeding']}: "
            f"{legal_position_json['category']}"
        )

        nodes = await retriever.aretrieve(query_text)

        # Видалення дублікатів
        unique_nodes = deduplicate_nodes(nodes)

        # Обмеження кількості результатів
        top_nodes = unique_nodes[:Settings.similarity_top_k]

        sources_output = "\n **Результати пошуку (наявні правові позиції Верховного Суду):** \n\n"
        for index, node in enumerate(top_nodes, start=1):
            source_title = node.node.metadata.get('title')
            doc_ids = node.node.metadata.get('doc_id')
            lp_ids = node.node.metadata.get('lp_id')
            links = get_links_html(doc_ids)
            links_lp = get_links_html_lp(lp_ids)
            sources_output += f"\n[{index}] *{source_title}* ⚖️ {links_lp} | {links} 👉 Score: {node.score}\n"

        return sources_output, top_nodes

    except Exception as e:
        return f"Помилка при пошуку: {str(e)}", None


async def search_with_raw_text(input_text: str) -> Tuple[str, Optional[List[NodeWithScore]]]:
    """Пошук на основі вхідного тексту з вибором відповідного ретривера."""
    try:
        if not input_text:
            return "Помилка: Порожній текст для пошуку", None

        if not embed_model:
            return "Помилка: пошук недоступний без налаштованого embedding API ключа (OpenAI або Gemini)", None

        retriever = search_components.get_retriever()
        if not retriever:
            return "Помилка: компоненти пошуку не ініціалізовано", None

        # Вибір ретривера залежно від довжини тексту
        text_length = get_text_length_without_spaces(input_text)
        try:
            if text_length < 1024:
                nodes = await retriever.aretrieve(input_text)
            else:
                # Для довгих текстів використовуємо тільки BM25
                bm25_retriever = search_components.get_component('bm25_retriever')
                if not bm25_retriever:
                    return "Помилка: BM25 ретривер не ініціалізовано", None
                nodes = await bm25_retriever.aretrieve(input_text)

            if not nodes:
                return "Не знайдено відповідних правових позицій", None

            # Видалення дублікатів
            unique_nodes = deduplicate_nodes(nodes)

            # Обмеження кількості результатів
            top_nodes = unique_nodes[:Settings.similarity_top_k]

            if not top_nodes:
                return "Не знайдено унікальних правових позицій після дедуплікації", None

            sources_output = "\n **Результати пошуку (наявні правові позиції Верховного Суду):** \n\n"
            for index, node in enumerate(top_nodes, start=1):
                source_title = node.node.metadata.get('title', 'Невідомий заголовок')
                doc_ids = node.node.metadata.get('doc_id', '')
                lp_ids = node.node.metadata.get('lp_id', '')
                links = get_links_html(doc_ids)
                links_lp = get_links_html_lp(lp_ids)
                sources_output += f"\n[{index}] *{source_title}* ⚖️ {links_lp} | {links} 👉 Score: {node.score}\n"

            return sources_output, top_nodes

        except Exception as e:
            return f"Помилка під час виконання пошуку: {str(e)}", None

    except Exception as e:
        return f"Помилка при пошуку: {str(e)}", None

async def analyze_action(
        legal_position_json: Dict,
        question: str,
        nodes: List[NodeWithScore],
        provider: str,
        model_name: str,
        temperature: float = GENERATION_TEMPERATURE,
        max_tokens: Optional[int] = None
) -> str:
    """Analyze search results using AI."""
    try:
        workflow = PrecedentAnalysisWorkflow(
            provider=ModelProvider(provider),
            model_name=AnalysisModelName(model_name),
            temperature=temperature,
            max_tokens=max_tokens
        )

        query = (
            f"{legal_position_json['title']}: "
            f"{legal_position_json['text']}: "
            f"{legal_position_json['proceeding']}: "
            f"{legal_position_json['category']}"
        )

        response_text = await workflow.run(
            query=query,
            question=question,
            nodes=nodes
        )

        output = f"**Аналіз ШІ (модель: {model_name}):**\n{response_text}\n\n"
        output += "**Наявні в базі правові позицій Верховного Суду:**\n\n"

        analysis_lines = response_text.split('\n')
        for line in analysis_lines:
            if line.startswith('* ['):
                index = line[3:line.index(']')]
                node = nodes[int(index) - 1]
                source_node = node.node

                source_title = source_node.metadata.get('title', 'Невідомий заголовок')
                source_text_lp = node.text
                doc_ids = source_node.metadata.get('doc_id')
                lp_id = source_node.metadata.get('lp_id')

                links = get_links_html(doc_ids)
                links_lp = get_links_html_lp(lp_id)

                output += f"[{index}]: *{clean_text(source_title)}* | {clean_text(source_text_lp)} | {links_lp} | {links}\n\n"

        return output

    except Exception as e:
        return f"Помилка при аналізі: {str(e)}"


if __name__ == "__main__":
    try:
        # Check which providers are available
        available_providers = []
        if OPENAI_API_KEY:
            available_providers.append("OpenAI")
        if ANTHROPIC_API_KEY:
            available_providers.append("Anthropic")
        if os.getenv("GEMINI_API_KEY"):
            available_providers.append("Gemini")
        if DEEPSEEK_API_KEY:
            available_providers.append("DeepSeek")

        if not available_providers:
            print("Error: No AI provider API keys configured. Please set at least one of:",
                  file=sys.stderr)
            print("  - OPENAI_API_KEY", file=sys.stderr)
            print("  - ANTHROPIC_API_KEY", file=sys.stderr)
            print("  - GEMINI_API_KEY", file=sys.stderr)
            print("  - DEEPSEEK_API_KEY", file=sys.stderr)
            sys.exit(1)

        print(f"Available AI providers: {', '.join(available_providers)}")

        # Check embedding availability for search
        if not embed_model:
            print("Warning: No embedding model configured. Search functionality will be disabled.")
            print("  To enable search, set either OPENAI_API_KEY or GEMINI_API_KEY")
        elif GEMINI_API_KEY and not OPENAI_API_KEY:
            print("Info: Using Gemini embeddings for search (OpenAI not configured)")

        if not all([AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY]):
            print("Warning: AWS credentials not configured. Will use local files only.")

        # Initialize components
        if initialize_components():
            print("Components initialized successfully!")

            # Import create_gradio_interface here to avoid circular import
            from interface import create_gradio_interface

            # Create and launch the interface
            app = create_gradio_interface()
            app.launch(
                server_name="0.0.0.0",
                server_port=7860,
                share=True
            )
        else:
            print("Failed to initialize components. Please check the logs for details.",
                  file=sys.stderr)
            sys.exit(1)
    except ImportError as e:
        print(f"Error importing required modules: {str(e)}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"Error starting application: {str(e)}", file=sys.stderr)
        sys.exit(1)