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

import sys, pathlib, os, threading, time, re, html, datetime

if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
    except Exception:
        pass

PROJECT_ROOT = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(PROJECT_ROOT))

import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from app.pipeline import solve_problem, load_env_file
from app.vision import extract_problem_from_image
from app.geometry_drawer import try_draw_geometry
from app.db import (
    record_user_activity,
    log_query,
    get_statistics,
    set_user_admin,
    is_user_admin,
    get_all_user_ids,
    log_feedback,
    get_recent_feedbacks,
    add_chat_message,
    get_recent_chat_history,
    clear_chat_history,
    ban_user,
    unban_user,
    is_user_banned,
    get_banned_users,
)
from app.security import analyze_message_threat
from app.voice import transcribe_voice
from app.pdf_generator import generate_math_pdf
from chat import universal_local_solve

load_env_file()

raw_token = os.getenv("TELEGRAM_BOT_TOKEN") or os.getenv("BOT_TOKEN") or os.getenv("TOKEN") or ""
TOKEN = str(raw_token).strip().strip("\"'").strip()
ADMIN_IDS = [7759713314]
_env_admin = str(os.getenv("ADMIN_ID") or "").strip().strip("\"'").strip()
if _env_admin:
    try:
        ADMIN_IDS.append(int(_env_admin))
    except Exception:
        pass

# Xato xabari kutayotgan foydalanuvchilar (user_id -> tegishli kontekst)
awaiting_bug_report: dict[int, str] = {}
_bug_report_lock = threading.Lock()

# Foydalanuvchining oxirgi yechilgan masalasi (PDF konspekt generatsiyasi uchun)
_last_user_solutions: dict[int, dict] = {}
_last_user_solutions_lock = threading.Lock()

# Matematik belgilar klaviaturasi sessiyalari (user_id -> joriy ifoda)
_math_pad_sessions: dict[int, str] = {}
_math_pad_lock = threading.Lock()

_SUBSCRIPT_MAP = str.maketrans("0123456789nijk", "β‚€β‚β‚‚β‚ƒβ‚„β‚…β‚†β‚‡β‚ˆβ‚‰β‚™α΅’β±Όβ‚–")
_SUPERSCRIPT_MAP = str.maketrans("0123456789n", "⁰¹²³⁴⁡⁢⁷⁸⁹ⁿ")

def check_is_admin(user_id: int) -> bool:
    if user_id in ADMIN_IDS:
        return True
    return is_user_admin(user_id)

if not TOKEN or TOKEN == "your_telegram_bot_token_here":
    print("=" * 70)
    print("DIQQAT: TELEGRAM_BOT_TOKEN topilmadi!")
    print(".env faylida TELEGRAM_BOT_TOKEN=... parametrini sozlang.")
    print("=" * 70)

bot = telebot.TeleBot(TOKEN if TOKEN else "dummy_token")

def clean_math_display(text: str) -> str:
    """Raw LaTeX va texnik belgilarni Telegram uchun chiroyli, insonbop ko'rinishga keltiradi."""
    if not text:
        return ""
    s = str(text)
    s = re.sub(r"\$\$(.*?)\$\$", r"\1", s, flags=re.DOTALL)
    s = re.sub(r"\\\[(.*?)\\\]", r"\1", s, flags=re.DOTALL)
    s = re.sub(r"\\\((.*?)\\\)", r"\1", s, flags=re.DOTALL)
    s = re.sub(r"(?<!\d)\$([^\n$]+?)\$(?!\d)", r"\1", s)
    s = re.sub(r"\\(?:text|mathrm|mathbf|mathit)\{([^{}]*)\}", r"\1", s)
    s = s.replace("\\left", "").replace("\\right", "")

    replacements = [
        ("\\times", "Γ—"), ("\\cdot", "Β·"), ("\\div", "Γ·"), ("\\pm", "Β±"), ("\\mp", "βˆ“"),
        ("\\leq", "≀"), ("\\le", "≀"), ("\\geq", "β‰₯"), ("\\ge", "β‰₯"),
        ("\\neq", "β‰ "), ("\\ne", "β‰ "), ("\\approx", "β‰ˆ"), ("\\infty", "∞"),
        ("\\pi", "Ο€"), ("\\alpha", "Ξ±"), ("\\beta", "Ξ²"), ("\\gamma", "Ξ³"),
        ("\\theta", "ΞΈ"), ("\\Delta", "Ξ”"), ("\\degree", "Β°"), ("^\\circ", "Β°"),
        ("\\Rightarrow", "β‡’"), ("\\rightarrow", "β†’"), ("\\to", "β†’"),
    ]
    for old, new in replacements:
        s = s.replace(old, new)

    s = s.replace("^{2}", "Β²").replace("^{3}", "Β³")
    s = re.sub(r"([A-Za-z0-9\)])\*\*([0-9]+)\b", lambda m: m.group(1) + m.group(2).translate(_SUPERSCRIPT_MAP), s)
    s = re.sub(r"([A-Za-z0-9\)])\^([0-9]+)\b", lambda m: m.group(1) + m.group(2).translate(_SUPERSCRIPT_MAP), s)
    s = re.sub(r"\b([A-Za-zА-Яа-я])_\{?([0-9nijk]+)\}?(?=$|[^A-Za-z0-9_])",
               lambda m: m.group(1) + m.group(2).translate(_SUBSCRIPT_MAP), s)

    for _ in range(2):
        s = re.sub(r"\\frac\{([^{}]+)\}\{([^{}]+)\}", lambda m: (
            f"{m.group(1)}/{m.group(2)}"
            if re.fullmatch(r"[A-Za-z0-9Ο€βˆšΒ²Β³β°ΒΉβ΄β΅βΆβ·βΈβΉβ‚€β‚β‚‚β‚ƒβ‚„β‚…β‚†β‚‡β‚ˆβ‚‰]+", m.group(1).strip())
            and re.fullmatch(r"[A-Za-z0-9Ο€βˆšΒ²Β³β°ΒΉβ΄β΅βΆβ·βΈβΉβ‚€β‚β‚‚β‚ƒβ‚„β‚…β‚†β‚‡β‚ˆβ‚‰]+", m.group(2).strip())
            else f"({m.group(1)})/({m.group(2)})"
        ), s)
        s = re.sub(r"\\sqrt\{([^{}]+)\}", r"√(\1)", s)
    s = re.sub(r"\\sqrt\s+([A-Za-z0-9]+)", r"√\1", s)
    s = re.sub(r"\bsqrt\(", "√(", s)
    s = re.sub(r"(?<![A-Za-z])(-?)oo(?![A-Za-z])", lambda m: f"{m.group(1)}∞", s)
    s = re.sub(r"(?<!\*)(?<=[A-Za-z0-9\)π²³⁴⁡⁢⁷⁸⁹⁰])\*(?!\*)(?=[A-Za-z0-9\(βˆšΟ€])", "Β·", s)
    # **qalin** CommonMark yozuvini Telegram Markdown *qalin* ga aylantirish
    s = re.sub(r"(^|[\s(>\"'])(\*\*)(?=\S)([^\n*]*?\S)\2", r"\1*\3*", s)
    s = re.sub(r"\n{3,}", "\n\n", s)
    return s.strip()

def _strip_markdown(text: str) -> str:
    return text.replace("*", "").replace("`", "")

def _strip_html_tags(text: str) -> str:
    return html.unescape(re.sub(r"</?(?:b|i|code|pre|u|s)>", "", text))

def _render_html_prose(text: str) -> str:
    """Matn ichidagi math * / _ ni buzmasdan, faqat xavfsiz HTML formatiga o'giradi."""
    escaped = html.escape(text)
    # **qalin** yoki *qalin* faqat so'z/tinish belgisi chegarasida bo'lsa (a*b emas!)
    escaped = re.sub(r"(^|[\s(>\"'])\*([^\s*][^\n*]*?[^\s*]|[^\s*])\*(?=$|[\s).,;:!?\"'Β»])", r"\1<b>\2</b>", escaped)
    escaped = re.sub(r"`([^`\n]+)`", r"<code>\1</code>", escaped)
    return escaped

def safe_send_reply(target_msg, text: str, reply_markup=None, edit_msg=None, parse_mode: str = "Markdown"):
    """Telegram xabarini Markdown/HTML bilan yuboradi/tahrirlaydi; parse xatosida oddiy matnga o'tadi."""
    if len(text) > 4000:
        text = text[:3990] + "\n..."
    fallback_plain = _strip_html_tags(text) if parse_mode == "HTML" else _strip_markdown(text)
    if edit_msg:
        try:
            bot.edit_message_text(text, chat_id=target_msg.chat.id, message_id=edit_msg.message_id,
                                  parse_mode=parse_mode, reply_markup=reply_markup)
            return
        except Exception:
            try:
                bot.edit_message_text(fallback_plain, chat_id=target_msg.chat.id,
                                      message_id=edit_msg.message_id, reply_markup=reply_markup)
                return
            except Exception:
                pass
    try:
        bot.reply_to(target_msg, text, parse_mode=parse_mode, reply_markup=reply_markup)
    except Exception:
        bot.reply_to(target_msg, fallback_plain, reply_markup=reply_markup)

def _typing_loop(chat_id: int, stop_event: threading.Event):
    while not stop_event.is_set():
        try:
            bot.send_chat_action(chat_id, "typing")
        except Exception:
            pass
        stop_event.wait(4.0)

def send_bug_report_to_admins(from_user, comment: str, reply_context: str = ""):
    """Foydalanuvchi xato xabari/taklifini bazaga yozadi va barcha adminlarga yuboradi."""
    log_feedback(
        user_id=from_user.id,
        username=from_user.username or "",
        first_name=from_user.first_name or "",
        message=comment or "(Faqat xabarga reply qilindi)",
        reply_context=reply_context
    )

    sender_name = f"@{from_user.username}" if from_user.username else (from_user.first_name or f"ID:{from_user.id}")
    admin_alert_html = (
        "🚨 <b>YANGI XATOLIK / FIKR XABARI!</b> πŸ“©\n\n"
        f"πŸ‘€ <b>Yuboruvchi:</b> {html.escape(sender_name)} (<code>{from_user.id}</code>)\n"
        f"πŸ’¬ <b>Foydalanuvchi izohi:</b>\n<i>{html.escape(comment or 'Izoh yozilmagan')}</i>\n"
    )
    if reply_context:
        admin_alert_html += f"\nπŸ“Œ <b>Tegishli xabar matni:</b>\n<code>{html.escape(reply_context[:350])}</code>"

    admin_alert_plain = (
        "🚨 YANGI XATOLIK / FIKR XABARI! πŸ“©\n\n"
        f"πŸ‘€ Yuboruvchi: {sender_name} (ID: {from_user.id})\n"
        f"πŸ’¬ Foydalanuvchi izohi:\n{comment or 'Izoh yozilmagan'}\n"
    )
    if reply_context:
        admin_alert_plain += f"\nπŸ“Œ Tegishli xabar matni:\n{reply_context[:350]}"

    for admin_id in set(ADMIN_IDS):
        try:
            bot.send_message(admin_id, admin_alert_html, parse_mode="HTML")
            print(f"Admin {admin_id} ga bildirishnoma yuborildi.")
        except Exception as e_html:
            print(f"HTML yuborishda xatolik ({admin_id}): {e_html}. Oddiy matn sinab ko'rilmoqda...")
            try:
                bot.send_message(admin_id, admin_alert_plain)
            except Exception as e_plain:
                print(f"Admin {admin_id} ga yuborib bo'lmadi: {e_plain}")

def alert_admins_threat(from_user, threat_type: str, message_text: str):
    """Xavfli foydalanuvchi aniqlanganda barcha adminlarga tezkor ogohlantirish va Ban tugmasini yuboradi."""
    now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    sender_name = f"@{from_user.username}" if from_user.username else (from_user.first_name or f"ID:{from_user.id}")
    
    kb = InlineKeyboardMarkup()
    kb.add(InlineKeyboardButton("🚫 Bloklash (Ban)", callback_data=f"ban_user_{from_user.id}"))
    
    alert_html = (
        "🚨 <b>XAVFLI HARAKAT / TAHDID ANIQLANDI!</b> ⚠️\n\n"
        f"πŸ‘€ <b>Foydalanuvchi:</b> {html.escape(sender_name)} (<code>{from_user.id}</code>)\n"
        f"πŸ“› <b>Ismi:</b> {html.escape(from_user.first_name or '')}\n"
        f"⚠️ <b>Tahdid turi:</b> <b>{html.escape(threat_type)}</b>\n"
        f"πŸ“ <b>Xabar matni:</b>\n<code>{html.escape(message_text[:400])}</code>\n"
        f"⏱ <b>Vaqt:</b> {now_str}\n\n"
        "<i>Quyidagi tugma orqali ushbu foydalanuvchini botdan zudlik bilan bloklashingiz mumkin:</i>"
    )

    alert_plain = (
        "🚨 XAVFLI HARAKAT / TAHDID ANIQLANDI! ⚠️\n\n"
        f"πŸ‘€ Foydalanuvchi: {sender_name} (ID: {from_user.id})\n"
        f"πŸ“› Ismi: {from_user.first_name or ''}\n"
        f"⚠️ Tahdid turi: {threat_type}\n"
        f"πŸ“ Xabar matni:\n{message_text[:400]}\n"
        f"⏱ Vaqt: {now_str}\n\n"
        f"Bloklash uchun buyruq: /ban {from_user.id}"
    )

    for admin_id in set(ADMIN_IDS):
        try:
            bot.send_message(admin_id, alert_html, parse_mode="HTML", reply_markup=kb)
            print(f"Admin {admin_id} ga xavfsizlik signali yuborildi.")
        except Exception:
            try:
                bot.send_message(admin_id, alert_plain, reply_markup=kb)
            except Exception as e:
                print(f"Admin {admin_id} ga xavfsizlik signalini yuborib bo'lmadi: {e}")

def setup_bot_commands():
    """Telegram ilovasida '/' tugmasi bosilganda chiquvchi buyruqlar menyusini minimalistik va qulay qilib sozlaydi."""
    try:
        user_commands = [
            telebot.types.BotCommand("start", "Botni ishga tushirish"),
            telebot.types.BotCommand("yangi", "Yangi suhbat (xotirani tozalash)"),
            telebot.types.BotCommand("klaviatura", "Matematik klaviatura & belgilar"),
            telebot.types.BotCommand("help", "Qo'llanma va yordam")
        ]
        bot.set_my_commands(user_commands)

        admin_commands = user_commands + [
            telebot.types.BotCommand("admin", "Admin boshqaruv paneli va statistika"),
            telebot.types.BotCommand("broadcast", "Foydalanuvchilarga ommaviy xabar"),
            telebot.types.BotCommand("banlar", "Bloklanganlar ro'yxati"),
            telebot.types.BotCommand("xatolar", "Kelgan taklif/fikr xabarlari")
        ]
        for aid in set(ADMIN_IDS):
            try:
                bot.set_my_commands(admin_commands, scope=telebot.types.BotCommandScopeChat(aid))
            except Exception:
                pass
        print("Telegram bot buyruqlari (/ menyusi) muvaffaqiyatli sozlandi.")
    except Exception as e:
        print(f"Buyruqlar menyusini sozlashda ogohlantirish: {e}")

@bot.message_handler(commands=['yangi', 'new', 'clear', 'reset'])
def new_chat_command(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    clear_chat_history(message.from_user.id)
    with _bug_report_lock:
        awaiting_bug_report.pop(message.from_user.id, None)
    with _math_pad_lock:
        _math_pad_sessions.pop(message.from_user.id, None)
    bot.reply_to(message, "πŸ”„ <b>Suhbat xotirasi tozalandi.</b> Yangi mavzu yoki misolingizni bemalol yozib yuboravering!", parse_mode="HTML")

@bot.message_handler(commands=['konspekt', 'pdf'])
def handle_pdf_command(message):
    user_id = message.from_user.id
    record_user_activity(user_id, message.from_user.username, message.from_user.first_name)
    with _last_user_solutions_lock:
        last_info = _last_user_solutions.get(user_id)
    if not last_info:
        bot.reply_to(
            message,
            "ℹ️ <b>Hozircha siz yechgan oxirgi masala topilmadi.</b>\n"
            "Avval biror masala yuboring (masalan: <code>x^2 - 5x + 6 = 0</code>), so'ngra <b>/konspekt</b> buyrug'ini bering!",
            parse_mode="HTML"
        )
        return

    wait_msg = bot.reply_to(message, "πŸ“„ <i>A4 PDF konspekt tayyorlanmoqda...</i>", parse_mode="HTML")
    def _worker():
        try:
            q = last_info["question"]
            sol = last_info["solution"]
            diag = last_info.get("diagram_path")
            if not diag or not os.path.exists(diag):
                diag = try_draw_geometry(q)
            pdf_path = generate_math_pdf(q, sol, diag)
            if pdf_path and os.path.exists(pdf_path):
                with open(pdf_path, "rb") as pdf_file:
                    bot.send_document(
                        message.chat.id,
                        pdf_file,
                        caption="πŸ“„ <b>Sincc.on: Ushbu masalaning A4 PDF Konspekti</b>\n"
                                "<i>Chop etish va darsda/imtihonda foydalanish uchun to'liq yechim va chizma.</i>",
                        parse_mode="HTML"
                    )
                try:
                    os.unlink(pdf_path)
                except Exception:
                    pass
                try:
                    bot.delete_message(message.chat.id, wait_msg.message_id)
                except Exception:
                    pass
            else:
                bot.edit_message_text("❌ PDF faylni yaratib bo'lmadi.", chat_id=message.chat.id, message_id=wait_msg.message_id)
        except Exception as e_pdf:
            print(f"[PDF Command xatosi]: {e_pdf}")
            try:
                bot.edit_message_text(f"❌ PDF yaratishda xatolik: {e_pdf}", chat_id=message.chat.id, message_id=wait_msg.message_id)
            except Exception:
                pass
    threading.Thread(target=_worker, daemon=True).start()

@bot.message_handler(commands=['id', 'myid'])
def show_my_id(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    bot.reply_to(message, f"πŸ†” Sizning Telegram ID raqamingiz: <code>{message.from_user.id}</code>", parse_mode="HTML")

@bot.message_handler(commands=['admin', 'stat', 'stats'])
def admin_panel(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    
    if not check_is_admin(message.from_user.id):
        bot.reply_to(message, "β›” Bu bo'lim faqat bot administratori uchun mo'ljallangan.")
        return

    try:
        stats = get_statistics()
        recent_text = ""
        for i, u in enumerate(stats["recent_users"], 1):
            uname = f"@{u[1]}" if u[1] else (u[2] or f"ID:{u[0]}")
            recent_text += f"{i}. {uname} β€” {u[3]} ta savol ({u[4][11:16]})\n"
        
        if not recent_text:
            recent_text = "Hozircha boshqa faol foydalanuvchilar yo'q.\n"

        kb = InlineKeyboardMarkup(row_width=2)
        kb.add(
            InlineKeyboardButton("πŸ”„ Yangilash", callback_data="admin_refresh"),
            InlineKeyboardButton("🚫 Bloklanganlar", callback_data="admin_banlar"),
        )
        kb.add(
            InlineKeyboardButton("πŸ“¬ Fikrlar/Xatolar", callback_data="admin_xatolar"),
            InlineKeyboardButton("πŸ“’ Xabar Yuborish", callback_data="admin_broadcast_help"),
        )

        report = (
            "πŸ“Š <b>Sincc.on Admin Statistikasi:</b>\n\n"
            f"πŸ‘₯ <b>Jami foydalanuvchilar:</b> {stats['total_users']} ta\n"
            f"πŸ“… <b>Bugungi faol:</b> {stats['active_today']} ta\n"
            f"⚑ <b>Jami yechilgan masalalar:</b> {stats['total_queries']} ta\n"
            f"   β€’ πŸ“ Matnli: {stats['text_queries']} ta\n"
            f"   β€’ πŸ“Έ Rasmli: {stats['photo_queries']} ta\n"
            f"   β€’ πŸŽ™ Ovozli: {stats.get('voice_queries', 0)} ta\n"
            f"πŸ“© <b>Xatolik/fikr xabarlari:</b> {stats.get('total_feedbacks', 0)} ta (/xatolar)\n"
            f"🚫 <b>Bloklanganlar:</b> {stats.get('total_banned', 0)} ta (/banlar)\n\n"
            f"πŸ“‹ <b>So'nggi foydalanuvchilar:</b>\n<code>{html.escape(recent_text)}</code>\n"
            "πŸ“’ <b>Admin buyruqlari:</b>\n"
            "β€’ <code>/broadcast &lt;matn&gt;</code> β€” Barcha foydalanuvchilarga xabar\n"
            "β€’ <code>/ban &lt;id&gt; [sabab]</code> β€” Foydalanuvchini bloklash\n"
            "β€’ <code>/unban &lt;id&gt;</code> β€” Blokdan chiqarish\n"
            "β€’ <code>/banlar</code> β€” Bloklanganlar ro'yxati\n"
            "β€’ <code>/xatolar</code> β€” Fikr/takliflar ro'yxati"
        )
        bot.reply_to(message, report, parse_mode="HTML", reply_markup=kb)
    except Exception as e:
        bot.reply_to(message, f"❌ Statistikani yuklashda xatolik: {e}")

@bot.message_handler(commands=['ban'])
def handle_ban_command(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    if not check_is_admin(message.from_user.id):
        bot.reply_to(message, "β›” Bu buyruq faqat admin uchun!")
        return
    parts = message.text.split(maxsplit=2)
    if len(parts) < 2:
        bot.reply_to(message, "Foydalanish: `/ban <user_id> [sabab]`\nMasalan: `/ban 123456789 spam`", parse_mode="Markdown")
        return
    try:
        target_uid = int(parts[1].strip())
    except ValueError:
        bot.reply_to(message, "❌ User ID butun son bo'lishi kerak!")
        return
    reason = parts[2].strip() if len(parts) > 2 else "Admin tomonidan buyruq orqali bloklandi"
    ban_user(target_uid, reason=reason, banned_by=message.from_user.id)
    bot.reply_to(message, f"βœ… Foydalanuvchi `{target_uid}` muvaffaqiyatli bloklandi.\nSabab: {reason}", parse_mode="Markdown")
    try:
        bot.send_message(target_uid, f"β›” Siz qoidabuzarlik sababli botdan chetlatildingiz.\nSabab: {reason}")
    except Exception:
        pass

@bot.message_handler(commands=['unban'])
def handle_unban_command(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    if not check_is_admin(message.from_user.id):
        bot.reply_to(message, "β›” Bu buyruq faqat admin uchun!")
        return
    parts = message.text.split(maxsplit=1)
    if len(parts) < 2:
        bot.reply_to(message, "Foydalanish: `/unban <user_id>`\nMasalan: `/unban 123456789`", parse_mode="Markdown")
        return
    try:
        target_uid = int(parts[1].strip())
    except ValueError:
        bot.reply_to(message, "❌ User ID butun son bo'lishi kerak!")
        return
    if unban_user(target_uid):
        bot.reply_to(message, f"βœ… Foydalanuvchi `{target_uid}` blokdan chiqarildi.", parse_mode="Markdown")
        try:
            bot.send_message(target_uid, "βœ… Botingizdan foydalanish huquqi qayta tiklandi. Xush kelibsiz!")
        except Exception:
            pass
    else:
        bot.reply_to(message, f"ℹ️ Foydalanuvchi `{target_uid}` bloklanganlar ro'yxatida topilmadi.", parse_mode="Markdown")

@bot.message_handler(commands=['banlar', 'banned'])
def handle_banned_list(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    if not check_is_admin(message.from_user.id):
        bot.reply_to(message, "β›” Bu buyruq faqat admin uchun!")
        return
    banned = get_banned_users(limit=15)
    if not banned:
        bot.reply_to(message, "βœ… Hozircha bloklangan foydalanuvchilar yo'q.")
        return
    text = "🚫 <b>Bloklangan foydalanuvchilar:</b>\n\n"
    for idx, b in enumerate(banned, 1):
        uname = f"@{b['username']}" if b['username'] else (b['first_name'] or f"ID:{b['user_id']}")
        text += f"{idx}. <b>{html.escape(uname)}</b> (<code>{b['user_id']}</code>)\n"
        text += f"   β€’ Sabab: <i>{html.escape(b['reason'])}</i>\n"
        text += f"   β€’ Vaqt: {b['banned_at'][:16]}\n"
    text += "\n<i>Blokdan chiqarish: /unban &lt;user_id&gt;</i>"
    bot.reply_to(message, text, parse_mode="HTML")

@bot.message_handler(commands=['xatolar', 'feedbacks'])
def show_feedbacks(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    if not check_is_admin(message.from_user.id):
        bot.reply_to(message, "β›” Bu bo'lim faqat bot administratori uchun mo'ljallangan.")
        return
    
    items = get_recent_feedbacks(limit=5)
    if not items:
        bot.reply_to(message, "πŸ“­ Hozircha hech qanday xatolik yoki fikr xabari kelib tushmagan.")
        return

    text = "πŸ“¬ <b>So'nggi 5 ta xatolik / fikr xabarlari:</b>\n\n"
    for item in items:
        fid, uid, uname, fname, fmsg, rcontext, ftime = item
        u_str = f"@{html.escape(uname)}" if uname else html.escape(fname or f"ID:{uid}")
        text += f"πŸ”Ή <b>#{fid}</b> | {u_str} | <i>{ftime[5:16]}</i>\n"
        text += f"πŸ’¬ <b>Fikr:</b> {html.escape(fmsg)}\n"
        if rcontext:
            text += f"πŸ“Œ <b>Kontekst:</b> <code>{html.escape(rcontext[:100])}...</code>\n"
        text += "------------------------\n"
    
    try:
        bot.reply_to(message, text, parse_mode="HTML")
    except Exception:
        plain_text = text.replace("<b>", "").replace("</b>", "").replace("<i>", "").replace("</i>", "").replace("<code>", "").replace("</code>", "")
        bot.reply_to(message, plain_text)

@bot.message_handler(commands=['xato', 'fikr', 'taklif', 'feedback'])
def report_feedback(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    parts = message.text.split(maxsplit=1)
    comment = parts[1].strip() if len(parts) > 1 else ""

    reply_context = ""
    if message.reply_to_message and message.reply_to_message.text:
        reply_context = message.reply_to_message.text[:400]

    if not comment and not reply_context:
        with _bug_report_lock:
            awaiting_bug_report[message.from_user.id] = ""
        instruction = (
            "πŸ“ *Qanday xatolik ko'rdingiz yoki taklifingiz bormi?*\n\n"
            "Shu xabardan keyingi xabaringizda yozib yuboring β€” men uni to'g'ridan-to'g'ri loyiha muallifiga yetkazaman.\n"
            "_(Bekor qilish uchun /yangi bosing)_"
        )
        bot.reply_to(message, instruction, parse_mode="Markdown")
        return

    send_bug_report_to_admins(message.from_user, comment, reply_context)
    bot.reply_to(
        message,
        "βœ… *Katta rahmat!* Xabaringiz loyiha muallifiga yetkazildi. 🀝",
        parse_mode="Markdown"
    )

@bot.message_handler(commands=['broadcast'])
def broadcast_message(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    if not check_is_admin(message.from_user.id):
        bot.reply_to(message, "β›” Bu buyruq faqat bot administratori uchun!")
        return
    text = message.text.replace("/broadcast", "", 1).strip()
    if not text:
        bot.reply_to(
            message,
            "πŸ“’ <b>Xabar yuborish tartibi:</b>\n"
            "<code>/broadcast Hurmatli foydalanuvchilar, botda yangi funksiyalar qo'shildi!</code>",
            parse_mode="HTML"
        )
        return
    
    user_ids = get_all_user_ids()
    if not user_ids:
        bot.reply_to(message, "Bazada foydalanuvchilar topilmadi.")
        return

    wait_msg = bot.reply_to(message, f"πŸ“’ Xabar {len(user_ids)} ta foydalanuvchiga yuborilmoqda...")
    success_count = 0
    for uid in user_ids:
        try:
            bot.send_message(uid, f"πŸ“’ <b>Sincc.on E'loni:</b>\n\n{html.escape(text)}", parse_mode="HTML")
            success_count += 1
        except Exception:
            try:
                bot.send_message(uid, f"πŸ“’ Sincc.on E'loni:\n\n{text}")
                success_count += 1
            except Exception:
                pass
    try:
        bot.edit_message_text(f"βœ… Xabar <b>{success_count}/{len(user_ids)}</b> ta foydalanuvchiga yetkazildi.",
                              chat_id=message.chat.id, message_id=wait_msg.message_id, parse_mode="HTML")
    except Exception:
        bot.reply_to(message, f"βœ… Xabar {success_count}/{len(user_ids)} ta foydalanuvchiga yetkazildi.")

@bot.message_handler(commands=['start'])
def send_welcome(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    with _bug_report_lock:
        awaiting_bug_report.pop(message.from_user.id, None)
    
    kb = InlineKeyboardMarkup(row_width=2)
    kb.add(
        InlineKeyboardButton("πŸ”’ Matematik Klaviatura", callback_data="open_math_pad"),
        InlineKeyboardButton("πŸ“– Bot Qo'llanmasi", callback_data="open_help_info"),
    )
    kb.add(
        InlineKeyboardButton("πŸ“₯ A4 PDF Konspekt", callback_data="get_pdf_solution"),
        InlineKeyboardButton("πŸ”„ Yangi Suhbat", callback_data="start_new_chat"),
    )

    fname = message.from_user.first_name or "do'stim"
    text = (
        f"Assalomu alaykum, <b>{html.escape(fname)}</b>! Men <b>Sincc.on</b> β€” matematika bo'yicha milliy AI ustozingizman. πŸ‘‹πŸ“\n\n"
        "Menga xohlagan matematik masalangizni yuborishingiz mumkin:\n"
        "β€’ πŸ“ <b>Matn ko'rinishida:</b> <code>x^2 - 5x + 6 = 0</code>\n"
        "β€’ πŸ“Έ <b>Rasm ko'rinishida:</b> Kitob yoki daftardagi misolni rasmga olib yuboring\n"
        "β€’ πŸŽ™ <b>Ovozli xabar:</b> Masala shartini audio tarzida ayting\n"
        "β€’ πŸ”’ <b>Klaviatura:</b> /klaviatura orqali qulay matematik belgilarni tering\n\n"
        "Tizim hisoblashlarni <b>100% xatosiz (SymPy ramziy yadrosi)</b> tekshiradi va qadam-baqadam yechim, qoidalar va geometrik chizmalar bilan tushuntiradi!\n\n"
        "<i>Boshlash uchun quyidagi tugmalardan birini bosing yoki to'g'ridan-to'g'ri misolingizni yozib yuboring:</i> πŸ‘‡"
    )
    safe_send_reply(message, text, reply_markup=kb, parse_mode="HTML")

@bot.message_handler(commands=['help', 'yordam', 'info', 'about'])
def send_help(message):
    record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    kb = InlineKeyboardMarkup(row_width=2)
    kb.add(
        InlineKeyboardButton("πŸ”’ Matematik Klaviatura", callback_data="open_math_pad"),
        InlineKeyboardButton("πŸ”„ Yangi Suhbat", callback_data="start_new_chat"),
    )
    kb.add(
        InlineKeyboardButton("πŸ“₯ PDF Konspekt", callback_data="get_pdf_solution"),
        InlineKeyboardButton("🚨 Fikr / Xatolik", callback_data="report_bug"),
    )
    
    help_text = (
        "πŸ“š <b>Sincc.on Botidan Foydalanish Qo'llanmasi:</b>\n\n"
        "<b>1. Masala yuborish usullari:</b>\n"
        "β€’ <b>Matn:</b> Algebra, geometriya, matnli masalalar (masalan: <i>Β«Hovuzni 1-quvur 3 soatda, 2-quvur 6 soatda to'ldiradi...Β»</i>)\n"
        "β€’ <b>Rasm (Vision OCR):</b> Yaxshi yorug'likda daftardagi qo'lyozma yoki darslik rasmini yuboring\n"
        "β€’ <b>Ovoz (Whisper):</b> Telegram audio yoki mikrofon orqali gapiring\n\n"
        "<b>2. Mavjud Buyruqlar:</b>\n"
        "β€’ /start β€” Botni ishga tushirish va asosiy menyu\n"
        "β€’ /klaviatura (yoki /belgilar) β€” Matematik belgilar inline paneli\n"
        "β€’ /konspekt (yoki /pdf) β€” Oxirgi yechimning chiroyli A4 PDF konspekti\n"
        "β€’ /yangi β€” Suhbat xotirasini tozalash (yangi mavzu boshlash)\n"
        "β€’ /help β€” Ushbu qo'llanma va yordam\n"
        "β€’ /xato (yoki /taklif) β€” Muallifga bevosita fikr/taklif bildirish\n"
        "β€’ /id β€” Telegram ID raqamingizni bilish\n\n"
        "<b>3. Savol-javob va chuqur tahlil:</b>\n"
        "Har bir yechimdan so'ng tushunmagan joyingizni bemalol qayta so'rashingiz mumkin:\n"
        "β€’ <i>Β«2-qadamni tushunmadim, soddaroq tushuntirΒ»</i>\n"
        "β€’ <i>Β«Boshqa usul bilan yechib ko'rsatΒ»</i>\n"
        "β€’ <i>Β«Shunga o'xshash yangi mashq ber, o'zim yechamanΒ»</i>"
    )
    safe_send_reply(message, help_text, reply_markup=kb, parse_mode="HTML")

def build_math_pad_keyboard() -> InlineKeyboardMarkup:
    """Matematik formulalar va belgilarni terish uchun qulay inline klaviatura paneli."""
    kb = InlineKeyboardMarkup(row_width=5)
    kb.row(
        InlineKeyboardButton("x", callback_data="pad_add_x"),
        InlineKeyboardButton("y", callback_data="pad_add_y"),
        InlineKeyboardButton("+", callback_data="pad_add_+"),
        InlineKeyboardButton("-", callback_data="pad_add_-"),
        InlineKeyboardButton("=", callback_data="pad_add_="),
    )
    kb.row(
        InlineKeyboardButton("xΒ²", callback_data="pad_add_Β²"),
        InlineKeyboardButton("xΒ³", callback_data="pad_add_Β³"),
        InlineKeyboardButton("√", callback_data="pad_add_√("),
        InlineKeyboardButton("Β·", callback_data="pad_add_*"),
        InlineKeyboardButton("/", callback_data="pad_add_/"),
    )
    kb.row(
        InlineKeyboardButton("(", callback_data="pad_add_("),
        InlineKeyboardButton(")", callback_data="pad_add_)"),
        InlineKeyboardButton("^", callback_data="pad_add_^"),
        InlineKeyboardButton("Ο€", callback_data="pad_add_Ο€"),
        InlineKeyboardButton("Β±", callback_data="pad_add_Β±"),
    )
    kb.row(
        InlineKeyboardButton("≀", callback_data="pad_add_≀"),
        InlineKeyboardButton("β‰₯", callback_data="pad_add_β‰₯"),
        InlineKeyboardButton("β‰ ", callback_data="pad_add_β‰ "),
        InlineKeyboardButton("sin", callback_data="pad_add_sin("),
        InlineKeyboardButton("cos", callback_data="pad_add_cos("),
    )
    kb.row(
        InlineKeyboardButton("⌫ O'chirish", callback_data="pad_backspace"),
        InlineKeyboardButton("πŸ—‘ Tozalash", callback_data="pad_clear"),
    )
    kb.row(
        InlineKeyboardButton("πŸš€ Masalani Yechish", callback_data="pad_solve"),
        InlineKeyboardButton("❌ Yopish", callback_data="pad_close"),
    )
    return kb

def get_math_pad_text(formula: str) -> str:
    display_f = formula if formula else "_(hali belgilar terilmadi)_"
    return (
        "πŸ”’ <b>Matematik Belgilar & Formula Paneli:</b>\n\n"
        f"πŸ“ <b>Joriy ifoda:</b> <code>{html.escape(display_f)}</code>\n\n"
        "<i>Quyidagi tugmalar orqali formulangizni shakllantiring va <b>Β«πŸš€ Masalani YechishΒ»</b> tugmasini bosing:</i>"
    )

def build_solution_keyboard() -> InlineKeyboardMarkup:
    kb = InlineKeyboardMarkup(row_width=2)
    kb.add(
        InlineKeyboardButton("❓ Tushunmadim", callback_data="explain_simpler"),
        InlineKeyboardButton("πŸ’‘ Boshqa usul", callback_data="alt_method"),
    )
    kb.add(
        InlineKeyboardButton("πŸ”„ O'xshash misol", callback_data="similar_problem"),
        InlineKeyboardButton("πŸ“₯ PDF Konspekt", callback_data="get_pdf_solution"),
    )
    kb.add(
        InlineKeyboardButton("πŸ”’ Matematik Belgilar", callback_data="open_math_pad"),
        InlineKeyboardButton("🚨 Xato / Taklif", callback_data="report_bug"),
    )
    return kb

def format_bot_response(javob: dict) -> tuple[str, InlineKeyboardMarkup | None, str]:
    """AI javobini turiga qarab (suhbat, nazariya yoki yechim) xavfsiz HTML Telegram matniga aylantiradi."""
    ans_type = javob.get("type", "solve")

    if ans_type == "chat":
        reply_raw = clean_math_display(javob.get("reply") or "\n".join(javob.get("steps", [])) or javob.get("final_answer", ""))
        if not reply_raw:
            reply_raw = "Salom! Matematika bo'yicha qanday savol yoki misolingiz bor?"
        return _render_html_prose(reply_raw), None, _strip_markdown(reply_raw)

    if ans_type in ("theory", "incomplete"):
        raw_reply = javob.get("reply")
        if raw_reply:
            text_raw = clean_math_display(raw_reply)
        else:
            chunks = [clean_math_display(s) for s in javob.get("steps", []) if s and str(s).strip()]
            fa = clean_math_display(str(javob.get("final_answer", "")).strip())
            tip = clean_math_display(javob.get("explanation_tip", ""))
            if fa and fa.lower() not in "\n".join(chunks).lower():
                chunks.append(f"πŸ“Œ {fa}")
            if tip:
                chunks.append(f"πŸ’‘ {tip}")
            text_raw = "\n\n".join(chunks) or "Savolingizni biroz aniqroq yozib bera olasizmi?"
        return _render_html_prose(text_raw), None, _strip_markdown(text_raw)

    # ans_type == "solve"
    if not javob.get("steps") and not str(javob.get("final_answer", "")).strip():
        err_text = clean_math_display(javob.get("note") or "") or (
            "Uzr, hozir serverda biroz uzilish bo'lib qoldi shekilli, javob ololmadim. "
            "Bir necha soniyadan keyin qayta yuborib ko'rasizmi? πŸ™"
        )
        return _render_html_prose(err_text), None, ""

    intro_raw = clean_math_display(javob.get("intro", ""))
    formatted_steps_html = []
    plain_steps = []
    for idx, s in enumerate(javob.get("steps", []), 1):
        s_clean = clean_math_display(str(s).strip())
        if not s_clean:
            continue
        m = re.match(r"^(?:πŸ”Ή\s*)?([0-9]+-(?:qadam|bosqich)|[0-9]+\.)[:\s]*(.*)", s_clean, re.IGNORECASE | re.DOTALL)
        if m:
            hdr = m.group(1).rstrip(":.")
            if hdr.isdigit():
                hdr = f"{hdr}-qadam"
            body = m.group(2).strip()
            if body:
                formatted_steps_html.append(f"πŸ”Ή <b>{html.escape(hdr)}:</b> {_render_html_prose(body)}")
                plain_steps.append(f"πŸ”Ή {hdr}: {_strip_markdown(body)}")
            else:
                formatted_steps_html.append(f"πŸ”Ή <b>{html.escape(hdr)}</b>")
                plain_steps.append(f"πŸ”Ή {hdr}")
        else:
            body = s_clean.lstrip("β€’- ")
            formatted_steps_html.append(f"πŸ”Ή <b>{idx}-qadam:</b> {_render_html_prose(body)}")
            plain_steps.append(f"πŸ”Ή {idx}-qadam: {_strip_markdown(body)}")

    formulas = [clean_math_display(str(f).strip()) for f in javob.get("formulas_used", []) if f and str(f).strip()]
    formulas_html = ""
    formulas_plain = ""
    if formulas:
        formulas_html = "πŸ“ <b>Ishlatilgan qoidalar:</b>\n" + "\n".join(f"β€’ {html.escape(_strip_markdown(f))}" for f in formulas)
        formulas_plain = "πŸ“ Ishlatilgan qoidalar:\n" + "\n".join(f"β€’ {_strip_markdown(f)}" for f in formulas)

    raw_ans = str(javob.get("final_answer", "")).strip()
    final_ans = clean_math_display(raw_ans)
    final_ans_plain = _strip_markdown(final_ans)
    ans_html = f"βœ… <b>Javob:</b>  <b>{html.escape(final_ans_plain)}</b>" if final_ans_plain else ""
    ans_plain = f"βœ… Javob:  {final_ans_plain}" if final_ans_plain else ""

    exp_tip = clean_math_display(javob.get("explanation_tip", ""))
    exp_tip_plain = _strip_markdown(exp_tip)
    tip_html = f"πŸ’‘ <i>{html.escape(exp_tip_plain)}</i>" if exp_tip_plain else ""
    tip_plain = f"πŸ’‘ {exp_tip_plain}" if exp_tip_plain else ""

    html_parts = []
    plain_parts = []
    if intro_raw:
        html_parts.append(_render_html_prose(intro_raw))
        plain_parts.append(_strip_markdown(intro_raw))
    if formatted_steps_html:
        html_parts.append("\n\n".join(formatted_steps_html))
        plain_parts.append("\n\n".join(plain_steps))
    if formulas_html:
        html_parts.append(formulas_html)
        plain_parts.append(formulas_plain)
    if ans_html:
        html_parts.append(ans_html)
        plain_parts.append(ans_plain)
    if tip_html:
        html_parts.append(tip_html)
        plain_parts.append(tip_plain)
    if javob.get("verified"):
        html_parts.append("βœ“ <i>SymPy da tekshirildi</i>")
        plain_parts.append("βœ“ SymPy da tekshirildi")

    return "\n\n".join(html_parts), build_solution_keyboard(), "\n\n".join(plain_parts)

def process_and_reply(message, existing_wait_msg=None, is_photo=False, is_voice=False, override_prompt=None,
                      bypass_cache=False, history_user_msg=None, actor_user=None):
    user_obj = actor_user or message.from_user
    user_id = user_obj.id
    try:
        record_user_activity(user_id, user_obj.username, user_obj.first_name)
    except Exception:
        pass

    savol = (override_prompt if override_prompt is not None else (message.text or "")).strip()
    if not savol:
        return

    wait_msg = existing_wait_msg
    if not wait_msg and (len(savol) > 15 or any(k in savol.lower() for k in ["=", ">", "<", "uchburchak", "tenglama", "ildiz", "hisoblang", "yeching"])):
        try:
            wait_msg = bot.reply_to(message, "⏳ <i>Masala tahlil qilinmoqda va hisob-kitob tekshirilmoqda...</i>", parse_mode="HTML")
        except Exception:
            pass

    stop_typing = threading.Event()
    typing_thread = threading.Thread(target=_typing_loop, args=(message.chat.id, stop_typing), daemon=True)
    typing_thread.start()

    try:
        # 1. Suhbat tarixini olamiz va aqlli Router/Dual-Agent pipeline ga yuboramiz
        chat_history = get_recent_chat_history(user_id, limit=8)
        javob = solve_problem(savol, chat_history=chat_history, bypass_cache=bypass_cache)

        # 2. Faqat haqiqiy hisob-kitob masalasi API dan to'liq tasdiq olmasa, lokal dvigatelni sinab ko'ramiz
        if javob.get("type", "solve") == "solve" and not javob.get("verified"):
            lokal = universal_local_solve(savol)
            if lokal and lokal.get("verified"):
                javob = lokal

        # 3. Statistikaga yozamiz
        try:
            q_type = "voice" if is_voice else ("photo" if is_photo else "text")
            log_query(
                user_id,
                query_type=q_type,
                question=savol,
                verified=bool(javob.get("verified"))
            )
        except Exception:
            pass

        # 4. Tabiiy va tushunarli javob tuzamiz (HTML rejimida * va _ xavfsiz!)
        reply, reply_markup, history_assistant_text = format_bot_response(javob)
        stop_typing.set()

        safe_send_reply(message, reply, reply_markup=reply_markup, edit_msg=wait_msg, parse_mode="HTML")

        # 5. Suhbat xotirasiga saqlaymiz (follow-up savollar uchun)
        user_hist = (history_user_msg if history_user_msg is not None else savol).strip()
        if user_hist and history_assistant_text:
            add_chat_message(user_id, "user", user_hist[:800])
            add_chat_message(user_id, "assistant", history_assistant_text[:1500])

        # 6. Faqat haqiqiy geometriya masalasida chizma chizib jo'natamiz
        saved_diag = None
        if javob.get("type", "solve") == "solve" and (javob.get("steps") or javob.get("final_answer")):
            diag_path = try_draw_geometry(savol)
            if diag_path and os.path.exists(diag_path):
                with open(diag_path, "rb") as photo_f:
                    bot.send_photo(message.chat.id, photo_f, caption="πŸ“ *Geometrik chizma:*", parse_mode="Markdown")
                saved_diag = diag_path

        # 7. PDF konspekt generatsiyasi uchun so'nggi yechimni xotirada saqlaymiz
        if javob.get("type", "solve") == "solve":
            with _last_user_solutions_lock:
                _last_user_solutions[user_id] = {
                    "question": savol,
                    "solution": javob,
                    "diagram_path": saved_diag
                }

    except Exception as e:
        stop_typing.set()
        err_msg = f"❌ Javob tayyorlashda kutilmagan xatolik yuz berdi: {e}"
        if wait_msg:
            try:
                bot.edit_message_text(err_msg, chat_id=message.chat.id, message_id=wait_msg.message_id)
            except Exception:
                pass
        else:
            bot.reply_to(message, err_msg)
    finally:
        stop_typing.set()
        if typing_thread and typing_thread.is_alive():
            typing_thread.join(timeout=0.5)

@bot.callback_query_handler(func=lambda call: True)
def handle_inline_callbacks(call):
    user_id = call.from_user.id
    data = call.data or ""
    msg = call.message
    orig_q = ""
    if msg and msg.reply_to_message and msg.reply_to_message.text:
        orig_q = msg.reply_to_message.text.strip()

    if data.startswith("ban_user_"):
        if not check_is_admin(user_id):
            bot.answer_callback_query(call.id, "β›” Faqat bot administratori bloklay oladi!", show_alert=True)
            return
        target_str = data.replace("ban_user_", "")
        try:
            target_uid = int(target_str)
            ban_user(target_uid, reason="Admin tomonidan xavfsizlik ogohlantirishidagi tugma orqali bloklandi", banned_by=user_id)
            bot.answer_callback_query(call.id, f"βœ… Foydalanuvchi ({target_uid}) bloklandi!", show_alert=True)
            if msg:
                bot.edit_message_reply_markup(
                    chat_id=msg.chat.id,
                    message_id=msg.message_id,
                    reply_markup=InlineKeyboardMarkup().add(
                        InlineKeyboardButton("βœ… Bloklangan (Banned)", callback_data="none")
                    )
                )
            try:
                bot.send_message(target_uid, "β›” Siz xavfsizlik qoidalarini buzganingiz sababli botdan chetlatildingiz.")
            except Exception:
                pass
        except Exception as e:
            bot.answer_callback_query(call.id, f"Xatolik: {e}")
        return

    if data == "report_bug":
        bot.answer_callback_query(call.id, "Izoh yozishingizni kutyapman...")
        msg_preview = (msg.text or "")[:300] if msg else ""
        context = f"{orig_q[:200]}\n---\n{msg_preview}".strip() if orig_q else msg_preview
        with _bug_report_lock:
            awaiting_bug_report[user_id] = context
        bot.send_message(
            msg.chat.id,
            "πŸ“ *Nima xato ko'rdingiz yoki qanday taklifingiz bor?*\n"
            "Keyingi xabaringizda yozib yuboring β€” to'g'ridan-to'g'ri loyiha muallifiga yetkazaman.\n"
            "_(Bekor qilish uchun /yangi bosing)_",
            parse_mode="Markdown"
        )
        return

    if data == "explain_simpler":
        bot.answer_callback_query(call.id, "Soddaroq tushuntirish tayyorlayapman...")
        prompt = (
            f"Oldingi '{orig_q[:300]}' masalasining yechimini tushunmadim. "
            "Iltimos, qiyin terminlar va formulalarga ko'mib yubormasdan, eng oddiy tilda bosqichma-bosqich tushuntirib ber."
            if orig_q else
            "Oxirgi tushuntirgan yechimingizni tushunmadim. Iltimos, juda sodda tilda qayta tushuntirib bering."
        )
        t = threading.Thread(
            target=process_and_reply,
            kwargs={
                "message": msg,
                "override_prompt": prompt,
                "bypass_cache": True,
                "history_user_msg": "Tushunmadim, soddaroq tushuntirib ber",
                "actor_user": call.from_user,
            }
        )
        t.start()
        return

    if data == "alt_method":
        bot.answer_callback_query(call.id, "Boshqa yechim usulini izlayapman...")
        prompt = (
            f"'{orig_q[:300]}' masalasini avvalgidan BOSHQA usul bilan "
            "(boshqa teorema, qisqa formula yoki mantiqiy yo'l orqali) yechib, javobini ham tekshirib ko'rsat."
            if orig_q else
            "Shu oxirgi masalani boshqa usul bilan yechib ko'rsating."
        )
        t = threading.Thread(
            target=process_and_reply,
            kwargs={
                "message": msg,
                "override_prompt": prompt,
                "bypass_cache": True,
                "history_user_msg": "Boshqa usul bilan yechib ber",
                "actor_user": call.from_user,
            }
        )
        t.start()
        return

    if data == "similar_problem":
        bot.answer_callback_query(call.id, "O'xshash mashq tayyorlanmoqda...")
        prompt = (
            f"Oldingi '{orig_q[:300]}' masalasiga o'xshash, xuddi shu matematik mavzu va qoidaga doir "
            "lekin boshqa sonlar bilan yangi amaliy misol tuzib ber va o'quvchiga uni mustaqil yechishni taklif qil. "
            "O'quvchini ruhlantirib, agar qiynalsa yordam berishingni ayt."
            if orig_q else
            "Oxirgi masalaga o'xshash yangi misol tuzib ber, o'zim yechib ko'raman."
        )
        t = threading.Thread(
            target=process_and_reply,
            kwargs={
                "message": msg,
                "override_prompt": prompt,
                "bypass_cache": True,
                "history_user_msg": "Shunga o'xshash yangi misol ber",
                "actor_user": call.from_user,
            }
        )
        t.start()
        return

    if data == "get_pdf_solution":
        with _last_user_solutions_lock:
            last_info = _last_user_solutions.get(user_id)
        if not last_info:
            bot.answer_callback_query(call.id, "Avval biror masala yuboring, shunda konspekt tayyorlayman!", show_alert=True)
            return
        bot.answer_callback_query(call.id, "πŸ“„ A4 PDF konspekt shakllantirilmoqda...")
        def _send_pdf_worker():
            try:
                q = last_info["question"]
                sol = last_info["solution"]
                diag = last_info.get("diagram_path")
                if not diag or not os.path.exists(diag):
                    diag = try_draw_geometry(q)
                pdf_path = generate_math_pdf(q, sol, diag)
                if pdf_path and os.path.exists(pdf_path):
                    with open(pdf_path, "rb") as pdf_file:
                        bot.send_document(
                            msg.chat.id,
                            pdf_file,
                            caption="πŸ“„ <b>Sincc.on: Ushbu masalaning A4 PDF Konspekti</b>\n"
                                    "<i>Chop etish va darsda/imtihonda foydalanish uchun to'liq yechim va chizma.</i>",
                            parse_mode="HTML"
                        )
                    try:
                        os.unlink(pdf_path)
                    except Exception:
                        pass
            except Exception as e_pdf:
                print(f"[PDF Telegram xatosi]: {e_pdf}")
                bot.send_message(msg.chat.id, f"❌ PDF konspekt yaratishda xatolik: {e_pdf}")
        threading.Thread(target=_send_pdf_worker, daemon=True).start()
        return

    if data == "open_math_pad":
        bot.answer_callback_query(call.id, "Matematik klaviatura ochilmoqda...")
        with _math_pad_lock:
            _math_pad_sessions[user_id] = ""
        kb = build_math_pad_keyboard()
        txt = get_math_pad_text("")
        bot.send_message(msg.chat.id, txt, parse_mode="HTML", reply_markup=kb)
        return

    if data.startswith("pad_add_"):
        sym = data[8:]
        with _math_pad_lock:
            curr = _math_pad_sessions.get(user_id, "")
            if len(curr) < 150:
                curr += sym
                _math_pad_sessions[user_id] = curr
        bot.answer_callback_query(call.id)
        kb = build_math_pad_keyboard()
        txt = get_math_pad_text(curr)
        try:
            bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
        except Exception:
            pass
        return

    if data == "pad_backspace":
        with _math_pad_lock:
            curr = _math_pad_sessions.get(user_id, "")
            if curr:
                for prefix in ("sin(", "cos(", "tan(", "log(", "ln(", "√("):
                    if curr.endswith(prefix):
                        curr = curr[:-len(prefix)]
                        break
                else:
                    curr = curr[:-1]
                _math_pad_sessions[user_id] = curr
        bot.answer_callback_query(call.id)
        kb = build_math_pad_keyboard()
        txt = get_math_pad_text(curr)
        try:
            bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
        except Exception:
            pass
        return

    if data == "pad_clear":
        with _math_pad_lock:
            _math_pad_sessions[user_id] = ""
        bot.answer_callback_query(call.id, "Formula tozalandi")
        kb = build_math_pad_keyboard()
        txt = get_math_pad_text("")
        try:
            bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
        except Exception:
            pass
        return

    if data == "pad_close":
        bot.answer_callback_query(call.id, "Klaviatura yopildi")
        try:
            bot.delete_message(msg.chat.id, msg.message_id)
        except Exception:
            try:
                bot.edit_message_text("πŸ”’ <i>Matematik klaviatura yopildi.</i>", chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML")
            except Exception:
                pass
        return

    if data == "pad_solve":
        with _math_pad_lock:
            formula = _math_pad_sessions.get(user_id, "").strip()
        if not formula:
            bot.answer_callback_query(call.id, "Formula bo'sh! Avval tugmalarni bosib ifoda tering.", show_alert=True)
            return
        bot.answer_callback_query(call.id, "Masala yechishga yuborilmoqda! πŸš€")
        try:
            bot.edit_message_text(
                f"πŸš€ <b>Hisoblanmoqda:</b> <code>{html.escape(formula)}</code>",
                chat_id=msg.chat.id,
                message_id=msg.message_id,
                parse_mode="HTML"
            )
        except Exception:
            pass
        t = threading.Thread(
            target=process_and_reply,
            kwargs={
                "message": msg,
                "override_prompt": formula,
                "actor_user": call.from_user,
            }
        )
        t.start()
        return

    if data == "open_help_info":
        bot.answer_callback_query(call.id)
        send_help(msg)
        return

    if data == "start_new_chat":
        clear_chat_history(user_id)
        with _bug_report_lock:
            awaiting_bug_report.pop(user_id, None)
        with _math_pad_lock:
            _math_pad_sessions.pop(user_id, None)
        bot.answer_callback_query(call.id, "Suhbat xotirasi tozalandi!")
        bot.send_message(msg.chat.id, "πŸ”„ <b>Suhbat xotirasi yangilandi.</b> Yangi masalangizni yuborishingiz mumkin!", parse_mode="HTML")
        return

    if data == "admin_refresh":
        if not check_is_admin(user_id):
            bot.answer_callback_query(call.id, "Faqat admin uchun!", show_alert=True)
            return
        bot.answer_callback_query(call.id, "Statistika yangilandi!")
        admin_panel(msg)
        return

    if data == "admin_banlar":
        if not check_is_admin(user_id):
            bot.answer_callback_query(call.id, "Faqat admin uchun!", show_alert=True)
            return
        bot.answer_callback_query(call.id)
        handle_banned_list(msg)
        return

    if data == "admin_xatolar":
        if not check_is_admin(user_id):
            bot.answer_callback_query(call.id, "Faqat admin uchun!", show_alert=True)
            return
        bot.answer_callback_query(call.id)
        show_feedbacks(msg)
        return

    if data == "admin_broadcast_help":
        if not check_is_admin(user_id):
            bot.answer_callback_query(call.id, "Faqat admin uchun!", show_alert=True)
            return
        bot.answer_callback_query(call.id)
        bot.send_message(msg.chat.id, "πŸ“’ Ommaviy xabar yuborish uchun quyidagi formatda yozing:\n<code>/broadcast Xabar matni...</code>", parse_mode="HTML")
        return

    bot.answer_callback_query(call.id)

@bot.message_handler(commands=['klaviatura', 'belgilar', 'formula', 'pad'])
def math_pad_command(message):
    user_id = message.from_user.id
    record_user_activity(user_id, message.from_user.username, message.from_user.first_name)
    with _math_pad_lock:
        _math_pad_sessions[user_id] = ""
    kb = build_math_pad_keyboard()
    txt = get_math_pad_text("")
    safe_send_reply(message, txt, reply_markup=kb, parse_mode="HTML")

@bot.message_handler(content_types=['photo'])
def handle_photo(message):
    user_id = message.from_user.id

    # 1. Bloklangan foydalanuvchini tekshirish
    is_banned, ban_reason = is_user_banned(user_id)
    if is_banned:
        bot.reply_to(message, f"β›” Siz qoidabuzarlik sababli botdan chetlatilgansiz.\nSabab: {ban_reason}")
        return

    # 2. Rasm izohida xavfli so'rovlar bormi?
    caption = (message.caption or "").strip()
    if caption and not check_is_admin(user_id):
        is_threat, threat_title, threat_reason = analyze_message_threat(user_id, caption)
        if is_threat:
            alert_admins_threat(message.from_user, threat_title, f"[Rasm izohi] {caption}")
            bot.reply_to(
                message,
                "⚠️ <b>Xavfsizlik ogohlantirishi:</b>\n"
                "Rasm izohida tizim xavfsizlik qoidalariga zid belgilar aniqlandi. "
                "Bu haqda loyiha administratoriga xabar berildi.",
                parse_mode="HTML"
            )
            return

    try:
        record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    except Exception:
        pass

    wait_msg = None
    try:
        wait_msg = bot.reply_to(message, "πŸ“Έ _Rasm o'qilmoqda..._", parse_mode="Markdown")
    except Exception:
        try:
            wait_msg = bot.reply_to(message, "πŸ“Έ Rasm o'qilmoqda...")
        except Exception:
            pass

    try:
        file_info = bot.get_file(message.photo[-1].file_id)
        downloaded_file = bot.download_file(file_info.file_path)
        user_caption = (message.caption or "").strip()
        extracted_text = extract_problem_from_image(downloaded_file, user_caption=user_caption)

        if not extracted_text:
            err = "❌ Rasmdan masala matnini o'qib bo'lmadi. Iltimos, yorug'roq yoki aniqroq rasm yuboring."
            if wait_msg:
                bot.edit_message_text(err, chat_id=message.chat.id, message_id=wait_msg.message_id)
            else:
                bot.reply_to(message, err)
            return

        cleaned_ocr = clean_math_display(extracted_text)
        preview = f"πŸ“ <b>Rasmdan o'qildi:</b>\n{_render_html_prose(cleaned_ocr)}\n\n⏳ <i>Yechim tayyorlanmoqda...</i>"
        if wait_msg:
            safe_send_reply(message, preview, edit_msg=wait_msg, parse_mode="HTML")
        message.text = cleaned_ocr
        t = threading.Thread(
            target=process_and_reply,
            kwargs={
                "message": message,
                "existing_wait_msg": wait_msg,
                "is_photo": True,
                "history_user_msg": f"[Rasm] {cleaned_ocr}",
            }
        )
        t.start()
    except Exception as e:
        err = f"❌ Rasmni yuklashda xatolik yuz berdi: {e}"
        if wait_msg:
            try:
                bot.edit_message_text(err, chat_id=message.chat.id, message_id=wait_msg.message_id)
            except Exception:
                pass
        else:
            bot.reply_to(message, err)

@bot.message_handler(content_types=['voice', 'audio'])
def handle_voice_message(message):
    user_id = message.from_user.id

    # 1. Bloklangan foydalanuvchini tekshirish
    is_banned, ban_reason = is_user_banned(user_id)
    if is_banned:
        bot.reply_to(message, f"β›” Siz qoidabuzarlik sababli botdan chetlatilgansiz.\nSabab: {ban_reason}")
        return

    try:
        record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
    except Exception:
        pass

    wait_msg = None
    try:
        wait_msg = bot.reply_to(message, "πŸŽ™ <i>Ovoz eshitilmoqda va matnga aylantirilmoqda...</i>", parse_mode="HTML")
    except Exception:
        pass

    try:
        file_obj = message.voice or message.audio
        if not file_obj:
            return
        file_info = bot.get_file(file_obj.file_id)
        downloaded_file = bot.download_file(file_info.file_path)
        ext = "ogg" if message.voice else "mp3"
        transcribed_text = transcribe_voice(downloaded_file, filename=f"voice.{ext}")

        if not transcribed_text:
            err = "❌ Ovozni aniqlab bo'lmadi. Iltimos, aniqroq gapirib qayta yuboring yoki matn ko'rinishida yozing."
            if wait_msg:
                bot.edit_message_text(err, chat_id=message.chat.id, message_id=wait_msg.message_id)
            else:
                bot.reply_to(message, err)
            return

        # 2. Xavfsizlik tahlili
        if not check_is_admin(user_id):
            is_threat, threat_title, threat_reason = analyze_message_threat(user_id, transcribed_text)
            if is_threat:
                alert_admins_threat(message.from_user, threat_title, f"[Ovozli xabar] {transcribed_text}")
                bot.reply_to(
                    message,
                    "⚠️ <b>Xavfsizlik ogohlantirishi:</b>\n"
                    "Ovozli xabarda tizim xavfsizlik qoidalariga zid belgilar aniqlandi. "
                    "Bu haqda loyiha administratoriga xabar berildi.",
                    parse_mode="HTML"
                )
                return

        cleaned_text = clean_math_display(transcribed_text)
        preview = f"πŸŽ™ <b>Ovozingizdan o'qildi:</b>\nΒ«<i>{_render_html_prose(cleaned_text)}</i>Β»\n\n⏳ <i>Yechim tayyorlanmoqda...</i>"
        if wait_msg:
            safe_send_reply(message, preview, edit_msg=wait_msg, parse_mode="HTML")
        message.text = cleaned_text
        t = threading.Thread(
            target=process_and_reply,
            kwargs={
                "message": message,
                "existing_wait_msg": wait_msg,
                "is_photo": False,
                "is_voice": True,
                "history_user_msg": f"[Ovoz] {cleaned_text}",
            }
        )
        t.start()
    except Exception as e:
        err = f"❌ Ovozli xabarni yuklashda xatolik yuz berdi: {e}"
        if wait_msg:
            try:
                bot.edit_message_text(err, chat_id=message.chat.id, message_id=wait_msg.message_id)
            except Exception:
                pass
        else:
            bot.reply_to(message, err)

@bot.message_handler(func=lambda message: True)
def handle_all_messages(message):
    text = (message.text or "").strip()
    if not text:
        return

    user_id = message.from_user.id

    # 1. Bloklangan foydalanuvchini tekshirish
    is_banned, ban_reason = is_user_banned(user_id)
    if is_banned:
        bot.reply_to(message, f"β›” Siz qoidabuzarlik sababli botdan chetlatilgansiz.\nSabab: {ban_reason}")
        return

    # 2. Admin bo'lmagan foydalanuvchilar xabarini xavfsizlik bo'yicha tahlil qilish
    if not check_is_admin(user_id):
        is_threat, threat_title, threat_reason = analyze_message_threat(user_id, text)
        if is_threat:
            alert_admins_threat(message.from_user, threat_title, text)
            bot.reply_to(
                message,
                "⚠️ <b>Xavfsizlik ogohlantirishi:</b>\n"
                "Yuborgan so'rovingizda tizim xavfsizlik qoidalariga zid belgilar aniqlandi. "
                "Bu haqda loyiha administratoriga xabar berildi.",
                parse_mode="HTML"
            )
            return

    # Agar foydalanuvchi tasodifan "/ xato" ko'rinishida bo'sh joy bilan buyruq yozsa
    if re.match(r"^/\s+(start|help|info|about|yangi|new|clear|reset|id|myid|admin|stat|stats|broadcast|xato|fikr|taklif|feedback|xatolar|feedbacks|ban|unban|banlar)\b", text, re.IGNORECASE):
        text = re.sub(r"^/\s+", "/", text)
        message.text = text

    if text.startswith("/"):
        cmd = text.split()[0].lower().split("@")[0]
        if cmd in ["/admin", "/stat", "/stats"]:
            admin_panel(message)
            return
        elif cmd in ["/start", "/help", "/info", "/about"]:
            send_welcome(message)
            return
        elif cmd in ["/yangi", "/new", "/clear", "/reset"]:
            new_chat_command(message)
            return
        elif cmd in ["/id", "/myid"]:
            show_my_id(message)
            return
        elif cmd == "/broadcast":
            broadcast_message(message)
            return
        elif cmd in ["/xato", "/fikr", "/taklif", "/feedback"]:
            report_feedback(message)
            return
        elif cmd in ["/xatolar", "/feedbacks"]:
            show_feedbacks(message)
            return
        elif cmd == "/ban":
            handle_ban_command(message)
            return
        elif cmd == "/unban":
            handle_unban_command(message)
            return
        elif cmd in ["/banlar", "/banned"]:
            handle_banned_list(message)
            return
        else:
            bot.reply_to(message, "ℹ️ Noma'lum buyruq. Savolingiz yoki misolingizni oddiy matn ko'rinishida yozavering.")
            return

    # Agar foydalanuvchi /xato yoki 🚨 Xato tugmasidan keyin izoh yozayotgan bo'lsa
    user_id = message.from_user.id
    with _bug_report_lock:
        has_pending_bug = user_id in awaiting_bug_report
        bug_ctx = awaiting_bug_report.pop(user_id, "") if has_pending_bug else ""
    if has_pending_bug:
        record_user_activity(user_id, message.from_user.username, message.from_user.first_name)
        send_bug_report_to_admins(message.from_user, text, bug_ctx)
        bot.reply_to(message, "βœ… *Katta rahmat!* Xabaringiz loyiha muallifiga yetkazildi. 🀝", parse_mode="Markdown")
        return

    t = threading.Thread(target=process_and_reply, args=(message,))
    t.start()

def run_bot():
    if not TOKEN or TOKEN == "dummy_token":
        print("Iltimos, avval .env fayliga TELEGRAM_BOT_TOKEN ni kiriting!")
        return
    print("=" * 70)
    print("Sincc.on Telegram Boti (Matn + Rasm-OCR + Ovoz-Whisper + Geometriya) ishga tushdi...")
    print("=" * 70)
    
    setup_bot_commands()
    
    while True:
        try:
            bot.infinity_polling(timeout=25, long_polling_timeout=25)
        except Exception as e:
            print(f"Telegram polling xatoligi: {e}. 3 soniyadan keyin qayta ulanadi...")
            time.sleep(3)

if __name__ == "__main__":
    run_bot()