File size: 60,565 Bytes
db37698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# admin_panel.py

import os
import json
import logging
import csv
import io
import asyncio
from datetime import datetime, timedelta
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler
from telegram.error import TelegramError

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import tempfile
import psutil
import platform
import time

# --- تنظیمات ---
ADMIN_IDS = list(map(int, os.environ.get("ADMIN_IDS", "").split(','))) if os.environ.get("ADMIN_IDS") else []

import data_manager

logger = logging.getLogger(__name__)

# --- دکوراتور برای دسترسی ادمین ---
def admin_only(func):
    async def wrapped(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
        if update.effective_user.id not in ADMIN_IDS:
            await update.message.reply_text("⛔️ شما دسترسی لازم برای اجرای این دستور را ندارید.")
            return
        return await func(update, context, *args, **kwargs)
    return wrapped

# --- هندلرهای دستورات ادمین ---
@admin_only
async def admin_commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """نمایش تمام دستورات موجود ادمین."""
    commands_text = (
        "📋 **دستورات ادمین ربات:**\n\n"
        "📊 `/stats` - نمایش آمار ربات\n"
        "📢 `/broadcast [پیام]` - ارسال پیام به تمام کاربران\n"
        "🎯 `/targeted_broadcast [معیار] [مقدار] [پیام]` - ارسال پیام هدفمند\n"
        "📅 `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]` - ارسال برنامه‌ریزی شده\n"
        "📋 `/list_scheduled` - نمایش لیست ارسال‌های برنامه‌ریزی شده\n"
        "🗑️ `/remove_scheduled [شماره]` - حذف ارسال برنامه‌ریزی شده\n"
        "🚫 `/ban [آیدی]` - مسدود کردن کاربر\n"
        "✅ `/unban [آیدی]` - رفع مسدودیت کاربر\n"
        "💌 `/direct_message [آیدی] [پیام]` - ارسال پیام مستقیم به کاربر\n"
        "ℹ️ `/user_info [آیدی]` - نمایش اطلاعات کاربر\n"
        "📝 `/logs` - نمایش آخرین لاگ‌ها\n"
        "📂 `/logs_file` - دانلود فایل کامل لاگ‌ها\n"
        "👥 `/users_list [صفحه]` - نمایش لیست کاربران\n"
        "🔍 `/user_search [نام]` - جستجوی کاربر بر اساس نام\n"
        "💾 `/backup` - ایجاد نسخه پشتیبان از داده‌ها\n"
        "📊 `/export_csv` - دانلود اطلاعات کاربران در فایل CSV\n"
        "🔧 `/maintenance [on/off]` - فعال/غیرفعال کردن حالت نگهداری\n"
        "👋 `/set_welcome [پیام]` - تنظیم پیام خوشامدگویی\n"
        "👋 `/set_goodbye [پیام]` - تنظیم پیام خداحافظی\n"
        "📈 `/activity_heatmap` - دریافت نمودار فعالیت کاربران\n"
        "⏱️ `/response_stats` - نمایش آمار زمان پاسخگویی\n"
        "🚫 `/add_blocked_word [کلمه]` - افزودن کلمه مسدود\n"
        "✅ `/remove_blocked_word [کلمه]` - حذف کلمه مسدود\n"
        "📜 `/list_blocked_words` - نمایش لیست کلمات مسدود\n"
        "💻 `/system_info` - نمایش اطلاعات سیستم\n"
        "🔄 `/reset_stats [messages/all]` - ریست کردن آمار\n"
        "🗑️ `/clear_context [آیدی]` - پاک کردن context کاربر\n"
        "📋 `/view_context [آیدی]` - مشاهده context کاربر\n"
        "📋 `/view_replies [user|group] [آیدی]` - مشاهده ریپلای‌ها\n"
        "🔄 `/set_context_mode [separate|group_shared|hybrid]` - تغییر حالت context\n"
        "📊 `/group_info [آیدی]` - نمایش اطلاعات گروه\n"
        "🗑️ `/clear_group_context [آیدی]` - پاک کردن context گروه\n"
        "💾 `/memory_status` - نمایش وضعیت حافظه\n"
        "📋 `/commands` - نمایش این لیست دستورات"
    )
    await update.message.reply_text(commands_text, parse_mode='Markdown')

@admin_only
async def admin_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """آمار ربات را نمایش می‌دهد."""
    total_users = len(data_manager.DATA['users'])
    total_groups = len(data_manager.DATA['groups'])
    total_messages = data_manager.DATA['stats']['total_messages']
    banned_count = len(data_manager.DATA['banned_users'])
    
    now = datetime.now()
    active_24h = sum(1 for user in data_manager.DATA['users'].values() 
                    if 'last_seen' in user and 
                    datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(hours=24))
    
    active_7d = sum(1 for user in data_manager.DATA['users'].values() 
                   if 'last_seen' in user and 
                   datetime.strptime(user['last_seen'], '%Y-%m-%d %H:%M:%S') > now - timedelta(days=7))

    active_users = sorted(
        data_manager.DATA['users'].items(),
        key=lambda item: item[1].get('last_seen', ''),
        reverse=True
    )[:5]

    active_users_text = "\n".join(
        [f"• {user_id}: {info.get('first_name', 'N/A')} (آخرین فعالیت: {info.get('last_seen', 'N/A')})"
         for user_id, info in active_users]
    )

    # آمار context
    users_with_context = sum(1 for user in data_manager.DATA['users'].values() 
                           if user.get('context') and len(user['context']) > 0)
    total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
    
    # آمار ریپلای‌ها
    total_replies = 0
    for user in data_manager.DATA['users'].values():
        if 'context' in user:
            total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
    
    # آمار گروه‌ها
    groups_with_context = sum(1 for group in data_manager.DATA['groups'].values() 
                            if group.get('context') and len(group['context']) > 0)

    text = (
        f"📊 **آمار ربات**\n\n"
        f"👥 **تعداد کل کاربران:** `{total_users}`\n"
        f"👥 **تعداد کل گروه‌ها:** `{total_groups}`\n"
        f"📝 **تعداد کل پیام‌ها:** `{total_messages}`\n"
        f"🚫 **کاربران مسدود شده:** `{banned_count}`\n"
        f"🟢 **کاربران فعال 24 ساعت گذشته:** `{active_24h}`\n"
        f"🟢 **کاربران فعال 7 روز گذشته:** `{active_7d}`\n"
        f"💭 **کاربران با context فعال:** `{users_with_context}`\n"
        f"💬 **گروه‌های با context فعال:** `{groups_with_context}`\n"
        f"📝 **کل پیام‌های context:** `{total_context_messages}`\n"
        f"📎 **کل ریپلای‌های ثبت شده:** `{total_replies}`\n"
        f"🔄 **حالت context فعلی:** `{data_manager.get_context_mode()}`\n\n"
        f"**۵ کاربر اخیر فعال:**\n{active_users_text}"
    )
    await update.message.reply_text(text, parse_mode='Markdown')

@admin_only
async def admin_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """یک پیام را به تمام کاربران ارسال می‌کند."""
    if not context.args:
        await update.message.reply_text("⚠️ لطفاً پیامی برای ارسال بنویسید.\nمثال: `/broadcast سلام به همه!`")
        return

    message_text = " ".join(context.args)
    user_ids = list(data_manager.DATA['users'].keys())
    total_sent = 0
    total_failed = 0

    await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(user_ids)}` کاربر...")

    for user_id_str in user_ids:
        try:
            await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
            total_sent += 1
            await asyncio.sleep(0.05)
        except TelegramError as e:
            logger.warning(f"Failed to send broadcast to {user_id_str}: {e}")
            total_failed += 1

    result_text = (
        f"✅ **ارسال همگانی تمام شد**\n\n"
        f"✅ موفق: `{total_sent}`\n"
        f"❌ ناموفق: `{total_failed}`"
    )
    await update.message.reply_text(result_text, parse_mode='Markdown')

@admin_only
async def admin_targeted_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ارسال پیام به گروه خاصی از کاربران بر اساس معیارهای مشخص."""
    if len(context.args) < 3:
        await update.message.reply_text("⚠️ فرمت صحیح: `/targeted_broadcast [معیار] [مقدار] [پیام]`\n"
                                       "معیارهای موجود: `active_days`, `message_count`, `banned`")
        return
    
    criteria = context.args[0].lower()
    value = context.args[1]
    message_text = " ".join(context.args[2:])
    
    target_users = []
    
    if criteria == "active_days":
        try:
            days = int(value)
            target_users = data_manager.get_active_users(days)
        except ValueError:
            await update.message.reply_text("⚠️ مقدار روز باید یک عدد صحیح باشد.")
            return
    
    elif criteria == "message_count":
        try:
            min_count = int(value)
            target_users = data_manager.get_users_by_message_count(min_count)
        except ValueError:
            await update.message.reply_text("⚠️ تعداد پیام باید یک عدد صحیح باشد.")
            return
    
    elif criteria == "banned":
        if value.lower() == "true":
            target_users = list(data_manager.DATA['banned_users'])
        elif value.lower() == "false":
            for user_id in data_manager.DATA['users']:
                if int(user_id) not in data_manager.DATA['banned_users']:
                    target_users.append(int(user_id))
        else:
            await update.message.reply_text("⚠️ مقدار برای معیار banned باید true یا false باشد.")
            return
    
    else:
        await update.message.reply_text("⚠️ معیار نامعتبر است. معیارهای موجود: active_days, message_count, banned")
        return
    
    if not target_users:
        await update.message.reply_text("هیچ کاربری با معیارهای مشخص شده یافت نشد.")
        return
    
    await update.message.reply_text(f"📣 در حال ارسال پیام به `{len(target_users)}` کاربر...")
    
    total_sent, total_failed = 0, 0
    for user_id in target_users:
        try:
            await context.bot.send_message(chat_id=user_id, text=message_text)
            total_sent += 1
            await asyncio.sleep(0.05)
        except TelegramError as e:
            logger.warning(f"Failed to send targeted broadcast to {user_id}: {e}")
            total_failed += 1
    
    result_text = f"✅ **ارسال هدفمند تمام شد**\n\n✅ موفق: `{total_sent}`\n❌ ناموفق: `{total_failed}`"
    await update.message.reply_text(result_text, parse_mode='Markdown')

@admin_only
async def admin_schedule_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """تنظیم ارسال برنامه‌ریزی شده پیام به همه کاربران."""
    if len(context.args) < 3:
        await update.message.reply_text("⚠️ فرمت صحیح: `/schedule_broadcast [YYYY-MM-DD] [HH:MM] [پیام]`")
        return
    
    try:
        date_str, time_str = context.args[0], context.args[1]
        message_text = " ".join(context.args[2:])
        
        scheduled_time = datetime.strptime(f"{date_str} {time_str}", '%Y-%m-%d %H:%M')
        
        if scheduled_time <= datetime.now():
            await update.message.reply_text("⚠️ زمان برنامه‌ریزی شده باید در آینده باشد.")
            return
        
        data_manager.DATA['scheduled_broadcasts'].append({
            'time': scheduled_time.strftime('%Y-%m-%d %H:%M:%S'),
            'message': message_text,
            'status': 'pending'
        })
        data_manager.save_data()
        
        await update.message.reply_text(f"✅ پیام برای زمان `{scheduled_time.strftime('%Y-%m-%d %H:%M')}` برنامه‌ریزی شد.")
        
    except ValueError:
        await update.message.reply_text("⚠️ فرمت زمان نامعتبر است. لطفاً از فرمت YYYY-MM-DD HH:MM استفاده کنید.")

@admin_only
async def admin_list_scheduled_broadcasts(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """نمایش لیست ارسال‌های برنامه‌ریزی شده."""
    if not data_manager.DATA['scheduled_broadcasts']:
        await update.message.reply_text("هیچ ارسال برنامه‌ریزی شده‌ای وجود ندارد.")
        return
    
    broadcasts_text = "📅 **لیست ارسال‌های برنامه‌ریزی شده:**\n\n"
    for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts'], 1):
        status_emoji = "✅" if broadcast['status'] == 'sent' else "⏳"
        broadcasts_text += f"{i}. {status_emoji} `{broadcast['time']}` - {broadcast['message'][:50]}...\n"
    
    await update.message.reply_text(broadcasts_text, parse_mode='Markdown')

@admin_only
async def admin_remove_scheduled_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """حذف یک ارسال برنامه‌ریزی شده."""
    if not context.args or not context.args[0].isdigit():
        await update.message.reply_text("⚠️ لطفاً شماره ارسال برنامه‌ریزی شده را وارد کنید.\nمثال: `/remove_scheduled 1`")
        return
    
    index = int(context.args[0]) - 1
    
    if not data_manager.DATA['scheduled_broadcasts'] or not (0 <= index < len(data_manager.DATA['scheduled_broadcasts'])):
        await update.message.reply_text("⚠️ شماره ارسال برنامه‌ریزی شده نامعتبر است.")
        return
    
    removed_broadcast = data_manager.DATA['scheduled_broadcasts'].pop(index)
    data_manager.save_data()
    
    await update.message.reply_text(f"✅ ارسال برنامه‌ریزی شده برای زمان `{removed_broadcast['time']}` حذف شد.")

@admin_only
async def admin_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """یک کاربر را با آیدی عددی مسدود کرده و به او اطلاع می‌دهد."""
    if not context.args or not context.args[0].isdigit():
        await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/ban 123456789`")
        return

    user_id_to_ban = int(context.args[0])

    if user_id_to_ban in ADMIN_IDS:
        await update.message.reply_text("🛡️ شما نمی‌توانید یک ادمین را مسدود کنید!")
        return

    if data_manager.is_user_banned(user_id_to_ban):
        await update.message.reply_text(f"کاربر `{user_id_to_ban}` از قبل مسدود شده است.")
        return

    data_manager.ban_user(user_id_to_ban)
    
    # ارسال پیام به کاربر مسدود شده
    try:
        await context.bot.send_message(
            chat_id=user_id_to_ban, 
            text="⛔️ شما توسط ادمین ربات مسدود شدید و دیگر نمی‌توانید از خدمات ربات استفاده کنید."
        )
    except TelegramError as e:
        logger.warning(f"Could not send ban notification to user {user_id_to_ban}: {e}")

    await update.message.reply_text(f"✅ کاربر `{user_id_to_ban}` با موفقیت مسدود شد.", parse_mode='Markdown')

@admin_only
async def admin_unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """مسدودیت یک کاربر را برمی‌دارد و به او اطلاع می‌دهد."""
    if not context.args or not context.args[0].isdigit():
        await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/unban 123456789`")
        return

    user_id_to_unban = int(context.args[0])

    if not data_manager.is_user_banned(user_id_to_unban):
        await update.message.reply_text(f"کاربر `{user_id_to_unban}` در لیست مسدود شده‌ها وجود ندارد.")
        return

    data_manager.unban_user(user_id_to_unban)

    # ارسال پیام به کاربر برای رفع مسدودیت
    try:
        await context.bot.send_message(
            chat_id=user_id_to_unban, 
            text="✅ مسدودیت شما توسط ادمین ربات برداشته شد. می‌توانید دوباره از ربات استفاده کنید."
        )
    except TelegramError as e:
        logger.warning(f"Could not send unban notification to user {user_id_to_unban}: {e}")

    await update.message.reply_text(f"✅ مسدودیت کاربر `{user_id_to_unban}` با موفقیت برداشته شد.", parse_mode='Markdown')

@admin_only
async def admin_direct_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ارسال پیام مستقیم به یک کاربر خاص."""
    if len(context.args) < 2:
        await update.message.reply_text("⚠️ فرمت صحیح: `/direct_message [آیدی] [پیام]`")
        return
    
    user_id_str = context.args[0]
    if not user_id_str.isdigit():
        await update.message.reply_text("⚠️ لطفاً یک آیدی عددی معتبر وارد کنید.")
        return
    
    message_text = " ".join(context.args[1:])
    user_id = int(user_id_str)
    
    try:
        await context.bot.send_message(chat_id=user_id, text=message_text)
        await update.message.reply_text(f"✅ پیام با موفقیت به کاربر `{user_id}` ارسال شد.", parse_mode='Markdown')
    except TelegramError as e:
        await update.message.reply_text(f"❌ خطا در ارسال پیام: {e}")

@admin_only
async def admin_userinfo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """اطلاعات یک کاربر خاص را نمایش می‌دهد."""
    if not context.args or not context.args[0].isdigit():
        await update.message.reply_text("⚠️ لطفاً آیدی عددی کاربر را وارد کنید.\nمثال: `/user_info 123456789`")
        return

    user_id = int(context.args[0])
    user_info = data_manager.DATA['users'].get(str(user_id))

    if not user_info:
        await update.message.reply_text(f"کاربری با آیدی `{user_id}` در دیتابیس یافت نشد.")
        return

    is_banned = "بله" if data_manager.is_user_banned(user_id) else "خیر"
    
    if 'first_seen' in user_info and 'last_seen' in user_info:
        try:
            first_date = datetime.strptime(user_info['first_seen'], '%Y-%m-%d %H:%M:%S')
            last_date = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
            days_active = max(1, (last_date - first_date).days)
            avg_messages = user_info.get('message_count', 0) / days_active
        except:
            avg_messages = user_info.get('message_count', 0)
    else:
        avg_messages = user_info.get('message_count', 0)
    
    # اطلاعات context
    context_messages = len(user_info.get('context', []))
    context_tokens = data_manager.get_context_token_count(user_id)
    
    # اطلاعات ریپلای‌ها
    reply_count = 0
    if 'context' in user_info:
        reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
    
    text = (
        f"ℹ️ **اطلاعات کاربر**\n\n"
        f"🆔 **آیدی:** `{user_id}`\n"
        f"👤 **نام:** {user_info.get('first_name', 'N/A')}\n"
        f"🔷 **نام کاربری:** @{user_info.get('username', 'N/A')}\n"
        f"📊 **تعداد پیام‌ها:** `{user_info.get('message_count', 0)}`\n"
        f"📈 **میانگین پیام در روز:** `{avg_messages:.2f}`\n"
        f"📎 **تعداد ریپلای‌ها:** `{reply_count}`\n"
        f"📅 **اولین پیام:** {user_info.get('first_seen', 'N/A')}\n"
        f"🕒 **آخرین فعالیت:** {user_info.get('last_seen', 'N/A')}\n"
        f"💭 **پیام‌های context:** `{context_messages}`\n"
        f"🔢 **توکن‌های context:** `{context_tokens}`\n"
        f"🚫 **وضعیت مسدودیت:** {is_banned}"
    )
    await update.message.reply_text(text, parse_mode='Markdown')

@admin_only
async def admin_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """آخرین خطوط لاگ ربات را ارسال می‌کند."""
    try:
        with open(data_manager.LOG_FILE, "r", encoding="utf-8") as f:
            lines = f.readlines()
            last_lines = lines[-30:]
            log_text = "".join(last_lines)
            if not log_text:
                await update.message.reply_text("فایل لاگ خالی است.")
                return
            
            if len(log_text) > 4096:
                for i in range(0, len(log_text), 4096):
                    await update.message.reply_text(f"```{log_text[i:i+4096]}```", parse_mode='Markdown')
            else:
                await update.message.reply_text(f"```{log_text}```", parse_mode='Markdown')

    except FileNotFoundError:
        await update.message.reply_text("فایل لاگ یافت نشد.")
    except Exception as e:
        await update.message.reply_text(f"خطایی در خواندن لاگ رخ داد: {e}")

@admin_only
async def admin_logs_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """فایل کامل لاگ ربات را ارسال می‌کند."""
    try:
        await update.message.reply_document(
            document=open(data_manager.LOG_FILE, 'rb'),
            caption="📂 فایل کامل لاگ‌های ربات"
        )
    except FileNotFoundError:
        await update.message.reply_text("فایل لاگ یافت نشد.")
    except Exception as e:
        await update.message.reply_text(f"خطایی در ارسال فایل لاگ رخ داد: {e}")

@admin_only
async def admin_users_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """نمایش لیست کامل کاربران با صفحه‌بندی."""
    users = data_manager.DATA['users']
    
    page = 1
    if context.args and context.args[0].isdigit():
        page = int(context.args[0])
        if page < 1: page = 1
    
    users_per_page = 20
    total_users = len(users)
    total_pages = (total_users + users_per_page - 1) // users_per_page
    
    if page > total_pages: page = total_pages
    
    start_idx = (page - 1) * users_per_page
    end_idx = min(start_idx + users_per_page, total_users)
    
    sorted_users = sorted(users.items(), key=lambda item: item[1].get('last_seen', ''), reverse=True)
    
    users_text = f"👥 **لیست کاربران (صفحه {page}/{total_pages})**\n\n"
    
    for i, (user_id, user_info) in enumerate(sorted_users[start_idx:end_idx], start=start_idx + 1):
        is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
        username = user_info.get('username', 'N/A')
        first_name = user_info.get('first_name', 'N/A')
        last_seen = user_info.get('last_seen', 'N/A')
        message_count = user_info.get('message_count', 0)
        context_count = len(user_info.get('context', []))
        
        # تعداد ریپلای‌ها
        reply_count = 0
        if 'context' in user_info:
            reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
        
        users_text += f"{i}. {is_banned} `{user_id}` - {first_name} (@{username})\n"
        users_text += f"   📝 پیام‌ها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلای‌ها: `{reply_count}`\n"
        users_text += f"   ⏰ آخرین فعالیت: `{last_seen}`\n\n"
    
    keyboard = []
    if page > 1: keyboard.append([InlineKeyboardButton("⬅️ صفحه قبل", callback_data=f"users_list:{page-1}")])
    if page < total_pages: keyboard.append([InlineKeyboardButton("➡️ صفحه بعد", callback_data=f"users_list:{page+1}")])
    
    reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
    await update.message.reply_text(users_text, parse_mode='Markdown', reply_markup=reply_markup)

@admin_only
async def admin_user_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """جستجوی کاربر بر اساس نام یا نام کاربری."""
    if not context.args:
        await update.message.reply_text("⚠️ لطفاً نام یا نام کاربری برای جستجو وارد کنید.\nمثال: `/user_search علی`")
        return
    
    search_term = " ".join(context.args).lower()
    users = data_manager.DATA['users']
    
    matching_users = []
    for user_id, user_info in users.items():
        first_name = (user_info.get('first_name') or '').lower()
        username = (user_info.get('username') or '').lower()
        
        if search_term in first_name or search_term in username:
            is_banned = "🚫" if int(user_id) in data_manager.DATA['banned_users'] else "✅"
            matching_users.append((user_id, user_info, is_banned))
    
    if not matching_users:
        await update.message.reply_text(f"هیچ کاربری با نام «{search_term}» یافت نشد.")
        return
    
    results_text = f"🔍 **نتایج جستجو برای «{search_term}»**\n\n"
    
    for user_id, user_info, is_banned in matching_users:
        username_display = user_info.get('username', 'N/A')
        first_name_display = user_info.get('first_name', 'N/A')
        last_seen = user_info.get('last_seen', 'N/A')
        message_count = user_info.get('message_count', 0)
        context_count = len(user_info.get('context', []))
        
        # تعداد ریپلای‌ها
        reply_count = 0
        if 'context' in user_info:
            reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
        
        results_text += f"{is_banned} `{user_id}` - {first_name_display} (@{username_display})\n"
        results_text += f"   📝 پیام‌ها: `{message_count}` | 💭 context: `{context_count}` | 📎 ریپلای‌ها: `{reply_count}`\n"
        results_text += f"   ⏰ آخرین فعالیت: `{last_seen}`\n\n"
    
    await update.message.reply_text(results_text, parse_mode='Markdown')

@admin_only
async def admin_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ایجاد نسخه پشتیبان از داده‌های ربات."""
    try:
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        backup_file = f"bot_backup_{timestamp}.json"
        
        data_to_backup = data_manager.DATA.copy()
        data_to_backup['banned_users'] = list(data_manager.DATA['banned_users'])
        
        with open(backup_file, 'w', encoding='utf-8') as f:
            json.dump(data_to_backup, f, indent=4, ensure_ascii=False)
        
        await update.message.reply_document(
            document=open(backup_file, 'rb'),
            caption=f"✅ نسخه پشتیبان با موفقیت ایجاد شد: {backup_file}"
        )
        
        logger.info(f"Backup created: {backup_file}")
        os.remove(backup_file)
    except Exception as e:
        await update.message.reply_text(f"❌ خطا در ایجاد نسخه پشتیبان: {e}")
        logger.error(f"Error creating backup: {e}")

@admin_only
async def admin_export_csv(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ایجاد و ارسال فایل CSV از اطلاعات کاربران."""
    users = data_manager.DATA['users']
    
    df_data = []
    for user_id, user_info in users.items():
        is_banned = "بله" if int(user_id) in data_manager.DATA['banned_users'] else "خیر"
        context_count = len(user_info.get('context', []))
        context_tokens = data_manager.get_context_token_count(int(user_id))
        
        # تعداد ریپلای‌ها
        reply_count = 0
        if 'context' in user_info:
            reply_count = sum(1 for msg in user_info['context'] if msg.get('has_reply', False))
        
        df_data.append({
            'User ID': user_id,
            'First Name': user_info.get('first_name', 'N/A'),
            'Username': user_info.get('username', 'N/A'),
            'Message Count': user_info.get('message_count', 0),
            'Context Messages': context_count,
            'Context Tokens': context_tokens,
            'Reply Count': reply_count,
            'First Seen': user_info.get('first_seen', 'N/A'),
            'Last Seen': user_info.get('last_seen', 'N/A'),
            'Banned': is_banned
        })
    
    df = pd.DataFrame(df_data)
    
    with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') as f:
        df.to_csv(f.name, index=False)
        temp_file_path = f.name
    
    await update.message.reply_document(
        document=open(temp_file_path, 'rb'),
        caption="📊 فایل CSV اطلاعات کاربران"
    )
    
    os.unlink(temp_file_path)

@admin_only
async def admin_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """حالت نگهداری ربات را فعال یا غیرفعال کرده و به کاربران اطلاع می‌دهد."""
    if not context.args or context.args[0].lower() not in ['on', 'off']:
        await update.message.reply_text("⚠️ فرمت صحیح: `/maintenance on` یا `/maintenance off`")
        return

    status = context.args[0].lower()
    
    if status == 'on':
        if data_manager.DATA.get('maintenance_mode', False):
            await update.message.reply_text("🔧 ربات از قبل در حالت نگهداری قرار دارد.")
            return
            
        data_manager.DATA['maintenance_mode'] = True
        data_manager.save_data()
        
        await update.message.reply_text("✅ حالت نگهداری ربات فعال شد. در حال اطلاع‌رسانی به کاربران...")
        
        user_ids = list(data_manager.DATA['users'].keys())
        for user_id_str in user_ids:
            try:
                if int(user_id_str) not in ADMIN_IDS:
                    await context.bot.send_message(
                        chat_id=int(user_id_str), 
                        text="🔧 ربات در حال حاضر در حالت به‌روزرسانی و نگهداری قرار دارد. لطفاً چند لحظه دیگر صبر کنید. از صبر شما سپاسگزاریم!"
                    )
                    await asyncio.sleep(0.05)
            except TelegramError:
                continue

    elif status == 'off':
        if not data_manager.DATA.get('maintenance_mode', False):
            await update.message.reply_text("✅ ربات از قبل در حالت عادی قرار دارد.")
            return

        data_manager.DATA['maintenance_mode'] = False
        data_manager.save_data()

        await update.message.reply_text("✅ حالت نگهداری ربات غیرفعال شد. در حال اطلاع‌رسانی به کاربران...")

        user_ids = list(data_manager.DATA['users'].keys())
        for user_id_str in user_ids:
            try:
                if int(user_id_str) not in ADMIN_IDS:
                    await context.bot.send_message(
                        chat_id=int(user_id_str), 
                        text="✅ به‌روزرسانی ربات به پایان رسید. از صبر شما سپاسگزاریم! می‌توانید دوباره از ربات استفاده کنید."
                    )
                    await asyncio.sleep(0.05)
            except TelegramError:
                continue

@admin_only
async def admin_set_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """تنظیم پیام خوشامدگویی جدید."""
    if not context.args:
        await update.message.reply_text("⚠️ لطفاً پیام خوشامدگویی جدید را وارد کنید.\n"
                                       "مثال: `/set_welcome سلام {user_mention}! به ربات خوش آمدید.`")
        return
    
    new_message = " ".join(context.args)
    data_manager.DATA['welcome_message'] = new_message
    data_manager.save_data()
    
    await update.message.reply_text("✅ پیام خوشامدگویی با موفقیت به‌روزرسانی شد.")

@admin_only
async def admin_set_goodbye_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """تنظیم پیام خداحافظی جدید."""
    if not context.args:
        await update.message.reply_text("⚠️ لطفاً پیام خداحافظی جدید را وارد کنید.\n"
                                       "مثال: `/set_goodbye {user_mention}، خداحافظ!`")
        return
    
    new_message = " ".join(context.args)
    data_manager.DATA['goodbye_message'] = new_message
    data_manager.save_data()
    
    await update.message.reply_text("✅ پیام خداحافظی با موفقیت به‌روزرسانی شد.")

@admin_only
async def admin_activity_heatmap(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ایجاد و ارسال نمودار فعالیت کاربران."""
    users = data_manager.DATA['users']
    activity_hours = [0] * 24
    
    for user_info in users.values():
        if 'last_seen' in user_info:
            try:
                last_seen = datetime.strptime(user_info['last_seen'], '%Y-%m-%d %H:%M:%S')
                activity_hours[last_seen.hour] += 1
            except ValueError:
                continue
    
    plt.figure(figsize=(12, 6))
    plt.bar(range(24), activity_hours, color='skyblue')
    plt.title('نمودار فعالیت کاربران بر اساس ساعت')
    plt.xlabel('ساعت')
    plt.ylabel('تعداد کاربران فعال')
    plt.xticks(range(24))
    plt.grid(axis='y', alpha=0.3)
    
    with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
        plt.savefig(f.name, bbox_inches='tight')
        temp_file_path = f.name
    
    plt.close()
    
    await update.message.reply_photo(
        photo=open(temp_file_path, 'rb'),
        caption="📊 نمودار فعالیت کاربران بر اساس ساعت"
    )
    
    os.unlink(temp_file_path)

@admin_only
async def admin_response_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """نمایش آمار زمان پاسخگویی ربات."""
    stats = data_manager.DATA['stats']
    await update.message.reply_text(
        "📈 **آمار زمان پاسخگویی ربات**\n\n"
        f"🟢 میانگین زمان پاسخگویی: `{stats.get('avg_response_time', 0):.2f}` ثانیه\n"
        f"🔴 بیشترین زمان پاسخگویی: `{stats.get('max_response_time', 0):.2f}` ثانیه\n"
        f"🟢 کمترین زمان پاسخگویی: `{stats.get('min_response_time', 0):.2f}` ثانیه\n"
        f"📊 کل پاسخ‌های ثبت شده: `{stats.get('total_responses', 0)}`"
    )

@admin_only
async def admin_add_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """افزودن کلمه یا عبارت به لیست کلمات مسدود شده."""
    if not context.args:
        await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
                                       "مثال: `/add_blocked_word کلمه_نامناسب`")
        return
    
    word = " ".join(context.args).lower()
    
    if word in data_manager.DATA['blocked_words']:
        await update.message.reply_text(f"⚠️ کلمه «{word}» از قبل در لیست کلمات مسدود شده وجود دارد.")
        return
    
    data_manager.DATA['blocked_words'].append(word)
    data_manager.save_data()
    
    await update.message.reply_text(f"✅ کلمه «{word}» به لیست کلمات مسدود شده اضافه شد.")

@admin_only
async def admin_remove_blocked_word(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """حذف کلمه یا عبارت از لیست کلمات مسدود شده."""
    if not context.args:
        await update.message.reply_text("⚠️ لطفاً کلمه یا عبارت مورد نظر را وارد کنید.\n"
                                       "مثال: `/remove_blocked_word کلمه_نامناسب`")
        return
    
    word = " ".join(context.args).lower()
    
    if word not in data_manager.DATA['blocked_words']:
        await update.message.reply_text(f"⚠️ کلمه «{word}» در لیست کلمات مسدود شده وجود ندارد.")
        return
    
    data_manager.DATA['blocked_words'].remove(word)
    data_manager.save_data()
    
    await update.message.reply_text(f"✅ کلمه «{word}» از لیست کلمات مسدود شده حذف شد.")

@admin_only
async def admin_list_blocked_words(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """نمایش لیست کلمات مسدود شده."""
    if not data_manager.DATA['blocked_words']:
        await update.message.reply_text("هیچ کلمه مسدود شده‌ای در لیست وجود ندارد.")
        return
    
    words_list = "\n".join([f"• {word}" for word in data_manager.DATA['blocked_words']])
    await update.message.reply_text(f"🚫 **لیست کلمات مسدود شده:**\n\n{words_list}")

@admin_only
async def admin_system_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """نمایش اطلاعات سیستم و منابع."""
    bot_start_time_str = data_manager.DATA.get('bot_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    try:
        bot_start_time = datetime.strptime(bot_start_time_str, '%Y-%m-%d %H:%M:%S')
        uptime = datetime.now() - bot_start_time
    except:
        uptime = "نامشخص"
    
    total_context_messages = sum(len(user.get('context', [])) for user in data_manager.DATA['users'].values())
    users_with_context = sum(1 for user in data_manager.DATA['users'].values() if user.get('context'))
    
    # تعداد کل ریپلای‌ها
    total_replies = 0
    for user in data_manager.DATA['users'].values():
        if 'context' in user:
            total_replies += sum(1 for msg in user['context'] if msg.get('has_reply', False))
    
    system_info = (
        f"💻 **اطلاعات سیستم:**\n\n"
        f"🖥️ سیستم‌عامل: {platform.system()} {platform.release()}\n"
        f"🐍 نسخه پایتون: {platform.python_version()}\n"
        f"💾 حافظه RAM استفاده شده: {psutil.virtual_memory().percent}%\n"
        f"💾 حافظه RAM آزاد: {psutil.virtual_memory().available / (1024**3):.2f} GB\n"
        f"💾 فضای دیسک استفاده شده: {psutil.disk_usage('/').percent}%\n"
        f"💾 فضای دیسک آزاد: {psutil.disk_usage('/').free / (1024**3):.2f} GB\n"
        f"⏱️ زمان اجرای ربات: {uptime}\n"
        f"💭 کاربران با context: {users_with_context}\n"
        f"💬 کل پیام‌های context: {total_context_messages}\n"
        f"📎 کل ریپلای‌های ثبت شده: {total_replies}"
    )
    
    await update.message.reply_text(system_info, parse_mode='Markdown')

@admin_only
async def admin_reset_stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ریست کردن آمار ربات."""
    if not context.args:
        await update.message.reply_text("⚠️ لطفاً نوع آماری که می‌خواهید ریست کنید را مشخص کنید.\n"
                                       "مثال: `/reset_stats messages` یا `/reset_stats all`")
        return
    
    stat_type = context.args[0].lower()
    
    if stat_type == "messages":
        data_manager.DATA['stats']['total_messages'] = 0
        for user_id in data_manager.DATA['users']:
            data_manager.DATA['users'][user_id]['message_count'] = 0
        await update.message.reply_text("✅ آمار پیام‌ها با موفقیت ریست شد.")
    
    elif stat_type == "all":
        data_manager.DATA['stats'] = {
            'total_messages': 0,
            'total_users': len(data_manager.DATA['users']),
            'total_groups': len(data_manager.DATA['groups']),
            'avg_response_time': 0,
            'max_response_time': 0,
            'min_response_time': 0,
            'total_responses': 0
        }
        for user_id in data_manager.DATA['users']:
            data_manager.DATA['users'][user_id]['message_count'] = 0
        await update.message.reply_text("✅ تمام آمارها با موفقیت ریست شد.")
    
    else:
        await update.message.reply_text("⚠️ نوع آمار نامعتبر است. گزینه‌های موجود: messages, all")
        return
    
    data_manager.save_data()

# --- دستورات مدیریت context ---
@admin_only
async def admin_clear_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """پاک کردن context یک کاربر"""
    if not context.args or not context.args[0].isdigit():
        await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/clear_context 123456789`")
        return
    
    user_id = int(context.args[0])
    data_manager.clear_user_context(user_id)
    
    await update.message.reply_text(f"✅ context کاربر `{user_id}` با موفقیت پاک شد.")

@admin_only
async def admin_view_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """مشاهده context یک کاربر"""
    if not context.args or not context.args[0].isdigit():
        await update.message.reply_text("⚠️ لطفاً آیدی کاربر را وارد کنید.\nمثال: `/view_context 123456789`")
        return
    
    user_id = int(context.args[0])
    user_context = data_manager.get_user_context(user_id)
    
    if not user_context:
        await update.message.reply_text(f"کاربر `{user_id}` context ندارد.")
        return
    
    context_text = f"📋 **Context کاربر `{user_id}`**\n\n"
    total_tokens = 0
    reply_count = 0
    
    for i, msg in enumerate(user_context, 1):
        role_emoji = "👤" if msg['role'] == 'user' else "🤖"
        tokens = data_manager.count_tokens(msg['content'])
        total_tokens += tokens
        
        # بررسی ریپلای
        has_reply = msg.get('has_reply', False)
        if has_reply:
            reply_count += 1
            reply_emoji = "📎"
        else:
            reply_emoji = ""
        
        content_preview = msg['content']
        if len(content_preview) > 100:
            content_preview = content_preview[:100] + "..."
        
        context_text += f"{i}. {role_emoji} {reply_emoji} **{msg['role']}** ({tokens} توکن)\n"
        context_text += f"   ⏰ {msg.get('timestamp', 'N/A')}\n"
        
        if has_reply:
            context_text += f"   📎 ریپلای به: {msg.get('reply_to_user_name', 'Unknown')}\n"
        
        context_text += f"   📝 {content_preview}\n\n"
    
    context_text += f"📊 **مجموع:** {len(user_context)} پیام، {total_tokens} توکن، {reply_count} ریپلای"
    
    await update.message.reply_text(context_text, parse_mode='Markdown')

@admin_only
async def admin_view_replies(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """مشاهده ریپلای‌های یک کاربر یا گروه"""
    if len(context.args) < 2:
        await update.message.reply_text(
            "⚠️ فرمت صحیح: `/view_replies [user|group] [آیدی]`\n"
            "مثال: `/view_replies user 123456789`\n"
            "مثال: `/view_replies group -1001234567890`"
        )
        return
    
    entity_type = context.args[0].lower()
    entity_id = context.args[1]
    
    if entity_type == 'user':
        try:
            user_id = int(entity_id)
            user_context = data_manager.get_user_context(user_id)
            if not user_context:
                await update.message.reply_text(f"کاربر `{entity_id}` context ندارد.")
                return
            
            replies = [msg for msg in user_context if msg.get('has_reply', False)]
            
            if not replies:
                await update.message.reply_text(f"کاربر `{entity_id}` هیچ ریپلای‌ای ثبت نکرده است.")
                return
            
            text = f"📋 **ریپلای‌های کاربر `{entity_id}`**\n\n"
            for i, msg in enumerate(replies, 1):
                text += f"{i}. **زمان:** {msg.get('timestamp', 'N/A')}\n"
                text += f"   **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
                if msg.get('is_reply_to_bot', False):
                    text += f"   **نوع:** ریپلای به ربات 🤖\n"
                else:
                    text += f"   **نوع:** ریپلای به کاربر\n"
                text += f"   **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
                text += f"   **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
            
            text += f"📊 **مجموع:** {len(replies)} ریپلای"
            
            await update.message.reply_text(text, parse_mode='Markdown')
        except ValueError:
            await update.message.reply_text("⚠️ آیدی کاربر باید عددی باشد.")
    
    elif entity_type == 'group':
        try:
            chat_id = int(entity_id)
            group_context = data_manager.get_group_context(chat_id)
            if not group_context:
                await update.message.reply_text(f"گروه `{entity_id}` context ندارد.")
                return
            
            replies = [msg for msg in group_context if msg.get('has_reply', False)]
            
            if not replies:
                await update.message.reply_text(f"گروه `{entity_id}` هیچ ریپلای‌ای ثبت نکرده است.")
                return
            
            text = f"📋 **ریپلای‌های گروه `{entity_id}`**\n\n"
            for i, msg in enumerate(replies, 1):
                user_name = msg.get('user_name', 'Unknown')
                text += f"{i}. **کاربر:** {user_name}\n"
                text += f"   **زمان:** {msg.get('timestamp', 'N/A')}\n"
                text += f"   **ریپلای به:** {msg.get('reply_to_user_name', 'Unknown')}\n"
                if msg.get('is_reply_to_bot', False):
                    text += f"   **نوع:** ریپلای به ربات 🤖\n"
                else:
                    text += f"   **نوع:** ریپلای به کاربر\n"
                text += f"   **متن ریپلای شده:** {msg.get('reply_to_content', '')}\n"
                text += f"   **پاسخ کاربر:** {msg.get('content', '')[:100]}...\n\n"
            
            text += f"📊 **مجموع:** {len(replies)} ریپلای"
            
            await update.message.reply_text(text, parse_mode='Markdown')
        except ValueError:
            await update.message.reply_text("⚠️ آیدی گروه باید عددی باشد.")
    
    else:
        await update.message.reply_text("⚠️ نوع نامعتبر. فقط 'user' یا 'group' مجاز است.")

# --- دستورات جدید برای مدیریت گروه‌ها ---
@admin_only
async def admin_set_context_mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """تنظیم حالت context ربات"""
    if not context.args or context.args[0].lower() not in ['separate', 'group_shared', 'hybrid']:
        await update.message.reply_text(
            "⚠️ فرمت صحیح: `/set_context_mode [separate|group_shared|hybrid]`\n\n"
            "• **separate**: هر کاربر context جداگانه دارد (8192 توکن)\n"
            "• **group_shared**: همه کاربران در یک گروه context مشترک دارند (16384 توکن)\n"
            "• **hybrid**: ترکیبی از context شخصی و گروهی\n\n"
            "💡 **توجه:** حالت group_shared حافظه بیشتری برای گروه‌ها فراهم می‌کند."
        )
        return
    
    mode = context.args[0].lower()
    if data_manager.set_context_mode(mode):
        await update.message.reply_text(f"✅ حالت context به `{mode}` تغییر یافت.")
    else:
        await update.message.reply_text("❌ خطا در تغییر حالت context.")

@admin_only
async def admin_group_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """نمایش اطلاعات یک گروه"""
    if not context.args or not context.args[0].lstrip('-').isdigit():
        await update.message.reply_text("⚠️ لطفاً آیدی عددی گروه را وارد کنید.\nمثال: `/group_info -1001234567890`")
        return
    
    chat_id = int(context.args[0])
    group_info = data_manager.DATA['groups'].get(str(chat_id))
    
    if not group_info:
        await update.message.reply_text(f"گروهی با آیدی `{chat_id}` در دیتابیس یافت نشد.")
        return
    
    # تبدیل set اعضا به لیست برای نمایش
    members = list(group_info.get('members', set()))
    members_count = len(members)
    
    # اطلاعات context گروه
    context_messages = len(group_info.get('context', []))
    total_tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info.get('context', []))
    
    # تعداد ریپلای‌ها در گروه
    reply_count = 0
    if 'context' in group_info:
        reply_count = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
    
    text = (
        f"📊 **اطلاعات گروه**\n\n"
        f"🆔 **آیدی:** `{chat_id}`\n"
        f"🏷️ **عنوان:** {group_info.get('title', 'N/A')}\n"
        f"📝 **تعداد پیام‌ها:** `{group_info.get('message_count', 0)}`\n"
        f"👥 **تعداد اعضا:** `{members_count}`\n"
        f"💭 **پیام‌های context:** `{context_messages}`\n"
        f"📎 **تعداد ریپلای‌ها:** `{reply_count}`\n"
        f"🔢 **توکن‌های context:** `{total_tokens}`\n"
        f"📅 **اولین فعالیت:** {group_info.get('first_seen', 'N/A')}\n"
        f"🕒 **آخرین فعالیت:** {group_info.get('last_seen', 'N/A')}"
    )
    
    await update.message.reply_text(text, parse_mode='Markdown')

@admin_only
async def admin_clear_group_context(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """پاک کردن context یک گروه"""
    if not context.args or not context.args[0].lstrip('-').isdigit():
        await update.message.reply_text("⚠️ لطفاً آیدی گروه را وارد کنید.\nمثال: `/clear_group_context -1001234567890`")
        return
    
    chat_id = int(context.args[0])
    data_manager.clear_group_context(chat_id)
    
    await update.message.reply_text(f"✅ context گروه `{chat_id}` با موفقیت پاک شد.")

@admin_only
async def admin_memory_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """نمایش وضعیت حافظه و context گروه‌ها"""
    groups = data_manager.DATA['groups']
    
    if not groups:
        await update.message.reply_text("هیچ گروهی در دیتابیس وجود ندارد.")
        return
    
    # محاسبه آمار
    total_groups = len(groups)
    groups_with_context = sum(1 for g in groups.values() if g.get('context'))
    total_context_messages = sum(len(g.get('context', [])) for g in groups.values())
    total_context_tokens = 0
    total_replies = 0
    
    for group_id, group_info in groups.items():
        if 'context' in group_info:
            total_context_tokens += sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
            total_replies += sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
    
    # لیست گروه‌هایی که بیشترین استفاده از حافظه را دارند
    groups_by_tokens = []
    for group_id, group_info in groups.items():
        if 'context' in group_info:
            tokens = sum(data_manager.count_tokens(msg['content']) for msg in group_info['context'])
            messages = len(group_info['context'])
            replies = sum(1 for msg in group_info['context'] if msg.get('has_reply', False))
            groups_by_tokens.append((group_id, tokens, messages, replies))
    
    # مرتب‌سازی بر اساس تعداد توکن
    groups_by_tokens.sort(key=lambda x: x[1], reverse=True)
    
    status_text = (
        f"💾 **وضعیت حافظه گروه‌ها**\n\n"
        f"📊 **آمار کلی:**\n"
        f"• تعداد کل گروه‌ها: `{total_groups}`\n"
        f"• گروه‌های دارای context: `{groups_with_context}`\n"
        f"• کل پیام‌های context: `{total_context_messages}`\n"
        f"• کل ریپلای‌ها: `{total_replies}`\n"
        f"• کل توکن‌های استفاده شده: `{total_context_tokens}`\n"
        f"• میانگین توکن per گروه: `{total_context_tokens/max(1, groups_with_context):.0f}`\n\n"
        f"🏆 **گروه‌های با بیشترین استفاده از حافظه:**\n"
    )
    
    for i, (group_id, tokens, messages, replies) in enumerate(groups_by_tokens[:10], 1):
        usage_percent = (tokens / 16384) * 100
        status_text += f"{i}. گروه `{group_id}`: {messages} پیام، {replies} ریپلای، {tokens} توکن ({usage_percent:.1f}%)\n"
    
    await update.message.reply_text(status_text, parse_mode='Markdown')

# --- هندلر برای دکمه‌های صفحه‌بندی ---
async def users_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """پردازش دکمه‌های صفحه‌بندی لیست کاربران."""
    query = update.callback_query
    await query.answer()
    
    if query.data.startswith("users_list:"):
        page = int(query.data.split(":")[1])
        context.args = [str(page)]
        await admin_users_list(update, context)

# --- تابع برای پردازش ارسال‌های برنامه‌ریزی شده ---
async def process_scheduled_broadcasts(context: ContextTypes.DEFAULT_TYPE):
    """پردازش ارسال‌های برنامه‌ریزی شده و ارسال پیام‌ها در زمان مقرر."""
    now = datetime.now()
    broadcasts_to_send_indices = []
    
    for i, broadcast in enumerate(data_manager.DATA['scheduled_broadcasts']):
        if broadcast['status'] == 'pending':
            broadcast_time = datetime.strptime(broadcast['time'], '%Y-%m-%d %H:%M:%S')
            if broadcast_time <= now:
                broadcasts_to_send_indices.append(i)

    if not broadcasts_to_send_indices:
        return
    
    user_ids = list(data_manager.DATA['users'].keys())
    
    for index in broadcasts_to_send_indices:
        broadcast = data_manager.DATA['scheduled_broadcasts'][index]
        message_text = broadcast['message']
        total_sent, total_failed = 0, 0
        
        for user_id_str in user_ids:
            try:
                await context.bot.send_message(chat_id=int(user_id_str), text=message_text)
                total_sent += 1
                await asyncio.sleep(0.05)
            except TelegramError as e:
                logger.warning(f"Failed to send scheduled broadcast to {user_id_str}: {e}")
                total_failed += 1
        
        # به‌روزرسانی وضعیت ارسال
        data_manager.DATA['scheduled_broadcasts'][index]['status'] = 'sent'
        data_manager.DATA['scheduled_broadcasts'][index]['sent_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
        data_manager.DATA['scheduled_broadcasts'][index]['sent_count'] = total_sent
        data_manager.DATA['scheduled_broadcasts'][index]['failed_count'] = total_failed
        
        logger.info(f"Scheduled broadcast sent: {total_sent} successful, {total_failed} failed")
    
    data_manager.save_data()

# --- تابع راه‌اندازی هندلرها ---
def setup_admin_handlers(application):
    """هندلرهای پنل ادمین را به اپلیکیشن اضافه می‌کند."""
    # هندلرهای اصلی
    application.add_handler(CommandHandler("commands", admin_commands))
    application.add_handler(CommandHandler("stats", admin_stats))
    application.add_handler(CommandHandler("broadcast", admin_broadcast))
    application.add_handler(CommandHandler("targeted_broadcast", admin_targeted_broadcast))
    application.add_handler(CommandHandler("schedule_broadcast", admin_schedule_broadcast))
    application.add_handler(CommandHandler("list_scheduled", admin_list_scheduled_broadcasts))
    application.add_handler(CommandHandler("remove_scheduled", admin_remove_scheduled_broadcast))
    application.add_handler(CommandHandler("ban", admin_ban))
    application.add_handler(CommandHandler("unban", admin_unban))
    application.add_handler(CommandHandler("direct_message", admin_direct_message))
    application.add_handler(CommandHandler("user_info", admin_userinfo))
    application.add_handler(CommandHandler("logs", admin_logs))
    application.add_handler(CommandHandler("logs_file", admin_logs_file))
    application.add_handler(CommandHandler("users_list", admin_users_list))
    application.add_handler(CommandHandler("user_search", admin_user_search))
    application.add_handler(CommandHandler("backup", admin_backup))
    application.add_handler(CommandHandler("export_csv", admin_export_csv))
    application.add_handler(CommandHandler("maintenance", admin_maintenance))
    application.add_handler(CommandHandler("set_welcome", admin_set_welcome_message))
    application.add_handler(CommandHandler("set_goodbye", admin_set_goodbye_message))
    application.add_handler(CommandHandler("activity_heatmap", admin_activity_heatmap))
    application.add_handler(CommandHandler("response_stats", admin_response_stats))
    application.add_handler(CommandHandler("add_blocked_word", admin_add_blocked_word))
    application.add_handler(CommandHandler("remove_blocked_word", admin_remove_blocked_word))
    application.add_handler(CommandHandler("list_blocked_words", admin_list_blocked_words))
    application.add_handler(CommandHandler("system_info", admin_system_info))
    application.add_handler(CommandHandler("reset_stats", admin_reset_stats))
    
    # هندلرهای مدیریت context
    application.add_handler(CommandHandler("clear_context", admin_clear_context))
    application.add_handler(CommandHandler("view_context", admin_view_context))
    application.add_handler(CommandHandler("view_replies", admin_view_replies))
    
    # هندلرهای جدید برای مدیریت گروه‌ها
    application.add_handler(CommandHandler("set_context_mode", admin_set_context_mode))
    application.add_handler(CommandHandler("group_info", admin_group_info))
    application.add_handler(CommandHandler("clear_group_context", admin_clear_group_context))
    application.add_handler(CommandHandler("memory_status", admin_memory_status))
    
    # هندلر برای دکمه‌های صفحه‌بندی
    application.add_handler(CallbackQueryHandler(users_list_callback, pattern="^users_list:"))
    
    # شروع وظیفه دوره‌ای برای بررسی ارسال‌های برنامه‌ریزی شده
    application.job_queue.run_repeating(process_scheduled_broadcasts, interval=60, first=0)
    
    logger.info("Admin panel handlers have been set up.")