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

هذا الملف يحتوي على الفئة الرئيسية لتطبيق المساعد الذكي مع دعم نموذج Claude AI.
"""

import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
import requests
import json
import time
import base64
import logging
import os
from datetime import datetime, timedelta
import io
import tempfile
import random
from io import BytesIO
from tempfile import NamedTemporaryFile
from PIL import Image
import arabic_reshaper
from bidi.algorithm import get_display
import matplotlib.font_manager as fm
import seaborn as sns

# تكوين الخطوط العربية
plt.rcParams['font.family'] = 'Arial'

# دالة مساعدة لعرض النص العربي بشكل صحيح
def get_display_arabic(text):
    """تحويل النص العربي للعرض الصحيح في الرسوم البيانية"""
    reshaped_text = arabic_reshaper.reshape(text)
    bidi_text = get_display(reshaped_text)
    return bidi_text

class ClaudeAIService:
    """
    فئة خدمة Claude AI للتحليل الذكي
    """
    def __init__(self):
        """تهيئة خدمة Claude AI"""
        self.api_url = "https://api.anthropic.com/v1/messages"
        
    def get_api_key(self):
        """الحصول على مفتاح API من متغيرات البيئة"""
        api_key = os.environ.get("anthropic")
        if not api_key:
            raise ValueError("مفتاح API لـ Claude غير موجود في متغيرات البيئة")
        return api_key
    
    def get_available_models(self):
        """
        الحصول على قائمة بالنماذج المتاحة
        
        العوائد:
            dict: قائمة بالنماذج مع وصفها
        """
        return {
            "claude-3-7-sonnet": "Claude 3.7 Sonnet - نموذج ذكي للمهام المتقدمة",
            "claude-3-5-haiku": "Claude 3.5 Haiku - أسرع نموذج للمهام اليومية"
        }
    
    def get_model_full_name(self, short_name):
        """
        تحويل الاسم المختصر للنموذج إلى الاسم الكامل
        
        المعلمات:
            short_name: الاسم المختصر للنموذج
            
        العوائد:
            str: الاسم الكامل للنموذج
        """
        valid_models = {
            "claude-3-7-sonnet": "claude-3-7-sonnet-20250219", 
            "claude-3-5-haiku": "claude-3-5-haiku-20240307"
        }
        
        return valid_models.get(short_name, short_name)
    
    def analyze_image(self, image_path, prompt, model_name="claude-3-7-sonnet"):
        """
        تحليل صورة باستخدام نموذج Claude AI
    
        المعلمات:
        image_path: مسار الصورة المراد تحليلها
        prompt: التوجيه للنموذج
        model_name: اسم نموذج Claude المراد استخدامه
    
        العوائد:
        dict: نتائج التحليل
        """
        try:
            # الحصول على مفتاح API
            api_key = self.get_api_key()
            
            # قراءة محتوى الملف مع ضغط الصور فقط
            file_size = os.path.getsize(image_path)
            _, ext = os.path.splitext(image_path)
            ext = ext.lower()

            if ext in ['.jpg', '.jpeg', '.png', '.gif', '.webp'] and file_size > 5 * 1024 * 1024:
                # فقط ضغط الصور العادية وليس ملفات PDF
                try:
                    with Image.open(image_path) as img:
                        # حفظ الصورة المضغوطة في ذاكرة مؤقتة
                        compressed_img_buffer = io.BytesIO()
                        
                        # حساب معامل الجودة المناسب
                        quality = min(95, int((5 * 1024 * 1024 / file_size) * 100))
                        
                        # حفظ الصورة بالجودة المحسوبة
                        img.save(compressed_img_buffer, format='JPEG', quality=quality)
                        compressed_img_buffer.seek(0)
                        
                        # استخدام البيانات المضغوطة
                        file_content = compressed_img_buffer.read()
                        logging.info(f"تم ضغط الصورة من {file_size/1024/1024:.2f} ميجابايت إلى {len(file_content)/1024/1024:.2f} ميجابايت")
                except Exception as e:
                    logging.error(f"خطأ أثناء ضغط الصورة: {str(e)}")
                    with open(image_path, 'rb') as f:
                        file_content = f.read()
            else:
                # استخدام الملف الأصلي للملفات غير الصور أو الصور الصغيرة
                with open(image_path, 'rb') as f:
                    file_content = f.read()

                # التحقق من حجم الملف بعد القراءة
                if len(file_content) > 5 * 1024 * 1024:
                    raise ValueError(f"حجم الملف ({len(file_content)/1024/1024:.2f} ميجابايت) يتجاوز الحد الأقصى (5 ميجابايت). يرجى تقليل حجم الملف قبل الرفع.")
            
            # تحويل المحتوى إلى Base64
            file_base64 = base64.b64encode(file_content).decode('utf-8')
            
            # تحديد نوع الملف من امتداده
            _, ext = os.path.splitext(image_path)
            ext = ext.lower()
            
            if ext in ('.jpg', '.jpeg'):
                file_type = "image/jpeg"
            elif ext == '.png':
                file_type = "image/png"
            elif ext == '.gif':
                file_type = "image/gif"
            elif ext == '.webp':
                file_type = "image/webp"
            else:
                file_type = "image/jpeg"  # افتراضي
            
            # التحقق من اسم النموذج وتصحيحه إذا لزم الأمر
            model_name = self.get_model_full_name(model_name)
            
            # إعداد البيانات للطلب
            headers = {
                "Content-Type": "application/json",
                "x-api-key": api_key,
                "anthropic-version": "2023-06-01"
            }
            
            payload = {
                "model": model_name,
                "max_tokens": 4096,
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                            {
                                "type": "image",
                                "source": {
                                    "type": "base64",
                                    "media_type": file_type,
                                    "data": file_base64
                                }
                            }
                        ]
                    }
                ]
            }
            
            # إرسال الطلب إلى API
            response = requests.post(
                self.api_url,
                headers=headers,
                json=payload,
                timeout=60
            )
            
            # التحقق من نجاح الطلب
            if response.status_code != 200:
                error_message = f"فشل طلب API: {response.status_code}"
                try:
                    error_details = response.json()
                    error_message += f"\nتفاصيل: {error_details}"
                except:
                    error_message += f"\nتفاصيل: {response.text}"
                
                return {"error": error_message}
            
            # معالجة الاستجابة
            result = response.json()
            
            return {
                "success": True,
                "content": result["content"][0]["text"],
                "model": result["model"],
                "usage": result.get("usage", {})
            }
            
        except Exception as e:
            logging.error(f"خطأ أثناء تحليل الصورة: {str(e)}")
            import traceback
            stack_trace = traceback.format_exc()
            return {"error": f"فشل في تحليل الصورة: {str(e)}\n{stack_trace}"}
    
    def chat_completion(self, messages, model_name="claude-3-7-sonnet"):
        """
        إكمال محادثة باستخدام نموذج Claude AI
        
        المعلمات:
            messages: سجل المحادثة
            model_name: اسم نموذج Claude المراد استخدامه
            
        العوائد:
            dict: نتائج الإكمال
        """
        try:
            # الحصول على مفتاح API
            api_key = self.get_api_key()
            
            # تحويل رسائل streamlit إلى تنسيق Claude API
            claude_messages = []
            for msg in messages:
                claude_messages.append({
                    "role": msg["role"],
                    "content": msg["content"]
                })
            
            # التحقق من اسم النموذج وتصحيحه إذا لزم الأمر
            model_name = self.get_model_full_name(model_name)
            
            # إعداد البيانات للطلب
            headers = {
                "Content-Type": "application/json",
                "x-api-key": api_key,
                "anthropic-version": "2023-06-01"
            }
            
            payload = {
                "model": model_name,
                "max_tokens": 2048,
                "messages": claude_messages,
                "temperature": 0.7
            }
            
            # إرسال الطلب إلى API
            response = requests.post(
                self.api_url,
                headers=headers,
                json=payload,
                timeout=30
            )
            
            # التحقق من نجاح الطلب
            if response.status_code != 200:
                error_message = f"فشل طلب API: {response.status_code}"
                try:
                    error_details = response.json()
                    error_message += f"\nتفاصيل: {error_details}"
                except:
                    error_message += f"\nتفاصيل: {response.text}"
                
                return {"error": error_message}
            
            # معالجة الاستجابة
            result = response.json()
            
            return {
                "success": True,
                "content": result["content"][0]["text"],
                "model": result["model"],
                "usage": result.get("usage", {})
            }
            
        except Exception as e:
            logging.error(f"خطأ أثناء إكمال المحادثة: {str(e)}")
            import traceback
            stack_trace = traceback.format_exc()
            return {"error": f"فشل في إكمال المحادثة: {str(e)}\n{stack_trace}"}

    def analyze_text(self, text, analysis_type="general", model_name="claude-3-5-haiku"):
        """
        تحليل النص باستخدام الذكاء الاصطناعي
        
        المعلمات:
            text: النص المراد تحليله
            analysis_type: نوع التحليل (general, requirements, risks, costs)
            model_name: اسم النموذج المستخدم
            
        العوائد:
            dict: نتائج التحليل
        """
        try:
            # تحديد التوجيه المناسب حسب نوع التحليل
            if analysis_type == "requirements":
                prompt = f"""
                قم بتحليل النص التالي واستخراج المتطلبات الرئيسية للمشروع. صنف المتطلبات إلى فئات (فنية، إدارية، مالية، قانونية) وحدد أولوية كل متطلب (عالية، متوسطة، منخفضة).
                
                النص:
                {text}
                
                قدم النتائج بتنسيق JSON يحتوي على مصفوفة من المتطلبات، كل متطلب يحتوي على: الوصف، الفئة، الأولوية.
                """
            elif analysis_type == "risks":
                prompt = f"""
                قم بتحليل النص التالي وتحديد المخاطر المحتملة للمشروع. لكل خطر، حدد احتمالية حدوثه (عالية، متوسطة، منخفضة) وتأثيره (عالي، متوسط، منخفض) واقترح استراتيجية للتخفيف من حدته.
                
                النص:
                {text}
                
                قدم النتائج بتنسيق JSON يحتوي على مصفوفة من المخاطر، كل خطر يحتوي على: الوصف، الاحتمالية، التأثير، استراتيجية التخفيف.
                """
            elif analysis_type == "costs":
                prompt = f"""
                قم بتحليل النص التالي وتحديد عناصر التكلفة المحتملة للمشروع. صنف التكاليف إلى فئات (مباشرة، غير مباشرة) وحدد ما إذا كانت ثابتة أو متغيرة.
                
                النص:
                {text}
                
                قدم النتائج بتنسيق JSON يحتوي على مصفوفة من عناصر التكلفة، كل عنصر يحتوي على: الوصف، الفئة، النوع (ثابت/متغير)، تقدير نسبي للتكلفة (%).
                """
            elif analysis_type == "local_content":
                prompt = f"""
                قم بتحليل النص التالي وتحديد عناصر المحتوى المحلي المحتملة. صنف العناصر إلى فئات (منتجات، خدمات، قوى عاملة) وحدد مدى توفرها محلياً (متوفر بشكل كامل، متوفر جزئياً، غير متوفر).
                
                النص:
                {text}
                
                قدم النتائج بتنسيق JSON يحتوي على مصفوفة من عناصر المحتوى المحلي، كل عنصر يحتوي على: الوصف، الفئة، مدى التوفر، تقدير نسبي للمساهمة في المحتوى المحلي (%).
                """
            else:  # general
                prompt = f"""
                قم بتحليل النص التالي وتلخيص النقاط الرئيسية. حدد الموضوعات الأساسية والأفكار المهمة والتوصيات إن وجدت.
                
                النص:
                {text}
                
                قدم النتائج بتنسيق JSON يحتوي على: ملخص عام، النقاط الرئيسية (مصفوفة)، التوصيات (مصفوفة).
                """
            
            # إنشاء رسائل المحادثة
            messages = [
                {"role": "user", "content": prompt}
            ]
            
            # استدعاء دالة إكمال المحادثة
            result = self.chat_completion(messages, model_name)
            
            # معالجة النتيجة
            if "error" in result:
                return result
            
            # محاولة تحويل النتيجة إلى JSON
            try:
                # استخراج النص من النتيجة
                content = result["content"]
                
                # البحث عن بداية ونهاية JSON
                json_start = content.find('{')
                json_end = content.rfind('}') + 1
                
                if json_start >= 0 and json_end > json_start:
                    json_str = content[json_start:json_end]
                    analysis_result = json.loads(json_str)
                    
                    return {
                        "success": True,
                        "result": analysis_result,
                        "model": result["model"]
                    }
                else:
                    # إذا لم يتم العثور على JSON، إرجاع النص كاملاً
                    return {
                        "success": True,
                        "result": {"text": content},
                        "model": result["model"]
                    }
            except Exception as e:
                # إذا فشل تحويل النتيجة إلى JSON، إرجاع النص كاملاً
                return {
                    "success": True,
                    "result": {"text": content},
                    "model": result["model"],
                    "parse_error": str(e)
                }
            
        except Exception as e:
            logging.error(f"خطأ أثناء تحليل النص: {str(e)}")
            import traceback
            stack_trace = traceback.format_exc()
            return {"error": f"فشل في تحليل النص: {str(e)}\n{stack_trace}"}


class AIAssistantApp:
    """وحدة المساعد الذكي"""
    
    def __init__(self):
        """تهيئة وحدة المساعد الذكي"""
        # التحقق من توفر مكتبة pdf2image
        try:
            from pdf2image import convert_from_path
            pdf_conversion_available = True
            self.pdf_conversion_available = True
            self.convert_from_path = convert_from_path
        except ImportError:
            pdf_conversion_available = False
            self.pdf_conversion_available = False
            
        # تحميل النماذج عند بدء التشغيل
        self.cost_model = self._load_cost_prediction_model()
        self.document_model = self._load_document_classifier_model()
        self.risk_model = self._load_risk_assessment_model()
        self.local_content_model = self._load_local_content_model()
        self.entity_model = self._load_entity_recognition_model()
        
        # إنشاء خدمة Claude AI
        self.claude_service = ClaudeAIService()
        
        # تهيئة قائمة الأسئلة والإجابات الشائعة
        self.faqs = [
            {
                "question": "كيف يمكنني إضافة مشروع جديد؟",
                "answer": "يمكنك إضافة مشروع جديد من خلال الانتقال إلى وحدة إدارة المشاريع، ثم النقر على زر 'إضافة مشروع جديد'، وملء النموذج بالبيانات المطلوبة."
            },
            {
                "question": "ما هي خطوات تسعير المناقصة؟",
                "answer": "تتضمن خطوات تسعير المناقصة: 1) تحليل مستندات المناقصة، 2) تحديد بنود العمل، 3) تقدير التكاليف المباشرة، 4) إضافة المصاريف العامة والأرباح، 5) احتساب المحتوى المحلي، 6) مراجعة النتائج النهائية."
            },
            {
                "question": "كيف يتم حساب المحتوى المحلي؟",
                "answer": "يتم حساب المحتوى المحلي بتحديد نسبة المنتجات والخدمات والقوى العاملة المحلية من إجمالي التكاليف. يتم استخدام قاعدة بيانات الموردين المعتمدين وتطبيق معادلات خاصة حسب متطلبات هيئة المحتوى المحلي."
            },
            {
                "question": "كيف يمكنني تصدير التقارير؟",
                "answer": "يمكنك تصدير التقارير من وحدة التقارير والتحليلات، حيث يوجد زر 'تصدير' في كل تقرير. يمكن تصدير التقارير بتنسيقات مختلفة مثل Excel و PDF و CSV."
            },
            {
                "question": "كيف يمكنني تقييم المخاطر للمشروع؟",
                "answer": "يمكنك تقييم المخاطر للمشروع من خلال وحدة المخاطر، حيث يمكنك إضافة المخاطر المحتملة وتقييم تأثيرها واحتماليتها، ثم وضع خطة الاستجابة المناسبة."
            },
            {
                "question": "ما هي طرق التسعير المتاحة في النظام؟",
                "answer": "يوفر النظام أربع طرق للتسعير: 1) التسعير القياسي، 2) التسعير غير المتزن، 3) التسعير التنافسي، 4) التسعير الموجه بالربحية. يمكنك اختيار الطريقة المناسبة حسب طبيعة المشروع واستراتيجية الشركة."
            },
            {
                "question": "كيف يمكنني معالجة مستندات المناقصة ضخمة الحجم؟",
                "answer": "يمكنك استخدام وحدة تحليل المستندات لمعالجة مستندات المناقصة ضخمة الحجم، حيث تقوم الوحدة بتحليل المستندات واستخراج المعلومات المهمة مثل مواصفات المشروع ومتطلباته وشروطه تلقائياً."
            }
        ]
    
    def _load_cost_prediction_model(self):
        """تحميل نموذج التنبؤ بالتكاليف"""
        # في البيئة الإنتاجية، سيتم تحميل نموذج حقيقي
        # هنا نقوم بإنشاء كائن محاكاة للنموذج
        return {"name": "cost_prediction_model", "version": "1.0.0", "status": "loaded"}
        
    def _load_document_classifier_model(self):
        """تحميل نموذج تصنيف المستندات"""
        return {"name": "document_classifier_model", "version": "1.0.0", "status": "loaded"}
        
    def _load_risk_assessment_model(self):
        """تحميل نموذج تقييم المخاطر"""
        return {"name": "risk_assessment_model", "version": "1.0.0", "status": "loaded"}
        
    def _load_local_content_model(self):
        """تحميل نموذج تحليل المحتوى المحلي"""
        return {"name": "local_content_model", "version": "1.0.0", "status": "loaded"}
        
    def _load_entity_recognition_model(self):
        """تحميل نموذج التعرف على الكيانات"""
        return {"name": "entity_recognition_model", "version": "1.0.0", "status": "loaded"}
    
    def render(self):
        """عرض واجهة وحدة المساعد الذكي"""
        
        st.markdown("<h1 class='module-title'>وحدة المساعد الذكي</h1>", unsafe_allow_html=True)
        
        tabs = st.tabs([
            "المساعد الذكي",
            "التنبؤ بالتكاليف",
            "تحليل المخاطر",
            "تحليل المستندات",
            "المحتوى المحلي",
            "الأسئلة الشائعة"
        ])
        
        with tabs[0]:
            self._render_ai_assistant_tab()
        
        with tabs[1]:
            self._render_cost_prediction_tab()
        
        with tabs[2]:
            self._render_risk_analysis_tab()
        
        with tabs[3]:
            self._render_document_analysis_tab()
        
        with tabs[4]:
            self._render_local_content_tab()
        
        with tabs[5]:
            self._render_faq_tab()
    
    def _render_ai_assistant_tab(self):
        """عرض تبويب المساعد الذكي مع دعم Claude AI"""
        
        st.markdown("### المساعد الذكي لتسعير المناقصات")
        
        # اختيار نموذج Claude
        claude_models = self.claude_service.get_available_models()
        
        selected_model = st.radio(
            "اختر نموذج الذكاء الاصطناعي",
            options=list(claude_models.keys()),
            format_func=lambda x: claude_models[x],
            horizontal=True,
            key="assistant_ai_model"
        )
        
        # عرض واجهة المحادثة
        st.markdown("""
        <div class="chat-container">
            <div class="chat-header">
                <h4>المساعد الذكي</h4>
                <p>تحدث مع المساعد الذكي للحصول على المساعدة في تسعير المناقصات وتحليل البيانات</p>
            </div>
        </div>
        """, unsafe_allow_html=True)
        
        # تهيئة محفوظات المحادثة في حالة الجلسة إذا لم تكن موجودة
        if 'ai_assistant_messages' not in st.session_state:
            st.session_state.ai_assistant_messages = [
                {"role": "assistant", "content": "مرحباً! أنا المساعد الذكي لنظام تسعير المناقصات. كيف يمكنني مساعدتك اليوم؟"}
            ]
        
        # عرض محفوظات المحادثة بتنسيق محسن
        chat_container = st.container()
        with chat_container:
            st.markdown("""
            <style>
            .chat-container {
                max-width: 800px;
                margin: 0 auto;
                padding: 20px;
            }
            .message {
                display: flex;
                margin-bottom: 20px;
                align-items: flex-start;
            }
            .user-message {
                justify-content: flex-end;
            }
            .assistant-message {
                justify-content: flex-start;
            }
            .avatar {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: bold;
                color: white;
                margin: 0 10px;
            }
            .user-avatar {
                background-color: #2196F3;
            }
            .assistant-avatar {
                background-color: #4CAF50;
            }
            .message-content {
                padding: 15px;
                border-radius: 15px;
                max-width: 70%;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            }
            .user-content {
                background-color: #E3F2FD;
                border-top-right-radius: 5px;
            }
            .assistant-content {
                background-color: #F5F5F5;
                border-top-left-radius: 5px;
            }
            .message-time {
                font-size: 0.8em;
                color: #757575;
                margin-top: 5px;
                text-align: right;
            }
            </style>
            """, unsafe_allow_html=True)

            for message in st.session_state.ai_assistant_messages:
                if message["role"] == "user":
                    st.markdown(f"""
                    <div class="message user-message">
                        <div class="message-content user-content">
                            {message["content"]}
                            <div class="message-time">أنت • الآن</div>
                        </div>
                        <div class="avatar user-avatar">أ</div>
                    </div>
                    """, unsafe_allow_html=True)
                else:
                    st.markdown(f"""
                    <div class="message assistant-message">
                        <div class="avatar assistant-avatar">م</div>
                        <div class="message-content assistant-content">
                            {message["content"]}
                            <div class="message-time">المساعد • الآن</div>
                        </div>
                    </div>
                    """, unsafe_allow_html=True)
        
        # إضافة خيار رفع الملفات
        uploaded_file = st.file_uploader(
            "اختياري: ارفع ملفًا للمساعدة (صورة، PDF)",
            type=["jpg", "jpeg", "png", "pdf"],
            key="assistant_file_upload"
        )
        
        # مربع إدخال الرسالة
        user_input = st.text_input("اكتب رسالتك هنا", key="ai_assistant_input")
        
        # زر إرسال مع تحليل ذكي
        col1, col2 = st.columns([3, 1])
        with col1:
            send_button = st.button("إرسال", key="send_message_button")
        with col2:
            analyze_options = st.selectbox(
                "تحليل ذكي",
                ["عام", "متطلبات", "مخاطر", "تكاليف", "محتوى محلي"],
                key="analyze_type"
            )
        
        # معالجة الإدخال
        if send_button and user_input:
            # إضافة رسالة المستخدم إلى المحادثة
            st.session_state.ai_assistant_messages.append(
                {"role": "user", "content": user_input}
            )
            
            # تحديد نوع التحليل
            analysis_type_map = {
                "عام": "general",
                "متطلبات": "requirements",
                "مخاطر": "risks",
                "تكاليف": "costs",
                "محتوى محلي": "local_content"
            }
            
            analysis_type = analysis_type_map.get(analyze_options, "general")
            
            # إظهار مؤشر التحميل
            with st.spinner("جاري التحليل..."):
                # تحليل النص باستخدام الذكاء الاصطناعي
                result = self.claude_service.analyze_text(user_input, analysis_type, selected_model)
                
                # إعداد الرد
                if "error" in result:
                    response = f"عذراً، حدث خطأ أثناء التحليل: {result['error']}"
                else:
                    # تنسيق النتيجة بشكل مقروء
                    if isinstance(result["result"], dict):
                        if "text" in result["result"]:
                            # إذا كانت النتيجة نصية
                            response = result["result"]["text"]
                        else:
                            # إذا كانت النتيجة هيكلية
                            response = "نتائج التحليل:\n\n"
                            for key, value in result["result"].items():
                                if isinstance(value, list):
                                    response += f"**{key}**:\n"
                                    for i, item in enumerate(value):
                                        if isinstance(item, dict):
                                            response += f"{i+1}. "
                                            for k, v in item.items():
                                                response += f"**{k}**: {v}, "
                                            response = response[:-2] + "\n"
                                        else:
                                            response += f"{i+1}. {item}\n"
                                else:
                                    response += f"**{key}**: {value}\n"
                    else:
                        response = str(result["result"])
            
            # إضافة رد المساعد إلى المحادثة
            st.session_state.ai_assistant_messages.append(
                {"role": "assistant", "content": response}
            )
            
            # إعادة تحميل الصفحة لعرض الرد
            st.experimental_rerun()
        
        # التحقق من وجود مفتاح API
        api_available = True
        try:
            self.claude_service.get_api_key()
        except ValueError:
            api_available = False
            st.warning("مفتاح API لـ Claude غير متوفر. يرجى إضافته في إعدادات النظام.")
    
    def _render_cost_prediction_tab(self):
        """عرض تبويب التنبؤ بالتكاليف"""
        st.markdown("### التنبؤ بالتكاليف")
        
        st.info("هذه الوحدة تساعدك في تقدير تكاليف المشاريع بناءً على بيانات المناقصات السابقة ومعايير التسعير المعتمدة.")
        
        # إنشاء نموذج إدخال البيانات
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("معلومات المشروع")
            project_type = st.selectbox(
                "نوع المشروع",
                ["مشروع إنشائي", "مشروع تقنية معلومات", "مشروع استشاري", "مشروع توريد", "أخرى"]
            )
            
            project_duration = st.number_input(
                "مدة المشروع (بالأشهر)",
                min_value=1,
                max_value=60,
                value=12
            )
            
            project_location = st.selectbox(
                "موقع المشروع",
                ["الرياض", "جدة", "الدمام", "مكة المكرمة", "المدينة المنورة", "أخرى"]
            )
        
        with col2:
            st.subheader("معايير التكلفة")
            
            direct_cost = st.number_input(
                "التكاليف المباشرة المقدرة (ريال)",
                min_value=0,
                value=1000000
            )
            
            overhead_percentage = st.slider(
                "نسبة المصاريف العامة (%)",
                min_value=5,
                max_value=30,
                value=15
            )
            
            profit_percentage = st.slider(
                "نسبة الربح المستهدفة (%)",
                min_value=5,
                max_value=30,
                value=20
            )
        
        # زر حساب التكلفة
        col1, col2 = st.columns([3, 1])
        with col1:
            calculate_button = st.button("حساب التكلفة التقديرية")
        with col2:
            ai_analysis = st.checkbox("تحليل ذكي", value=True)
        
        if calculate_button:
            # حساب التكلفة (هذا مثال بسيط)
            overhead_cost = direct_cost * (overhead_percentage / 100)
            profit = direct_cost * (profit_percentage / 100)
            total_cost = direct_cost + overhead_cost + profit
            
            # عرض النتائج
            st.success("تم حساب التكلفة التقديرية بنجاح!")
            
            col1, col2, col3 = st.columns(3)
            
            with col1:
                st.metric("التكاليف المباشرة", f"{direct_cost:,.2f} ريال")
            
            with col2:
                st.metric("المصاريف العامة", f"{overhead_cost:,.2f} ريال")
            
            with col3:
                st.metric("الربح المتوقع", f"{profit:,.2f} ريال")
            
            st.metric("إجمالي التكلفة التقديرية", f"{total_cost:,.2f} ريال", delta="تقدير أولي")
            
            # عرض رسم بياني للتكاليف
            fig = go.Figure()
            
            # إضافة البيانات
            labels = ["التكاليف المباشرة", "المصاريف العامة", "الربح المتوقع"]
            values = [direct_cost, overhead_cost, profit]
            colors = ['#1f77b4', '#ff7f0e', '#2ca02c']
            
            fig.add_trace(go.Pie(
                labels=[get_display_arabic(label) for label in labels],
                values=values,
                textinfo='percent+label',
                insidetextorientation='radial',
                marker=dict(colors=colors),
                hole=0.4
            ))
            
            # تخصيص الرسم البياني
            fig.update_layout(
                title=get_display_arabic("توزيع التكاليف"),
                height=400,
                margin=dict(l=0, r=0, t=40, b=0),
                font=dict(size=14),
                legend=dict(
                    orientation="h",
                    yanchor="bottom",
                    y=-0.2,
                    xanchor="center",
                    x=0.5
                )
            )
            
            st.plotly_chart(fig, use_container_width=True)
            
            # تحليل ذكي للتكاليف إذا تم تحديد الخيار
            if ai_analysis:
                with st.spinner("جاري تحليل التكاليف باستخدام الذكاء الاصطناعي..."):
                    # إنشاء نص وصفي للمشروع
                    project_description = f"""
                    نوع المشروع: {project_type}
                    مدة المشروع: {project_duration} أشهر
                    موقع المشروع: {project_location}
                    التكاليف المباشرة: {direct_cost:,.2f} ريال
                    نسبة المصاريف العامة: {overhead_percentage}%
                    نسبة الربح المستهدفة: {profit_percentage}%
                    إجمالي التكلفة التقديرية: {total_cost:,.2f} ريال
                    """
                    
                    # تحليل النص باستخدام الذكاء الاصطناعي
                    result = self.claude_service.analyze_text(project_description, "costs")
                    
                    if "error" not in result:
                        st.subheader("تحليل التكاليف بالذكاء الاصطناعي")
                        
                        # عرض نتائج التحليل
                        if isinstance(result["result"], dict) and "text" not in result["result"]:
                            # إذا كانت النتيجة هيكلية
                            if "عناصر التكلفة" in result["result"]:
                                cost_items = result["result"]["عناصر التكلفة"]
                                
                                # إنشاء جدول لعناصر التكلفة
                                cost_data = []
                                for item in cost_items:
                                    if isinstance(item, dict):
                                        cost_data.append({
                                            "الوصف": item.get("الوصف", ""),
                                            "الفئة": item.get("الفئة", ""),
                                            "النوع": item.get("النوع", ""),
                                            "التقدير النسبي": item.get("تقدير نسبي للتكلفة", "")
                                        })
                                
                                if cost_data:
                                    cost_df = pd.DataFrame(cost_data)
                                    st.dataframe(cost_df, use_container_width=True)
                        else:
                            # إذا كانت النتيجة نصية
                            st.write(result["result"].get("text", "لا توجد نتائج تحليل"))
    
    def _render_risk_analysis_tab(self):
        """عرض تبويب تحليل المخاطر"""
        st.markdown("### تحليل المخاطر")
        
        st.info("هذه الوحدة تساعدك في تحديد وتقييم المخاطر المحتملة للمشروع ووضع خطط الاستجابة المناسبة.")
        
        # إنشاء جدول المخاطر
        st.subheader("سجل المخاطر")
        
        # بيانات نموذجية للمخاطر
        risk_data = {
            "المخاطر": [
                "تأخر توريد المواد",
                "تغيير متطلبات المشروع",
                "نقص العمالة الماهرة",
                "مشاكل فنية غير متوقعة",
                "تغيرات في الأنظمة واللوائح"
            ],
            "الاحتمالية": [
                "متوسطة",
                "عالية",
                "منخفضة",
                "متوسطة",
                "منخفضة"
            ],
            "التأثير": [
                "عالي",
                "عالي",
                "متوسط",
                "عالي",
                "عالي"
            ],
            "درجة الخطورة": [
                "عالية",
                "عالية",
                "متوسطة",
                "عالية",
                "متوسطة"
            ],
            "خطة الاستجابة": [
                "التعاقد مع موردين بدلاء",
                "توثيق المتطلبات وإدارة التغيير",
                "التعاقد المبكر مع فرق العمل",
                "إجراء اختبارات مبكرة",
                "متابعة التحديثات التنظيمية"
            ]
        }
        
        risk_df = pd.DataFrame(risk_data)
        st.dataframe(risk_df, use_container_width=True)
        
        # إضافة مخاطر جديدة
        st.subheader("إضافة مخاطر جديدة")
        
        col1, col2 = st.columns(2)
        
        with col1:
            new_risk = st.text_input("وصف المخاطرة")
            probability = st.selectbox(
                "احتمالية الحدوث",
                ["منخفضة", "متوسطة", "عالية"]
            )
        
        with col2:
            impact = st.selectbox(
                "التأثير",
                ["منخفض", "متوسط", "عالي"]
            )
            response_plan = st.text_area("خطة الاستجابة")
        
        col1, col2 = st.columns([3, 1])
        with col1:
            add_button = st.button("إضافة المخاطرة")
        with col2:
            ai_suggestion = st.checkbox("اقتراح ذكي", value=True)
        
        if ai_suggestion and new_risk:
            with st.spinner("جاري تحليل المخاطرة باستخدام الذكاء الاصطناعي..."):
                # تحليل المخاطرة باستخدام الذكاء الاصطناعي
                risk_description = f"المخاطرة: {new_risk}"
                result = self.claude_service.analyze_text(risk_description, "risks")
                
                if "error" not in result and isinstance(result["result"], dict):
                    if "المخاطر" in result["result"] and isinstance(result["result"]["المخاطر"], list):
                        risk_analysis = result["result"]["المخاطر"][0]
                        
                        if isinstance(risk_analysis, dict):
                            st.success("تم تحليل المخاطرة بنجاح!")
                            
                            # عرض نتائج التحليل
                            col1, col2 = st.columns(2)
                            with col1:
                                st.write("**الاحتمالية المقترحة:**", risk_analysis.get("الاحتمالية", "غير محدد"))
                                st.write("**التأثير المقترح:**", risk_analysis.get("التأثير", "غير محدد"))
                            with col2:
                                st.write("**استراتيجية التخفيف المقترحة:**", risk_analysis.get("استراتيجية التخفيف", "غير محدد"))
        
        if add_button and new_risk:
            st.success("تمت إضافة المخاطرة بنجاح!")
        
        # عرض مصفوفة المخاطر
        st.subheader("مصفوفة المخاطر")
        
        # بيانات مصفوفة المخاطر
        risk_matrix = np.array([
            [1, 2, 3],
            [2, 4, 6],
            [3, 6, 9]
        ])
        
        # إنشاء مصفوفة المخاطر باستخدام Plotly
        fig = go.Figure()
        
        # تحديد الألوان
        colorscale = [
            [0, '#1a9850'],      # أخضر داكن (مخاطر منخفضة)
            [0.3, '#91cf60'],    # أخضر فاتح
            [0.5, '#ffffbf'],    # أصفر
            [0.7, '#fc8d59'],    # برتقالي
            [1, '#d73027']       # أحمر (مخاطر عالية)
        ]
        
        # إنشاء مصفوفة المخاطر
        fig.add_trace(go.Heatmap(
            z=risk_matrix,
            x=['منخفض', 'متوسط', 'عالي'],
            y=['منخفضة', 'متوسطة', 'عالية'],
            text=risk_matrix,
            texttemplate="%{text}",
            textfont={"size":20},
            colorscale=colorscale,
            showscale=True,
            colorbar=dict(
                title=get_display_arabic("درجة الخطورة"),
                titleside="right",
                titlefont=dict(size=14),
                tickfont=dict(size=12),
            )
        ))
        
        # تخصيص الرسم البياني
        fig.update_layout(
            title=get_display_arabic("مصفوفة المخاطر"),
            height=500,
            margin=dict(l=50, r=50, t=50, b=50),
            xaxis=dict(
                title=get_display_arabic("التأثير"),
                titlefont=dict(size=14),
                tickfont=dict(size=12),
            ),
            yaxis=dict(
                title=get_display_arabic("الاحتمالية"),
                titlefont=dict(size=14),
                tickfont=dict(size=12),
            ),
            font=dict(size=14)
        )
        
        # عرض الرسم البياني
        st.plotly_chart(fig, use_container_width=True)
        
        # تحليل المخاطر باستخدام الذكاء الاصطناعي
        st.subheader("تحليل المخاطر بالذكاء الاصطناعي")
        
        risk_text = st.text_area("أدخل وصف المشروع لتحليل المخاطر المحتملة", height=150)
        
        if st.button("تحليل المخاطر"):
            if risk_text:
                with st.spinner("جاري تحليل المخاطر باستخدام الذكاء الاصطناعي..."):
                    # تحليل النص باستخدام الذكاء الاصطناعي
                    result = self.claude_service.analyze_text(risk_text, "risks")
                    
                    if "error" not in result:
                        st.success("تم تحليل المخاطر بنجاح!")
                        
                        # عرض نتائج التحليل
                        if isinstance(result["result"], dict) and "المخاطر" in result["result"]:
                            risks = result["result"]["المخاطر"]
                            
                            # إنشاء جدول للمخاطر
                            risk_data = []
                            for risk in risks:
                                if isinstance(risk, dict):
                                    risk_data.append({
                                        "المخاطر": risk.get("الوصف", ""),
                                        "الاحتمالية": risk.get("الاحتمالية", ""),
                                        "التأثير": risk.get("التأثير", ""),
                                        "خطة الاستجابة": risk.get("استراتيجية التخفيف", "")
                                    })
                            
                            if risk_data:
                                risk_df = pd.DataFrame(risk_data)
                                st.dataframe(risk_df, use_container_width=True)
                        else:
                            # إذا كانت النتيجة نصية
                            st.write(result["result"].get("text", "لا توجد نتائج تحليل"))
                    else:
                        st.error(f"حدث خطأ أثناء التحليل: {result['error']}")
            else:
                st.warning("يرجى إدخال وصف المشروع لتحليل المخاطر.")
    
    def _render_document_analysis_tab(self):
        """عرض تبويب تحليل المستندات"""
        st.markdown("### تحليل المستندات")
        
        st.info("هذه الوحدة تساعدك في تحليل مستندات المناقصات واستخراج المعلومات المهمة منها.")
        
        # رفع المستندات
        uploaded_file = st.file_uploader(
            "ارفع مستند المناقصة (PDF, DOCX, XLSX)",
            type=["pdf", "docx", "xlsx"],
            key="document_analysis_upload"
        )
        
        if uploaded_file is not None:
            # عرض معلومات الملف
            file_details = {
                "اسم الملف": uploaded_file.name,
                "نوع الملف": uploaded_file.type,
                "حجم الملف": f"{uploaded_file.size / 1024:.2f} كيلوبايت"
            }
            
            st.json(file_details)
            
            # خيارات التحليل
            analysis_options = st.multiselect(
                "اختر أنواع التحليل",
                [
                    "استخراج المتطلبات",
                    "تحديد المواعيد النهائية",
                    "تحليل الشروط والأحكام",
                    "استخراج جداول الكميات",
                    "تحديد المعايير الفنية"
                ],
                default=["استخراج المتطلبات", "تحديد المواعيد النهائية"]
            )
            
            col1, col2 = st.columns([3, 1])
            with col1:
                analyze_button = st.button("تحليل المستند")
            with col2:
                ai_analysis = st.checkbox("تحليل ذكي", value=True)
            
            if analyze_button:
                # عرض شريط التقدم
                progress_bar = st.progress(0)
                status_text = st.empty()
                
                # محاكاة عملية التحليل
                for i in range(101):
                    progress_bar.progress(i)
                    if i < 30:
                        status_text.text("جاري معالجة المستند...")
                    elif i < 60:
                        status_text.text("جاري استخراج النصوص...")
                    elif i < 90:
                        status_text.text("جاري تحليل المحتوى...")
                    else:
                        status_text.text("جاري إعداد النتائج...")
                    time.sleep(0.02)
                
                st.success("تم تحليل المستند بنجاح!")
                
                # عرض نتائج التحليل
                st.subheader("نتائج التحليل")
                
                # بيانات نموذجية للنتائج
                if "استخراج المتطلبات" in analysis_options:
                    st.write("#### المتطلبات الرئيسية")
                    requirements = [
                        "توفير فريق عمل مؤهل لا يقل عن 10 أفراد",
                        "خبرة سابقة في مشاريع مماثلة لا تقل عن 5 سنوات",
                        "شهادة ISO 9001 للجودة",
                        "تقديم ضمان بنكي بنسبة 5% من قيمة العقد",
                        "الالتزام بمعايير السلامة المهنية"
                    ]
                    for req in requirements:
                        st.markdown(f"- {req}")
                
                if "تحديد المواعيد النهائية" in analysis_options:
                    st.write("#### المواعيد النهائية")
                    deadlines = {
                        "تقديم العروض": "15/05/2025",
                        "بدء المشروع": "01/06/2025",
                        "المرحلة الأولى": "01/08/2025",
                        "المرحلة الثانية": "01/10/2025",
                        "تسليم المشروع": "31/12/2025"
                    }
                    deadline_df = pd.DataFrame(list(deadlines.items()), columns=["المرحلة", "التاريخ"])
                    st.dataframe(deadline_df, use_container_width=True)
                
                if "تحليل الشروط والأحكام" in analysis_options:
                    st.write("#### الشروط والأحكام الهامة")
                    terms = [
                        "غرامة التأخير: 1% من قيمة العقد عن كل أسبوع تأخير",
                        "مدة الضمان: سنتان من تاريخ الاستلام النهائي",
                        "شروط الدفع: 20% دفعة مقدمة، 60% على مراحل، 20% بعد الاستلام النهائي",
                        "التحكيم: وفقاً لأنظمة المملكة العربية السعودية",
                        "التأمين: يجب توفير تأمين شامل للمشروع"
                    ]
                    for term in terms:
                        st.markdown(f"- {term}")
                
                # تحليل ذكي للمستند إذا تم تحديد الخيار
                if ai_analysis:
                    st.subheader("تحليل المستند بالذكاء الاصطناعي")
                    
                    # محاكاة تحليل المستند
                    with st.spinner("جاري تحليل المستند باستخدام الذكاء الاصطناعي..."):
                        # محاكاة نص المستند
                        document_text = """
                        مناقصة رقم: 2025/123
                        
                        المشروع: تطوير نظام إدارة المشاريع
                        
                        المتطلبات الفنية:
                        1. تطوير نظام متكامل لإدارة المشاريع
                        2. توفير واجهة مستخدم سهلة الاستخدام
                        3. دعم اللغة العربية والإنجليزية
                        4. توفير تقارير تحليلية متقدمة
                        5. دعم الأجهزة المحمولة
                        
                        المواعيد:
                        - آخر موعد لتقديم العروض: 15/05/2025
                        - بدء المشروع: 01/06/2025
                        - تسليم المرحلة الأولى: 01/08/2025
                        - تسليم المرحلة الثانية: 01/10/2025
                        - التسليم النهائي: 31/12/2025
                        
                        الشروط والأحكام:
                        - مدة العقد: 12 شهر
                        - غرامة التأخير: 1% من قيمة العقد عن كل أسبوع تأخير
                        - شروط الدفع: 20% دفعة مقدمة، 60% على مراحل، 20% بعد الاستلام النهائي
                        - الضمان: سنتان من تاريخ الاستلام النهائي
                        """
                        
                        # تحليل النص باستخدام الذكاء الاصطناعي
                        result = self.claude_service.analyze_text(document_text, "requirements")
                        
                        if "error" not in result:
                            # عرض نتائج التحليل
                            if isinstance(result["result"], dict) and "المتطلبات" in result["result"]:
                                requirements = result["result"]["المتطلبات"]
                                
                                # إنشاء جدول للمتطلبات
                                req_data = []
                                for req in requirements:
                                    if isinstance(req, dict):
                                        req_data.append({
                                            "الوصف": req.get("الوصف", ""),
                                            "الفئة": req.get("الفئة", ""),
                                            "الأولوية": req.get("الأولوية", "")
                                        })
                                
                                if req_data:
                                    req_df = pd.DataFrame(req_data)
                                    st.dataframe(req_df, use_container_width=True)
                            else:
                                # إذا كانت النتيجة نصية
                                st.write(result["result"].get("text", "لا توجد نتائج تحليل"))
                        else:
                            st.error(f"حدث خطأ أثناء التحليل: {result['error']}")
    
    def _render_local_content_tab(self):
        """عرض تبويب المحتوى المحلي"""
        st.markdown("### تحليل المحتوى المحلي")
        
        st.info("هذه الوحدة تساعدك في حساب وتحسين نسبة المحتوى المحلي في المشاريع وفقاً لمتطلبات هيئة المحتوى المحلي.")
        
        # إنشاء نموذج إدخال البيانات
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("بيانات المشروع")
            project_value = st.number_input(
                "القيمة الإجمالية للمشروع (ريال)",
                min_value=0,
                value=5000000
            )
            
            project_sector = st.selectbox(
                "قطاع المشروع",
                ["البناء والتشييد", "تقنية المعلومات", "الطاقة", "النقل", "الصحة", "أخرى"]
            )
        
        with col2:
            st.subheader("بيانات المحتوى المحلي")
            
            local_products = st.number_input(
                "قيمة المنتجات المحلية (ريال)",
                min_value=0,
                value=2000000
            )
            
            local_services = st.number_input(
                "قيمة الخدمات المحلية (ريال)",
                min_value=0,
                value=1000000
            )
            
            local_workforce = st.number_input(
                "تكلفة القوى العاملة المحلية (ريال)",
                min_value=0,
                value=1500000
            )
        
        # زر حساب المحتوى المحلي
        col1, col2 = st.columns([3, 1])
        with col1:
            calculate_button = st.button("حساب نسبة المحتوى المحلي")
        with col2:
            ai_optimization = st.checkbox("تحسين ذكي", value=True)
        
        if calculate_button:
            # حساب نسبة المحتوى المحلي
            total_local_content = local_products + local_services + local_workforce
            local_content_percentage = (total_local_content / project_value) * 100
            
            # عرض النتائج
            st.success("تم حساب نسبة المحتوى المحلي بنجاح!")
            
            col1, col2 = st.columns(2)
            
            with col1:
                st.metric("إجمالي المحتوى المحلي", f"{total_local_content:,.2f} ريال")
                st.metric("نسبة المحتوى المحلي", f"{local_content_percentage:.2f}%")
                
                # تقييم النسبة
                if local_content_percentage >= 70:
                    st.success("ممتاز! نسبة المحتوى المحلي تتجاوز المتطلبات.")
                elif local_content_percentage >= 50:
                    st.info("جيد. نسبة المحتوى المحلي تلبي الحد الأدنى من المتطلبات.")
                else:
                    st.warning("تحذير: نسبة المحتوى المحلي أقل من المتطلبات. يرجى العمل على تحسينها.")
            
            with col2:
                # عرض رسم بياني للمحتوى المحلي
                fig = go.Figure()
                
                # إضافة البيانات
                labels = ["المنتجات المحلية", "الخدمات المحلية", "القوى العاملة المحلية", "غير محلي"]
                values = [local_products, local_services, local_workforce, project_value - total_local_content]
                colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
                
                fig.add_trace(go.Pie(
                    labels=[get_display_arabic(label) for label in labels],
                    values=values,
                    textinfo='percent',
                    insidetextorientation='radial',
                    marker=dict(colors=colors),
                    hole=0.4
                ))
                
                # تخصيص الرسم البياني
                fig.update_layout(
                    title=get_display_arabic("توزيع المحتوى المحلي"),
                    height=400,
                    margin=dict(l=0, r=0, t=40, b=0),
                    font=dict(size=14),
                    legend=dict(
                        orientation="h",
                        yanchor="bottom",
                        y=-0.2,
                        xanchor="center",
                        x=0.5
                    )
                )
                
                st.plotly_chart(fig, use_container_width=True)
            
            # عرض تفاصيل المحتوى المحلي
            st.subheader("تفاصيل المحتوى المحلي")
            
            # إنشاء جدول البيانات
            local_content_data = {
                "العنصر": ["المنتجات المحلية", "الخدمات المحلية", "القوى العاملة المحلية", "إجمالي المحتوى المحلي", "غير محلي", "إجمالي المشروع"],
                "القيمة (ريال)": [local_products, local_services, local_workforce, total_local_content, project_value - total_local_content, project_value],
                "النسبة (%)": [
                    local_products / project_value * 100,
                    local_services / project_value * 100,
                    local_workforce / project_value * 100,
                    local_content_percentage,
                    (project_value - total_local_content) / project_value * 100,
                    100
                ]
            }
            
            local_content_df = pd.DataFrame(local_content_data)
            local_content_df["النسبة (%)"] = local_content_df["النسبة (%)"].round(2)
            local_content_df["القيمة (ريال)"] = local_content_df["القيمة (ريال)"].apply(lambda x: f"{x:,.2f}")
            
            st.dataframe(local_content_df, use_container_width=True)
            
            # تحسين المحتوى المحلي باستخدام الذكاء الاصطناعي
            if ai_optimization:
                st.subheader("توصيات تحسين المحتوى المحلي")
                
                with st.spinner("جاري تحليل وتحسين المحتوى المحلي باستخدام الذكاء الاصطناعي..."):
                    # إنشاء وصف للمشروع
                    project_description = f"""
                    قطاع المشروع: {project_sector}
                    القيمة الإجمالية للمشروع: {project_value:,.2f} ريال
                    قيمة المنتجات المحلية: {local_products:,.2f} ريال ({local_products/project_value*100:.2f}%)
                    قيمة الخدمات المحلية: {local_services:,.2f} ريال ({local_services/project_value*100:.2f}%)
                    تكلفة القوى العاملة المحلية: {local_workforce:,.2f} ريال ({local_workforce/project_value*100:.2f}%)
                    إجمالي المحتوى المحلي: {total_local_content:,.2f} ريال ({local_content_percentage:.2f}%)
                    """
                    
                    # تحليل النص باستخدام الذكاء الاصطناعي
                    result = self.claude_service.analyze_text(project_description, "local_content")
                    
                    if "error" not in result:
                        # عرض نتائج التحليل
                        if isinstance(result["result"], dict):
                            if "توصيات" in result["result"]:
                                recommendations = result["result"]["توصيات"]
                                
                                for i, rec in enumerate(recommendations):
                                    st.markdown(f"**{i+1}. {rec}**")
                            elif "عناصر المحتوى المحلي" in result["result"]:
                                items = result["result"]["عناصر المحتوى المحلي"]
                                
                                # إنشاء جدول للعناصر
                                items_data = []
                                for item in items:
                                    if isinstance(item, dict):
                                        items_data.append({
                                            "الوصف": item.get("الوصف", ""),
                                            "الفئة": item.get("الفئة", ""),
                                            "مدى التوفر": item.get("مدى التوفر", ""),
                                            "المساهمة": item.get("تقدير نسبي للمساهمة في المحتوى المحلي", "")
                                        })
                                
                                if items_data:
                                    items_df = pd.DataFrame(items_data)
                                    st.dataframe(items_df, use_container_width=True)
                            else:
                                # إذا كانت النتيجة نصية
                                st.write(result["result"].get("text", "لا توجد نتائج تحليل"))
                        else:
                            st.write("لا توجد توصيات متاحة.")
                    else:
                        st.error(f"حدث خطأ أثناء التحليل: {result['error']}")
        
        # توصيات لتحسين المحتوى المحلي
        st.subheader("توصيات عامة لتحسين المحتوى المحلي")
        
        recommendations = [
            "استخدام منتجات محلية الصنع بدلاً من المستوردة حيثما أمكن",
            "التعاقد مع موردين محليين معتمدين من هيئة المحتوى المحلي",
            "توظيف وتدريب كوادر سعودية للعمل في المشروع",
            "الاستفادة من برامج دعم المحتوى المحلي المقدمة من الجهات الحكومية",
            "تطوير شراكات مع مصنعين محليين لتوطين التقنيات المطلوبة"
        ]
        
        for rec in recommendations:
            st.markdown(f"- {rec}")
    
    def _render_faq_tab(self):
        """عرض تبويب الأسئلة الشائعة"""
        st.markdown("### الأسئلة الشائعة")
        
        st.info("هذه الصفحة تحتوي على إجابات للأسئلة الشائعة حول استخدام نظام تسعير المناقصات.")
        
        # عرض الأسئلة الشائعة
        for i, faq in enumerate(self.faqs):
            with st.expander(faq["question"]):
                st.write(faq["answer"])
        
        # إضافة سؤال جديد
        st.subheader("هل لديك سؤال آخر؟")
        
        new_question = st.text_input("اكتب سؤالك هنا")
        
        col1, col2 = st.columns([3, 1])
        with col1:
            send_button = st.button("إرسال السؤال")
        with col2:
            ai_answer = st.checkbox("إجابة ذكية", value=True)
        
        if send_button and new_question:
            if ai_answer:
                with st.spinner("جاري تحليل السؤال باستخدام الذكاء الاصطناعي..."):
                    # تحليل السؤال باستخدام الذكاء الاصطناعي
                    result = self.claude_service.chat_completion([
                        {"role": "user", "content": f"السؤال: {new_question}\n\nالرجاء الإجابة على هذا السؤال المتعلق بنظام تسعير المناقصات بشكل مختصر ومفيد."}
                    ])
                    
                    if "error" not in result:
                        st.success("تم تحليل السؤال والإجابة عليه!")
                        
                        # عرض الإجابة
                        st.info(f"**سؤالك:** {new_question}")
                        st.write(f"**الإجابة:** {result['content']}")
                    else:
                        st.error(f"حدث خطأ أثناء تحليل السؤال: {result['error']}")
                        st.success("تم إرسال سؤالك بنجاح! سيتم الرد عليه في أقرب وقت.")
            else:
                st.success("تم إرسال سؤالك بنجاح! سيتم الرد عليه في أقرب وقت.")
        elif send_button:
            st.error("يرجى كتابة السؤال قبل الإرسال.")