File size: 45,207 Bytes
86fc9d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# data_manager.py - سیستم Hybrid پیشرفته کامل

import os
import json
import logging
from datetime import datetime, timedelta
import tiktoken
import threading
import time

# --- افزودن قفل برای ایمنی thread-safe ---
DATA_LOCK = threading.Lock()

# --- تنظیمات مسیر فایل‌ها ---
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_FILE = os.path.join(BASE_DIR, "bot_data.json")
LOG_FILE = os.path.join(BASE_DIR, "bot.log")

# --- کش داده‌های گلوبال ---
DATA = {
    "users": {},
    "groups": {},
    "banned_users": set(),
    "stats": {
        "total_messages": 0,
        "total_users": 0,
        "total_groups": 0,
        "avg_response_time": 0.0,
        "max_response_time": 0.0,
        "min_response_time": float('inf'),
        "total_responses": 0
    },
    "welcome_message": "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.",
    "group_welcome_message": "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید",
    "goodbye_message": "کاربر {user_mention} گروه را ترک کرد. خداحافظ!",
    "maintenance_mode": False,
    "blocked_words": [],
    "scheduled_broadcasts": [],
    "bot_start_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    "context_mode": "hybrid",  # تغییر پیش‌فرض به hybrid
    "system_instructions": {
        "global": "شما یک دستیار هوشمند فارسی هستید. پاسخ‌های شما باید مفید، دقیق و دوستانه باشد. از کلمات فارسی صحیح استفاده کنید و در صورت نیاز توضیحات کامل ارائه دهید.",
        "groups": {},
        "users": {}
    },
    "hybrid_settings": {  # تنظیمات جدید برای Hybrid پیشرفته
        "mode": "advanced",  # basic یا advanced
        "enable_user_tracking": True,
        "max_other_users": 5,
        "personal_context_weight": 1.0,
        "group_context_weight": 0.8,
        "other_users_weight": 0.6,
        "max_combined_tokens": 30000,
        "enable_cross_user_references": True
    }
}

logger = logging.getLogger(__name__)

# --- توابع کمکی ---
def count_tokens(text: str) -> int:
    """شمارش تعداد توکن‌های متن با استفاده از tokenizer"""
    try:
        encoding = tiktoken.get_encoding("cl100k_base")
        return len(encoding.encode(text))
    except Exception as e:
        logger.warning(f"Error counting tokens: {e}, using fallback")
        return max(1, len(text) // 4)

def load_data():
    """داده‌ها را از فایل JSON بارگذاری کرده و در کش گلوبال ذخیره می‌کند."""
    global DATA
    with DATA_LOCK:
        try:
            if not os.path.exists(DATA_FILE):
                logger.info(f"فایل داده در {DATA_FILE} یافت نشد. یک فایل جدید ایجاد می‌شود.")
                save_data()
                return

            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                loaded_data = json.load(f)
                loaded_data['banned_users'] = set(loaded_data.get('banned_users', []))
                
                # اطمینان از وجود کلیدهای جدید
                if 'groups' not in loaded_data: loaded_data['groups'] = {}
                if 'context_mode' not in loaded_data: loaded_data['context_mode'] = 'hybrid'
                if 'group_welcome_message' not in loaded_data: 
                    loaded_data['group_welcome_message'] = "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم..."
                if 'total_groups' not in loaded_data.get('stats', {}): 
                    if 'stats' not in loaded_data: loaded_data['stats'] = {}
                    loaded_data['stats']['total_groups'] = len(loaded_data.get('groups', {}))
                
                # اطمینان از وجود hybrid_settings
                if 'hybrid_settings' not in loaded_data:
                    loaded_data['hybrid_settings'] = DATA['hybrid_settings']
                
                # تبدیل اعضای گروه از list به set
                for group_id in loaded_data.get('groups', {}):
                    if 'members' in loaded_data['groups'][group_id]:
                        if isinstance(loaded_data['groups'][group_id]['members'], list):
                            loaded_data['groups'][group_id]['members'] = set(loaded_data['groups'][group_id]['members'])
                        elif not isinstance(loaded_data['groups'][group_id]['members'], set):
                            loaded_data['groups'][group_id]['members'] = set()
                    else:
                        loaded_data['groups'][group_id]['members'] = set()
                
                # اطمینان از وجود context برای گروه‌های قدیمی
                for group_id in loaded_data.get('groups', {}):
                    if 'context' not in loaded_data['groups'][group_id]:
                        loaded_data['groups'][group_id]['context'] = []
                
                # اطمینان از وجود context برای کاربران قدیمی
                for user_id in loaded_data.get('users', {}):
                    if 'context' not in loaded_data['users'][user_id]:
                        loaded_data['users'][user_id]['context'] = []
                
                # اطمینان از وجود کلیدهای آمار پاسخگویی
                if 'stats' in loaded_data:
                    stats_keys = ['avg_response_time', 'max_response_time', 'min_response_time', 'total_responses']
                    for key in stats_keys:
                        if key not in loaded_data['stats']:
                            if key == 'min_response_time':
                                loaded_data['stats'][key] = float('inf')
                            else:
                                loaded_data['stats'][key] = 0.0
                
                # اطمینان از وجود system_instructions
                if 'system_instructions' not in loaded_data:
                    loaded_data['system_instructions'] = DATA['system_instructions']

                if 'added_admins' not in loaded_data:
                    loaded_data['added_admins'] = []
                
                DATA.update(loaded_data)
                logger.info(f"داده‌ها با موفقیت از {DATA_FILE} بارگذاری شدند.")

        except json.JSONDecodeError as e:
            logger.error(f"خطا در خواندن JSON از {DATA_FILE}: {e}. ربات با داده‌های اولیه شروع به کار می‌کند.")
        except Exception as e:
            logger.error(f"خطای غیرمنتظره هنگام بارگذاری داده‌ها: {e}. ربات با داده‌های اولیه شروع به کار می‌کند.")

def save_data():
    """کش گلوبال داده‌ها را در فایل JSON ذخیره می‌کند."""
    global DATA
    with DATA_LOCK:
        try:
            data_to_save = DATA.copy()
            data_to_save['banned_users'] = list(DATA['banned_users'])
            
            # تبدیل set اعضای گروه به list برای ذخیره JSON
            for group_id in data_to_save.get('groups', {}):
                if 'members' in data_to_save['groups'][group_id]:
                    if isinstance(data_to_save['groups'][group_id]['members'], set):
                        data_to_save['groups'][group_id]['members'] = list(data_to_save['groups'][group_id]['members'])
                    elif not isinstance(data_to_save['groups'][group_id]['members'], list):
                        data_to_save['groups'][group_id]['members'] = []
            
            with open(DATA_FILE, 'w', encoding='utf-8') as f:
                json.dump(data_to_save, f, indent=4, ensure_ascii=False)
            logger.debug(f"داده‌ها با موفقیت در {DATA_FILE} ذخیره شدند.")
        except Exception as e:
            logger.error(f"خطای مهلک: امکان ذخیره داده‌ها در {DATA_FILE} وجود ندارد. خطا: {e}")

# --- توابع مدیریت کاربران ---
def update_user_stats(user_id: int, user):
    """آمار کاربر را پس از هر پیام به‌روز کرده و داده‌ها را ذخیره می‌کند."""
    global DATA
    with DATA_LOCK:
        now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        user_id_str = str(user_id)
        
        if user_id_str not in DATA['users']:
            DATA['users'][user_id_str] = {
                'first_name': user.first_name,
                'username': user.username,
                'first_seen': now_str,
                'message_count': 0,
                'context': [],
                'last_group_activity': {},
                'user_profile': {
                    'language_preference': 'fa',
                    'interaction_style': 'normal'
                }
            }
            DATA['stats']['total_users'] += 1
            logger.info(f"کاربر جدید ثبت شد: {user_id} ({user.first_name})")

        DATA['users'][user_id_str]['last_seen'] = now_str
        DATA['users'][user_id_str]['message_count'] += 1
        DATA['stats']['total_messages'] += 1
        
        save_data()

def update_response_stats(response_time: float):
    """آمار زمان پاسخگویی را به‌روز می‌کند."""
    global DATA
    with DATA_LOCK:
        if DATA['stats']['total_responses'] == 0:
            DATA['stats']['min_response_time'] = response_time

        DATA['stats']['total_responses'] += 1
        
        # محاسبه میانگین جدید
        current_avg = DATA['stats']['avg_response_time']
        total_responses = DATA['stats']['total_responses']
        new_avg = ((current_avg * (total_responses - 1)) + response_time) / total_responses
        DATA['stats']['avg_response_time'] = new_avg
        
        # به‌روزرسانی حداکثر و حداقل زمان پاسخگویی
        if response_time > DATA['stats']['max_response_time']:
            DATA['stats']['max_response_time'] = response_time
        
        if response_time < DATA['stats']['min_response_time']:
            DATA['stats']['min_response_time'] = response_time
        
        save_data()

# --- توابع مدیریت مسدودیت ---
def is_user_banned(user_id: int) -> bool:
    """بررسی می‌کند آیا کاربر مسدود شده است یا خیر."""
    return user_id in DATA['banned_users']

def ban_user(user_id: int):
    """کاربر را مسدود کرده و ذخیره می‌کند."""
    with DATA_LOCK:
        DATA['banned_users'].add(user_id)
        save_data()

def unban_user(user_id: int):
    """مسدودیت کاربر را برداشته و ذخیره می‌کند."""
    with DATA_LOCK:
        DATA['banned_users'].discard(user_id)
        save_data()

def contains_blocked_words(text: str) -> bool:
    """بررسی می‌کند آیا متن حاوی کلمات مسدود شده است یا خیر."""
    if not DATA['blocked_words']:
        return False
    
    text_lower = text.lower()
    for word in DATA['blocked_words']:
        if word in text_lower:
            return True
    
    return False

# --- توابع مدیریت کاربران و گروه‌ها ---
def get_active_users(days: int) -> list:
    """لیست کاربران فعال در بازه زمانی مشخص را برمی‌گرداند."""
    now = datetime.now()
    cutoff_date = now - timedelta(days=days)
    
    active_users = []
    for user_id, user_info in DATA['users'].items():
        if 'last_seen' in user_info:
            try:
                last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
                if last_seen >= cutoff_date:
                    active_users.append(int(user_id))
            except ValueError:
                continue
    
    return active_users

def get_users_by_message_count(min_count: int) -> list:
    """لیست کاربران با تعداد پیام بیشتر یا مساوی مقدار مشخص را برمی‌گرداند."""
    users = []
    for user_id, user_info in DATA['users'].items():
        if user_info.get('message_count', 0) >= min_count:
            users.append(int(user_id))
    
    return users

# --- توابع مدیریت context کاربران ---
def add_to_user_context(user_id: int, role: str, content: str):
    """اضافه کردن پیام به context کاربر و محدود کردن به ۱۰۲۴ توکن"""
    add_to_user_context_with_reply(user_id, role, content, None)

def add_to_user_context_with_reply(user_id: int, role: str, content: str, reply_info: dict = None):
    """اضافه کردن پیام به context کاربر با اطلاعات ریپلای"""
    with DATA_LOCK:
        user_id_str = str(user_id)
        
        if user_id_str not in DATA['users']:
            return
        
        if 'context' not in DATA['users'][user_id_str]:
            DATA['users'][user_id_str]['context'] = []
        
        # اضافه کردن پیام جدید
        message = {
            'role': role,
            'content': content,
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'has_reply': False
        }
        
        if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
            message['has_reply'] = True
            message['reply_to_user_id'] = reply_info.get('replied_user_id')
            message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
            message['reply_to_content'] = reply_info['replied_text']
            message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
            message['reply_timestamp'] = reply_info.get('timestamp', time.time())
        
        DATA['users'][user_id_str]['context'].append(message)
        
        # محدود کردن context به 16384 توکن
        trim_user_context(user_id, max_tokens=16384)
        
        save_data()

def trim_user_context(user_id: int, max_tokens: int = 16384):
    """کوتاه کردن context کاربر به تعداد توکن مشخص"""
    user_id_str = str(user_id)
    
    if user_id_str not in DATA['users'] or 'context' not in DATA['users'][user_id_str]:
        return
    
    context = DATA['users'][user_id_str]['context']
    
    if not context:
        return
    
    # محاسبه توکن‌های کل
    total_tokens = sum(count_tokens(msg['content']) for msg in context)
    
    # حذف قدیمی‌ترین پیام‌ها تا زمانی که توکن‌ها زیر حد مجاز باشد
    while total_tokens > max_tokens and len(context) > 1:
        removed_message = context.pop(0)
        total_tokens -= count_tokens(removed_message['content'])
    
    # اگر هنوز بیشتر از حد مجاز است، از محتوای پیام‌ها کم کن
    if total_tokens > max_tokens and context:
        last_message = context[-1]
        content = last_message['content']
        
        tokens = count_tokens(content)
        if tokens > max_tokens:
            context.pop()
        else:
            while tokens > (max_tokens - (total_tokens - tokens)) and content:
                words = content.split()
                if len(words) > 1:
                    content = ' '.join(words[:-1])
                else:
                    content = content[:-1] if len(content) > 1 else ''
                tokens = count_tokens(content)
            
            if content:
                context[-1]['content'] = content
            else:
                context.pop()
    
    save_data()

def get_user_context(user_id: int) -> list:
    """دریافت context کاربر"""
    user_id_str = str(user_id)
    
    if user_id_str not in DATA['users']:
        return []
    
    return DATA['users'][user_id_str].get('context', []).copy()

def clear_user_context(user_id: int):
    """پاک کردن context کاربر"""
    with DATA_LOCK:
        user_id_str = str(user_id)
        
        if user_id_str in DATA['users']:
            if 'context' in DATA['users'][user_id_str]:
                DATA['users'][user_id_str]['context'] = []
                save_data()
                logger.info(f"Context cleared for user {user_id}")

def get_context_summary(user_id: int) -> str:
    """خلاصه‌ای از context کاربر"""
    context = get_user_context(user_id)
    if not context:
        return "بدون تاریخچه"
    
    total_messages = len(context)
    total_tokens = sum(count_tokens(msg['content']) for msg in context)
    
    # تعداد ریپلای‌ها
    reply_count = sum(1 for msg in context if msg.get('has_reply', False))
    
    # نمایش آخرین پیام
    last_message = context[-1] if context else {}
    last_content = last_message.get('content', '')[:50]
    if len(last_message.get('content', '')) > 50:
        last_content += "..."
    
    return f"{total_messages} پیام ({total_tokens} توکن) - {reply_count} ریپلای - آخرین: {last_message.get('role', '')}: {last_content}"

def get_context_for_api(user_id: int) -> list:
    """فرمت context برای ارسال به API"""
    context = get_user_context(user_id)
    
    api_context = []
    for msg in context:
        api_context.append({
            'role': msg['role'],
            'content': msg['content']
        })
    
    return api_context

def get_context_token_count(user_id: int) -> int:
    """تعداد کل توکن‌های context کاربر"""
    context = get_user_context(user_id)
    return sum(count_tokens(msg['content']) for msg in context)

# --- توابع مدیریت گروه‌ها ---
def update_group_stats(chat_id: int, chat, user_id: int = None):
    """آمار گروه را به‌روز کرده و داده‌ها را ذخیره می‌کند."""
    global DATA
    with DATA_LOCK:
        now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        chat_id_str = str(chat_id)
        
        if chat_id_str not in DATA['groups']:
            DATA['groups'][chat_id_str] = {
                'title': chat.title if hasattr(chat, 'title') else 'Private Group',
                'type': chat.type,
                'first_seen': now_str,
                'message_count': 0,
                'members': set(),
                'context': [],
                'recent_users': [],
                'last_activity': now_str
            }
            DATA['stats']['total_groups'] += 1
            logger.info(f"گروه جدید ثبت شد: {chat_id} ({chat.title if hasattr(chat, 'title') else 'Private'})")

        DATA['groups'][chat_id_str]['last_seen'] = now_str
        DATA['groups'][chat_id_str]['last_activity'] = now_str
        DATA['groups'][chat_id_str]['message_count'] += 1
        
        # اضافه کردن کاربر به لیست اعضای گروه
        if user_id is not None:
            if 'members' not in DATA['groups'][chat_id_str]:
                DATA['groups'][chat_id_str]['members'] = set()
            elif isinstance(DATA['groups'][chat_id_str]['members'], list):
                DATA['groups'][chat_id_str]['members'] = set(DATA['groups'][chat_id_str]['members'])
            
            DATA['groups'][chat_id_str]['members'].add(user_id)
            
            # به‌روزرسانی لیست کاربران اخیر
            if 'recent_users' not in DATA['groups'][chat_id_str]:
                DATA['groups'][chat_id_str]['recent_users'] = []
            
            # حذف کاربر از لیست اگر وجود دارد
            recent_users = DATA['groups'][chat_id_str]['recent_users']
            recent_users = [uid for uid in recent_users if uid != user_id]
            
            # اضافه کردن کاربر به ابتدای لیست
            recent_users.insert(0, user_id)
            
            # محدود کردن به 20 کاربر اخیر
            if len(recent_users) > 20:
                recent_users = recent_users[:20]
            
            DATA['groups'][chat_id_str]['recent_users'] = recent_users
        
        save_data()

def add_to_group_context(chat_id: int, role: str, content: str, user_name: str = None):
    """اضافه کردن پیام به context گروه و محدود کردن به 16384 توکن"""
    add_to_group_context_with_reply(chat_id, role, content, user_name, None, None)

def add_to_group_context_with_reply(chat_id: int, role: str, content: str, user_name: str = None, 
                                   reply_info: dict = None, user_id: int = None):
    """اضافه کردن پیام به context گروه با اطلاعات ریپلای"""
    with DATA_LOCK:
        chat_id_str = str(chat_id)
        
        if chat_id_str not in DATA['groups']:
            return
        
        if 'context' not in DATA['groups'][chat_id_str]:
            DATA['groups'][chat_id_str]['context'] = []
        
        # اضافه کردن نام کاربر به محتوا اگر مشخص باشد
        if user_name and role == 'user':
            content_with_name = f"{user_name}: {content}"
        else:
            content_with_name = content
        
        # اضافه کردن پیام جدید با اطلاعات کامل
        message = {
            'role': role,
            'content': content_with_name if role == 'user' else content,
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'user_name': user_name if role == 'user' else None,
            'user_id': user_id,  # ذخیره user_id برای مدیریت Hybrid
            'has_reply': False,
            'message_type': 'group'
        }
        
        if reply_info and 'replied_text' in reply_info and reply_info['replied_text']:
            message['has_reply'] = True
            message['reply_to_user_id'] = reply_info.get('replied_user_id')
            message['reply_to_user_name'] = reply_info.get('replied_user_name', 'Unknown')
            message['reply_to_content'] = reply_info['replied_text']
            message['is_reply_to_bot'] = reply_info.get('is_reply_to_bot', False)
            message['reply_timestamp'] = reply_info.get('timestamp', time.time())
        
        DATA['groups'][chat_id_str]['context'].append(message)
        
        # محدود کردن context گروه
        trim_group_context(chat_id, max_tokens=32768)
        
        save_data()

def optimize_group_context(chat_id: int):
    """بهینه‌سازی context گروه برای حفظ مهم‌ترین پیام‌ها"""
    chat_id_str = str(chat_id)
    
    if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
        return
    
    context = DATA['groups'][chat_id_str]['context']
    if len(context) <= 10:
        return
    
    # محاسبه اهمیت هر پیام
    scored_messages = []
    for i, msg in enumerate(context):
        score = 0
        
        # امتیاز بر اساس طول
        content_length = len(msg['content'])
        score += min(content_length / 100, 10)
        
        # امتیاز بر اساس تازگی
        recency = len(context) - i
        score += min(recency / 10, 20)
        
        # امتیاز بیشتر برای پاسخ‌های هوش مصنوعی
        if msg['role'] == 'assistant':
            score += 15
        
        # امتیاز بیشتر برای پیام‌های دارای ریپلای
        if msg.get('has_reply', False):
            score += 10
        
        # امتیاز منفی برای پیام‌های کوتاه
        if content_length < 20:
            score -= 5
        
        scored_messages.append((score, msg))
    
    # مرتب‌سازی بر اساس امتیاز
    scored_messages.sort(key=lambda x: x[0], reverse=True)
    
    # حفظ 90% از پیام‌های با بالاترین امتیاز
    keep_count = int(len(scored_messages) * 0.9)
    kept_messages = [msg for _, msg in scored_messages[:keep_count]]
    
    # مرتب‌سازی مجدد بر اساس زمان
    kept_messages.sort(key=lambda x: x.get('timestamp', ''))
    
    DATA['groups'][chat_id_str]['context'] = kept_messages
    save_data()
    
    logger.info(f"Optimized group {chat_id} context: {len(context)} -> {len(kept_messages)} messages")

def trim_group_context(chat_id: int, max_tokens: int = 32768):
    """کوتاه کردن context گروه به تعداد توکن مشخص"""
    chat_id_str = str(chat_id)
    
    if chat_id_str not in DATA['groups'] or 'context' not in DATA['groups'][chat_id_str]:
        return
    
    context = DATA['groups'][chat_id_str]['context']
    
    if not context:
        return
    
    # محاسبه توکن‌های کل
    total_tokens = sum(count_tokens(msg['content']) for msg in context)
    
    # اگر تعداد توکن‌ها بیش از حد مجاز است، ابتدا بهینه‌سازی کن
    if total_tokens > max_tokens * 1.5:
        optimize_group_context(chat_id)
        context = DATA['groups'][chat_id_str]['context']
        total_tokens = sum(count_tokens(msg['content']) for msg in context)
    
    # حذف قدیمی‌ترین پیام‌ها
    while total_tokens > max_tokens and len(context) > 1:
        removed_message = context.pop(0)
        total_tokens -= count_tokens(removed_message['content'])
    
    # اگر هنوز بیشتر از حد مجاز است، از محتوای پیام‌ها کم کن
    if total_tokens > max_tokens and context:
        last_message = context[-1]
        content = last_message['content']
        
        tokens = count_tokens(content)
        if tokens > max_tokens:
            context.pop()
        else:
            while tokens > (max_tokens - (total_tokens - tokens)) and content:
                words = content.split()
                if len(words) > 1:
                    content = ' '.join(words[:-1])
                else:
                    content = content[:-1] if len(content) > 1 else ''
                tokens = count_tokens(content)
            
            if content:
                context[-1]['content'] = content
            else:
                context.pop()
    
    save_data()

def get_group_context(chat_id: int) -> list:
    """دریافت context گروه"""
    chat_id_str = str(chat_id)
    
    if chat_id_str not in DATA['groups']:
        return []
    
    return DATA['groups'][chat_id_str].get('context', []).copy()

def get_context_for_api_group(chat_id: int) -> list:
    """فرمت context گروه برای ارسال به API"""
    context = get_group_context(chat_id)
    
    api_context = []
    for msg in context:
        api_context.append({
            'role': msg['role'],
            'content': msg['content']
        })
    
    return api_context

def clear_group_context(chat_id: int):
    """پاک کردن context گروه"""
    with DATA_LOCK:
        chat_id_str = str(chat_id)
        
        if chat_id_str in DATA['groups']:
            if 'context' in DATA['groups'][chat_id_str]:
                DATA['groups'][chat_id_str]['context'] = []
                save_data()
                logger.info(f"Context cleared for group {chat_id}")

def get_group_context_summary(chat_id: int) -> str:
    """خلاصه‌ای از context گروه"""
    context = get_group_context(chat_id)
    if not context:
        return "بدون تاریخچه"
    
    total_messages = len(context)
    total_tokens = sum(count_tokens(msg['content']) for msg in context)
    
    # تعداد ریپلای‌ها
    reply_count = sum(1 for msg in context if msg.get('has_reply', False))
    
    # شمارش کاربران منحصربه‌فرد
    unique_users = set()
    for msg in context:
        if msg.get('user_id'):
            unique_users.add(msg['user_id'])
    
    last_message = context[-1] if context else {}
    last_content = last_message.get('content', '')[:50]
    if len(last_message.get('content', '')) > 50:
        last_content += "..."
    
    return f"{total_messages} پیام ({total_tokens} توکن) - {len(unique_users)} کاربر - {reply_count} ریپلای - آخرین: {last_content}"

# --- توابع سیستم Hybrid پیشرفته ---
def add_to_hybrid_context_advanced(user_id: int, chat_id: int, role: str, content: str, 
                                   user_name: str = None, reply_info: dict = None):
    """
    ذخیره پیشرفته در context ترکیبی
    هم در تاریخچه شخصی و هم در تاریخچه گروه ذخیره می‌شود
    """
    # ذخیره در تاریخچه شخصی کاربر
    add_to_user_context_with_reply(user_id, role, content, reply_info)
    
    # ذخیره در تاریخچه گروه با اطلاعات کامل
    add_to_group_context_with_reply(chat_id, role, content, user_name, reply_info, user_id)

def get_advanced_hybrid_context_for_api(user_id: int, chat_id: int) -> list:
    """
    دریافت context ترکیبی پیشرفته برای ارسال به API
    ترکیب هوشمندانه:
    1. تاریخچه شخصی کاربر
    2. تاریخچه گروه (بدون تکراری‌ها)
    3. اطلاعات کاربران دیگر فعال در گروه
    """
    # 1. دریافت system instruction
    system_instruction = get_system_instruction(user_id=user_id, chat_id=chat_id)
    
    # 2. دریافت تاریخچه شخصی کاربر
    user_context = get_context_for_api(user_id)
    
    # 3. دریافت تاریخچه گروه
    group_context_raw = get_group_context(chat_id)
    
    # 4. فیلتر کردن: حذف پیام‌های تکراری کاربر فعلی از تاریخچه گروه
    user_messages_in_personal = set()
    for msg in user_context:
        if msg['role'] == 'user':
            # استخراج متن اصلی (بدون نام کاربر)
            content = msg['content']
            user_messages_in_personal.add(content[:100])  # ذخیره 100 کاراکتر اول
    
    filtered_group_context = []
    for msg in group_context_raw:
        if msg.get('user_id') == user_id and msg['role'] == 'user':
            # بررسی اینکه آیا این پیام در تاریخچه شخصی کاربر هست
            content_snippet = msg['content'][:100]
            if content_snippet in user_messages_in_personal:
                continue  # حذف پیام تکراری
        filtered_group_context.append(msg)
    
    # 5. دریافت اطلاعات کاربران دیگر در گروه
    other_users_info = get_other_users_summary_in_group(user_id, chat_id)
    
    # 6. ترکیب پیام‌ها
    combined_context = []
    
    # اضافه کردن system instruction
    if system_instruction:
        combined_context.append({"role": "system", "content": system_instruction})
    
    # اضافه کردن دستور ویژه برای حالت Hybrid
    hybrid_instruction = f"""
    شما در حال پاسخ به کاربر {user_id} ({get_user_name(user_id)}) در یک گروه هستید.
    
    اطلاعات وضعیت:
    - حالت: Hybrid پیشرفته
    - کاربر فعلی: {get_user_name(user_id)} (آیدی: {user_id})
    - گروه: {get_group_name(chat_id)}
    - کاربران دیگر فعال در گروه: {len(other_users_info)} کاربر
    
    دستورالعمل‌ها:
    1. پاسخ‌های شما باید مخصوص کاربر فعلی ({get_user_name(user_id)}) باشد.
    2. می‌توانید به کاربران دیگر نیز در پاسخ اشاره کنید اگر مرتبط است.
    3. از تاریخچه شخصی کاربر و تاریخچه گروه استفاده کنید.
    4. پاسخ‌های دقیق و مرتبط بدهید.
    """
    
    combined_context.append({"role": "system", "content": hybrid_instruction})
    
    # اضافه کردن اطلاعات خلاصه کاربران دیگر
    if other_users_info and DATA['hybrid_settings']['enable_cross_user_references']:
        other_users_summary = "📋 **اطلاعات کاربران دیگر در گروه:**\n"
        for info in other_users_info:
            other_users_summary += f"- {info['name']}: {info['summary']}\n"
        
        combined_context.append({
            "role": "system",
            "content": other_users_summary[:500] + "..." if len(other_users_summary) > 500 else other_users_summary
        })
    
    # اضافه کردن تاریخچه شخصی کاربر
    combined_context.extend(user_context[-10:])  # فقط 10 پیام آخر شخصی
    
    # اضافه کردن تاریخچه گروه فیلتر شده
    for msg in filtered_group_context[-20:]:  # فقط 20 پیام آخر گروه
        combined_context.append({
            'role': msg['role'],
            'content': msg['content']
        })
    
    # محدود کردن کل توکن‌ها
    return limit_context_tokens(combined_context, DATA['hybrid_settings']['max_combined_tokens'])

def get_other_users_summary_in_group(current_user_id: int, chat_id: int) -> list:
    """دریافت خلاصه اطلاعات کاربران دیگر در گروه"""
    chat_id_str = str(chat_id)
    
    if chat_id_str not in DATA['groups']:
        return []
    
    group_info = DATA['groups'][chat_id_str]
    recent_users = group_info.get('recent_users', [])
    
    other_users_info = []
    
    for other_user_id in recent_users[:DATA['hybrid_settings']['max_other_users']]:
        if other_user_id == current_user_id:
            continue
        
        user_info = DATA['users'].get(str(other_user_id), {})
        if not user_info:
            continue
        
        user_name = user_info.get('first_name', 'کاربر')
        message_count = user_info.get('message_count', 0)
        last_seen = user_info.get('last_seen', 'نامشخص')
        
        # دریافت آخرین پیام در گروه از این کاربر
        last_group_message = None
        for msg in reversed(group_info.get('context', [])):
            if msg.get('user_id') == other_user_id and msg['role'] == 'user':
                last_group_message = msg['content'][:100]
                if len(msg['content']) > 100:
                    last_group_message += "..."
                break
        
        # ایجاد خلاصه
        summary = f"{message_count} پیام"
        if last_group_message:
            summary += f" - آخرین: {last_group_message}"
        
        other_users_info.append({
            'user_id': other_user_id,
            'name': user_name,
            'message_count': message_count,
            'last_seen': last_seen,
            'last_message': last_group_message,
            'summary': summary
        })
    
    return other_users_info

def get_recent_users_in_group(chat_id: int, limit: int = 5) -> list:
    """دریافت لیست کاربران اخیراً فعال در گروه"""
    chat_id_str = str(chat_id)
    
    if chat_id_str not in DATA['groups']:
        return []
    
    group_info = DATA['groups'][chat_id_str]
    recent_users = group_info.get('recent_users', [])
    
    return recent_users[:limit]

def get_user_name(user_id: int) -> str:
    """دریافت نام کاربر"""
    user_id_str = str(user_id)
    user_info = DATA['users'].get(user_id_str, {})
    return user_info.get('first_name', f"کاربر {user_id}")

def get_group_name(chat_id: int) -> str:
    """دریافت نام گروه"""
    chat_id_str = str(chat_id)
    group_info = DATA['groups'].get(chat_id_str, {})
    return group_info.get('title', f"گروه {chat_id}")

def limit_context_tokens(context: list, max_tokens: int) -> list:
    """محدود کردن context به تعداد توکن مشخص"""
    if not context:
        return context
    
    total_tokens = sum(count_tokens(msg['content']) for msg in context)
    
    if total_tokens <= max_tokens:
        return context
    
    # حذف پیام‌ها از ابتدا تا زمانی که توکن‌ها زیر حد مجاز باشد
    limited_context = context.copy()
    while total_tokens > max_tokens and len(limited_context) > 1:
        # سعی نکنیم system instructions را حذف کنیم
        if limited_context[0]['role'] == 'system':
            # سیستم را حذف نکن، پیام بعدی را حذف کن
            if len(limited_context) > 2:
                removed = limited_context.pop(1)
                total_tokens -= count_tokens(removed['content'])
            else:
                break
        else:
            removed = limited_context.pop(0)
            total_tokens -= count_tokens(removed['content'])
    
    return limited_context

def get_hybrid_context_summary(user_id: int, chat_id: int) -> str:
    """خلاصه‌ای از context ترکیبی پیشرفته"""
    personal_summary = get_context_summary(user_id)
    group_summary = get_group_context_summary(chat_id)
    
    # اطلاعات کاربران دیگر
    other_users = get_recent_users_in_group(chat_id, limit=5)
    other_users_count = len([uid for uid in other_users if uid != user_id])
    
    hybrid_mode = DATA['hybrid_settings']['mode']
    
    return (
        f"📊 **حالت Hybrid {hybrid_mode} فعال**\n\n"
        f"👤 **شخصی شما:** {personal_summary}\n"
        f"👥 **گروه:** {group_summary}\n"
        f"👥 **کاربران فعال دیگر در گروه:** {other_users_count} کاربر\n"
        f"⚙️ **تنظیمات:**\n"
        f"• وزن تاریخچه شخصی: {DATA['hybrid_settings']['personal_context_weight']}\n"
        f"• وزن تاریخچه گروه: {DATA['hybrid_settings']['group_context_weight']}\n"
        f"• ارجاع به کاربران دیگر: {'فعال ✅' if DATA['hybrid_settings']['enable_cross_user_references'] else 'غیرفعال ❌'}"
    )

# --- توابع مدیریت حالت context ---
def get_context_mode() -> str:
    """دریافت حالت فعلی context"""
    return DATA.get('context_mode', 'hybrid')

def set_context_mode(mode: str):
    """تنظیم حالت context"""
    valid_modes = ['separate', 'group_shared', 'hybrid']
    if mode in valid_modes:
        DATA['context_mode'] = mode
        save_data()
        logger.info(f"Context mode changed to: {mode}")
        return True
    return False

def set_hybrid_mode(mode: str):
    """تنظیم حالت Hybrid"""
    if mode in ['basic', 'advanced']:
        if 'hybrid_settings' not in DATA:
            DATA['hybrid_settings'] = {}
        
        DATA['hybrid_settings']['mode'] = mode
        
        if mode == 'advanced':
            # تنظیمات پیشرفته
            DATA['hybrid_settings']['enable_user_tracking'] = True
            DATA['hybrid_settings']['max_other_users'] = 5
            DATA['hybrid_settings']['personal_context_weight'] = 1.0
            DATA['hybrid_settings']['group_context_weight'] = 0.8
            DATA['hybrid_settings']['other_users_weight'] = 0.6
            DATA['hybrid_settings']['max_combined_tokens'] = 30000
            DATA['hybrid_settings']['enable_cross_user_references'] = True
        else:
            # تنظیمات ساده
            DATA['hybrid_settings']['enable_user_tracking'] = True
            DATA['hybrid_settings']['max_other_users'] = 3
            DATA['hybrid_settings']['personal_context_weight'] = 1.0
            DATA['hybrid_settings']['group_context_weight'] = 0.7
            DATA['hybrid_settings']['other_users_weight'] = 0.4
            DATA['hybrid_settings']['max_combined_tokens'] = 25000
            DATA['hybrid_settings']['enable_cross_user_references'] = False
        
        save_data()
        logger.info(f"Hybrid mode set to: {mode}")
        return True
    return False

# --- توابع مدیریت system instructions ---
def get_system_instruction(user_id: int = None, chat_id: int = None) -> str:
    """دریافت system instruction مناسب برای کاربر/گروه"""
    user_id_str = str(user_id) if user_id else None
    chat_id_str = str(chat_id) if chat_id else None
    
    # بررسی برای کاربر
    if user_id_str and user_id_str in DATA['system_instructions']['users']:
        instruction_data = DATA['system_instructions']['users'][user_id_str]
        if instruction_data.get('enabled', True):
            return instruction_data.get('instruction', '')
    
    # بررسی برای گروه
    if chat_id_str and chat_id_str in DATA['system_instructions']['groups']:
        instruction_data = DATA['system_instructions']['groups'][chat_id_str]
        if instruction_data.get('enabled', True):
            return instruction_data.get('instruction', '')
    
    # بازگشت به حالت سراسری
    return DATA['system_instructions'].get('global', '')

def set_global_system_instruction(instruction: str) -> bool:
    """تنظیم system instruction سراسری"""
    DATA['system_instructions']['global'] = instruction
    save_data()
    return True

def set_group_system_instruction(chat_id: int, instruction: str, set_by_user_id: int) -> bool:
    """تنظیم system instruction برای گروه"""
    chat_id_str = str(chat_id)
    DATA['system_instructions']['groups'][chat_id_str] = {
        'instruction': instruction,
        'set_by': set_by_user_id,
        'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'enabled': True
    }
    save_data()
    return True

def set_user_system_instruction(user_id: int, instruction: str, set_by_user_id: int) -> bool:
    """تنظیم system instruction برای کاربر"""
    user_id_str = str(user_id)
    DATA['system_instructions']['users'][user_id_str] = {
        'instruction': instruction,
        'set_by': set_by_user_id,
        'set_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'enabled': True
    }
    save_data()
    return True

def remove_group_system_instruction(chat_id: int) -> bool:
    """حذف system instruction گروه"""
    chat_id_str = str(chat_id)
    if chat_id_str in DATA['system_instructions']['groups']:
        del DATA['system_instructions']['groups'][chat_id_str]
        save_data()
        return True
    return False

def remove_user_system_instruction(user_id: int) -> bool:
    """حذف system instruction کاربر"""
    user_id_str = str(user_id)
    if user_id_str in DATA['system_instructions']['users']:
        del DATA['system_instructions']['users'][user_id_str]
        save_data()
        return True
    return False

def toggle_group_system_instruction(chat_id: int, enabled: bool) -> bool:
    """فعال/غیرفعال کردن system instruction گروه"""
    chat_id_str = str(chat_id)
    if chat_id_str in DATA['system_instructions']['groups']:
        DATA['system_instructions']['groups'][chat_id_str]['enabled'] = enabled
        save_data()
        return True
    return False

def toggle_user_system_instruction(user_id: int, enabled: bool) -> bool:
    """فعال/غیرفعال کردن system instruction کاربر"""
    user_id_str = str(user_id)
    if user_id_str in DATA['system_instructions']['users']:
        DATA['system_instructions']['users'][user_id_str]['enabled'] = enabled
        save_data()
        return True
    return False

def get_system_instruction_info(user_id: int = None, chat_id: int = None) -> dict:
    """دریافت اطلاعات system instruction"""
    user_id_str = str(user_id) if user_id else None
    chat_id_str = str(chat_id) if chat_id else None
    
    result = {
        'has_instruction': False,
        'type': 'global',
        'instruction': DATA['system_instructions'].get('global', ''),
        'details': None
    }
    
    if user_id_str and user_id_str in DATA['system_instructions']['users']:
        user_data = DATA['system_instructions']['users'][user_id_str]
        result.update({
            'has_instruction': True,
            'type': 'user',
            'instruction': user_data.get('instruction', ''),
            'details': user_data
        })
    elif chat_id_str and chat_id_str in DATA['system_instructions']['groups']:
        group_data = DATA['system_instructions']['groups'][chat_id_str]
        result.update({
            'has_instruction': True,
            'type': 'group',
            'instruction': group_data.get('instruction', ''),
            'details': group_data
        })
    
    return result

# بارگذاری اولیه داده‌ها
load_data()
logger.info(f"Data loaded. Context mode: {get_context_mode()}, Hybrid mode: {DATA['hybrid_settings']['mode']}")