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

State lives in bot_state.py. This file re-exports everything so
`import bot; bot.cache_gc` etc. continue to work.
"""
import asyncio
import csv
import io
import json
import logging
import threading
import time
import traceback
import uuid
from datetime import datetime, timezone

from config import (
    BACKUP_ENABLED_DEFAULT, BACKUP_CHANNEL_ID, VERSION,
    PAGE_SIZE, FETCH_LIMIT, QUERY_TIMEOUT, USER_COOLDOWN,
    BATCH_MAX, BATCH_TIMEOUT, ADMIN_TOKEN, OWNER_IDS,
    BROADCAST_DELAY, BROADCAST_MAX_LEN,
    DAILY_QUOTA,
)
from engine import (
    run_search_safe, search_fast_apis_filtered, asur_lookup_filtered,
    search_apis_filtered, dedup_records, render_page, _plain_record,
    normalize_phone, check_api_health, warm_phone_cache,
    con_ready, warmed, esc,
)
from bot_state import (
    ACTIVITY_LOG, ACTIVE_USERS, UNIQUE_USERS, BANNED_USERS, BAN_REASONS,
    MAINTENANCE_MODE, SEARCH_CACHE, SEARCH_CACHE_LOCK, USER_HISTORY,
    USER_LAST, STATS, PHONE_COUNTS,
    _activity_lock, _state_lock,
    tg, send, edit, send_document,
    _short_user, _fmt_ts, _today_utc,
    is_duplicate_update,
    check_force_join,
    _is_unlimited, check_quota, incr_quota, check_flood,
    _log_activity, _get_live_users, _get_stats, _add_to_history,
    _avg_latency_today,
    _is_banned, _ban_user, _unban_user,
    _get_maintenance, _set_maintenance,
    _is_admin_session, _grant_admin, _revoke_admin,
    _admin_state_get, _admin_state_set, _admin_state_clear,
    cache_gc,
)

log = logging.getLogger("bot")

# Runtime toggle (local to bot.py — mutated by /backup and admin panel)
BACKUP_ENABLED = BACKUP_ENABLED_DEFAULT

# ══════════════════════════════════════════════════════════════════
# ADMIN RENDERS
# ══════════════════════════════════════════════════════════════════
def admin_menu_kb():
    m_on, _ = _get_maintenance()
    maint_label = "🔴 Maintenance: ON" if m_on else "🟢 Maintenance: OFF"
    backup_label = "📥 Backup: ON" if BACKUP_ENABLED else "📥 Backup: OFF"
    return {"inline_keyboard": [
        [{"text": "🔴 Live Users", "callback_data": "adm:live"},
         {"text": "📈 Stats", "callback_data": "adm:stats"}],
        [{"text": "📜 Activity Log", "callback_data": "adm:log:0"},
         {"text": "👥 All Users", "callback_data": "adm:users:0"}],
        [{"text": "🔍 Top Searches", "callback_data": "adm:top"},
         {"text": "🚫 Banned", "callback_data": "adm:banned"}],
        [{"text": "🚫 Ban User", "callback_data": "adm:ban"},
         {"text": "✅ Unban User", "callback_data": "adm:unban"}],
        [{"text": "📢 Broadcast", "callback_data": "adm:broadcast"},
         {"text": "📥 Export Log", "callback_data": "adm:export"}],
        [{"text": "🔎 Log by Phone", "callback_data": "adm:logphone"},
         {"text": maint_label, "callback_data": "adm:maint"}],
        [{"text": "🔧 API Status", "callback_data": "adm:apistatus"},
         {"text": backup_label, "callback_data": "adm:backuptoggle"}],
        [{"text": "🔄 Refresh", "callback_data": "adm:menu"}],
    ]}


def render_admin_menu():
    m_on, reason = _get_maintenance()
    m_line = f"🔴 Maintenance ON — {esc(reason)}" if m_on else "🟢 Operational"
    b_line = "📥 Backup forwarding: ON" if BACKUP_ENABLED else "📥 Backup forwarding: OFF"
    return (f"🛡️ <b>Admin Panel</b> — v{VERSION}\n━━━━━━━━━━━━━━━━━━\n"
            f"{m_line}\n{b_line}\n"
            f"👥 Users: {len(UNIQUE_USERS)} · 🚫 Banned: {len(BANNED_USERS)}\n\n"
            "Tap a button or use commands:\n"
            "• /live /stats /log /users /top\n"
            "• /ban &lt;id&gt; [reason] · /unban &lt;id&gt;\n"
            "• /broadcast &lt;msg&gt;\n"
            "• /export · /logphone &lt;num&gt;\n"
            "• /maintenance on|off [reason]\n"
            "• /apistatus · /backup on|off\n"
            "• /reload · /cancel · /logout")


def render_live():
    live = _get_live_users()
    if not live:
        return (f"🔴 <b>Live Users</b>\n\n"
                f"No one active in the last {LIVE_WINDOW // 60} minutes.")
    lines = [f"🔴 <b>Live Users</b> (last {LIVE_WINDOW // 60} min): "
             f"<b>{len(live)}</b>\n"]
    for uid, ts in live[:25]:
        lines.append(f"• {_short_user(uid)} — {_fmt_ts(ts)}")
    return "\n".join(lines)


def render_stats():
    s = _get_stats()
    uptime = (time.time() - STATS["started"]) / 60
    return ("📈 <b>Bot Statistics</b>\n━━━━━━━━━━━━━━━━━━\n"
            f"⏱️ Uptime: <code>{uptime:.1f} min</code>\n"
            f"👥 Unique users: <code>{s['unique_users']}</code>\n"
            f"🔴 Live now: <code>{s['live_users']}</code>\n"
            f"📅 Active today: <code>{s['today_users']}</code>\n"
            f"🔍 Searches today: <code>{s['today_searches']}</code>\n"
            f"🔍 Total searches: <code>{s['total_searches']}</code>\n"
            f"📊 Peak concurrent: <code>{s['peak_concurrent']}</code>\n"
            f"🚫 Banned users: <code>{s['banned_count']}</code>\n"
            f"💾 Cached queries: <code>{s['cached_searches']}</code>\n"
            f"📥 Backup sent: <code>{s['backup_sent']}</code>\n"
            f"📜 Log entries: <code>{s['total_log_entries']}</code>\n"
            f"⏰ Timeouts: <code>{STATS['timeouts']}</code>\n"
            f"❌ Errors: <code>{STATS['errors']}</code>")


def render_log(entries, page=0, page_size=8):
    total = len(entries)
    total_pages = max(1, (total + page_size - 1) // page_size)
    page = max(0, min(page, total_pages - 1))
    chunk = entries[page * page_size:(page + 1) * page_size]
    if not chunk:
        return "📜 <b>Activity Log</b>\n\nNo activity yet.", None
    lines = [f"📜 <b>Activity Log</b> — page {page + 1}/{total_pages} "
             f"({total} entries)\n"]
    for e in chunk:
        uname = e.get("username")
        first = e.get("first_name")
        name_str = f"@{uname}" if uname else (first or "(no name)")
        reply = e.get("summary") or e.get("reply_type") or "-"
        elapsed = e.get("elapsed_ms", 0)
        source = e.get("source") or ""
        block = (f"<code>{_fmt_ts(e['ts'])}</code> · "
                 f"<b>{esc(name_str)}</b> · <code>{e['user_id']}</code>\n")
        block += f"  📥 <code>{esc(e['input'] or '-')}</code>\n"
        reply_line = f"  📤 {esc(reply)}"
        if elapsed:
            reply_line += f" · {elapsed}ms"
        if source:
            reply_line += f" · {source}"
        lines.append(block + reply_line)
    text = "\n\n".join(lines)
    nav = []
    if page > 0:
        nav.append({"text": "◀ Newer", "callback_data": f"adm:log:{page - 1}"})
    nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "adm:noop"})
    if page < total_pages - 1:
        nav.append({"text": "Older ▶", "callback_data": f"adm:log:{page + 1}"})
    return text, ({"inline_keyboard": [nav]} if len(nav) > 1 else None)


def render_users(page=0, page_size=8):
    users = sorted(UNIQUE_USERS.items(), key=lambda kv: -kv[1]["last_seen"])
    total = len(users)
    total_pages = max(1, (total + page_size - 1) // page_size)
    page = max(0, min(page, total_pages - 1))
    chunk = users[page * page_size:(page + 1) * page_size]
    if not chunk:
        return "👥 <b>All Users</b>\n\nNo users yet.", None
    lines = [f"👥 <b>All Users</b> — page {page + 1}/{total_pages} "
             f"({total} total)\n"]
    for uid, info in chunk:
        username = info.get("username")
        first = info.get("first_name") or ""
        name_str = f"@{username}" if username else (first or "(no name)")
        ban_mark = " 🚫" if _is_banned(uid) else ""
        lines.append(f"<b>{esc(name_str)}</b>{ban_mark} · "
                     f"<code>{uid}</code>\n"
                     f"  Requests: {info['count']} · "
                     f"Last: {_fmt_ts(info['last_seen'])}")
    text = "\n\n".join(lines)
    nav = []
    if page > 0:
        nav.append({"text": "◀ Prev", "callback_data": f"adm:users:{page - 1}"})
    nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "adm:noop"})
    if page < total_pages - 1:
        nav.append({"text": "Next ▶", "callback_data": f"adm:users:{page + 1}"})
    return text, ({"inline_keyboard": [nav]} if len(nav) > 1 else None)


def render_top():
    if not PHONE_COUNTS:
        return "🔍 <b>Top Searched Numbers</b>\n\nNo searches yet."
    lines = ["🔍 <b>Top Searched Numbers</b>\n"]
    for i, (num, cnt) in enumerate(PHONE_COUNTS.most_common(10), 1):
        lines.append(f"{i}. <code>{num}</code> — {cnt} time(s)")
    return "\n".join(lines)


def render_banned():
    with _state_lock:
        if not BANNED_USERS:
            return "🚫 <b>Banned Users</b>\n\nNo banned users."
        lines = [f"🚫 <b>Banned Users</b> ({len(BANNED_USERS)})\n"]
        for uid in list(BANNED_USERS)[:30]:
            reason = BAN_REASONS.get(uid) or "—"
            lines.append(f"• {_short_user(uid)} — {esc(reason)}")
    return "\n".join(lines)

# ══════════════════════════════════════════════════════════════════
# BACKUP FORWARDER
# ══════════════════════════════════════════════════════════════════
def _build_backup_payload(user, phone, status, elapsed, fast_data,
                          asur_data, db_results, combined_count):
    return {
        "meta": {"ts_utc": datetime.now(timezone.utc).isoformat(),
                 "bot_version": VERSION,
                 "telegram_user_id": user.get("id"),
                 "username": user.get("username"),
                 "first_name": user.get("first_name")},
        "input": {"mobile": phone},
        "status": status,
        "elapsed_s": round(elapsed, 2),
        "aadhaar_resolution": asur_data.get("aadhaar_res") or {},
        "api_responses_raw": {**(fast_data.get("raw") or {}),
                              **(asur_data.get("api_results") or {})},
        "api_status": {**(fast_data.get("source_status") or {}),
                       **(asur_data.get("source_status") or {})},
        "db_results": db_results or [],
        "records_shown": combined_count,
    }


async def forward_to_backup(user, phone, status, elapsed, fast_data,
                            asur_data, db_results, combined_count):
    if not BACKUP_CHANNEL_ID or not BACKUP_ENABLED:
        return
    try:
        payload = _build_backup_payload(user, phone, status, elapsed,
                                        fast_data, asur_data,
                                        db_results, combined_count)
        header = (f"📥 <b>New lookup</b>\n"
                  f"👤 User: <code>{user.get('id')}</code>"
                  f"{' (@' + esc(user.get('username')) + ')' if user.get('username') else ''}\n"
                  f"📱 Mobile: <code>{esc(phone)}</code>\n"
                  f"📊 Status: <b>{esc(status)}</b> · "
                  f"📄 Records: <b>{combined_count}</b> · "
                  f"⏱️ {elapsed:.1f}s")
        await send(BACKUP_CHANNEL_ID, header)
        json_str = json.dumps(payload, indent=2, ensure_ascii=False,
                              default=str)
        await send_document(BACKUP_CHANNEL_ID,
                            f"lookup_{phone}_{int(time.time())}.json",
                            json_str.encode("utf-8"),
                            caption=f"Mobile {phone} — {status}")
        STATS["backup_sent"] += 1
    except Exception as e:
        log.warning(f"[backup] forward failed: {e!r}")

# ══════════════════════════════════════════════════════════════════
# SEARCH FLOW
# ══════════════════════════════════════════════════════════════════
async def _db_search_async(phone, loop):
    if not con_ready.is_set():
        return []
    try:
        return await asyncio.wait_for(
            loop.run_in_executor(None, run_search_safe, phone, FETCH_LIMIT),
            timeout=QUERY_TIMEOUT + 10)
    except (asyncio.TimeoutError, TimeoutError):
        STATS["timeouts"] += 1
        log.warning(f"DB timeout for {phone}")
        return []
    except Exception as e:
        STATS["errors"] += 1
        log.warning(f"DB error for {phone}: {e!r}")
        return []


async def _show_progressive(chat_id, message_id, phone, results, elapsed,
                            source_note="", extras_block="", asur_data=None):
    search_id = uuid.uuid4().hex[:10]
    total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
    SEARCH_CACHE[search_id] = {
        "ts": time.time(), "results": results, "query": phone,
        "elapsed": elapsed, "source_note": source_note,
        "extras_block": extras_block, "asur_data": asur_data or {},
    }
    try:
        await edit(chat_id, message_id,
                   render_page(results, 0, total_pages, phone,
                               elapsed, source_note, extras_block),
                   reply_markup=page_keyboard(search_id, 0, total_pages))
    except Exception as e:
        log.warning(f"progressive render failed: {e!r}")
    return search_id


async def _do_progressive_search(phone, chat_id, placeholder_id, user):
    t0 = time.time()
    loop = asyncio.get_running_loop()
    db_task = asyncio.create_task(_db_search_async(phone, loop))
    fast_task = asyncio.create_task(search_fast_apis_filtered(phone))
    asur_task = asyncio.create_task(asur_lookup_filtered(phone))

    fast_data = {"records": [], "source_status": {}, "raw": {}, "elapsed": 0.0}
    try:
        fast_data = await asyncio.wait_for(fast_task, timeout=75)
    except asyncio.TimeoutError:
        log.warning(f"Fast API timeout for {phone}")
    except Exception as e:
        log.warning(f"Fast API error for {phone}: {e!r}")

    fast_records = dedup_records(fast_data.get("records") or [])
    search_id = None
    extras_block = ""
    asur_data = {"records": [], "extras": "", "aadhaar_res": {},
                 "api_results": {}, "source_status": {}, "elapsed": 0.0}

    if fast_records:
        search_id = await _show_progressive(
            chat_id, placeholder_id, phone, fast_records,
            fast_data.get("elapsed", 0.0),
            source_note="⚡ Fast results — enriching…")

    try:
        asur_data = await asyncio.wait_for(asur_task, timeout=90)
    except asyncio.TimeoutError:
        log.warning(f"ASUR timeout for {phone}")
    except Exception as e:
        log.warning(f"ASUR error for {phone}: {e!r}")

    asur_records = dedup_records(asur_data.get("records") or [])
    extras_block = asur_data.get("extras") or ""

    if (asur_records or extras_block) and (fast_records or search_id):
        combined_sofar = dedup_records(fast_records + asur_records)
        elapsed = time.time() - t0
        note = "🪪 ASUR data added — database query ongoing…"
        asur_snapshot = {"aadhaar_res": asur_data.get("aadhaar_res"),
                         "api_results": asur_data.get("api_results"),
                         "source_status": asur_data.get("source_status")}
        if search_id:
            SEARCH_CACHE[search_id].update({
                "results": combined_sofar, "extras_block": extras_block,
                "asur_data": asur_snapshot, "elapsed": elapsed,
                "source_note": note, "ts": time.time(),
            })
            total_pages = max(1, (len(combined_sofar) + PAGE_SIZE - 1) // PAGE_SIZE)
            try:
                await edit(chat_id, placeholder_id,
                           render_page(combined_sofar, 0, total_pages, phone,
                                       elapsed, note, extras_block),
                           reply_markup=page_keyboard(search_id, 0, total_pages))
            except Exception as e:
                log.warning(f"ASUR phase render failed: {e!r}")
        else:
            search_id = await _show_progressive(
                chat_id, placeholder_id, phone, combined_sofar, elapsed,
                source_note=note, extras_block=extras_block,
                asur_data=asur_snapshot)

    db_results = []
    try:
        db_results = await db_task
    except Exception as e:
        log.warning(f"DB task raised for {phone}: {e!r}")

    elapsed = time.time() - t0
    combined = dedup_records(fast_records + asur_records + (db_results or []))
    new_from_db = max(0, len(combined) - len(dedup_records(fast_records + asur_records)))

    if fast_records and (asur_records or extras_block) and db_results:
        source = "hybrid"
    elif db_results:
        source = "duckdb"
    elif fast_records or asur_records or extras_block:
        source = "api"
    else:
        source = "empty"

    if not combined and not extras_block:
        _log_activity(user, "search", phone, "no_results",
                      "no records", int(elapsed * 1000), source)
        try:
            await edit(chat_id, placeholder_id,
                       f"❌ <b>No record found</b>\n\n"
                       f"📱 <code>{esc(phone)}</code>\n"
                       f"⏱️ {elapsed:.1f}s")
        except Exception:
            pass
        asyncio.create_task(forward_to_backup(
            user, phone, "empty", elapsed, fast_data, asur_data, db_results, 0))
        return 0, elapsed, source

    note = ""
    if new_from_db > 0 and (fast_records or asur_records):
        note = f"➕ {new_from_db} more from database"
    total_pages = max(1, (len(combined) + PAGE_SIZE - 1) // PAGE_SIZE)
    asur_snapshot = {"aadhaar_res": asur_data.get("aadhaar_res"),
                     "api_results": asur_data.get("api_results"),
                     "source_status": asur_data.get("source_status")}

    if search_id:
        SEARCH_CACHE[search_id].update({
            "results": combined, "elapsed": elapsed, "source_note": note,
            "extras_block": extras_block, "asur_data": asur_snapshot,
            "ts": time.time(),
        })
        try:
            await edit(chat_id, placeholder_id,
                       render_page(combined, 0, total_pages, phone,
                                   elapsed, note, extras_block),
                       reply_markup=page_keyboard(search_id, 0, total_pages))
        except Exception as e:
            log.warning(f"final render failed: {e!r}")
    else:
        search_id = await _show_progressive(
            chat_id, placeholder_id, phone, combined, elapsed,
            source_note=note, extras_block=extras_block,
            asur_data=asur_snapshot)

    STATS["queries"] += 1
    _add_to_history(user.get("id"), phone, len(combined), elapsed, source)
    _log_activity(user, "search", phone, "results",
                  f"{len(combined)} result(s) (+{new_from_db} new)",
                  int(elapsed * 1000), source)
    status = "success" if len(combined) > 0 else "empty"
    asyncio.create_task(forward_to_backup(
        user, phone, status, elapsed, fast_data, asur_data, db_results,
        len(combined)))
    return len(combined), elapsed, source


async def _search_quiet(phone):
    loop = asyncio.get_running_loop()
    api_task = asyncio.create_task(search_apis_filtered(phone))
    db_task = asyncio.create_task(_db_search_async(phone, loop))
    api_res, db_res = [], []
    try:
        r = await asyncio.wait_for(api_task, timeout=25)
        api_res = r.get("records") or []
    except Exception:
        pass
    try:
        db_res = await asyncio.wait_for(db_task,
                                        timeout=max(5, BATCH_TIMEOUT - 25))
    except Exception:
        pass
    combined = dedup_records(api_res + (db_res or []))
    return len(combined), len(combined) > 0

# ══════════════════════════════════════════════════════════════════
# PAGE KEYBOARD
# ══════════════════════════════════════════════════════════════════
def page_keyboard(search_id, page, total_pages, has_export=True):
    nav = []
    if page > 0:
        nav.append({"text": "◀ Prev",
                    "callback_data": f"p:{search_id}:{page-1}"})
    nav.append({"text": f"{page+1} / {total_pages}",
                "callback_data": "noop"})
    if page < total_pages - 1:
        nav.append({"text": "Next ▶",
                    "callback_data": f"p:{search_id}:{page+1}"})
    rows = [nav]
    extras = [{"text": "📋 Copy page",
               "callback_data": f"c:{search_id}:{page}"}]
    if has_export:
        extras.append({"text": "📥 Export",
                       "callback_data": f"e:{search_id}"})
    rows.append(extras)
    return {"inline_keyboard": rows}

# ══════════════════════════════════════════════════════════════════
# WELCOME
# ══════════════════════════════════════════════════════════════════
WELCOME_TEMPLATE = (
    "👋 <b>Phone Lookup Bot</b> v{v}\n\n"
    "Send me any <b>10-digit mobile number</b> and I'll return every "
    "record we have on file.\n\n"
    "📌 <b>Examples</b>\n"
    "• <code>9876543210</code>\n"
    "• <code>+91 98765 43210</code>\n"
    "• <code>9876543210,9876543211</code> (batch)\n\n"
    "<i>Commands:</i>\n"
    "• /start — this message\n"
    "• /info — bot info\n"
    "• /status — bot health\n"
    "• /history — your last 10 searches\n"
    "• /whoami — your profile &amp; quota\n"
    "• /daily — today's quota\n"
    "• /myid — your Telegram ID\n"
    "• /feedback &lt;msg&gt; — send feedback\n"
    "• /report &lt;num&gt; — flag wrong data")

# ══════════════════════════════════════════════════════════════════
# MESSAGE HANDLER
# ══════════════════════════════════════════════════════════════════
async def handle_message(msg):
    try:
        chat_id = msg["chat"]["id"]
        user = msg.get("from") or {}
        user_id = user.get("id")
        text = (msg.get("text") or "").strip()
        log.info(f"Message from {user_id}: {text[:50]!r}")
        if not text or user_id is None:
            return

        if _is_banned(user_id):
            with _state_lock:
                reason = BAN_REASONS.get(user_id) or "no reason given"
            await send(chat_id,
                       f"🚫 <b>You are banned.</b>\n\nReason: {esc(reason)}")
            _log_activity(user, "banned_hit", text[:40], "blocked", reason)
            return

        state = _admin_state_get(user_id)
        if state == "await_admin_token" and not _is_admin_session(user_id):
            _admin_state_clear(user_id)
            if ADMIN_TOKEN and text == ADMIN_TOKEN:
                _grant_admin(user_id)
                _log_activity(user, "admin_login", "***", "granted",
                              "session started")
                await send(chat_id, "✅ <b>Admin access granted</b>",
                           reply_markup=admin_menu_kb())
                await send(chat_id, render_admin_menu())
            else:
                _log_activity(user, "admin_login", "***", "denied",
                              "invalid token")
                await send(chat_id,
                           "❌ <b>Invalid token.</b>\nTry /admin again.")
            return

        if state and _is_admin_session(user_id):
            _admin_state_clear(user_id)
            if state == "await_ban_id":
                parts = text.split(None, 1)
                target = parts[0].lstrip("@")
                reason = parts[1] if len(parts) > 1 else ""
                try:
                    tid = int(target)
                except ValueError:
                    await send(chat_id, "❗ Invalid user ID.")
                    return
                _ban_user(tid, reason)
                _log_activity(user, "admin", f"/ban {tid}", "banned",
                              reason or "no reason")
                await send(chat_id,
                           f"🚫 Banned <code>{tid}</code> — "
                           f"{esc(reason or 'no reason')}")
                return
            if state == "await_unban_id":
                try:
                    tid = int(text.strip())
                except ValueError:
                    await send(chat_id, "❗ Invalid user ID.")
                    return
                ok = _unban_user(tid)
                _log_activity(user, "admin", f"/unban {tid}", "unbanned")
                await send(chat_id,
                           "✅ Unbanned." if ok else "ℹ️ User was not banned.")
                return
            if state == "await_broadcast":
                asyncio.create_task(_run_broadcast(chat_id, text))
                _log_activity(user, "admin", "/broadcast", "sending",
                              f"{len(text)} chars")
                return
            if state == "await_logphone":
                phone, hint = normalize_phone(text)
                if not phone:
                    await send(chat_id, f"❗ {hint}")
                    return
                entries = [e for e in ACTIVITY_LOG
                           if e["action"] == "search" and e["input"] == phone]
                entries.reverse()
                if not entries:
                    await send(chat_id,
                               f"🔎 No searches logged for <code>{phone}</code>.")
                    return
                lines = [f"🔎 <b>Searches for</b> <code>{phone}</code> "
                         f"({len(entries)} total)\n"]
                for e in entries[:20]:
                    uname = e.get("username")
                    first = e.get("first_name")
                    nm = f"@{uname}" if uname else (first or "(anon)")
                    lines.append(f"• {_fmt_ts(e['ts'])} · {esc(nm)} · "
                                 f"<code>{e['user_id']}</code>")
                await send(chat_id, "\n".join(lines))
                _log_activity(user, "admin", f"logphone {phone}", "text")
                return
            if state == "await_maint_reason":
                _set_maintenance(True, text[:100])
                _log_activity(user, "admin", "maintenance on", "state",
                              text[:100])
                await send(chat_id,
                           f"🔴 <b>Maintenance ON</b>\n"
                           f"Reason: {esc(text[:100])}")
                return

        m_on, m_reason = _get_maintenance()
        if m_on and not _is_admin_session(user_id):
            if text in ("/start", "/help", "/status", "/info", "/myid"):
                pass
            else:
                await send(chat_id,
                           f"🛠️ <b>Bot under maintenance</b>\n\n{esc(m_reason)}")
                _log_activity(user, "maintenance_block", text[:40], "blocked")
                return

        if not await check_force_join(chat_id, user, text):
            return

        if text == "/admin":
            if not ADMIN_TOKEN:
                await send(chat_id, "⚠️ Admin panel is not configured.")
                return
            if _is_admin_session(user_id):
                _log_activity(user, "admin", "/admin", "menu")
                await send(chat_id, render_admin_menu(),
                           reply_markup=admin_menu_kb())
            else:
                _admin_state_set(user_id, "await_admin_token")
                await send(chat_id,
                           "🔐 <b>Admin access required</b>\n\n"
                           "Send the admin token to continue. "
                           "It expires in 3 minutes.")
            return

        if text == "/logout":
            if _is_admin_session(user_id):
                _revoke_admin(user_id)
                _log_activity(user, "admin_logout", "/logout", "revoked")
                await send(chat_id, "✅ Admin session ended.")
            else:
                await send(chat_id, "You are not logged in as admin.")
            return

        if text.startswith("/") and _is_admin_session(user_id):
            await _handle_admin_command(chat_id, user, text, user_id)
            return

        if text == "/status":
            uptime = (time.time() - STATS["started"]) / 60
            m_on, _ = _get_maintenance()
            _log_activity(user, "status", "/status", "text")
            import config as _cfg
            await send(chat_id,
                f"<b>📊 Bot Status</b> — v{VERSION}\n\n"
                f"⏱️ Uptime: <code>{uptime:.1f} min</code>\n"
                f"🔌 DuckDB main: <code>{con_ready.is_set()}</code>\n"
                f"🔥 Cache warmed: <code>{warmed.is_set()}</code>\n"
                f"📂 HiTeck: <code>{len(_cfg.PARQUET_URLS)}</code> · "
                f"Flipkart: <code>{len(_cfg.FLIPKART_URLS)}</code>\n"
                f"🔗 APIs: <code>850CR + IndData + ASUR×4</code>\n"
                f"🛠️ Maintenance: <code>{m_on}</code>\n"
                f"📥 Backup: <code>{BACKUP_ENABLED}</code>\n"
                f"🔍 Queries: <code>{STATS['queries']}</code>\n"
                f"⏰ Timeouts: <code>{STATS['timeouts']}</code>\n"
                f"❌ Errors: <code>{STATS['errors']}</code>")
            return

        if text == "/info":
            uptime = (time.time() - STATS["started"]) / 60
            s = _get_stats()
            _log_activity(user, "info", "/info", "text")
            await send(chat_id,
                f"ℹ️ <b>About This Bot</b>\n━━━━━━━━━━━━━━━━━━\n"
                f"🤖 Version: <code>{VERSION}</code>\n"
                f"📊 Sources: HiTeck (7) + Flipkart (1) + 2 APIs + ASUR×4\n"
                f"👥 Unique users: <code>{s['unique_users']}</code>\n"
                f"🔍 Searches: <code>{s['total_searches']}</code>\n"
                f"⏱️ Avg latency (today): "
                f"<code>{_avg_latency_today():.1f}s</code>\n"
                f"🕒 Uptime: <code>{uptime:.0f} min</code>\n"
                "━━━━━━━━━━━━━━━━━━\n"
                "Built with ❤️ for fast, private lookups.")
            return

        if text == "/history":
            with _activity_lock:
                h = list(USER_HISTORY.get(user_id, []))
            _log_activity(user, "history", "/history", "text")
            if not h:
                await send(chat_id,
                           "📭 <b>No history yet</b>\n\n"
                           "Search a number to start.")
                return
            rows = [[{"text": f"{i}. {item['phone']} ({item['count']} res)",
                      "callback_data": f"h:{item['phone']}"}]
                    for i, item in enumerate(h, 1)]
            await send(chat_id,
                       "🕘 <b>Your last searches</b>\n\nTap to search again:",
                       reply_markup={"inline_keyboard": rows})
            return

        if text == "/myid":
            _log_activity(user, "myid", "/myid", "text")
            await send(chat_id,
                       f"🆔 <b>Your Telegram ID</b>\n<code>{user_id}</code>")
            return

        if text == "/whoami":
            _, remaining = check_quota(user_id)
            banned = _is_banned(user_id)
            admin = _is_admin_session(user_id)
            owner = user_id in OWNER_IDS
            with _activity_lock:
                info = UNIQUE_USERS.get(user_id, {})
                first_seen = info.get("first_seen")
                count = info.get("count", 0)
            lines = ["🆔 <b>Your Info</b>", f"• ID: <code>{user_id}</code>"]
            if user.get("username"):
                lines.append(f"• Username: @{esc(user['username'])}")
            if user.get("first_name"):
                lines.append(f"• Name: {esc(user['first_name'])}")
            if first_seen:
                lines.append("• First seen: " +
                             time.strftime('%Y-%m-%d %H:%M',
                                           time.gmtime(first_seen)))
            lines.append(f"• Total requests: {count}")
            if _is_unlimited(user_id):
                lines.append("• Daily quota: ∞")
            else:
                lines.append(f"• Daily quota: {DAILY_QUOTA - remaining}/"
                             f"{DAILY_QUOTA} remaining")
            if owner:
                lines.append("• Status: 👑 Owner")
            elif admin:
                lines.append("• Status: 🛡️ Admin")
            if banned:
                with _state_lock:
                    reason = BAN_REASONS.get(user_id) or "no reason"
                lines.append(f"• Status: 🚫 Banned ({esc(reason)})")
            _log_activity(user, "whoami", "/whoami", "text")
            await send(chat_id, "\n".join(lines))
            return

        if text == "/daily":
            if _is_unlimited(user_id):
                await send(chat_id,
                           "📊 <b>Daily Quota</b>\n\n♾️ Unlimited (admin/owner)")
            else:
                _, remaining = check_quota(user_id)
                used = DAILY_QUOTA - remaining
                await send(chat_id,
                           f"📊 <b>Daily Quota</b>\n\n"
                           f"Used: <code>{used}</code>/"
                           f"<code>{DAILY_QUOTA}</code>\n"
                           f"Remaining: <code>{remaining}</code>")
            _log_activity(user, "daily", "/daily", "text")
            return

        if text == "/ping":
            uptime = (time.time() - STATS["started"]) / 60
            _log_activity(user, "ping", "/ping", "text")
            await send(chat_id,
                       f"🏓 <b>Pong!</b>\n\n⏱️ Uptime: {uptime:.1f} min\n"
                       f"🕐 {time.strftime('%H:%M:%S', time.gmtime())} UTC")
            return

        if text.startswith("/feedback"):
            fb = text[len("/feedback"):].strip()
            if not fb:
                await send(chat_id,
                           "❌ Usage: <code>/feedback your message</code>")
                return
            if BACKUP_CHANNEL_ID:
                await send(BACKUP_CHANNEL_ID,
                           f"💬 <b>Feedback</b>\n"
                           f"👤 {_short_user(user_id, user)}\n\n"
                           f"{esc(fb[:3000])}")
            await send(chat_id, "✅ Thanks for your feedback!")
            _log_activity(user, "feedback", fb[:60], "text")
            return

        if text.startswith("/report"):
            arg = text[len("/report"):].strip()
            if not arg:
                await send(chat_id,
                           "❌ Usage: <code>/report 9876543210 [reason]</code>")
                return
            parts = arg.split(None, 1)
            phone, hint = normalize_phone(parts[0])
            if not phone:
                await send(chat_id, f"❌ Invalid number: {hint}")
                return
            reason = parts[1] if len(parts) > 1 else ""
            if BACKUP_CHANNEL_ID:
                await send(BACKUP_CHANNEL_ID,
                           f"🚩 <b>Report</b>\n"
                           f"👤 {_short_user(user_id, user)}\n"
                           f"📱 <code>{phone}</code>\n"
                           f"📝 {esc(reason or '(no reason given)')}")
            await send(chat_id,
                       f"✅ Report submitted for <code>{phone}</code>.")
            _log_activity(user, "report", phone, "text", reason[:80])
            return

        if text in ("/start", "/help"):
            _log_activity(user, "start", text, "text")
            await send(chat_id, WELCOME_TEMPLATE.format(v=VERSION))
            if not warmed.is_set():
                threading.Thread(target=warm_phone_cache, daemon=True).start()
            return

        if "," in text:
            parts = [p.strip() for p in text.split(",") if p.strip()]
            if len(parts) < 2:
                await send(chat_id,
                           "❌ <b>Batch format</b>\n\n"
                           "Example: <code>9876543210,9876543211</code>")
                return
            if len(parts) > BATCH_MAX:
                await send(chat_id,
                           f"❌ Max {BATCH_MAX} numbers per batch.")
                return
            phones = []
            for p in parts:
                ph, hint = normalize_phone(p)
                if not ph:
                    await send(chat_id,
                               f"❌ Invalid: <code>{esc(p)}</code> — {hint}")
                    return
                phones.append(ph)
            await _handle_batch(chat_id, user, phones)
            return

        phone, hint = normalize_phone(text)
        if not phone:
            _log_activity(user, "invalid", text, "error", hint)
            await send(chat_id,
                       "❌ <b>Invalid input</b>\n\n"
                       "Send a 10-digit number.\n"
                       "Also accepts: <code>+91 98765 43210</code>, "
                       "<code>09876543210</code>, "
                       "<code>9876543210,9876543211</code>")
            return

        remaining_mute = check_flood(user_id)
        if remaining_mute:
            await send(chat_id,
                       f"⏳ Slow down! Try again in {remaining_mute}s.")
            _log_activity(user, "flood_muted", phone, "blocked",
                          f"{remaining_mute}s")
            return

        now = time.time()
        if now - USER_LAST.get(user_id, 0) < USER_COOLDOWN:
            wait = USER_COOLDOWN - (now - USER_LAST.get(user_id, 0))
            _log_activity(user, "cooldown", phone, "text",
                          f"wait {wait:.0f}s")
            await send(chat_id, f"⏳ Wait {wait:.0f}s before next search.")
            return
        USER_LAST[user_id] = now

        ok, remaining = check_quota(user_id)
        if not ok:
            await send(chat_id,
                       f"❌ <b>Daily quota reached</b>\n\n"
                       f"You've used all {DAILY_QUOTA} queries for today.\n"
                       f"Resets at 00:00 UTC.")
            _log_activity(user, "quota_exceeded", phone, "blocked")
            return
        incr_quota(user_id)

        if text.strip() != phone and not text.strip().isdigit():
            await send(chat_id, f"ℹ️ Interpreted as <code>{phone}</code>")
        if not warmed.is_set():
            threading.Thread(target=warm_phone_cache, daemon=True).start()

        placeholder = await send(
            chat_id,
            f"🔍 <b>Searching…</b>\n\n📱 <code>{esc(phone)}</code>\n\n"
            f"<i>Fast results appear instantly; database enrich follows.</i>")
        if placeholder is None:
            return

        try:
            await _do_progressive_search(phone, chat_id, placeholder, user)
        except asyncio.TimeoutError:
            STATS["timeouts"] += 1
            _log_activity(user, "search", phone, "timeout",
                          "progressive timeout")
            await edit(chat_id, placeholder, "⏱️ Timed out. Try again.")
        except Exception as e:
            STATS["errors"] += 1
            log.error(f"progressive search error: {e!r}\n"
                      f"{traceback.format_exc()}")
            _log_activity(user, "search", phone, "error", str(e)[:100])
            await edit(chat_id, placeholder,
                       f"❌ Error: <code>{esc(str(e)[:200])}</code>")
    except Exception as e:
        log.error(f"handle_message fatal: {e!r}\n{traceback.format_exc()}")

# ══════════════════════════════════════════════════════════════════
# ADMIN COMMANDS
# ══════════════════════════════════════════════════════════════════
async def _handle_admin_command(chat_id, user, text, user_id):
    global BACKUP_ENABLED
    cmd = text.split()[0].lower()
    args = text.split()[1:]

    if cmd == "/live":
        _log_activity(user, "admin", "/live", "text")
        await send(chat_id, render_live())
        return
    if cmd == "/stats":
        _log_activity(user, "admin", "/stats", "text")
        await send(chat_id, render_stats())
        return
    if cmd == "/users":
        _log_activity(user, "admin", "/users", "text")
        t, kb = render_users(0)
        await send(chat_id, t, reply_markup=kb)
        return
    if cmd == "/top":
        _log_activity(user, "admin", "/top", "text")
        await send(chat_id, render_top())
        return
    if cmd == "/log":
        entries = list(ACTIVITY_LOG)
        entries.reverse()
        label = ""
        if args:
            try:
                tid = int(args[0])
                entries = [e for e in entries if e["user_id"] == tid]
                label = f" (user {tid})"
            except ValueError:
                target = args[0].lstrip("@").lower()
                entries = [e for e in entries
                           if (e.get("username") or "").lower() == target]
                label = f" (@{target})"
        _log_activity(user, "admin", text, "log_view")
        t, kb = render_log(entries, 0)
        if label:
            t = t.replace("<b>Activity Log</b>",
                          f"<b>Activity Log{label}</b>", 1)
        await send(chat_id, t, reply_markup=kb)
        return
    if cmd == "/banned":
        _log_activity(user, "admin", "/banned", "text")
        await send(chat_id, render_banned())
        return
    if cmd == "/ban":
        if not args:
            _admin_state_set(user_id, "await_ban_id")
            await send(chat_id, "Send user ID (and optional reason):")
            return
        try:
            tid = int(args[0].lstrip("@"))
        except ValueError:
            await send(chat_id, "❗ Invalid user ID.")
            return
        reason = " ".join(args[1:]) if len(args) > 1 else ""
        _ban_user(tid, reason)
        _log_activity(user, "admin", f"/ban {tid}", "banned",
                      reason or "no reason")
        await send(chat_id,
                   f"🚫 Banned <code>{tid}</code> — "
                   f"{esc(reason or 'no reason')}")
        return
    if cmd == "/unban":
        if not args:
            _admin_state_set(user_id, "await_unban_id")
            await send(chat_id, "Send user ID to unban:")
            return
        try:
            tid = int(args[0])
        except ValueError:
            await send(chat_id, "❗ Invalid user ID.")
            return
        ok = _unban_user(tid)
        _log_activity(user, "admin", f"/unban {tid}", "unbanned")
        await send(chat_id,
                   "✅ Unbanned." if ok else "ℹ️ User was not banned.")
        return
    if cmd == "/broadcast":
        if not args:
            _admin_state_set(user_id, "await_broadcast")
            await send(chat_id,
                       "Send the message to broadcast to all users:")
            return
        await send(chat_id,
                   "ℹ️ Use /broadcast with no args, then send the message.")
        return
    if cmd == "/export":
        _log_activity(user, "admin", "/export", "file")
        await _send_log_export(chat_id)
        return
    if cmd == "/logphone":
        if not args:
            _admin_state_set(user_id, "await_logphone")
            await send(chat_id, "Send a 10-digit number to search the log:")
            return
        phone, hint = normalize_phone(args[0])
        if not phone:
            await send(chat_id, f"❗ {hint}")
            return
        entries = [e for e in ACTIVITY_LOG
                   if e["action"] == "search" and e["input"] == phone]
        entries.reverse()
        if not entries:
            await send(chat_id, f"🔎 No searches for <code>{phone}</code>.")
            return
        lines = [f"🔎 <b>Searches for</b> <code>{phone}</code> "
                 f"({len(entries)})\n"]
        for e in entries[:20]:
            uname = e.get("username")
            first = e.get("first_name")
            nm = f"@{uname}" if uname else (first or "(anon)")
            lines.append(f"• {_fmt_ts(e['ts'])} · {esc(nm)} · "
                         f"<code>{e['user_id']}</code>")
        await send(chat_id, "\n".join(lines))
        return
    if cmd == "/maintenance":
        if not args:
            m_on, m_reason = _get_maintenance()
            st = "ON" if m_on else "OFF"
            await send(chat_id, f"🛠️ Maintenance: <b>{st}</b>" +
                       (f"\nReason: {esc(m_reason)}" if m_on else ""))
            return
        mode = args[0].lower()
        if mode == "on":
            reason = " ".join(args[1:]) if len(args) > 1 else ""
            if reason:
                _set_maintenance(True, reason)
                _log_activity(user, "admin", "maintenance on", "state",
                              reason)
                await send(chat_id, f"🔴 Maintenance ON — {esc(reason)}")
            else:
                _admin_state_set(user_id, "await_maint_reason")
                await send(chat_id, "Send a short reason for maintenance:")
            return
        elif mode == "off":
            _set_maintenance(False)
            _log_activity(user, "admin", "maintenance off", "state")
            await send(chat_id, "🟢 Maintenance OFF")
            return
        await send(chat_id, "Usage: /maintenance on|off [reason]")
        return
    if cmd == "/apistatus":
        await send(chat_id, "🔍 Pinging APIs…")
        h = await check_api_health()
        lines = ["🔧 <b>API Status</b>\n"]
        for name, st in h.items():
            icon = "✅" if st.get("ok") else "❌"
            lines.append(f"{icon} <code>{name}</code> — "
                         f"{st.get('latency_ms', '?')}ms")
        await send(chat_id, "\n".join(lines))
        _log_activity(user, "admin", "/apistatus", "text")
        return
    if cmd == "/backup":
        if not args:
            await send(chat_id,
                       f"📥 Backup forwarding: "
                       f"<b>{'ON' if BACKUP_ENABLED else 'OFF'}</b>")
            return
        mode = args[0].lower()
        if mode == "on":
            BACKUP_ENABLED = True
            _log_activity(user, "admin", "backup on", "state")
            await send(chat_id, "✅ Backup forwarding ON")
        elif mode == "off":
            BACKUP_ENABLED = False
            _log_activity(user, "admin", "backup off", "state")
            await send(chat_id, "🚫 Backup forwarding OFF")
        else:
            await send(chat_id, "Usage: /backup on|off")
        return
    if cmd == "/reload":
        from bot_state import (_member_cache, _pending_query, _seen_updates,
                               _member_lock, _pending_lock, _seen_updates_lock)
        with _member_lock:
            _member_cache.clear()
        with _pending_lock:
            _pending_query.clear()
        with _seen_updates_lock:
            _seen_updates.clear()
        SEARCH_CACHE.clear()
        _log_activity(user, "admin", "/reload", "state")
        await send(chat_id, "✅ Caches cleared")
        return
    if cmd == "/cancel":
        _admin_state_clear(user_id)
        _log_activity(user, "admin", "/cancel", "state")
        await send(chat_id, "✅ Pending prompt cancelled")
        return
    await send(chat_id, render_admin_menu(), reply_markup=admin_menu_kb())

# ══════════════════════════════════════════════════════════════════
# BATCH / BROADCAST / EXPORT
# ══════════════════════════════════════════════════════════════════
async def _handle_batch(chat_id, user, phones):
    await send(chat_id,
               f"🔍 <b>Batch search</b> — {len(phones)} number(s)…")
    t0 = time.time()
    tasks = [asyncio.create_task(_search_quiet(p)) for p in phones]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    total_elapsed = time.time() - t0
    lines = [f"📊 <b>Batch results</b> ({len(phones)} numbers) — "
             f"{total_elapsed:.1f}s\n"]
    for phone, res in zip(phones, results):
        if isinstance(res, Exception):
            lines.append(f"❌ <code>{phone}</code> — error: "
                         f"{esc(str(res)[:60])}")
        else:
            n, ok = res
            lines.append(f"✅ <code>{phone}</code> — {n} record(s)"
                         if ok else
                         f"❌ <code>{phone}</code> — no results")
    kb_rows = [[{"text": f"View {p}", "callback_data": f"h:{p}"}]
               for p in phones]
    _log_activity(user, "batch_search", ",".join(phones), "text",
                  f"{len(phones)} nums in {total_elapsed:.1f}s")
    await send(chat_id, "\n".join(lines),
               reply_markup={"inline_keyboard": kb_rows})


async def _run_broadcast(admin_chat_id, message):
    with _activity_lock:
        recipients = list(UNIQUE_USERS.keys())
    if not recipients:
        await send(admin_chat_id, "📭 No users to broadcast to.")
        return
    message = message[:BROADCAST_MAX_LEN]
    await send(admin_chat_id,
               f"📢 Broadcasting to <b>{len(recipients)}</b> users…")
    sent = 0
    failed = 0
    for uid in recipients:
        if _is_banned(uid):
            continue
        try:
            res = await tg("sendMessage",
                           {"chat_id": uid,
                            "text": f"📢 <b>Announcement</b>\n\n{message}",
                            "parse_mode": "HTML",
                            "disable_web_page_preview": True},
                           timeout=15)
            if res.get("ok"):
                sent += 1
            else:
                failed += 1
        except Exception:
            failed += 1
        await asyncio.sleep(BROADCAST_DELAY)
    await send(admin_chat_id,
               f"✅ <b>Broadcast complete</b>\n\n"
               f"Sent: <code>{sent}</code>\n"
               f"Failed: <code>{failed}</code>")
    _log_activity({"id": 0}, "admin", "broadcast", "done",
                  f"sent={sent} failed={failed}")


async def _send_log_export(chat_id):
    entries = list(ACTIVITY_LOG)
    if not entries:
        await send(chat_id, "📭 No activity to export.")
        return
    buf = io.StringIO()
    w = csv.writer(buf)
    w.writerow(["timestamp", "user_id", "username", "first_name",
                "action", "input", "reply_type", "summary",
                "elapsed_ms", "source"])
    for e in entries:
        w.writerow([
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e["ts"])),
            e["user_id"], e.get("username") or "",
            e.get("first_name") or "", e["action"],
            e.get("input", ""), e.get("reply_type", ""),
            e.get("summary", ""), e.get("elapsed_ms", 0),
            e.get("source", ""),
        ])
    csv_bytes = buf.getvalue().encode("utf-8")
    ts = time.strftime("%Y%m%d_%H%M%S")
    await send_document(chat_id, f"activity_log_{ts}.csv", csv_bytes,
                        caption=f"📥 Activity log — {len(entries)} entries")

# ══════════════════════════════════════════════════════════════════
# CALLBACK HANDLER
# ══════════════════════════════════════════════════════════════════
async def handle_callback(cb):
    global BACKUP_ENABLED
    try:
        data = cb.get("data", "")
        cb_id = cb["id"]
        msg = cb.get("message") or {}
        chat_id = msg.get("chat", {}).get("id")
        message_id = msg.get("message_id")
        user = cb.get("from") or {}
        user_id = user.get("id")
        if not chat_id or not message_id:
            await tg("answerCallbackQuery", {"callback_query_id": cb_id})
            return
        if _is_banned(user_id):
            await tg("answerCallbackQuery",
                     {"callback_query_id": cb_id,
                      "text": "🚫 You are banned.",
                      "show_alert": True})
            return

        if data == "join:check":
            from bot_state import (_member_cache, _member_lock,
                                   _pending_query, _pending_lock)
            with _member_lock:
                _member_cache.pop(user_id, None)
            ok = await _is_channel_member(user_id)
            if not ok:
                await tg("answerCallbackQuery",
                         {"callback_query_id": cb_id,
                          "text": "You haven't joined yet. Please join first.",
                          "show_alert": True})
                return
            await tg("answerCallbackQuery",
                     {"callback_query_id": cb_id, "text": "✅ Verified!"})
            try:
                await tg("deleteMessage",
                         {"chat_id": chat_id, "message_id": message_id})
            except Exception:
                pass
            with _pending_lock:
                pending = _pending_query.pop(user_id, None)
            if pending:
                ptext, _, pts = pending
                from config import PENDING_QUERY_TTL
                if time.time() - pts < PENDING_QUERY_TTL:
                    await handle_message({"chat": {"id": chat_id},
                                          "from": user, "text": ptext})
                    _log_activity(user, "join_verified", ptext[:40], "replay")
                    return
            await send(chat_id,
                       "✅ <b>Thanks for joining!</b>\n\n"
                       "Send a 10-digit mobile number to start.")
            _log_activity(user, "join_verified", "-", "ok")
            return

        if data.startswith("adm:"):
            if not _is_admin_session(user_id):
                await tg("answerCallbackQuery",
                         {"callback_query_id": cb_id,
                          "text": "Admin session expired — send /admin again.",
                          "show_alert": True})
                return
            parts = data.split(":")
            action = parts[1] if len(parts) > 1 else "menu"
            if action == "menu":
                await edit(chat_id, message_id, render_admin_menu(),
                           reply_markup=admin_menu_kb())
            elif action == "live":
                await edit(chat_id, message_id, render_live(),
                           reply_markup=admin_menu_kb())
            elif action == "stats":
                await edit(chat_id, message_id, render_stats(),
                           reply_markup=admin_menu_kb())
            elif action == "top":
                await edit(chat_id, message_id, render_top(),
                           reply_markup=admin_menu_kb())
            elif action == "banned":
                await edit(chat_id, message_id, render_banned(),
                           reply_markup=admin_menu_kb())
            elif action == "log":
                page = int(parts[2]) if len(parts) > 2 else 0
                entries = list(ACTIVITY_LOG)
                entries.reverse()
                t, kb = render_log(entries, page)
                await edit(chat_id, message_id, t, reply_markup=kb)
            elif action == "users":
                page = int(parts[2]) if len(parts) > 2 else 0
                t, kb = render_users(page)
                await edit(chat_id, message_id, t, reply_markup=kb)
            elif action == "ban":
                _admin_state_set(user_id, "await_ban_id")
                await edit(chat_id, message_id,
                           "🚫 Send user ID (and optional reason):")
            elif action == "unban":
                _admin_state_set(user_id, "await_unban_id")
                await edit(chat_id, message_id,
                           "✅ Send user ID to unban:")
            elif action == "broadcast":
                _admin_state_set(user_id, "await_broadcast")
                await edit(chat_id, message_id,
                           "📢 Send the message to broadcast:")
            elif action == "export":
                await edit(chat_id, message_id, "📥 Generating export…",
                           reply_markup=admin_menu_kb())
                await _send_log_export(chat_id)
            elif action == "logphone":
                _admin_state_set(user_id, "await_logphone")
                await edit(chat_id, message_id,
                           "🔎 Send a 10-digit number:")
            elif action == "maint":
                m_on, _ = _get_maintenance()
                if m_on:
                    _set_maintenance(False)
                    await edit(chat_id, message_id,
                               "🟢 Maintenance OFF",
                               reply_markup=admin_menu_kb())
                else:
                    _admin_state_set(user_id, "await_maint_reason")
                    await edit(chat_id, message_id,
                               "Send a short maintenance reason:")
            elif action == "apistatus":
                await edit(chat_id, message_id, "🔍 Pinging APIs…")
                h = await check_api_health()
                lines = ["🔧 <b>API Status</b>\n"]
                for name, st in h.items():
                    icon = "✅" if st.get("ok") else "❌"
                    lines.append(f"{icon} <code>{name}</code> — "
                                 f"{st.get('latency_ms', '?')}ms")
                await edit(chat_id, message_id, "\n".join(lines),
                           reply_markup=admin_menu_kb())
            elif action == "backuptoggle":
                BACKUP_ENABLED = not BACKUP_ENABLED
                await edit(chat_id, message_id, render_admin_menu(),
                           reply_markup=admin_menu_kb())
            elif action == "noop":
                pass
            await tg("answerCallbackQuery", {"callback_query_id": cb_id})
            _log_activity(user, "admin", data, "menu")
            return

        if data.startswith("h:"):
            phone = data.split(":", 1)[1]
            await tg("answerCallbackQuery",
                     {"callback_query_id": cb_id,
                      "text": f"Searching {phone}…"})
            await handle_message({"chat": {"id": chat_id},
                                  "from": user, "text": phone})
            return

        if data.startswith("c:"):
            try:
                _, sid, page_s = data.split(":")
                page = int(page_s)
            except Exception:
                await tg("answerCallbackQuery",
                         {"callback_query_id": cb_id})
                return
            with SEARCH_CACHE_LOCK:
                entry = SEARCH_CACHE.get(sid)
            if not entry:
                await tg("answerCallbackQuery",
                         {"callback_query_id": cb_id,
                          "text": "Session expired.",
                          "show_alert": True})
                return
            results = entry["results"]
            total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
            page = max(0, min(page, total_pages - 1))
            start = page * PAGE_SIZE
            chunk = results[start:start + PAGE_SIZE]
            text = "\n\n".join(_plain_record(start + i + 1, r)
                               for i, r in enumerate(chunk))
            await send(chat_id,
                       f"<b>📋 Copy text for page {page + 1}</b>\n\n"
                       f"<pre>{esc(text[:3500])}</pre>")
            await tg("answerCallbackQuery",
                     {"callback_query_id": cb_id,
                      "text": "Sent as copyable message"})
            _log_activity(user, "copy", entry["query"], "text")
            return

        if data.startswith("e:"):
            sid = data.split(":", 1)[1]
            with SEARCH_CACHE_LOCK:
                entry = SEARCH_CACHE.get(sid)
            if not entry:
                await tg("answerCallbackQuery",
                         {"callback_query_id": cb_id,
                          "text": "Session expired.",
                          "show_alert": True})
                return
            phone = entry["query"]
            results = entry["results"]
            payload = json.dumps({
                "phone": phone,
                "records": results,
                "extras": entry.get("extras_block", ""),
                "source_note": entry.get("source_note", ""),
                "elapsed_s": entry.get("elapsed", 0),
                "asurpapa": entry.get("asur_data", {}),
            }, indent=2, ensure_ascii=False,
                default=str).encode("utf-8")
            await send_document(chat_id, f"results_{phone}.json", payload,
                                caption=f"📥 {len(results)} record(s) "
                                        f"for {phone}")
            await tg("answerCallbackQuery",
                     {"callback_query_id": cb_id, "text": "Sent as file"})
            _log_activity(user, "export", phone, "file",
                          f"{len(results)} records")
            return

        if data == "noop" or not data.startswith("p:"):
            await tg("answerCallbackQuery", {"callback_query_id": cb_id})
            return

        try:
            _, search_id, page_str = data.split(":")
            page = int(page_str)
        except Exception:
            await tg("answerCallbackQuery", {"callback_query_id": cb_id})
            return

        with SEARCH_CACHE_LOCK:
            entry = SEARCH_CACHE.get(search_id)
        if not entry:
            await tg("answerCallbackQuery",
                     {"callback_query_id": cb_id,
                      "text": "Session expired — search again.",
                      "show_alert": True})
            return
        results = entry["results"]
        total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
        page = max(0, min(page, total_pages - 1))
        await edit(chat_id, message_id,
                   render_page(results, page, total_pages, entry["query"],
                               entry["elapsed"],
                               entry.get("source_note", ""),
                               entry.get("extras_block", "")),
                   reply_markup=page_keyboard(search_id, page, total_pages))
        await tg("answerCallbackQuery", {"callback_query_id": cb_id})
        _log_activity(user, "paginate", entry["query"], "page",
                      f"page {page + 1}/{total_pages}")
    except Exception as e:
        log.error(f"handle_callback fatal: {e!r}\n{traceback.format_exc()}")

# ══════════════════════════════════════════════════════════════════
# RE-EXPORTS — everything app.py and admin_panel.py need
# ══════════════════════════════════════════════════════════════════
__all__ = [
    "handle_message", "handle_callback", "is_duplicate_update", "cache_gc",
    "tg", "send", "edit", "send_document",
    "ACTIVITY_LOG", "UNIQUE_USERS", "ACTIVE_USERS", "BANNED_USERS",
    "BAN_REASONS", "MAINTENANCE_MODE", "SEARCH_CACHE", "STATS",
    "BACKUP_ENABLED", "USER_HISTORY", "USER_LAST", "PHONE_COUNTS",
    "_activity_lock", "_state_lock", "SEARCH_CACHE_LOCK",
    "_ban_user", "_unban_user",
    "_set_maintenance", "_get_maintenance",
    "_revoke_admin", "_is_admin_session", "_grant_admin",
    "_get_stats", "_get_live_users",
    "_short_user", "_fmt_ts", "_today_utc",
    "_log_activity", "_add_to_history",
    "_is_banned", "_is_unlimited",
    "check_quota", "incr_quota", "check_flood",
    "check_force_join",
    "_admin_state_get", "_admin_state_set", "_admin_state_clear",
    "_db_search_async", "_show_progressive", "_do_progressive_search",
    "page_keyboard", "WELCOME_TEMPLATE",
    "forward_to_backup", "_build_backup_payload",
    "_handle_batch", "_run_broadcast", "_send_log_export",
    "admin_menu_kb", "render_admin_menu", "render_live", "render_stats",
    "render_log", "render_users", "render_top", "render_banned",
]