File size: 38,749 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
import os
import logging
import asyncio
import httpx
import time
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from openai import AsyncOpenAI
from keep_alive import start_keep_alive
from datetime import datetime
from flask import Flask, jsonify

import threading

flask_app = Flask(__name__)

@flask_app.route('/')
def home():
    return jsonify({"status": "ok", "service": "telegram-bot"})

@flask_app.route('/health')
def health_check():
    return jsonify({
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "service": "telegram-bot"
    })

@flask_app.route('/webhook', methods=['POST'])
def webhook_receiver():
    """این endpoint توسط Telegram استفاده می‌شود"""
    # Telegram webhook handler
    pass

def run_flask():
    """اجرای Flask در یک thread جداگانه"""
    port = int(os.environ.get("FLASK_PORT", 5000))
    flask_app.run(host='0.0.0.0', port=port)

# وارد کردن مدیر داده‌ها و پنل ادمین
import data_manager
import admin_panel
import system_instruction_handlers

# بارگذاری داده‌ها در ابتدا
data_manager.load_data()

# شروع سرویس نگه داشتن ربات فعال
start_keep_alive()

# --- بهبود لاگینگ ---
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", 
    level=logging.INFO,
    filename=data_manager.LOG_FILE, 
    filemode='a'
)
logger = logging.getLogger(__name__)

try:
    with open(data_manager.LOG_FILE, 'a') as f:
        f.write("")
except Exception as e:
    print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
    logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")

# --- ایجاد یک کلاینت HTTP بهینه‌سازی‌شده ---
http_client = httpx.AsyncClient(
    http2=True,
    limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
    timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
)

# کلاینت OpenAI (HuggingFace)
client = AsyncOpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.environ["HF_TOKEN"],
    http_client=http_client
)

# --- دیکشنری برای مدیریت وظایف پس‌زمینه هر کاربر ---
user_tasks = {}  # برای چت خصوصی: {user_id: task}
user_group_tasks = {}  # برای گروه: {(chat_id, user_id): task}

# --- توابع کمکی برای مدیریت ریپلای ---
def extract_reply_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> tuple:
    """استخراج اطلاعات از ریپلای"""
    message = update.message
    
    # اگر ریپلای وجود نداشت
    if not message or not message.reply_to_message:
        return None, None, None, None
    
    replied_message = message.reply_to_message
    
    # اطلاعات پیام ریپلای شده
    replied_user_id = replied_message.from_user.id if replied_message.from_user else None
    replied_user_name = replied_message.from_user.first_name if replied_message.from_user else "Unknown"
    
    # استخراج متن پیام ریپلای شده
    replied_text = ""
    if replied_message.text:
        replied_text = replied_message.text
    elif replied_message.caption:
        replied_text = replied_message.caption
    
    # بررسی اینکه آیا ریپلای به ربات است
    is_reply_to_bot = False
    if replied_message.from_user:
        if replied_message.from_user.is_bot:
            is_reply_to_bot = True
        elif context.bot and context.bot.username and replied_message.text:
            if f"@{context.bot.username}" in replied_message.text:
                is_reply_to_bot = True
    
    return replied_user_id, replied_user_name, replied_text, is_reply_to_bot

def format_reply_message(user_message: str, replied_user_name: str, replied_text: str, 
                         is_reply_to_bot: bool = False, current_user_name: str = None) -> str:
    """فرمت‌دهی پیام با در نظر گرفتن ریپلای"""
    if not replied_text:
        return user_message
    
    # محدود کردن طول متن ریپلای شده
    if len(replied_text) > 100:
        replied_preview = replied_text[:97] + "..."
    else:
        replied_preview = replied_text
    
    # حذف منشن ربات از متن ریپلای شده اگر وجود دارد
    replied_preview = replied_preview.replace("@", "(at)")
    
    if is_reply_to_bot:
        if current_user_name:
            return f"📎 {current_user_name} در پاسخ به ربات: «{replied_preview}»\n\n{user_message}"
        else:
            return f"📎 ریپلای به ربات: «{replied_preview}»\n\n{user_message}"
    else:
        if current_user_name:
            return f"📎 {current_user_name} در پاسخ به {replied_user_name}: «{replied_preview}»\n\n{user_message}"
        else:
            return f"📎 ریپلای به {replied_user_name}: «{replied_preview}»\n\n{user_message}"

def create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot):
    """ایجاد دیکشنری اطلاعات ریپلای"""
    if not replied_text:
        return None
    
    return {
        'replied_user_id': replied_user_id,
        'replied_user_name': replied_user_name,
        'replied_text': replied_text[:1500],
        'is_reply_to_bot': is_reply_to_bot,
        'timestamp': time.time()
    }

# --- توابع کمکی برای مدیریت وظایف ---
def _cleanup_task(task: asyncio.Task, task_dict: dict, task_id: int):
    if task_id in task_dict and task_dict[task_id] == task:
        del task_dict[task_id]
        logger.info(f"Cleaned up finished task for ID {task_id}.")
    try:
        exception = task.exception()
        if exception:
            logger.error(f"Background task for ID {task_id} failed: {exception}")
    except asyncio.CancelledError:
        logger.info(f"Task for ID {task_id} was cancelled.")
    except asyncio.InvalidStateError:
        pass

def _cleanup_user_group_task(task: asyncio.Task, chat_id: int, user_id: int):
    """پاک‌سازی وظایف کاربران در گروه"""
    task_key = (chat_id, user_id)
    if task_key in user_group_tasks and user_group_tasks[task_key] == task:
        del user_group_tasks[task_key]
        logger.info(f"Cleaned up finished task for group {chat_id}, user {user_id}.")
    try:
        exception = task.exception()
        if exception:
            logger.error(f"Background task for group {chat_id}, user {user_id} failed: {exception}")
    except asyncio.CancelledError:
        logger.info(f"Task for group {chat_id}, user {user_id} was cancelled.")
    except asyncio.InvalidStateError:
        pass

async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE, 
                               custom_message: str = None, reply_info: dict = None):
    """پردازش درخواست کاربر در چت خصوصی"""
    chat_id = update.effective_chat.id
    user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
    user_id = update.effective_user.id
    
    if not user_message:
        logger.warning(f"No message content for user {user_id}")
        return
    
    if reply_info is None:
        replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
        reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
    
    if reply_info and reply_info.get('replied_text'):
        formatted_message = format_reply_message(
            user_message, 
            reply_info.get('replied_user_name', 'Unknown'),
            reply_info.get('replied_text'),
            reply_info.get('is_reply_to_bot', False)
        )
    else:
        formatted_message = user_message
    
    start_time = time.time()

    try:
        await context.bot.send_chat_action(chat_id=chat_id, action="typing")
        
        user_context = data_manager.get_context_for_api(user_id)
        
        data_manager.add_to_user_context_with_reply(user_id, "user", formatted_message, reply_info)
        
        system_instruction = data_manager.get_system_instruction(user_id=user_id)
        
        messages = []
        
        if system_instruction:
            messages.append({"role": "system", "content": system_instruction})
        
        messages.extend(user_context.copy())
        messages.append({"role": "user", "content": formatted_message})
        
        logger.info(f"User {user_id} sending {len(messages)} messages to AI")
        if reply_info and reply_info.get('replied_text'):
            logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
        
        response = await client.chat.completions.create(
            model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
            messages=messages,
            temperature=0.7,
            top_p=0.95,
            stream=False,
        )
        
        end_time = time.time()
        response_time = end_time - start_time
        data_manager.update_response_stats(response_time)
        
        ai_response = response.choices[0].message.content
        
        data_manager.add_to_user_context(user_id, "assistant", ai_response)
        
        await update.message.reply_text(ai_response)
        data_manager.update_user_stats(user_id, update.effective_user)

    except httpx.TimeoutException:
        logger.warning(f"Request timed out for user {user_id}.")
        await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
    except Exception as e:
        logger.error(f"Error while processing message for user {user_id}: {e}")
        await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")

async def _process_group_request(update: Update, context: ContextTypes.DEFAULT_TYPE, 
                                custom_message: str = None, reply_info: dict = None):
    """پردازش درخواست در گروه با حالت Hybrid پیشرفته"""
    chat_id = update.effective_chat.id
    user_message = custom_message if custom_message is not None else (update.message.text or update.message.caption or "")
    user_id = update.effective_user.id
    user_name = update.effective_user.first_name
    
    if not user_message:
        logger.warning(f"No message content for group {chat_id}, user {user_id}")
        return
    
    if reply_info is None:
        replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
        reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
    
    if reply_info and reply_info.get('replied_text'):
        formatted_message = format_reply_message(
            user_message,
            reply_info.get('replied_user_name', 'Unknown'),
            reply_info.get('replied_text'),
            reply_info.get('is_reply_to_bot', False),
            user_name
        )
    else:
        formatted_message = user_message
    
    start_time = time.time()

    try:
        await context.bot.send_chat_action(chat_id=chat_id, action="typing")
        
        context_mode = data_manager.get_context_mode()
        hybrid_mode = data_manager.DATA['hybrid_settings']['mode']
        
        if context_mode == 'hybrid' and hybrid_mode == 'advanced':
            # حالت Hybrid پیشرفته
            messages = data_manager.get_advanced_hybrid_context_for_api(user_id, chat_id)
            
            data_manager.add_to_hybrid_context_advanced(
                user_id, chat_id, "user", formatted_message, user_name, reply_info
            )
            
            messages.append({
                "role": "user",
                "content": f"{user_name}: {formatted_message}"
            })
            
            logger.info(f"Group {chat_id} - Advanced Hybrid mode active for user {user_id}")
            
        elif context_mode == 'hybrid':
            # حالت Hybrid ساده
            messages = data_manager.get_context_for_api(user_id)
            group_context = data_manager.get_context_for_api_group(chat_id)
            
            data_manager.add_to_hybrid_context_advanced(
                user_id, chat_id, "user", formatted_message, user_name, reply_info
            )
            
            messages.extend(group_context[-10:])  # اضافه کردن 10 پیام آخر گروه
            messages.append({
                "role": "user",
                "content": f"{user_name}: {formatted_message}"
            })
            
        elif context_mode == 'group_shared':
            messages = data_manager.get_context_for_api_group(chat_id)
            data_manager.add_to_group_context_with_reply(
                chat_id, "user", formatted_message, user_name, reply_info, user_id
            )
            
            messages.append({
                "role": "user", 
                "content": f"{user_name}: {formatted_message}"
            })
            
        else:  # separate
            messages = data_manager.get_context_for_api(user_id)
            data_manager.add_to_user_context_with_reply(
                user_id, "user", formatted_message, reply_info
            )
            
            messages.append({"role": "user", "content": formatted_message})
        
        system_instruction = data_manager.get_system_instruction(user_id=user_id, chat_id=chat_id)
        
        if system_instruction:
            messages.insert(0, {"role": "system", "content": system_instruction})
        
        logger.info(f"Group {chat_id} - User {user_id} ({context_mode} mode) sending {len(messages)} messages to AI")
        
        if reply_info and reply_info.get('replied_text'):
            logger.info(f"Reply info: replied_to={reply_info.get('replied_user_name')}, is_to_bot={reply_info.get('is_reply_to_bot')}")
        
        response = await client.chat.completions.create(
            model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
            messages=messages,
            temperature=0.7,
            top_p=0.95,
            stream=False,
        )
        
        end_time = time.time()
        response_time = end_time - start_time
        data_manager.update_response_stats(response_time)
        
        ai_response = response.choices[0].message.content
        
        if context_mode == 'hybrid':
            data_manager.add_to_hybrid_context_advanced(
                user_id, chat_id, "assistant", ai_response, None, None
            )
        elif context_mode == 'group_shared':
            data_manager.add_to_group_context(chat_id, "assistant", ai_response)
        else:
            data_manager.add_to_user_context(user_id, "assistant", ai_response)
        
        data_manager.update_group_stats(chat_id, update.effective_chat, user_id)
        
        await update.message.reply_text(
            ai_response,
            reply_to_message_id=update.message.message_id
        )

    except httpx.TimeoutException:
        logger.warning(f"Request timed out for group {chat_id}, user {user_id}.")
        await update.message.reply_text(
            "⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.",
            reply_to_message_id=update.message.message_id
        )
    except Exception as e:
        logger.error(f"Error while processing message for group {chat_id}, user {user_id}: {e}")
        await update.message.reply_text(
            "❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
            reply_to_message_id=update.message.message_id
        )

# --- هندلرهای اصلی ربات ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    user_id = user.id
    chat = update.effective_chat
    
    if chat.type in ['group', 'supergroup']:
        data_manager.update_group_stats(chat.id, chat, user_id)
        
        welcome_msg = data_manager.DATA.get('group_welcome_message', 
            "سلام به همه! 🤖\n\nمن یک ربات هوشمند هستم. برای استفاده از من در گروه:\n1. مستقیم با من چت کنید\n2. یا با منشن کردن من سوال بپرسید\n3. یا روی پیام‌ها ریپلای کنید")
        
        context_mode = data_manager.get_context_mode()
        hybrid_mode = data_manager.DATA['hybrid_settings']['mode']
        
        mode_info = ""
        if context_mode == 'hybrid':
            mode_info = f"\n\n🎯 **حالت فعلی:** Hybrid ({hybrid_mode})\n"
            if hybrid_mode == 'advanced':
                mode_info += "• سیستم Hybrid پیشرفته فعال است\n"
                mode_info += "• ربات هر کاربر را جداگانه می‌شناسد\n"
                mode_info += "• تاریخچه شخصی + گروهی + آگاهی از دیگر کاربران\n"
            else:
                mode_info += "• سیستم Hybrid ساده فعال است\n"
                mode_info += "• تاریخچه شخصی + گروهی\n"
        elif context_mode == 'group_shared':
            mode_info = "\n\n📝 **نکته:** در این گروه از context مشترک استفاده می‌شود. همه کاربران تاریخچه مکالمه یکسانی دارند."
        else:
            mode_info = "\n\n📝 **نکته:** در این گروه هر کاربر تاریخچه مکالمه جداگانه خود را دارد."
        
        system_info = data_manager.get_system_instruction_info(chat_id=chat.id)
        if system_info['type'] == 'group' and system_info['has_instruction']:
            instruction_preview = system_info['instruction'][:100] + "..." if len(system_info['instruction']) > 100 else system_info['instruction']
            mode_info += f"\n\n⚙️ **سیستم‌اینستراکشن گروه:**\n{instruction_preview}"
        
        await update.message.reply_html(
            welcome_msg + mode_info,
            disable_web_page_preview=True
        )
    else:
        data_manager.update_user_stats(user_id, user)
        
        welcome_msg = data_manager.DATA.get('welcome_message', 
            "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.\n\n💡 **نکته:** می‌توانید روی پیام‌های من ریپلای کنید تا من ارتباط را بهتر بفهمم.")
        
        await update.message.reply_html(
            welcome_msg.format(user_mention=user.mention_html()),
            disable_web_page_preview=True
        )

async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """پاک کردن تاریخچه چت"""
    user_id = update.effective_user.id
    chat = update.effective_chat
    
    if chat.type in ['group', 'supergroup']:
        data_manager.clear_group_context(chat.id)
        
        context_mode = data_manager.get_context_mode()
        if context_mode == 'group_shared':
            await update.message.reply_text(
                "🧹 تاریخچه مکالمه گروه پاک شد.\n"
                "از این لحظه مکالمه جدیدی برای همه اعضای گروه شروع خواهد شد."
            )
        elif context_mode == 'hybrid':
            await update.message.reply_text(
                "🧹 تاریخچه مکالمه گروه پاک شد.\n"
                "تاریخچه شخصی شما همچنان حفظ شده است.\n"
                "از این لحظه مکالمه جدیدی در گروه شروع خواهد شد."
            )
        else:
            await update.message.reply_text(
                "🧹 تاریخچه مکالمه شخصی شما در این گروه پاک شد.\n"
                "از این لحظه مکالمه جدیدی شروع خواهد شد."
            )
    else:
        data_manager.clear_user_context(user_id)
        
        await update.message.reply_text(
            "🧹 تاریخچه مکالمه شما پاک شد.\n"
            "از این لحظه مکالمه جدیدی شروع خواهد شد."
        )

async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """نمایش اطلاعات context"""
    user_id = update.effective_user.id
    chat = update.effective_chat
    
    if chat.type in ['group', 'supergroup']:
        context_mode = data_manager.get_context_mode()
        
        if context_mode == 'hybrid':
            hybrid_summary = data_manager.get_hybrid_context_summary(user_id, chat.id)
            await update.message.reply_text(
                f"📊 **اطلاعات تاریخچه مکالمه (حالت Hybrid پیشرفته):**\n\n"
                f"{hybrid_summary}\n\n"
                f"🎯 **ویژگی‌های این حالت:**\n"
                f"✅ تاریخچه شخصی شما حفظ می‌شود (تا 16384 توکن)\n"
                f"✅ تاریخچه گروه کامل ذخیره می‌شود (تا 32768 توکن)\n"
                f"✅ اطلاعات دیگر کاربران فعال در نظر گرفته می‌شود\n"
                f"✅ ربات می‌داند که چند کاربر در حال گفتگو هستند\n"
                f"✅ پاسخ‌ها دقیق و مرتبط با هر کاربر خواهند بود\n\n"
                f"برای پاک کردن تاریخچه شخصی از /clear استفاده کنید.\n"
                f"برای پاک کردن تاریخچه گروه، ادمین از /clear_group_context استفاده کند."
            )
        elif context_mode == 'group_shared':
            context_summary = data_manager.get_group_context_summary(chat.id)
            await update.message.reply_text(
                f"📊 **اطلاعات تاریخچه مکالمه گروه:**\n\n"
                f"{context_summary}\n\n"
                f"**حالت:** مشترک بین همه اعضای گروه\n"
                f"**سقف توکن:** 32768 توکن\n"
                f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
            )
        else:
            context_summary = data_manager.get_context_summary(user_id)
            await update.message.reply_text(
                f"📊 **اطلاعات تاریخچه مکالمه شخصی شما در این گروه:**\n\n"
                f"{context_summary}\n\n"
                f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
            )
    else:
        context_summary = data_manager.get_context_summary(user_id)
        await update.message.reply_text(
            f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
            f"{context_summary}\n\n"
            f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
        )

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """نمایش دستورات کمک"""
    user_id = update.effective_user.id
    chat = update.effective_chat
    
    admin_ids = admin_panel.get_admin_ids()
    is_admin_bot = user_id in admin_ids
    is_admin_group = system_instruction_handlers.is_group_admin(update) if chat.type in ['group', 'supergroup'] else False
    
    context_mode = data_manager.get_context_mode()
    hybrid_mode = data_manager.DATA['hybrid_settings']['mode']
    
    if chat.type in ['group', 'supergroup']:
        help_text = (
            f"🤖 **دستورات ربات در گروه:**\n\n"
            f"🟢 `/start` - شروع کار با ربات در گروه\n"
            f"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
            f"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
            f"🟢 `/help` - نمایش این پیام راهنما\n\n"
            f"📝 **نکته:** ربات به سه صورت کار می‌کند:\n"
            f"1. پاسخ به پیام‌های مستقیم\n"
            f"2. پاسخ وقتی منشن می‌شوید\n"
            f"3. پاسخ به ریپلای‌ها (روی پیام‌های من یا دیگران)\n\n"
            f"**حالت فعلی:** {context_mode}"
        )
        
        if context_mode == 'hybrid':
            help_text += f" ({hybrid_mode})\n"
            if hybrid_mode == 'advanced':
                help_text += (
                    "• **Hybrid پیشرفته**: هر کاربر تاریخچه شخصی + گروهی + آگاهی از دیگران\n"
                    "• ربات شما را جداگانه می‌شناسد و پاسخ‌های شخصی‌سازی شده می‌دهد\n"
                )
            else:
                help_text += (
                    "• **Hybrid ساده**: تاریخچه شخصی + گروهی\n"
                    "• پاسخ‌ها بر اساس ترکیب تاریخچه شما و گروه\n"
                )
        elif context_mode == 'group_shared':
            help_text += "\n• **مشترک گروهی**: همه کاربران تاریخچه مشترک دارند\n"
        else:
            help_text += "\n• **جداگانه**: هر کاربر تاریخچه جداگانه خود را دارد\n"
        
        help_text += "\n💡 **مزایای حالت Hybrid پیشرفته:**\n"
        help_text += "✅ ربات تاریخچه شخصی شما را به خاطر می‌سپارد\n"
        help_text += "✅ ربات از مکالمات گروه نیز آگاه است\n"
        help_text += "✅ آگاهی از کاربران دیگر فعال در گروه\n"
        help_text += "✅ پاسخ‌های دقیق‌تر و شخصی‌سازی شده\n"
        help_text += "✅ برای بحث‌های گروهی پیچیده ایده‌آل است"
        
        help_text += "\n\n⚙️ **دستورات System Instruction:**\n"
        
        if is_admin_bot or is_admin_group:
            help_text += (
                "• `/system [متن]` - تنظیم system instruction برای این گروه\n"
                "• `/system clear` - حذف system instruction این گروه\n"
                "• `/system_status` - نمایش وضعیت فعلی\n"
                "• `/system_help` - نمایش راهنما\n\n"
            )
            
            if is_admin_bot:
                help_text += "🎯 **دسترسی ادمین ربات:**\n"
                help_text += "- می‌توانید Global System Instruction را مدیریت کنید\n"
                help_text += "- برای تنظیم Global از دستور `/set_global_system` استفاده کنید\n"
                help_text += "- می‌توانید حالت context را با `/set_context_mode` تغییر دهید\n"
                help_text += "- می‌توانید حالت Hybrid را با `/set_hybrid_mode` تنظیم کنید\n"
            else:
                help_text += "🎯 **دسترسی ادمین گروه:**\n"
                help_text += "- فقط می‌توانید system instruction همین گروه را مدیریت کنید\n"
        else:
            help_text += (
                "این دستورات فقط برای ادمین‌های گروه در دسترس است.\n"
                "برای تنظیم شخصیت ربات در این گروه، با ادمین‌های گروه تماس بگیرید."
            )
            
    else:
        help_text = (
            "🤖 **دستورات ربات:**\n\n"
            "🟢 `/start` - شروع کار با ربات\n"
            "🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
            "🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
            "🟢 `/help` - نمایش این پیام راهنما\n\n"
            "📝 **نکته:** ربات تاریخچه مکالمه شما را تا 16384 توکن ذخیره می‌کند. "
            "می‌توانید روی پیام‌های من ریپلای کنید تا من ارتباط را بهتر بفهمم.\n"
            "برای شروع مکالمه جدید از دستور /clear استفاده کنید."
        )
        
        help_text += "\n\n⚙️ **دستورات System Instruction:**\n"
        
        if is_admin_bot:
            help_text += (
                "• `/system_status` - نمایش وضعیت Global System Instruction\n"
                "• `/system_help` - نمایش راهنما\n\n"
                "🎯 **دسترسی ادمین ربات:**\n"
                "- می‌توانید Global System Instruction را مدیریت کنید\n"
                "- از پنل ادمین برای تنظیمات پیشرفته استفاده کنید"
            )
        else:
            help_text += "این دستورات فقط برای ادمین‌های ربات در دسترس است."
    
    await update.message.reply_text(help_text, parse_mode='Markdown')

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """هندلر اصلی برای پیام‌ها"""
    if not update.message:
        return
    
    user_id = update.effective_user.id
    chat = update.effective_chat
    
    if data_manager.is_user_banned(user_id):
        logger.info(f"Banned user {user_id} tried to send a message.")
        return
    
    admin_ids = admin_panel.get_admin_ids()
    if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_ids:
        await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
        return

    message_text = update.message.text or update.message.caption or ""
    if not message_text:
        return
    
    if data_manager.contains_blocked_words(message_text):
        logger.info(f"User {user_id} sent a message with a blocked word.")
        return

    if chat.type in ['group', 'supergroup']:
        task_key = (chat.id, user_id)
        
        if task_key in user_group_tasks and not user_group_tasks[task_key].done():
            user_group_tasks[task_key].cancel()
            logger.info(f"Cancelled previous task for group {chat.id}, user {user_id} to start a new one.")

        task = asyncio.create_task(_process_group_request(update, context))
        user_group_tasks[task_key] = task
        task.add_done_callback(lambda t: _cleanup_user_group_task(t, chat.id, user_id))
    else:
        if user_id in user_tasks and not user_tasks[user_id].done():
            user_tasks[user_id].cancel()
            logger.info(f"Cancelled previous task for user {user_id} to start a new one.")

        task = asyncio.create_task(_process_user_request(update, context))
        user_tasks[user_id] = task
        task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))

async def mention_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """هندلر برای زمانی که ربات در گروه منشن می‌شود"""
    if not update.message:
        return
    
    if update.effective_chat.type in ['group', 'supergroup']:
        replied_user_id, replied_user_name, replied_text, is_reply_to_bot = extract_reply_info(update, context)
        reply_info = create_reply_info_dict(replied_user_id, replied_user_name, replied_text, is_reply_to_bot)
        
        message_text = update.message.text or ""
        bot_username = context.bot.username
        
        if bot_username and f"@{bot_username}" in message_text:
            message_text = message_text.replace(f"@{bot_username}", "").strip()
        
        if message_text:
            user_name = update.effective_user.first_name
            
            if reply_info and reply_info.get('replied_text'):
                formatted_message = format_reply_message(
                    message_text,
                    reply_info.get('replied_user_name', 'Unknown'),
                    reply_info.get('replied_text'),
                    reply_info.get('is_reply_to_bot', False),
                    user_name
                )
            else:
                formatted_message = message_text
            
            task_key = (update.effective_chat.id, update.effective_user.id)
            
            if task_key in user_group_tasks and not user_group_tasks[task_key].done():
                user_group_tasks[task_key].cancel()
                logger.info(f"Cancelled previous task for group {update.effective_chat.id}, user {update.effective_user.id} to start a new one.")

            task = asyncio.create_task(_process_group_request(update, context, formatted_message, reply_info))
            user_group_tasks[task_key] = task
            task.add_done_callback(lambda t: _cleanup_user_group_task(t, update.effective_chat.id, update.effective_user.id))
        else:
            await update.message.reply_text("بله؟ چگونه می‌توانم کمک کنم؟")

async def reply_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """هندلر مخصوص ریپلای‌ها"""
    if not update.message:
        return
    
    message_text = update.message.text or update.message.caption or ""
    if not message_text:
        return
    
    user_id = update.effective_user.id
    chat = update.effective_chat
    
    if data_manager.is_user_banned(user_id):
        return
    
    admin_ids = admin_panel.get_admin_ids()
    if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_ids:
        return

    if data_manager.contains_blocked_words(message_text):
        return

    if chat.type in ['group', 'supergroup']:
        task_key = (chat.id, user_id)
        
        if task_key in user_group_tasks and not user_group_tasks[task_key].done():
            user_group_tasks[task_key].cancel()
            logger.info(f"Cancelled previous task for group {chat.id}, user {user_id} to start a new one.")

        task = asyncio.create_task(_process_group_request(update, context))
        user_group_tasks[task_key] = task
        task.add_done_callback(lambda t: _cleanup_user_group_task(t, chat.id, user_id))
    else:
        if user_id in user_tasks and not user_tasks[user_id].done():
            user_tasks[user_id].cancel()
            logger.info(f"Cancelled previous task for user {user_id} to start a new one.")

        task = asyncio.create_task(_process_user_request(update, context))
        user_tasks[user_id] = task
        task.add_done_callback(lambda t: _cleanup_task(t, user_tasks, user_id))

def main() -> None:

    flask_thread = threading.Thread(target=run_flask, daemon=True)
    flask_thread.start()
    logger.info(f"Flask server started on port {os.environ.get('FLASK_PORT', 5000)}")
    
    token = os.environ.get("BOT_TOKEN")
    if not token:
        logger.error("BOT_TOKEN not set in environment variables!")
        return

    application = (
        Application.builder()
        .token(token)
        .concurrent_updates(True)
        .build()
    )

    # هندلرهای کاربران
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("clear", clear_chat))
    application.add_handler(CommandHandler("context", context_info))
    application.add_handler(CommandHandler("help", help_command))
    
    # هندلر برای ریپلای‌ها
    application.add_handler(MessageHandler(
        filters.TEXT & filters.REPLY, 
        reply_handler
    ))
    
    # هندلر برای منشن در گروه
    application.add_handler(MessageHandler(
        filters.TEXT & filters.Entity("mention") & filters.ChatType.GROUPS, 
        mention_handler
    ))
    
    # هندلر برای پیام‌های متنی معمولی
    application.add_handler(MessageHandler(
        filters.TEXT & ~filters.COMMAND & filters.ChatType.PRIVATE & ~filters.REPLY, 
        handle_message
    ))
    
    # هندلر برای پیام‌های متنی در گروه
    application.add_handler(MessageHandler(
        filters.TEXT & ~filters.COMMAND & filters.ChatType.GROUPS & 
        ~filters.Entity("mention") & ~filters.REPLY, 
        handle_message
    ))
    
    # راه‌اندازی و ثبت هندلرهای پنل ادمین
    admin_panel.setup_admin_handlers(application)
    
    # راه‌اندازی هندلرهای system instruction
    system_instruction_handlers.setup_system_instruction_handlers(application)

    # تنظیم هندلر خطا
    async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
        logger.error(f"Exception while handling an update: {context.error}")
        try:
            if update and update.message:
                await update.message.reply_text("❌ خطایی در پردازش درخواست شما رخ داد.")
        except:
            pass
    
    application.add_error_handler(error_handler)

    # --- بخش حیاتی: راه‌اندازی وب‌سرویس ---
    port = int(os.environ.get("PORT", 8443))
    webhook_url = os.environ.get("RENDER_EXTERNAL_URL")
    
    logger.info(f"Starting bot with port={port}, webhook_url={webhook_url}")
    
    if webhook_url:
        # استفاده از webhook در Render
        webhook_url = webhook_url.rstrip('/') + "/webhook"
        logger.info(f"Using webhook: {webhook_url}")
        
        # شروع وب‌سرویس با webhook
        application.run_webhook(
            listen="0.0.0.0",
            port=port,
            url_path="webhook",
            webhook_url=webhook_url,
            secret_token=os.environ.get("WEBHOOK_SECRET", None)
        )
    else:
        # استفاده از polling (برای توسعه محلی)
        logger.info("Using polling mode (local development)")
        application.run_polling()

if __name__ == "__main__":
    main()