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

محلل الأسعار لنظام إدارة المناقصات

"""

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
from scipy import stats
import logging

logger = logging.getLogger('tender_system.pricing.analyzer')

class PriceAnalyzer:
    """فئة تحليل الأسعار"""
    
    def __init__(self, db_connector):
        """تهيئة محلل الأسعار"""
        self.db = db_connector
        self.charts_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "data", "charts")
        
        # إنشاء مجلد الرسوم البيانية إذا لم يكن موجودًا
        os.makedirs(self.charts_dir, exist_ok=True)
    
    def get_price_history(self, item_id, start_date=None, end_date=None):
        """الحصول على تاريخ الأسعار لبند معين

        

        المعلمات:

            item_id (int): معرف البند

            start_date (str, optional): تاريخ البداية بتنسيق 'YYYY-MM-DD'

            end_date (str, optional): تاريخ النهاية بتنسيق 'YYYY-MM-DD'

            

        العائد:

            pandas.DataFrame: إطار بيانات يحتوي على تاريخ الأسعار

        """
        try:
            query = """

                SELECT 

                    pih.id,

                    pih.price,

                    pih.price_date,

                    pih.price_source,

                    pih.notes,

                    pib.code,

                    pib.name,

                    mu.name as unit_name,

                    mu.symbol as unit_symbol

                FROM 

                    pricing_items_history pih

                JOIN 

                    pricing_items_base pib ON pih.base_item_id = pib.id

                LEFT JOIN 

                    measurement_units mu ON pib.unit_id = mu.id

                WHERE 

                    pih.base_item_id = ?

            """
            
            params = [item_id]
            
            if start_date:
                query += " AND pih.price_date >= ?"
                params.append(start_date)
            
            if end_date:
                query += " AND pih.price_date <= ?"
                params.append(end_date)
            
            query += " ORDER BY pih.price_date ASC"
            
            results = self.db.fetch_all(query, params)
            
            if not results:
                logger.warning(f"لا توجد بيانات تاريخية للسعر للبند رقم {item_id}")
                return pd.DataFrame()
            
            # تحويل النتائج إلى إطار بيانات
            df = pd.DataFrame(results, columns=[
                'id', 'price', 'price_date', 'price_source', 'notes', 
                'code', 'name', 'unit_name', 'unit_symbol'
            ])
            
            # تحويل تاريخ السعر إلى نوع datetime
            df['price_date'] = pd.to_datetime(df['price_date'])
            
            return df
            
        except Exception as e:
            logger.error(f"خطأ في الحصول على تاريخ الأسعار: {str(e)}")
            return pd.DataFrame()
    
    def analyze_price_trends(self, item_id, start_date=None, end_date=None):
        """تحليل اتجاهات الأسعار

        

        المعلمات:

            item_id (int): معرف البند

            start_date (str, optional): تاريخ البداية بتنسيق 'YYYY-MM-DD'

            end_date (str, optional): تاريخ النهاية بتنسيق 'YYYY-MM-DD'

            

        العائد:

            dict: قاموس يحتوي على نتائج تحليل اتجاهات الأسعار

        """
        try:
            # الحصول على تاريخ الأسعار
            df = self.get_price_history(item_id, start_date, end_date)
            
            if df.empty:
                return {
                    'status': 'error',
                    'message': 'لا توجد بيانات كافية لتحليل اتجاهات الأسعار'
                }
            
            # حساب الإحصاءات الأساسية
            stats_data = {
                'min_price': df['price'].min(),
                'max_price': df['price'].max(),
                'avg_price': df['price'].mean(),
                'median_price': df['price'].median(),
                'std_dev': df['price'].std(),
                'price_range': df['price'].max() - df['price'].min(),
                'count': len(df),
                'start_date': df['price_date'].min().strftime('%Y-%m-%d'),
                'end_date': df['price_date'].max().strftime('%Y-%m-%d'),
                'duration_days': (df['price_date'].max() - df['price_date'].min()).days,
                'item_name': df['name'].iloc[0],
                'item_code': df['code'].iloc[0],
                'unit': df['unit_symbol'].iloc[0] if not pd.isna(df['unit_symbol'].iloc[0]) else ''
            }
            
            # حساب التغير المطلق والنسبي
            if len(df) >= 2:
                first_price = df['price'].iloc[0]
                last_price = df['price'].iloc[-1]
                
                stats_data['absolute_change'] = last_price - first_price
                stats_data['percentage_change'] = ((last_price - first_price) / first_price) * 100
                
                # حساب معدل التغير السنوي
                years = stats_data['duration_days'] / 365.0
                if years > 0:
                    stats_data['annual_change_rate'] = (((last_price / first_price) ** (1 / years)) - 1) * 100
                else:
                    stats_data['annual_change_rate'] = 0
            else:
                stats_data['absolute_change'] = 0
                stats_data['percentage_change'] = 0
                stats_data['annual_change_rate'] = 0
            
            # تحليل الاتجاه باستخدام الانحدار الخطي
            if len(df) >= 3:
                # إنشاء متغير مستقل (الأيام منذ أول تاريخ)
                df['days'] = (df['price_date'] - df['price_date'].min()).dt.days
                
                # حساب الانحدار الخطي
                slope, intercept, r_value, p_value, std_err = stats.linregress(df['days'], df['price'])
                
                stats_data['trend_slope'] = slope
                stats_data['trend_intercept'] = intercept
                stats_data['trend_r_squared'] = r_value ** 2
                stats_data['trend_p_value'] = p_value
                stats_data['trend_std_err'] = std_err
                
                # تحديد اتجاه السعر
                if p_value < 0.05:  # إذا كان الاتجاه ذو دلالة إحصائية
                    if slope > 0:
                        stats_data['trend_direction'] = 'upward'
                        stats_data['trend_description'] = 'اتجاه تصاعدي'
                    elif slope < 0:
                        stats_data['trend_direction'] = 'downward'
                        stats_data['trend_description'] = 'اتجاه تنازلي'
                    else:
                        stats_data['trend_direction'] = 'stable'
                        stats_data['trend_description'] = 'مستقر'
                else:
                    stats_data['trend_direction'] = 'no_significant_trend'
                    stats_data['trend_description'] = 'لا يوجد اتجاه واضح'
                
                # حساب التقلب (معامل الاختلاف)
                stats_data['volatility'] = (df['price'].std() / df['price'].mean()) * 100
                
                # تصنيف التقلب
                if stats_data['volatility'] < 5:
                    stats_data['volatility_level'] = 'low'
                    stats_data['volatility_description'] = 'منخفض'
                elif stats_data['volatility'] < 15:
                    stats_data['volatility_level'] = 'medium'
                    stats_data['volatility_description'] = 'متوسط'
                else:
                    stats_data['volatility_level'] = 'high'
                    stats_data['volatility_description'] = 'مرتفع'
            else:
                stats_data['trend_direction'] = 'insufficient_data'
                stats_data['trend_description'] = 'بيانات غير كافية'
                stats_data['volatility'] = 0
                stats_data['volatility_level'] = 'unknown'
                stats_data['volatility_description'] = 'غير معروف'
            
            # إنشاء رسم بياني للاتجاه
            chart_path = self._create_trend_chart(df, stats_data, item_id)
            stats_data['chart_path'] = chart_path
            
            return {
                'status': 'success',
                'data': stats_data
            }
            
        except Exception as e:
            logger.error(f"خطأ في تحليل اتجاهات الأسعار: {str(e)}")
            return {
                'status': 'error',
                'message': f'حدث خطأ أثناء تحليل اتجاهات الأسعار: {str(e)}'
            }
    
    def _create_trend_chart(self, df, stats_data, item_id):
        """إنشاء رسم بياني للاتجاه

        

        المعلمات:

            df (pandas.DataFrame): إطار البيانات

            stats_data (dict): بيانات الإحصاءات

            item_id (int): معرف البند

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني جديد
            plt.figure(figsize=(10, 6))
            
            # رسم نقاط البيانات
            plt.scatter(df['price_date'], df['price'], color='blue', alpha=0.6, label='أسعار فعلية')
            
            # رسم خط الاتجاه إذا كان هناك بيانات كافية
            if len(df) >= 3 and 'trend_slope' in stats_data:
                # إنشاء خط الاتجاه
                x_trend = pd.date_range(start=df['price_date'].min(), end=df['price_date'].max(), periods=100)
                days_trend = [(date - df['price_date'].min()).days for date in x_trend]
                y_trend = stats_data['trend_slope'] * np.array(days_trend) + stats_data['trend_intercept']
                
                # رسم خط الاتجاه
                plt.plot(x_trend, y_trend, color='red', linestyle='--', label='خط الاتجاه')
            
            # رسم خط متوسط السعر
            plt.axhline(y=stats_data['avg_price'], color='green', linestyle='-', alpha=0.5, label='متوسط السعر')
            
            # إضافة عنوان ومحاور
            plt.title(f"تحليل اتجاه السعر - {stats_data['item_name']} ({stats_data['item_code']})")
            plt.xlabel('التاريخ')
            plt.ylabel(f"السعر ({stats_data['unit']})")
            
            # إضافة شبكة
            plt.grid(True, linestyle='--', alpha=0.7)
            
            # إضافة وسيلة إيضاح
            plt.legend()
            
            # تنسيق التاريخ على المحور السيني
            plt.gcf().autofmt_xdate()
            
            # إضافة معلومات إحصائية
            info_text = (
                f"التغير: {stats_data['percentage_change']:.2f}%\n"
                f"التقلب: {stats_data['volatility']:.2f}%\n"
            )
            
            if 'trend_r_squared' in stats_data:
                info_text += f"R²: {stats_data['trend_r_squared']:.3f}"
            
            plt.annotate(info_text, xy=(0.02, 0.95), xycoords='axes fraction', 
                        bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", alpha=0.8))
            
            # حفظ الرسم البياني
            chart_filename = f"price_trend_{item_id}_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني للاتجاه: {str(e)}")
            return None
    
    def compare_prices(self, items, date=None):
        """مقارنة الأسعار بين عدة بنود

        

        المعلمات:

            items (list): قائمة بمعرفات البنود

            date (str, optional): تاريخ المقارنة بتنسيق 'YYYY-MM-DD'

            

        العائد:

            dict: قاموس يحتوي على نتائج مقارنة الأسعار

        """
        try:
            if not items:
                return {
                    'status': 'error',
                    'message': 'لم يتم تحديد أي بنود للمقارنة'
                }
            
            comparison_data = []
            
            for item_id in items:
                # الحصول على معلومات البند الأساسية
                item_query = """

                    SELECT 

                        id, code, name, description, 

                        (SELECT name FROM measurement_units WHERE id = unit_id) as unit_name,

                        (SELECT symbol FROM measurement_units WHERE id = unit_id) as unit_symbol,

                        base_price, last_updated_date

                    FROM 

                        pricing_items_base

                    WHERE 

                        id = ?

                """
                
                item_result = self.db.fetch_one(item_query, [item_id])
                
                if not item_result:
                    logger.warning(f"البند رقم {item_id} غير موجود")
                    continue
                
                item_data = {
                    'id': item_result[0],
                    'code': item_result[1],
                    'name': item_result[2],
                    'description': item_result[3],
                    'unit_name': item_result[4],
                    'unit_symbol': item_result[5],
                    'base_price': item_result[6],
                    'last_updated_date': item_result[7]
                }
                
                # إذا تم تحديد تاريخ، نبحث عن السعر في ذلك التاريخ
                if date:
                    price_query = """

                        SELECT price, price_date, price_source

                        FROM pricing_items_history

                        WHERE base_item_id = ?

                        AND price_date <= ?

                        ORDER BY price_date DESC

                        LIMIT 1

                    """
                    
                    price_result = self.db.fetch_one(price_query, [item_id, date])
                    
                    if price_result:
                        item_data['price'] = price_result[0]
                        item_data['price_date'] = price_result[1]
                        item_data['price_source'] = price_result[2]
                    else:
                        # إذا لم يتم العثور على سعر في التاريخ المحدد، نستخدم السعر الأساسي
                        item_data['price'] = item_data['base_price']
                        item_data['price_date'] = item_data['last_updated_date']
                        item_data['price_source'] = 'base_price'
                else:
                    # إذا لم يتم تحديد تاريخ، نستخدم أحدث سعر
                    price_query = """

                        SELECT price, price_date, price_source

                        FROM pricing_items_history

                        WHERE base_item_id = ?

                        ORDER BY price_date DESC

                        LIMIT 1

                    """
                    
                    price_result = self.db.fetch_one(price_query, [item_id])
                    
                    if price_result:
                        item_data['price'] = price_result[0]
                        item_data['price_date'] = price_result[1]
                        item_data['price_source'] = price_result[2]
                    else:
                        # إذا لم يتم العثور على سعر، نستخدم السعر الأساسي
                        item_data['price'] = item_data['base_price']
                        item_data['price_date'] = item_data['last_updated_date']
                        item_data['price_source'] = 'base_price'
                
                comparison_data.append(item_data)
            
            if not comparison_data:
                return {
                    'status': 'error',
                    'message': 'لم يتم العثور على أي بنود للمقارنة'
                }
            
            # إنشاء رسم بياني للمقارنة
            chart_path = self._create_comparison_chart(comparison_data, date)
            
            return {
                'status': 'success',
                'data': {
                    'items': comparison_data,
                    'comparison_date': date if date else 'latest',
                    'chart_path': chart_path
                }
            }
            
        except Exception as e:
            logger.error(f"خطأ في مقارنة الأسعار: {str(e)}")
            return {
                'status': 'error',
                'message': f'حدث خطأ أثناء مقارنة الأسعار: {str(e)}'
            }
    
    def _create_comparison_chart(self, comparison_data, date=None):
        """إنشاء رسم بياني للمقارنة

        

        المعلمات:

            comparison_data (list): بيانات المقارنة

            date (str, optional): تاريخ المقارنة

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني جديد
            plt.figure(figsize=(12, 6))
            
            # إعداد البيانات للرسم
            names = [f"{item['code']} - {item['name']}" for item in comparison_data]
            prices = [item['price'] for item in comparison_data]
            
            # رسم الأعمدة
            bars = plt.bar(names, prices, color='skyblue', edgecolor='navy')
            
            # إضافة القيم فوق الأعمدة
            for bar in bars:
                height = bar.get_height()
                plt.text(bar.get_x() + bar.get_width()/2., height + 0.1,
                        f'{height:.2f}', ha='center', va='bottom')
            
            # إضافة عنوان ومحاور
            title = "مقارنة الأسعار"
            if date:
                title += f" (بتاريخ {date})"
            
            plt.title(title)
            plt.xlabel('البنود')
            plt.ylabel('السعر')
            
            # تدوير تسميات المحور السيني لتجنب التداخل
            plt.xticks(rotation=45, ha='right')
            
            # إضافة شبكة
            plt.grid(True, linestyle='--', alpha=0.7, axis='y')
            
            # ضبط التخطيط
            plt.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"price_comparison_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني للمقارنة: {str(e)}")
            return None
    
    def calculate_price_volatility(self, item_id, period='1y'):
        """حساب تقلب الأسعار

        

        المعلمات:

            item_id (int): معرف البند

            period (str): الفترة الزمنية ('1m', '3m', '6m', '1y', '2y', '5y', 'all')

            

        العائد:

            dict: قاموس يحتوي على نتائج حساب تقلب الأسعار

        """
        try:
            # تحديد تاريخ البداية بناءً على الفترة
            end_date = datetime.now().strftime('%Y-%m-%d')
            
            if period == '1m':
                start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
            elif period == '3m':
                start_date = (datetime.now() - timedelta(days=90)).strftime('%Y-%m-%d')
            elif period == '6m':
                start_date = (datetime.now() - timedelta(days=180)).strftime('%Y-%m-%d')
            elif period == '1y':
                start_date = (datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d')
            elif period == '2y':
                start_date = (datetime.now() - timedelta(days=730)).strftime('%Y-%m-%d')
            elif period == '5y':
                start_date = (datetime.now() - timedelta(days=1825)).strftime('%Y-%m-%d')
            else:  # 'all'
                start_date = None
            
            # الحصول على تاريخ الأسعار
            df = self.get_price_history(item_id, start_date, end_date)
            
            if df.empty or len(df) < 2:
                return {
                    'status': 'error',
                    'message': 'لا توجد بيانات كافية لحساب تقلب الأسعار'
                }
            
            # حساب التقلب (معامل الاختلاف)
            mean_price = df['price'].mean()
            std_dev = df['price'].std()
            volatility = (std_dev / mean_price) * 100
            
            # حساب التغيرات النسبية
            df['price_shift'] = df['price'].shift(1)
            df = df.dropna()
            
            if not df.empty:
                df['price_change_pct'] = ((df['price'] - df['price_shift']) / df['price_shift']) * 100
                
                # حساب إحصاءات التغيرات
                max_increase = df['price_change_pct'].max()
                max_decrease = df['price_change_pct'].min()
                avg_change = df['price_change_pct'].mean()
                median_change = df['price_change_pct'].median()
                
                # حساب عدد التغيرات الإيجابية والسلبية
                positive_changes = (df['price_change_pct'] > 0).sum()
                negative_changes = (df['price_change_pct'] < 0).sum()
                no_changes = (df['price_change_pct'] == 0).sum()
                
                # تصنيف التقلب
                if volatility < 5:
                    volatility_level = 'low'
                    volatility_description = 'منخفض'
                elif volatility < 15:
                    volatility_level = 'medium'
                    volatility_description = 'متوسط'
                else:
                    volatility_level = 'high'
                    volatility_description = 'مرتفع'
                
                # إنشاء رسم بياني للتقلب
                chart_path = self._create_volatility_chart(df, item_id, period)
                
                return {
                    'status': 'success',
                    'data': {
                        'item_id': item_id,
                        'item_name': df['name'].iloc[0],
                        'item_code': df['code'].iloc[0],
                        'period': period,
                        'start_date': df['price_date'].min().strftime('%Y-%m-%d'),
                        'end_date': df['price_date'].max().strftime('%Y-%m-%d'),
                        'data_points': len(df),
                        'mean_price': mean_price,
                        'std_dev': std_dev,
                        'volatility': volatility,
                        'volatility_level': volatility_level,
                        'volatility_description': volatility_description,
                        'max_increase': max_increase,
                        'max_decrease': max_decrease,
                        'avg_change': avg_change,
                        'median_change': median_change,
                        'positive_changes': positive_changes,
                        'negative_changes': negative_changes,
                        'no_changes': no_changes,
                        'chart_path': chart_path
                    }
                }
            else:
                return {
                    'status': 'error',
                    'message': 'لا توجد بيانات كافية لحساب تقلب الأسعار بعد معالجة البيانات'
                }
            
        except Exception as e:
            logger.error(f"خطأ في حساب تقلب الأسعار: {str(e)}")
            return {
                'status': 'error',
                'message': f'حدث خطأ أثناء حساب تقلب الأسعار: {str(e)}'
            }
    
    def _create_volatility_chart(self, df, item_id, period):
        """إنشاء رسم بياني للتقلب

        

        المعلمات:

            df (pandas.DataFrame): إطار البيانات

            item_id (int): معرف البند

            period (str): الفترة الزمنية

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني بمحورين
            fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10), gridspec_kw={'height_ratios': [2, 1]})
            
            # الرسم البياني العلوي: سعر البند عبر الزمن
            ax1.plot(df['price_date'], df['price'], 'b-', linewidth=2)
            ax1.set_title(f"سعر البند عبر الزمن - {df['name'].iloc[0]} ({df['code'].iloc[0]})")
            ax1.set_xlabel('التاريخ')
            ax1.set_ylabel('السعر')
            ax1.grid(True, linestyle='--', alpha=0.7)
            
            # إضافة نطاق الانحراف المعياري
            mean_price = df['price'].mean()
            std_dev = df['price'].std()
            
            ax1.axhline(y=mean_price, color='g', linestyle='-', alpha=0.8, label='متوسط السعر')
            ax1.axhline(y=mean_price + std_dev, color='r', linestyle='--', alpha=0.5, label='انحراف معياري +1')
            ax1.axhline(y=mean_price - std_dev, color='r', linestyle='--', alpha=0.5, label='انحراف معياري -1')
            
            ax1.fill_between(df['price_date'], mean_price - std_dev, mean_price + std_dev, color='gray', alpha=0.2)
            ax1.legend()
            
            # الرسم البياني السفلي: التغيرات النسبية
            ax2.bar(df['price_date'], df['price_change_pct'], color='skyblue', edgecolor='navy', alpha=0.7)
            ax2.set_title('التغيرات النسبية في السعر (%)')
            ax2.set_xlabel('التاريخ')
            ax2.set_ylabel('التغير النسبي (%)')
            ax2.grid(True, linestyle='--', alpha=0.7)
            
            # إضافة خط الصفر
            ax2.axhline(y=0, color='k', linestyle='-', alpha=0.3)
            
            # تنسيق التاريخ على المحور السيني
            fig.autofmt_xdate()
            
            # ضبط التخطيط
            plt.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"price_volatility_{item_id}_{period}_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني للتقلب: {str(e)}")
            return None
    
    def perform_sensitivity_analysis(self, project_id, variable_items, ranges):
        """إجراء تحليل الحساسية

        

        المعلمات:

            project_id (int): معرف المشروع

            variable_items (list): قائمة بمعرفات البنود المتغيرة

            ranges (dict): نطاقات التغيير لكل بند

            

        العائد:

            dict: قاموس يحتوي على نتائج تحليل الحساسية

        """
        try:
            # الحصول على بنود المشروع
            query = """

                SELECT 

                    id, item_number, description, quantity, unit_price, total_price

                FROM 

                    project_pricing_items

                WHERE 

                    project_id = ?

            """
            
            results = self.db.fetch_all(query, [project_id])
            
            if not results:
                return {
                    'status': 'error',
                    'message': 'لا توجد بنود للمشروع المحدد'
                }
            
            # تحويل النتائج إلى إطار بيانات
            project_items = pd.DataFrame(results, columns=[
                'id', 'item_number', 'description', 'quantity', 'unit_price', 'total_price'
            ])
            
            # حساب إجمالي المشروع الأصلي
            original_total = project_items['total_price'].sum()
            
            # تحضير بيانات تحليل الحساسية
            sensitivity_data = []
            
            for item_id in variable_items:
                if item_id not in project_items['id'].values:
                    logger.warning(f"البند رقم {item_id} غير موجود في المشروع")
                    continue
                
                # الحصول على معلومات البند
                item_info = project_items[project_items['id'] == item_id].iloc[0]
                
                # الحصول على نطاق التغيير للبند
                if str(item_id) in ranges:
                    item_range = ranges[str(item_id)]
                else:
                    # استخدام نطاق افتراضي إذا لم يتم تحديد نطاق
                    item_range = {'min': -20, 'max': 20, 'step': 10}
                
                # إنشاء قائمة بنسب التغيير
                change_percentages = list(range(
                    item_range['min'], 
                    item_range['max'] + item_range['step'], 
                    item_range['step']
                ))
                
                item_sensitivity = {
                    'item_id': item_id,
                    'item_number': item_info['item_number'],
                    'description': item_info['description'],
                    'original_price': item_info['unit_price'],
                    'original_total': item_info['total_price'],
                    'changes': []
                }
                
                # حساب تأثير كل نسبة تغيير
                for percentage in change_percentages:
                    # حساب السعر الجديد
                    new_price = item_info['unit_price'] * (1 + percentage / 100)
                    new_total = new_price * item_info['quantity']
                    
                    # حساب إجمالي المشروع الجديد
                    project_total = original_total - item_info['total_price'] + new_total
                    
                    # حساب التغير في إجمالي المشروع
                    project_change = ((project_total - original_total) / original_total) * 100
                    
                    item_sensitivity['changes'].append({
                        'percentage': percentage,
                        'new_price': new_price,
                        'new_total': new_total,
                        'project_total': project_total,
                        'project_change': project_change
                    })
                
                sensitivity_data.append(item_sensitivity)
            
            if not sensitivity_data:
                return {
                    'status': 'error',
                    'message': 'لا توجد بنود صالحة لتحليل الحساسية'
                }
            
            # إنشاء رسم بياني لتحليل الحساسية
            chart_path = self._create_sensitivity_chart(sensitivity_data, original_total, project_id)
            
            return {
                'status': 'success',
                'data': {
                    'project_id': project_id,
                    'original_total': original_total,
                    'sensitivity_data': sensitivity_data,
                    'chart_path': chart_path
                }
            }
            
        except Exception as e:
            logger.error(f"خطأ في إجراء تحليل الحساسية: {str(e)}")
            return {
                'status': 'error',
                'message': f'حدث خطأ أثناء إجراء تحليل الحساسية: {str(e)}'
            }
    
    def _create_sensitivity_chart(self, sensitivity_data, original_total, project_id):
        """إنشاء رسم بياني لتحليل الحساسية

        

        المعلمات:

            sensitivity_data (list): بيانات تحليل الحساسية

            original_total (float): إجمالي المشروع الأصلي

            project_id (int): معرف المشروع

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني جديد
            plt.figure(figsize=(12, 8))
            
            # رسم خطوط الحساسية لكل بند
            for item in sensitivity_data:
                percentages = [change['percentage'] for change in item['changes']]
                project_changes = [change['project_change'] for change in item['changes']]
                
                plt.plot(percentages, project_changes, marker='o', linewidth=2, 
                        label=f"{item['item_number']} - {item['description'][:30]}...")
            
            # إضافة عنوان ومحاور
            plt.title(f"تحليل الحساسية للمشروع رقم {project_id}")
            plt.xlabel('نسبة التغيير في سعر البند (%)')
            plt.ylabel('نسبة التغيير في إجمالي المشروع (%)')
            
            # إضافة خط الصفر
            plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)
            plt.axvline(x=0, color='k', linestyle='-', alpha=0.3)
            
            # إضافة شبكة
            plt.grid(True, linestyle='--', alpha=0.7)
            
            # إضافة وسيلة إيضاح
            plt.legend(loc='best')
            
            # إضافة معلومات إضافية
            info_text = f"إجمالي المشروع الأصلي: {original_total:,.2f}"
            plt.annotate(info_text, xy=(0.02, 0.02), xycoords='axes fraction', 
                        bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", alpha=0.8))
            
            # ضبط التخطيط
            plt.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"sensitivity_analysis_{project_id}_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني لتحليل الحساسية: {str(e)}")
            return None
    
    def analyze_price_correlations(self, items):
        """تحليل ارتباطات الأسعار بين عدة بنود

        

        المعلمات:

            items (list): قائمة بمعرفات البنود

            

        العائد:

            dict: قاموس يحتوي على نتائج تحليل الارتباطات

        """
        try:
            if not items or len(items) < 2:
                return {
                    'status': 'error',
                    'message': 'يجب تحديد بندين على الأقل لتحليل الارتباطات'
                }
            
            # جمع بيانات الأسعار لجميع البنود
            all_prices = {}
            item_names = {}
            
            for item_id in items:
                # الحصول على تاريخ الأسعار
                df = self.get_price_history(item_id)
                
                if df.empty:
                    logger.warning(f"لا توجد بيانات تاريخية للسعر للبند رقم {item_id}")
                    continue
                
                # تخزين بيانات الأسعار
                all_prices[item_id] = df[['price_date', 'price']].copy()
                item_names[item_id] = f"{df['code'].iloc[0]} - {df['name'].iloc[0]}"
            
            if len(all_prices) < 2:
                return {
                    'status': 'error',
                    'message': 'لا توجد بيانات كافية لتحليل الارتباطات'
                }
            
            # إنشاء إطار بيانات موحد بتواريخ مشتركة
            # أولاً، نجمع جميع التواريخ الفريدة
            all_dates = set()
            for item_id, df in all_prices.items():
                all_dates.update(df['price_date'].dt.strftime('%Y-%m-%d').tolist())
            
            # إنشاء إطار بيانات جديد بجميع التواريخ
            unified_df = pd.DataFrame({'price_date': sorted(list(all_dates))})
            unified_df['price_date'] = pd.to_datetime(unified_df['price_date'])
            
            # إضافة أسعار كل بند
            for item_id, df in all_prices.items():
                # تحويل إطار البيانات إلى سلسلة زمنية مفهرسة بالتاريخ
                price_series = df.set_index('price_date')['price']
                
                # إعادة فهرسة السلسلة الزمنية لتتوافق مع التواريخ الموحدة
                unified_df[f'price_{item_id}'] = unified_df['price_date'].map(
                    lambda x: price_series.get(x, None)
                )
            
            # ملء القيم المفقودة باستخدام الاستيفاء الخطي
            price_columns = [col for col in unified_df.columns if col.startswith('price_')]
            unified_df[price_columns] = unified_df[price_columns].interpolate(method='linear')
            
            # حذف الصفوف التي لا تزال تحتوي على قيم مفقودة
            unified_df = unified_df.dropna()
            
            if len(unified_df) < 3:
                return {
                    'status': 'error',
                    'message': 'لا توجد بيانات كافية بعد معالجة التواريخ المشتركة'
                }
            
            # حساب مصفوفة الارتباط
            correlation_matrix = unified_df[price_columns].corr()
            
            # تحويل مصفوفة الارتباط إلى تنسيق أكثر قابلية للقراءة
            correlation_data = []
            
            for i, item1_id in enumerate(items):
                if f'price_{item1_id}' not in correlation_matrix.columns:
                    continue
                    
                for j, item2_id in enumerate(items):
                    if f'price_{item2_id}' not in correlation_matrix.columns or i >= j:
                        continue
                    
                    correlation = correlation_matrix.loc[f'price_{item1_id}', f'price_{item2_id}']
                    
                    # تحديد قوة واتجاه الارتباط
                    if abs(correlation) < 0.3:
                        strength = 'weak'
                        strength_description = 'ضعيف'
                    elif abs(correlation) < 0.7:
                        strength = 'moderate'
                        strength_description = 'متوسط'
                    else:
                        strength = 'strong'
                        strength_description = 'قوي'
                    
                    if correlation > 0:
                        direction = 'positive'
                        direction_description = 'طردي'
                    else:
                        direction = 'negative'
                        direction_description = 'عكسي'
                    
                    correlation_data.append({
                        'item1_id': item1_id,
                        'item1_name': item_names.get(item1_id, f'البند {item1_id}'),
                        'item2_id': item2_id,
                        'item2_name': item_names.get(item2_id, f'البند {item2_id}'),
                        'correlation': correlation,
                        'strength': strength,
                        'strength_description': strength_description,
                        'direction': direction,
                        'direction_description': direction_description
                    })
            
            if not correlation_data:
                return {
                    'status': 'error',
                    'message': 'لم يتم العثور على ارتباطات بين البنود المحددة'
                }
            
            # إنشاء رسم بياني للارتباطات
            chart_path = self._create_correlation_chart(correlation_matrix, item_names)
            
            # إنشاء رسم بياني لتطور الأسعار
            trends_chart_path = self._create_price_trends_chart(unified_df, price_columns, item_names)
            
            return {
                'status': 'success',
                'data': {
                    'correlation_data': correlation_data,
                    'chart_path': chart_path,
                    'trends_chart_path': trends_chart_path
                }
            }
            
        except Exception as e:
            logger.error(f"خطأ في تحليل ارتباطات الأسعار: {str(e)}")
            return {
                'status': 'error',
                'message': f'حدث خطأ أثناء تحليل ارتباطات الأسعار: {str(e)}'
            }
    
    def _create_correlation_chart(self, correlation_matrix, item_names):
        """إنشاء رسم بياني لمصفوفة الارتباط

        

        المعلمات:

            correlation_matrix (pandas.DataFrame): مصفوفة الارتباط

            item_names (dict): قاموس بأسماء البنود

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني جديد
            plt.figure(figsize=(10, 8))
            
            # إنشاء خريطة حرارية للارتباطات
            mask = np.triu(np.ones_like(correlation_matrix, dtype=bool))
            cmap = sns.diverging_palette(230, 20, as_cmap=True)
            
            # تعديل تسميات المحاور
            labels = [item_names.get(int(col.split('_')[1]), col) for col in correlation_matrix.columns]
            
            # رسم الخريطة الحرارية
            sns.heatmap(correlation_matrix, mask=mask, cmap=cmap, vmax=1, vmin=-1, center=0,
                        square=True, linewidths=.5, cbar_kws={"shrink": .5}, annot=True,
                        xticklabels=labels, yticklabels=labels)
            
            # إضافة عنوان
            plt.title('مصفوفة ارتباط الأسعار بين البنود')
            
            # ضبط التخطيط
            plt.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"price_correlation_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني لمصفوفة الارتباط: {str(e)}")
            return None
    
    def _create_price_trends_chart(self, unified_df, price_columns, item_names):
        """إنشاء رسم بياني لتطور الأسعار

        

        المعلمات:

            unified_df (pandas.DataFrame): إطار البيانات الموحد

            price_columns (list): أسماء أعمدة الأسعار

            item_names (dict): قاموس بأسماء البنود

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني جديد
            plt.figure(figsize=(12, 6))
            
            # رسم تطور الأسعار لكل بند
            for col in price_columns:
                item_id = int(col.split('_')[1])
                item_name = item_names.get(item_id, f'البند {item_id}')
                
                # تطبيع الأسعار للمقارنة (القيمة الأولى = 100)
                first_price = unified_df[col].iloc[0]
                normalized_prices = (unified_df[col] / first_price) * 100
                
                plt.plot(unified_df['price_date'], normalized_prices, linewidth=2, label=item_name)
            
            # إضافة عنوان ومحاور
            plt.title('تطور الأسعار النسبية للبنود (القيمة الأولى = 100)')
            plt.xlabel('التاريخ')
            plt.ylabel('السعر النسبي')
            
            # إضافة شبكة
            plt.grid(True, linestyle='--', alpha=0.7)
            
            # إضافة وسيلة إيضاح
            plt.legend(loc='best')
            
            # تنسيق التاريخ على المحور السيني
            plt.gcf().autofmt_xdate()
            
            # ضبط التخطيط
            plt.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"price_trends_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني لتطور الأسعار: {str(e)}")
            return None
    
    def compare_with_market_prices(self, items):
        """مقارنة أسعار البنود مع أسعار السوق

        

        المعلمات:

            items (list): قائمة بمعرفات البنود

            

        العائد:

            dict: قاموس يحتوي على نتائج المقارنة

        """
        try:
            if not items:
                return {
                    'status': 'error',
                    'message': 'لم يتم تحديد أي بنود للمقارنة'
                }
            
            comparison_data = []
            
            for item_id in items:
                # الحصول على معلومات البند الأساسية
                item_query = """

                    SELECT 

                        id, code, name, description, 

                        (SELECT name FROM measurement_units WHERE id = unit_id) as unit_name,

                        (SELECT symbol FROM measurement_units WHERE id = unit_id) as unit_symbol,

                        base_price, last_updated_date

                    FROM 

                        pricing_items_base

                    WHERE 

                        id = ?

                """
                
                item_result = self.db.fetch_one(item_query, [item_id])
                
                if not item_result:
                    logger.warning(f"البند رقم {item_id} غير موجود")
                    continue
                
                item_data = {
                    'id': item_result[0],
                    'code': item_result[1],
                    'name': item_result[2],
                    'description': item_result[3],
                    'unit_name': item_result[4],
                    'unit_symbol': item_result[5],
                    'base_price': item_result[6],
                    'last_updated_date': item_result[7]
                }
                
                # الحصول على أحدث سعر للبند
                price_query = """

                    SELECT price, price_date, price_source

                    FROM pricing_items_history

                    WHERE base_item_id = ?

                    ORDER BY price_date DESC

                    LIMIT 1

                """
                
                price_result = self.db.fetch_one(price_query, [item_id])
                
                if price_result:
                    item_data['current_price'] = price_result[0]
                    item_data['price_date'] = price_result[1]
                    item_data['price_source'] = price_result[2]
                else:
                    # إذا لم يتم العثور على سعر، نستخدم السعر الأساسي
                    item_data['current_price'] = item_data['base_price']
                    item_data['price_date'] = item_data['last_updated_date']
                    item_data['price_source'] = 'base_price'
                
                # الحصول على متوسط سعر السوق (من مصادر مختلفة)
                market_query = """

                    SELECT AVG(price) as avg_price

                    FROM pricing_items_history

                    WHERE base_item_id = ? AND price_source != 'internal'

                    AND price_date >= date('now', '-6 months')

                """
                
                market_result = self.db.fetch_one(market_query, [item_id])
                
                if market_result and market_result[0]:
                    item_data['market_price'] = market_result[0]
                    
                    # حساب الفرق بين السعر الحالي وسعر السوق
                    item_data['price_difference'] = item_data['current_price'] - item_data['market_price']
                    item_data['price_difference_percentage'] = (item_data['price_difference'] / item_data['market_price']) * 100
                    
                    # تحديد حالة السعر
                    if abs(item_data['price_difference_percentage']) < 5:
                        item_data['price_status'] = 'competitive'
                        item_data['price_status_description'] = 'تنافسي'
                    elif item_data['price_difference_percentage'] < 0:
                        item_data['price_status'] = 'below_market'
                        item_data['price_status_description'] = 'أقل من السوق'
                    else:
                        item_data['price_status'] = 'above_market'
                        item_data['price_status_description'] = 'أعلى من السوق'
                else:
                    # إذا لم يتم العثور على سعر سوق، نستخدم متوسط الأسعار الداخلية
                    internal_query = """

                        SELECT AVG(price) as avg_price

                        FROM pricing_items_history

                        WHERE base_item_id = ?

                        AND price_date >= date('now', '-6 months')

                    """
                    
                    internal_result = self.db.fetch_one(internal_query, [item_id])
                    
                    if internal_result and internal_result[0]:
                        item_data['market_price'] = internal_result[0]
                        item_data['price_difference'] = item_data['current_price'] - item_data['market_price']
                        item_data['price_difference_percentage'] = (item_data['price_difference'] / item_data['market_price']) * 100
                        
                        # تحديد حالة السعر
                        if abs(item_data['price_difference_percentage']) < 5:
                            item_data['price_status'] = 'competitive'
                            item_data['price_status_description'] = 'تنافسي'
                        elif item_data['price_difference_percentage'] < 0:
                            item_data['price_status'] = 'below_average'
                            item_data['price_status_description'] = 'أقل من المتوسط'
                        else:
                            item_data['price_status'] = 'above_average'
                            item_data['price_status_description'] = 'أعلى من المتوسط'
                    else:
                        item_data['market_price'] = None
                        item_data['price_difference'] = None
                        item_data['price_difference_percentage'] = None
                        item_data['price_status'] = 'unknown'
                        item_data['price_status_description'] = 'غير معروف'
                
                comparison_data.append(item_data)
            
            if not comparison_data:
                return {
                    'status': 'error',
                    'message': 'لم يتم العثور على أي بنود للمقارنة'
                }
            
            # إنشاء رسم بياني للمقارنة
            chart_path = self._create_market_comparison_chart(comparison_data)
            
            return {
                'status': 'success',
                'data': {
                    'items': comparison_data,
                    'chart_path': chart_path
                }
            }
            
        except Exception as e:
            logger.error(f"خطأ في مقارنة الأسعار مع أسعار السوق: {str(e)}")
            return {
                'status': 'error',
                'message': f'حدث خطأ أثناء مقارنة الأسعار مع أسعار السوق: {str(e)}'
            }
    
    def _create_market_comparison_chart(self, comparison_data):
        """إنشاء رسم بياني لمقارنة الأسعار مع أسعار السوق

        

        المعلمات:

            comparison_data (list): بيانات المقارنة

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # تصفية البنود التي لها أسعار سوق
            valid_items = [item for item in comparison_data if item.get('market_price') is not None]
            
            if not valid_items:
                return None
            
            # إنشاء رسم بياني جديد
            plt.figure(figsize=(12, 6))
            
            # إعداد البيانات للرسم
            names = [f"{item['code']} - {item['name'][:20]}..." for item in valid_items]
            current_prices = [item['current_price'] for item in valid_items]
            market_prices = [item['market_price'] for item in valid_items]
            
            # إنشاء مواقع الأعمدة
            x = np.arange(len(names))
            width = 0.35
            
            # رسم الأعمدة
            plt.bar(x - width/2, current_prices, width, label='السعر الحالي', color='skyblue')
            plt.bar(x + width/2, market_prices, width, label='سعر السوق', color='lightgreen')
            
            # إضافة تسميات وعنوان
            plt.xlabel('البنود')
            plt.ylabel('السعر')
            plt.title('مقارنة الأسعار الحالية مع أسعار السوق')
            plt.xticks(x, names, rotation=45, ha='right')
            plt.legend()
            
            # إضافة شبكة
            plt.grid(True, linestyle='--', alpha=0.7, axis='y')
            
            # إضافة قيم الفروق النسبية
            for i, item in enumerate(valid_items):
                if 'price_difference_percentage' in item and item['price_difference_percentage'] is not None:
                    percentage = item['price_difference_percentage']
                    color = 'green' if percentage < 0 else 'red' if percentage > 0 else 'black'
                    plt.annotate(f"{percentage:.1f}%", 
                                xy=(x[i], max(current_prices[i], market_prices[i]) * 1.05),
                                ha='center', va='bottom', color=color,
                                bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", alpha=0.8))
            
            # ضبط التخطيط
            plt.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"market_comparison_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني لمقارنة الأسعار مع أسعار السوق: {str(e)}")
            return None
    
    def analyze_cost_drivers(self, project_id):
        """تحليل محركات التكلفة للمشروع

        

        المعلمات:

            project_id (int): معرف المشروع

            

        العائد:

            dict: قاموس يحتوي على نتائج تحليل محركات التكلفة

        """
        try:
            # الحصول على بنود المشروع
            query = """

                SELECT 

                    id, item_number, description, quantity, unit_price, total_price,

                    (SELECT name FROM pricing_categories WHERE id = 

                        (SELECT category_id FROM pricing_items_base WHERE id = base_item_id)

                    ) as category_name

                FROM 

                    project_pricing_items

                WHERE 

                    project_id = ?

            """
            
            results = self.db.fetch_all(query, [project_id])
            
            if not results:
                return {
                    'status': 'error',
                    'message': 'لا توجد بنود للمشروع المحدد'
                }
            
            # تحويل النتائج إلى إطار بيانات
            df = pd.DataFrame(results, columns=[
                'id', 'item_number', 'description', 'quantity', 'unit_price', 
                'total_price', 'category_name'
            ])
            
            # معالجة القيم المفقودة في عمود الفئة
            df['category_name'] = df['category_name'].fillna('أخرى')
            
            # حساب إجمالي المشروع
            project_total = df['total_price'].sum()
            
            # تحليل البنود حسب الفئة
            category_analysis = df.groupby('category_name').agg({
                'total_price': 'sum'
            }).reset_index()
            
            # إضافة النسبة المئوية
            category_analysis['percentage'] = (category_analysis['total_price'] / project_total) * 100
            
            # ترتيب الفئات حسب التكلفة
            category_analysis = category_analysis.sort_values('total_price', ascending=False)
            
            # تحليل البنود الأعلى تكلفة
            top_items = df.sort_values('total_price', ascending=False).head(10)
            top_items['percentage'] = (top_items['total_price'] / project_total) * 100
            
            # حساب تركيز التكلفة (نسبة باريتو)
            df_sorted = df.sort_values('total_price', ascending=False)
            df_sorted['cumulative_cost'] = df_sorted['total_price'].cumsum()
            df_sorted['cumulative_percentage'] = (df_sorted['cumulative_cost'] / project_total) * 100
            
            # تحديد عدد البنود التي تشكل 80% من التكلفة
            items_80_percent = len(df_sorted[df_sorted['cumulative_percentage'] <= 80])
            if items_80_percent == 0:
                items_80_percent = 1
            
            pareto_ratio = items_80_percent / len(df)
            
            # إنشاء رسوم بيانية
            category_chart_path = self._create_category_chart(category_analysis)
            top_items_chart_path = self._create_top_items_chart(top_items)
            pareto_chart_path = self._create_pareto_chart(df_sorted)
            
            return {
                'status': 'success',
                'data': {
                    'project_id': project_id,
                    'project_total': project_total,
                    'category_analysis': category_analysis.to_dict('records'),
                    'top_items': top_items.to_dict('records'),
                    'pareto_ratio': pareto_ratio,
                    'items_80_percent': items_80_percent,
                    'total_items': len(df),
                    'category_chart_path': category_chart_path,
                    'top_items_chart_path': top_items_chart_path,
                    'pareto_chart_path': pareto_chart_path
                }
            }
            
        except Exception as e:
            logger.error(f"خطأ في تحليل محركات التكلفة: {str(e)}")
            return {
                'status': 'error',
                'message': f'حدث خطأ أثناء تحليل محركات التكلفة: {str(e)}'
            }
    
    def _create_category_chart(self, category_analysis):
        """إنشاء رسم بياني للتكاليف حسب الفئة

        

        المعلمات:

            category_analysis (pandas.DataFrame): تحليل الفئات

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني جديد
            plt.figure(figsize=(10, 6))
            
            # رسم مخطط دائري
            plt.pie(
                category_analysis['total_price'],
                labels=category_analysis['category_name'],
                autopct='%1.1f%%',
                startangle=90,
                shadow=False,
                wedgeprops={'edgecolor': 'white', 'linewidth': 1}
            )
            
            # إضافة عنوان
            plt.title('توزيع التكاليف حسب الفئة')
            
            # جعل الرسم البياني دائريًا
            plt.axis('equal')
            
            # ضبط التخطيط
            plt.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"cost_category_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني للتكاليف حسب الفئة: {str(e)}")
            return None
    
    def _create_top_items_chart(self, top_items):
        """إنشاء رسم بياني للبنود الأعلى تكلفة

        

        المعلمات:

            top_items (pandas.DataFrame): البنود الأعلى تكلفة

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني جديد
            plt.figure(figsize=(12, 6))
            
            # إعداد البيانات للرسم
            items = [f"{row['item_number']} - {row['description'][:20]}..." for _, row in top_items.iterrows()]
            costs = top_items['total_price'].tolist()
            
            # رسم الأعمدة
            bars = plt.barh(items, costs, color='skyblue', edgecolor='navy')
            
            # إضافة القيم على الأعمدة
            for i, bar in enumerate(bars):
                width = bar.get_width()
                plt.text(width * 1.01, bar.get_y() + bar.get_height()/2,
                        f'{width:,.0f} ({top_items["percentage"].iloc[i]:.1f}%)',
                        va='center')
            
            # إضافة عنوان ومحاور
            plt.title('البنود الأعلى تكلفة')
            plt.xlabel('التكلفة')
            plt.ylabel('البنود')
            
            # إضافة شبكة
            plt.grid(True, linestyle='--', alpha=0.7, axis='x')
            
            # ضبط التخطيط
            plt.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"top_cost_items_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني للبنود الأعلى تكلفة: {str(e)}")
            return None
    
    def _create_pareto_chart(self, df_sorted):
        """إنشاء رسم بياني لتحليل باريتو

        

        المعلمات:

            df_sorted (pandas.DataFrame): إطار البيانات المرتب

            

        العائد:

            str: مسار ملف الرسم البياني

        """
        try:
            # إنشاء رسم بياني جديد
            fig, ax1 = plt.subplots(figsize=(12, 6))
            
            # إعداد البيانات للرسم
            x = range(1, len(df_sorted) + 1)
            y1 = df_sorted['total_price'].tolist()
            y2 = df_sorted['cumulative_percentage'].tolist()
            
            # رسم الأعمدة (التكلفة)
            ax1.bar(x, y1, color='skyblue', alpha=0.7)
            ax1.set_xlabel('عدد البنود')
            ax1.set_ylabel('التكلفة', color='navy')
            ax1.tick_params(axis='y', labelcolor='navy')
            
            # إنشاء محور ثانوي
            ax2 = ax1.twinx()
            
            # رسم الخط (النسبة التراكمية)
            ax2.plot(x, y2, 'r-', linewidth=2, marker='o', markersize=4)
            ax2.set_ylabel('النسبة التراكمية (%)', color='red')
            ax2.tick_params(axis='y', labelcolor='red')
            
            # إضافة خط 80%
            ax2.axhline(y=80, color='green', linestyle='--', alpha=0.7)
            
            # إضافة عنوان
            plt.title('تحليل باريتو للتكاليف')
            
            # إضافة شبكة
            ax1.grid(True, linestyle='--', alpha=0.7)
            
            # ضبط التخطيط
            fig.tight_layout()
            
            # حفظ الرسم البياني
            chart_filename = f"pareto_analysis_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
            chart_path = os.path.join(self.charts_dir, chart_filename)
            plt.savefig(chart_path, dpi=100, bbox_inches='tight')
            plt.close()
            
            return chart_path
            
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسم بياني لتحليل باريتو: {str(e)}")
            return None
    
    def generate_price_analysis_charts(self, analysis_type, params):
        """إنشاء رسوم بيانية لتحليل الأسعار

        

        المعلمات:

            analysis_type (str): نوع التحليل

            params (dict): معلمات التحليل

            

        العائد:

            dict: قاموس يحتوي على مسارات الرسوم البيانية

        """
        try:
            if analysis_type == 'trend':
                # تحليل اتجاه السعر
                if 'item_id' not in params:
                    return {
                        'status': 'error',
                        'message': 'لم يتم تحديد معرف البند'
                    }
                
                result = self.analyze_price_trends(
                    params['item_id'],
                    params.get('start_date'),
                    params.get('end_date')
                )
                
                if result['status'] == 'success':
                    return {
                        'status': 'success',
                        'charts': [result['data']['chart_path']]
                    }
                else:
                    return result
                
            elif analysis_type == 'comparison':
                # مقارنة الأسعار
                if 'items' not in params:
                    return {
                        'status': 'error',
                        'message': 'لم يتم تحديد البنود للمقارنة'
                    }
                
                result = self.compare_prices(
                    params['items'],
                    params.get('date')
                )
                
                if result['status'] == 'success':
                    return {
                        'status': 'success',
                        'charts': [result['data']['chart_path']]
                    }
                else:
                    return result
                
            elif analysis_type == 'volatility':
                # تحليل تقلب الأسعار
                if 'item_id' not in params:
                    return {
                        'status': 'error',
                        'message': 'لم يتم تحديد معرف البند'
                    }
                
                result = self.calculate_price_volatility(
                    params['item_id'],
                    params.get('period', '1y')
                )
                
                if result['status'] == 'success':
                    return {
                        'status': 'success',
                        'charts': [result['data']['chart_path']]
                    }
                else:
                    return result
                
            elif analysis_type == 'sensitivity':
                # تحليل الحساسية
                if 'project_id' not in params or 'variable_items' not in params:
                    return {
                        'status': 'error',
                        'message': 'لم يتم تحديد معرف المشروع أو البنود المتغيرة'
                    }
                
                result = self.perform_sensitivity_analysis(
                    params['project_id'],
                    params['variable_items'],
                    params.get('ranges', {})
                )
                
                if result['status'] == 'success':
                    return {
                        'status': 'success',
                        'charts': [result['data']['chart_path']]
                    }
                else:
                    return result
                
            elif analysis_type == 'correlation':
                # تحليل الارتباطات
                if 'items' not in params:
                    return {
                        'status': 'error',
                        'message': 'لم يتم تحديد البنود للتحليل'
                    }
                
                result = self.analyze_price_correlations(params['items'])
                
                if result['status'] == 'success':
                    return {
                        'status': 'success',
                        'charts': [result['data']['chart_path'], result['data']['trends_chart_path']]
                    }
                else:
                    return result
                
            elif analysis_type == 'market_comparison':
                # مقارنة مع أسعار السوق
                if 'items' not in params:
                    return {
                        'status': 'error',
                        'message': 'لم يتم تحديد البنود للمقارنة'
                    }
                
                result = self.compare_with_market_prices(params['items'])
                
                if result['status'] == 'success':
                    return {
                        'status': 'success',
                        'charts': [result['data']['chart_path']]
                    }
                else:
                    return result
                
            elif analysis_type == 'cost_drivers':
                # تحليل محركات التكلفة
                if 'project_id' not in params:
                    return {
                        'status': 'error',
                        'message': 'لم يتم تحديد معرف المشروع'
                    }
                
                result = self.analyze_cost_drivers(params['project_id'])
                
                if result['status'] == 'success':
                    return {
                        'status': 'success',
                        'charts': [
                            result['data']['category_chart_path'],
                            result['data']['top_items_chart_path'],
                            result['data']['pareto_chart_path']
                        ]
                    }
                else:
                    return result
                
            else:
                return {
                    'status': 'error',
                    'message': f'نوع التحليل غير معروف: {analysis_type}'
                }
                
        except Exception as e:
            logger.error(f"خطأ في إنشاء رسوم بيانية لتحليل الأسعار: {str(e)}")
            return {
                'status': 'error',
                'message': f'حدث خطأ أثناء إنشاء رسوم بيانية لتحليل الأسعار: {str(e)}'
            }