File size: 95,769 Bytes
7226ab4
 
17b4d76
7226ab4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
const ConfigManager = require('./ConfigManager');
const PresenceSimulator = require('./PresenceSimulator');
const StickerViewOnceHandler = require('./StickerViewOnceHandler');
const MediaProcessor = require('./MediaProcessor');
const CybersecurityToolkit = require('./CybersecurityToolkit');
const OSINTFramework = require('./OSINTFramework');
const SubscriptionManager = require('./SubscriptionManager');
const SecurityLogger = require('./SecurityLogger');
const fs = require('fs');
const path = require('path');

/**
 * ═══════════════════════════════════════════════════════════════════════
 * COMMAND HANDLER - AKIRA BOT V21.02.2025
 * ═══════════════════════════════════════════════════════════════════════
 * ✅ Sistema completo de comandos com permissões por tier
 * ✅ Rate limiting inteligente e proteção contra abuso
 * ✅ Menus profissionais e formatados em ASCII art
 * ✅ Funcionalidades enterprise-grade
 * ✅ Logging de ações administrativas
 * ✅ Simulações realistas de presença (digitação, gravação, ticks)
 * ═══════════════════════════════════════════════════════════════════════
 */

// Sistema de rate limiting para features premium (1x a cada 3 meses para users)
const premiumFeatureUsage = new Map();

// Log de ações administrativas
const adminLog = new Map();

// PresenceSimulator será inicializado no construtor
let presenceSimulator = null;

class CommandHandler {
  constructor(botCore, sock = null) {
    this.bot = botCore;
    this.config = ConfigManager.getInstance();
    this.sock = sock;
    
    // Inicializa handlers de mídia
    if (sock) {
      this.stickerHandler = new StickerViewOnceHandler(sock, this.config);
      this.mediaProcessor = new MediaProcessor();
      console.log('✅ Handlers de mídia inicializados: StickerViewOnceHandler, MediaProcessor');
    }
    
    // Inicializa ferramentas de cybersecurity (ENTERPRISE)
    this.cybersecurityToolkit = new CybersecurityToolkit(sock, this.config);
    this.osintFramework = new OSINTFramework(this.config);
    this.subscriptionManager = new SubscriptionManager(this.config);
    this.securityLogger = new SecurityLogger(this.config);
    console.log('✅ Ferramentas ENTERPRISE inicializadas: CybersecurityToolkit, OSINTFramework, SubscriptionManager, SecurityLogger');
    
    // Inicializa PresenceSimulator se socket for fornecido
    if (sock) {
      presenceSimulator = new PresenceSimulator(sock);
      console.log('✅ PresenceSimulator inicializado para CommandHandler');
    }
  }

  /**
   * Inicializa o socket do Baileys (usado se não foi passado no construtor)
   */
  setSocket(sock) {
    this.sock = sock;
    
    // Inicializa handlers de mídia se ainda não foram
    if (!this.stickerHandler) {
      this.stickerHandler = new StickerViewOnceHandler(sock, this.config);
      this.mediaProcessor = new MediaProcessor();
      console.log('✅ Handlers de mídia inicializados via setSocket()');
    }
    
    if (!presenceSimulator && sock) {
      presenceSimulator = new PresenceSimulator(sock);
      console.log('✅ PresenceSimulator inicializado via setSocket()');
    }
  }

  /**
   * Simula digitação realista antes de responder a um comando
   */
  async simulateTyping(jid, text) {
    if (!presenceSimulator) return;
    const duration = presenceSimulator.calculateTypingDuration(text);
    await presenceSimulator.simulateTyping(jid, duration);
  }

  /**
   * Simula gravação de áudio antes de enviar áudio
   */
  async simulateRecording(jid, text) {
    if (!presenceSimulator) return;
    const duration = presenceSimulator.calculateRecordingDuration(text);
    await presenceSimulator.simulateRecording(jid, duration);
  }

  /**
   * Marca mensagem com ticks apropriados
   */
  async markMessageStatus(m, wasActivated = true) {
    if (!presenceSimulator) return;
    await presenceSimulator.simulateTicks(m, wasActivated);
  }

  /**
   * Verifica se usuário tem acesso a feature premium
   * Users comuns: 1x a cada 90 dias
   * Owners/Admins: Ilimitado
   */
  canUsePremiumFeature(userId, isOwner = false) {
    if (isOwner) return true; // Owners têm acesso ilimitado

    const now = new Date();
    const usage = premiumFeatureUsage.get(userId) || { 
      lastUse: 0, 
      count: 0, 
      resetDate: new Date(now.getTime() - 95 * 24 * 60 * 60 * 1000) // Garante reset
    };
    
    const threeMonthsInMs = 90 * 24 * 60 * 60 * 1000;
    const hasResetWindow = (now.getTime() - usage.resetDate.getTime()) >= threeMonthsInMs;
    
    if (hasResetWindow) {
      usage.count = 0;
      usage.resetDate = now;
    }
    
    const canUse = usage.count === 0;
    if (canUse) {
      usage.count = 1;
      usage.lastUse = now.getTime();
      premiumFeatureUsage.set(userId, usage);
    }
    
    return canUse;
  }

  /**
   * Log de ação administrativa
   */
  logAdminAction(userId, userName, action, target = null, details = '') {
    const timestamp = new Date().toISOString();
    const logEntry = `[${timestamp}] ${action} | User: ${userName} (${userId}) | Target: ${target || 'N/A'} | Details: ${details}`;
    
    console.log(`📋 [ADMIN LOG] ${logEntry}`);
    
    const logsPath = path.join(this.config.LOGS_FOLDER, 'admin_actions.log');
    try {
      fs.appendFileSync(logsPath, logEntry + '\n');
    } catch (e) {
      console.error('Erro ao registrar ação:', e);
    }
  }

  /**
   * Formato para separadores de menu
   */
  createMenuBar(char = '═', length = 54) {
    return char.repeat(length);
  }

  /**
   * Cria cabeçalho profissional de menu
   */
  createMenuHeader(emoji, title) {
    const maxLen = 50;
    const titleFormatted = title.length > maxLen ? title.substring(0, maxLen - 3) + '...' : title;
    return `╔${this.createMenuBar('═', 52)}
${emoji}  ${titleFormatted.padEnd(48)}
${this.createMenuBar('═', 52)}╝`;
  }

  /**
   * Cria seção de menu formatada
   */
  createMenuSection(emoji, title) {
    return `\n${this.createMenuBar()}
${emoji} ${title}
${this.createMenuBar()}`;
  }

  async handle(m, meta) {
    // meta: { nome, numeroReal, texto, replyInfo, ehGrupo }
    try {
      const { nome, numeroReal, texto, replyInfo, ehGrupo } = meta;
      const mp = this.bot.messageProcessor;
      const parsed = mp.parseCommand(texto);
      if (!parsed) return false;

      const senderId = numeroReal;
      const sock = this.bot.sock;

      // Helpers de permissão
      const isOwner = () => {
        try { return this.config.isDono(senderId, nome); } catch { return false; }
      };

      const ownerOnly = async (fn) => {
        if (!isOwner()) {
          await sock.sendMessage(m.key.remoteJid, { 
            text: '🚫 *COMANDO RESTRITO*\n\nApenas o proprietário (Isaac Quarenta) pode usar este comando.\n\n💡 Se deseja acesso a features premium, use #donate para apoiar o projeto!' 
          }, { quoted: m });
          return true;
        }
        return await fn();
      };

      const cmd = parsed.comando.toLowerCase();
      const args = parsed.args;
      const full = parsed.textoCompleto;

      // Rate limiting
      if (!mp.checkRateLimit(senderId)) {
        await sock.sendMessage(m.key.remoteJid, { 
          text: '⏰ *AGUARDE UM MOMENTO*\n\nVocê está usando comandos muito rápido. Por favor, aguarde alguns segundos.' 
        }, { quoted: m });
        return true;
      }

      // ═══════════════════════════════════════════════════════════════
      // COMANDOS PÚBLICOS
      // ═══════════════════════════════════════════════════════════════

      // PING - Testar latência
      if (cmd === 'ping') {
        const startTime = Date.now();
        const sentMsg = await sock.sendMessage(m.key.remoteJid, { 
          text: '🏓 Pong!' 
        }, { quoted: m });
        const latency = Date.now() - startTime;
        
        const uptime = process.uptime();
        const hours = Math.floor(uptime / 3600);
        const minutes = Math.floor((uptime % 3600) / 60);
        
        await sock.sendMessage(m.key.remoteJid, { 
          text: `📊 *LATÊNCIA E STATUS*

🏓 Latência: ${latency}ms
⏱️ Uptime: ${hours}h ${minutes}m
🤖 Bot: ${this.bot.sock.user ? '✅ Online' : '❌ Offline'}
📡 API: ${this.config.API_URL}` 
        });
        return true;
      }

      // INFO DO BOT
      if (cmd === 'info' || cmd === 'botinfo' || cmd === 'about') {
        const infoText = this.createMenuHeader('🤖', 'INFORMAÇÕES DO BOT') + `

*Nome:* Akira Bot V21.02.2025
*Desenvolvedor:* Isaac Quarenta
*País:* 🇦🇴 Luanda, Angola

${this.createMenuSection('⚙️', 'CONFIGURAÇÃO TÉCNICA')}
*Número:* ${this.config.BOT_NUMERO_REAL}
*Prefixo:* ${this.config.PREFIXO}
*Status:* ${this.bot.sock.user ? '✅ Online' : '❌ Offline'}
*Uptime:* ${Math.floor(process.uptime())}s
*API:* Hugging Face

${this.createMenuSection('✨', 'RECURSOS IMPLEMENTADOS')}
✅ IA Conversacional (GPT-like)
✅ Áudio Inteligente (STT + TTS)
✅ Criação de Stickers
✅ Download de Áudio YouTube
✅ Sistema de Níveis e XP
✅ Moderação Avançada
✅ Anti-link automático
✅ Sistema de Mute progressivo
✅ Logging de ações
✅ Rate limiting por usuário

${this.createMenuSection('🎤', 'SERVIÇOS DE ÁUDIO')}
*STT:* Deepgram (nova-2) - 200h/mês gratuito
*TTS:* Google Text-to-Speech - Ilimitado
*Idiomas Suportados:* Português, Inglês, Espanhol, Francês, +15 idiomas

${this.createMenuSection('🔐', 'SEGURANÇA')}
🛡️ Validação de usuários
🔒 Encriptação de dados
⏱️ Rate limiting inteligente
🚫 Bloqueio de spam
📋 Logging completo de ações

${this.createMenuSection('💡', 'COMANDOS RÁPIDOS')}
#menu - Ver todos os comandos
#help - Ajuda sobre comandos
#donate - Apoiar o projeto
#stats - Ver estatísticas

*Desenvolvido com ❤️ por Isaac Quarenta*
_Versão v21.02.2025 - Enterprise Grade_`;

        await sock.sendMessage(m.key.remoteJid, { text: infoText }, { quoted: m });
        return true;
      }

      // MENU / HELP
      if (cmd === 'help' || cmd === 'menu' || cmd === 'comandos' || cmd === 'ajuda') {
        const menuText = this.createMenuHeader('🤖', 'MENU COMPLETO - AKIRA BOT V21') + `

${this.createMenuSection('🎨', 'MÍDIA E CRIATIVIDADE')}
*#sticker* - Criar sticker de imagem
*#s* ou *#fig* - Aliases para sticker
*#gif* - Criar sticker animado (máx 30s)
*#toimg* - Converter sticker para imagem
*#play <nome/link>* - Baixar áudio do YouTube
*#tts <idioma> <texto>* - Converter texto em voz
*#ping* - Testar latência do bot

${this.createMenuSection('🎤', 'ÁUDIO INTELIGENTE')}
Envie mensagens de voz e eu respondo automaticamente!
• Em PV: Respondo qualquer áudio
• Em grupos: Mencione "Akira" ou responda ao meu áudio
• Transcrição interna (nunca mostrada)
• Resposta automática em áudio

${this.createMenuSection('👥', 'PERFIL E REGISTRO')}
*#perfil* - Ver seu perfil e estatísticas
*#info* - Informações pessoais
*#registrar Nome|Idade* - Registrar no bot
*#level* - Ver seu nível e progresso XP
*#stats* - Suas estatísticas completas

${this.createMenuSection('⚙️', 'COMANDOS DE GRUPO (Dono)')}
*#add <número>* - Adicionar membro
*#remove @membro* - Remover membro
*#ban @membro* - Banir membro
*#promote @membro* - Dar admin
*#demote @membro* - Remover admin
*#mute @usuário* - Mutar por 5 min (progressivo)
*#desmute @usuário* - Desmutar
*#warn @usuário* - Dar aviso
*#clearwarn @usuário* - Remover avisos

${this.createMenuSection('🛡️', 'MODERAÇÃO E PROTEÇÃO')}
*#antilink on* - Ativar anti-link automático
*#antilink off* - Desativar anti-link
*#antilink status* - Ver status
*#level on* - Ativar sistema de níveis
*#level off* - Desativar sistema de níveis
*#apagar* - Apagar mensagem (responda a ela)

${this.createMenuSection('💬', 'CONVERSA NORMAL')}
Apenas mencione "Akira" em grupos ou responda minhas mensagens
Em PV, converse naturalmente - sempre online!

${this.createMenuSection('⚠️', 'INFORMAÇÕES IMPORTANTES')}
🔐 Comandos de grupo: Apenas proprietário
📊 Sistema de XP: Ganha automaticamente ao conversar
🏆 Leveling: Suba de nível conversando
🎁 Rewards: Conquiste badges e prêmios
🛡️ Proteção: Anti-spam, anti-link, anti-abuse

${this.createMenuSection('❤️', 'APOIAR O PROJETO')}
*#donate* - Ver formas de apoio
Seu apoio ajuda a manter o bot online e com novas features!

*Desenvolvido com ❤️ por Isaac Quarenta*
_Versão v21.02.2025 - Enterprise Grade_`;

        await sock.sendMessage(m.key.remoteJid, { text: menuText }, { quoted: m });
        return true;
      }

      // DONATE
      if (cmd === 'donate' || cmd === 'doar' || cmd === 'apoia' || cmd === 'doacao' || cmd === 'apoiar') {
        const donateText = this.createMenuHeader('❤️', 'APOIE O PROJETO AKIRA BOT') + `

${this.createMenuSection('🙏', 'POR QUE APOIAR?')}
✅ Mantém o bot online 24/7
✅ Desenvolvimento de novas features
✅ Manutenção de servidores
✅ Melhorias de performance
✅ Suporte prioritário
✅ Acesso a recursos premium

${this.createMenuSection('💰', 'FORMAS DE APOIO')}

*🔑 PIX (INSTANTÂNEO)*
E-mail: akira.bot.dev@gmail.com
Chave: akira.bot.dev@gmail.com
CPF: Disponível em contato direto

*☕ COMPRE UM CAFÉ (Ko-fi)*
https://ko-fi.com/isaacquarenta
Pague quanto quiser, quanto puder

*💳 PAYPAL*
https://paypal.me/isaacquarenta
Internacional e seguro

*🎁 VALORES SUGERIDOS*
R$ 5 - Mantém 1 dia online + Agradecimento especial
R$ 20 - 1 semana online + Suporte prioritário
R$ 50 - 1 mês online + Acesso a features premium
R$ 100+ - 1 mês + Desenvolvimento customizado

${this.createMenuSection('🎉', 'BENEFÍCIOS DO APOIADOR')}
✨ Seu nome em parede de honra
✨ Badge especial "Apoiador" no bot
✨ Acesso a features beta primeiro
✨ Suporte técnico direto (WhatsApp)
✨ Customizações personalizadas
✨ Renovação automática de benefícios

${this.createMenuSection('📊', 'IMPACTO DA SUA DOAÇÃO')}
💵 R$ 5 = 1 dia online para todos os usuários
💵 R$ 20 = 1 semana de operação contínua
💵 R$ 50 = 1 mês de servidor + 1 feature nova
💵 R$ 100+ = 3 meses de operação + desenvolvimento customizado

${this.createMenuSection('📲', 'CONTATO')}
WhatsApp: +244 937 035 662
Email: isaac.quarenta@akira.bot
Discord: [Disponível em breve]

*Obrigado por apoiar um projeto feito com ❤️ paixão!*
_Cada real faz diferença no desenvolvimento do Akira Bot_

🚀 Desenvolvido com ❤️ por Isaac Quarenta`;

        await sock.sendMessage(m.key.remoteJid, { text: donateText }, { quoted: m });
        return true;
      }

      // ═══════════════════════════════════════════════════════════════
      // COMANDOS DE MANUTENÇÃO DE PERFIL
      // ═══════════════════════════════════════════════════════════════

      if (cmd === 'perfil' || cmd === 'profile' || cmd === 'myperfil') {
        try {
          const uid = m.key.participant || m.key.remoteJid;
          const dbFolder = path.join(this.config.DATABASE_FOLDER, 'datauser');
          const regPath = path.join(dbFolder, 'registered.json');
          
          let userData = { name: 'Não registrado', age: '?', registeredAt: 'N/A' };
          
          if (fs.existsSync(regPath)) {
            const registered = JSON.parse(fs.readFileSync(regPath, 'utf8') || '[]');
            const user = registered.find(u => u.id === uid);
            if (user) {
              userData = user;
            }
          }

          let levelRecord = null;
          if (this.bot.levelSystem && this.bot.levelSystem.getGroupRecord) {
            levelRecord = this.bot.levelSystem.getGroupRecord(m.key.remoteJid, uid, true);
          }
          const level = (levelRecord && levelRecord.level) ? levelRecord.level : 0;
          const xp = (levelRecord && levelRecord.xp) ? levelRecord.xp : 0;
          let nextLevelXp = 1000;
          if (this.bot.levelSystem && this.bot.levelSystem.requiredXp) {
            nextLevelXp = this.bot.levelSystem.requiredXp(level + 1) || 1000;
          }
          const progressPct = Math.min(100, Math.floor((xp / nextLevelXp) * 100));

          const profileText = this.createMenuHeader('👤', 'SEU PERFIL') + `

${this.createMenuSection('📝', 'INFORMAÇÕES PESSOAIS')}
*Nome:* ${userData.name || 'Desconhecido'}
*Idade:* ${userData.age || '?'} anos
*JID:* ${uid}
*Registrado em:* ${userData.registeredAt || 'Nunca'}

${this.createMenuSection('🎮', 'ESTATÍSTICAS DE JOGO')}
*Nível:* ${level}
*Experiência (XP):* ${xp}
*Próximo nível:* ${nextLevelXp}
*Progresso:* ${'█'.repeat(Math.floor(progressPct / 10))}${'░'.repeat(10 - Math.floor(progressPct / 10))} ${progressPct}%

${this.createMenuSection('🏆', 'CONQUISTAS')}
${level >= 5 ? '✅ Bronze - Nível 5' : '⬜ Bronze - Nível 5'}
${level >= 10 ? '✅ Prata - Nível 10' : '⬜ Prata - Nível 10'}
${level >= 25 ? '✅ Ouro - Nível 25' : '⬜ Ouro - Nível 25'}
${level >= 50 ? '✅ Platina - Nível 50' : '⬜ Platina - Nível 50'}
${level >= 100 ? '✅ Diamante - Nível 100' : '⬜ Diamante - Nível 100'}

${this.createMenuSection('💡', 'DICAS PARA SUBIR')}
💬 Converse naturalmente para ganhar XP
🎤 Responda áudios e converse
🏆 Participe de desafios
💰 Apoie o projeto e ganhe bônus

Quer registrar seu perfil? Use: #registrar Nome|Idade`;

          await sock.sendMessage(m.key.remoteJid, { text: profileText }, { quoted: m });
        } catch (e) {
          console.error('Erro em perfil:', e);
        }
        return true;
      }

      if (cmd === 'registrar' || cmd === 'register' || cmd === 'reg') {
        try {
          const dbFolder = path.join(this.config.DATABASE_FOLDER, 'datauser');
          if (!fs.existsSync(dbFolder)) fs.mkdirSync(dbFolder, { recursive: true });
          const regPath = path.join(dbFolder, 'registered.json');
          if (!fs.existsSync(regPath)) fs.writeFileSync(regPath, JSON.stringify([], null, 2));

          if (!full || !full.includes('|')) {
            await sock.sendMessage(m.key.remoteJid, { 
              text: '📝 *COMO REGISTRAR*\n\nUso: `#registrar Nome|Idade`\n\nExemplo:\n`#registrar Isaac Quarenta|25`' 
            }, { quoted: m });
            return true;
          }

          const [nomeUser, idadeStr] = full.split('|').map(s => s.trim());
          const idade = parseInt(idadeStr, 10);

          if (!nomeUser || isNaN(idade) || idade < 1 || idade > 120) {
            await sock.sendMessage(m.key.remoteJid, { 
              text: '❌ Formato inválido! Nome válido e idade entre 1-120.' 
            }, { quoted: m });
            return true;
          }

          const registered = JSON.parse(fs.readFileSync(regPath, 'utf8') || '[]');
          const senderJid = m.key.participant || m.key.remoteJid;

          if (registered.find(u => u.id === senderJid)) {
            await sock.sendMessage(m.key.remoteJid, { 
              text: '✅ Você já está registrado!\n\nUse #perfil para ver suas informações.' 
            }, { quoted: m });
            return true;
          }

          const serial = (Date.now().toString(36) + Math.random().toString(36).slice(2, 10)).toUpperCase();
          registered.push({
            id: senderJid,
            name: nomeUser,
            age: idade,
            time: new Date().toISOString(),
            serial,
            registeredAt: new Date().toLocaleDateString('pt-BR')
          });

          fs.writeFileSync(regPath, JSON.stringify(registered, null, 2));

          // Garante que existe registro de níveis
          if (this.bot.levelSystem) {
            this.bot.levelSystem.getGroupRecord(m.key.remoteJid, senderJid, true);
          }

          await sock.sendMessage(m.key.remoteJid, { 
            text: `✅ *REGISTRO COMPLETO!*

*Bem-vindo ${nomeUser}!*

🎮 Seu ID: ${serial}
📅 Registrado em: ${new Date().toLocaleDateString('pt-BR')}
🏆 Nível inicial: 1
⭐ XP inicial: 0

Agora você pode usar #perfil para ver suas estatísticas!
Ganhe XP conversando naturalmente com o bot.` 
          }, { quoted: m });
        } catch (e) {
          console.error('Erro em registrar:', e);
          await sock.sendMessage(m.key.remoteJid, { text: '❌ Erro ao registrar.' }, { quoted: m });
        }
        return true;
      }

      if (cmd === 'level' || cmd === 'nivel' || cmd === 'rank') {
        try {
          const gid = m.key.remoteJid;
          const isGroup = String(gid).endsWith('@g.us');

          if (!isGroup) {
            await sock.sendMessage(gid, { 
              text: '📵 Sistema de level funciona apenas em grupos.' 
            }, { quoted: m });
            return true;
          }

          const sub = (args[0] || '').toLowerCase();

          if (['on', 'off', 'status'].includes(sub)) {
            return await ownerOnly(async () => {
              // Toggle leveling system
              const togglesPath = path.join(this.config.DATABASE_FOLDER, 'group_settings.json');
              let toggles = {};

              if (fs.existsSync(togglesPath)) {
                toggles = JSON.parse(fs.readFileSync(togglesPath, 'utf8') || '{}');
              }

              if (sub === 'on') {
                toggles[gid] = { levelingEnabled: true };
                fs.writeFileSync(togglesPath, JSON.stringify(toggles, null, 2));
                this.logAdminAction(senderId, nome, 'LEVEL_ON', gid, 'Sistema de níveis ativado');
                await sock.sendMessage(gid, { 
                  text: '✅ *SISTEMA DE LEVEL ATIVADO!*\n\nOs membros agora ganham XP ao conversar e sobem de nível!' 
                }, { quoted: m });
              } else if (sub === 'off') {
                if (toggles[gid]) delete toggles[gid].levelingEnabled;
                fs.writeFileSync(togglesPath, JSON.stringify(toggles, null, 2));
                this.logAdminAction(senderId, nome, 'LEVEL_OFF', gid, 'Sistema de níveis desativado');
                await sock.sendMessage(gid, { 
                  text: '🚫 *SISTEMA DE LEVEL DESATIVADO!*\n\nOs membros não ganham mais XP.' 
                }, { quoted: m });
              } else {
                const isEnabled = (toggles[gid] && toggles[gid].levelingEnabled) ? toggles[gid].levelingEnabled : false;
                await sock.sendMessage(gid, { 
                  text: `📊 *STATUS DO LEVEL:* ${isEnabled ? '✅ ATIVADO' : '❌ DESATIVADO'}` 
                }, { quoted: m });
              }
              return true;
            });
          }

          // Mostrar level do usuário
          const uid = m.key.participant || m.key.remoteJid;
          let rec = { level: 0, xp: 0 };
          if (this.bot.levelSystem && this.bot.levelSystem.getGroupRecord) {
            rec = this.bot.levelSystem.getGroupRecord(gid, uid, true) || { level: 0, xp: 0 };
          }
          let nextReq = 1000;
          if (this.bot.levelSystem && this.bot.levelSystem.requiredXp) {
            nextReq = this.bot.levelSystem.requiredXp(rec.level + 1) || 1000;
          }
          const pct = Math.min(100, Math.floor((rec.xp / nextReq) * 100));

          const levelText = `🎉 *SEU NÍVEL NO GRUPO*

📊 Nível: ${rec.level}
⭐ XP: ${rec.xp}/${nextReq}
📈 Progresso: ${'█'.repeat(Math.floor(pct / 10))}${'░'.repeat(10 - Math.floor(pct / 10))} ${pct}%

💡 Ganhe XP conversando naturalmente no grupo!`;

          await sock.sendMessage(gid, { text: levelText }, { quoted: m });
        } catch (e) {
          console.error('Erro em level:', e);
        }
        return true;
      }

      // ═══════════════════════════════════════════════════════════════
      // COMANDOS DE MODERAÇÃO (DONO APENAS)
      // ═══════════════════════════════════════════════════════════════

      if (cmd === 'add') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, { text: '❌ Este comando funciona apenas em grupos.' }, { quoted: m });
              return true;
            }

            const numero = args[0];
            if (!numero) {
              await sock.sendMessage(m.key.remoteJid, { text: '📱 Uso: #add 244123456789' }, { quoted: m });
              return true;
            }

            const jid = `${numero.replace(/\D/g, '')}@s.whatsapp.net`;
            await sock.groupParticipantsUpdate(m.key.remoteJid, [jid], 'add');
            this.logAdminAction(senderId, nome, 'ADD_MEMBER', numero, `Adicionado ao grupo ${m.key.remoteJid}`);
            await sock.sendMessage(m.key.remoteJid, { 
              text: `✅ ${numero} foi adicionado ao grupo com sucesso!` 
            }, { quoted: m });
          } catch (e) {
            console.error('Erro ao adicionar:', e);
            await sock.sendMessage(m.key.remoteJid, { 
              text: '❌ Erro ao adicionar. Verifique se sou admin.' 
            }, { quoted: m });
          }
          return true;
        });
      }

      if (cmd === 'remove' || cmd === 'kick' || cmd === 'ban') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, { text: '❌ Este comando funciona apenas em grupos.' }, { quoted: m });
              return true;
            }

            let targets = [];
            if (m.message && m.message.extendedTextMessage && m.message.extendedTextMessage.contextInfo && m.message.extendedTextMessage.contextInfo.mentionedJid) {
              targets = m.message.extendedTextMessage.contextInfo.mentionedJid || [];
            }
            if (!targets.length && replyInfo && replyInfo.participantJidCitado) {
              targets = [replyInfo.participantJidCitado];
            }

            if (!targets.length) {
              await sock.sendMessage(m.key.remoteJid, { 
                text: '❌ Marque (@) o membro ou responda mensagem dele com #remove' 
              }, { quoted: m });
              return true;
            }

            await sock.groupParticipantsUpdate(m.key.remoteJid, targets, 'remove');
            this.logAdminAction(senderId, nome, 'REMOVE_MEMBERS', targets.length + ' membros', m.key.remoteJid);
            await sock.sendMessage(m.key.remoteJid, { 
              text: `✅ ${targets.length} membro(s) removido(s) do grupo.` 
            }, { quoted: m });
          } catch (e) {
            console.error('Erro ao remover:', e);
            await sock.sendMessage(m.key.remoteJid, { 
              text: '❌ Erro ao remover. Verifique permissões.' 
            }, { quoted: m });
          }
          return true;
        });
      }

      if (cmd === 'promote') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, { text: '❌ Este comando funciona apenas em grupos.' }, { quoted: m });
              return true;
            }

            let targets = [];
            if (m.message && m.message.extendedTextMessage && m.message.extendedTextMessage.contextInfo && m.message.extendedTextMessage.contextInfo.mentionedJid) {
              targets = m.message.extendedTextMessage.contextInfo.mentionedJid || [];
            }
            if (!targets.length && replyInfo && replyInfo.participantJidCitado) {
              targets = [replyInfo.participantJidCitado];
            }

            if (!targets.length) {
              await sock.sendMessage(m.key.remoteJid, { 
                text: '❌ Marque (@) o membro ou responda mensagem dele com #promote' 
              }, { quoted: m });
              return true;
            }

            await sock.groupParticipantsUpdate(m.key.remoteJid, targets, 'promote');
            this.logAdminAction(senderId, nome, 'PROMOTE_MEMBERS', targets.length + ' membros', m.key.remoteJid);
            await sock.sendMessage(m.key.remoteJid, { 
              text: `✅ ${targets.length} membro(s) promovido(s) a admin.` 
            }, { quoted: m });
          } catch (e) {
            console.error('Erro ao promover:', e);
            await sock.sendMessage(m.key.remoteJid, { 
              text: '❌ Erro ao promover. Verifique permissões.' 
            }, { quoted: m });
          }
          return true;
        });
      }

      if (cmd === 'demote') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, { text: '❌ Este comando funciona apenas em grupos.' }, { quoted: m });
              return true;
            }

            let targets = [];
            if (m.message && m.message.extendedTextMessage && m.message.extendedTextMessage.contextInfo && m.message.extendedTextMessage.contextInfo.mentionedJid) {
              targets = m.message.extendedTextMessage.contextInfo.mentionedJid || [];
            }
            if (!targets.length && replyInfo && replyInfo.participantJidCitado) {
              targets = [replyInfo.participantJidCitado];
            }

            if (!targets.length) {
              await sock.sendMessage(m.key.remoteJid, { 
                text: '❌ Marque (@) o admin ou responda mensagem dele com #demote' 
              }, { quoted: m });
              return true;
            }

            await sock.groupParticipantsUpdate(m.key.remoteJid, targets, 'demote');
            this.logAdminAction(senderId, nome, 'DEMOTE_MEMBERS', targets.length + ' membros', m.key.remoteJid);
            await sock.sendMessage(m.key.remoteJid, { 
              text: `✅ ${targets.length} admin(s) rebaixado(s).` 
            }, { quoted: m });
          } catch (e) {
            console.error('Erro ao rebaixar:', e);
            await sock.sendMessage(m.key.remoteJid, { 
              text: '❌ Erro ao rebaixar. Verifique permissões.' 
            }, { quoted: m });
          }
          return true;
        });
      }

      if (cmd === 'mute') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, { text: '❌ Este comando funciona apenas em grupos.' }, { quoted: m });
              return true;
            }

            let target = null;
            let mentions = [];
            if (m.message && m.message.extendedTextMessage && m.message.extendedTextMessage.contextInfo && m.message.extendedTextMessage.contextInfo.mentionedJid) {
              mentions = m.message.extendedTextMessage.contextInfo.mentionedJid || [];
            }
            if (mentions.length) target = mentions[0];
            else if (replyInfo && replyInfo.participantJidCitado) target = replyInfo.participantJidCitado;

            if (!target) {
              await sock.sendMessage(m.key.remoteJid, { 
                text: '❌ Marque (@) o membro ou responda mensagem dele com #mute' 
              }, { quoted: m });
              return true;
            }

            let muteResult = { minutes: 5, muteCount: 1 };
            if (this.bot.moderationSystem && this.bot.moderationSystem.muteUser) {
              muteResult = this.bot.moderationSystem.muteUser(m.key.remoteJid, target, 5) || { minutes: 5, muteCount: 1 };
            }
            this.logAdminAction(senderId, nome, 'MUTE_USER', target, `${muteResult.minutes} minutos`);

            const expiryTime = new Date(Date.now() + muteResult.minutes * 60 * 1000).toLocaleTimeString('pt-BR');
            let msg = `🔇 *USUÁRIO MUTADO!*\n\n⏱️ Duração: ${muteResult.minutes} minutos\n⏰ Expira em: ${expiryTime}`;
            if (muteResult.muteCount > 1) {
              msg += `\n\n⚠️ ALERTA: Este usuário já foi mutado ${muteResult.muteCount} vezes hoje!`;
            }

            await sock.sendMessage(m.key.remoteJid, { text: msg }, { quoted: m });
          } catch (e) {
            console.error('Erro em mute:', e);
          }
          return true;
        });
      }

      if (cmd === 'desmute') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, { text: '❌ Este comando funciona apenas em grupos.' }, { quoted: m });
              return true;
            }

            let target = null;
            let mentions = [];
            if (m.message && m.message.extendedTextMessage && m.message.extendedTextMessage.contextInfo && m.message.extendedTextMessage.contextInfo.mentionedJid) {
              mentions = m.message.extendedTextMessage.contextInfo.mentionedJid || [];
            }
            if (mentions.length) target = mentions[0];
            else if (replyInfo && replyInfo.participantJidCitado) target = replyInfo.participantJidCitado;

            if (!target) {
              await sock.sendMessage(m.key.remoteJid, { 
                text: '❌ Marque (@) o membro ou responda mensagem dele com #desmute' 
              }, { quoted: m });
              return true;
            }

            if (this.bot.moderationSystem && this.bot.moderationSystem.unmuteUser) {
              this.bot.moderationSystem.unmuteUser(m.key.remoteJid, target);
            }
            this.logAdminAction(senderId, nome, 'UNMUTE_USER', target, 'Mutação removida');
            await sock.sendMessage(m.key.remoteJid, { 
              text: '🔊 *USUÁRIO DESMUTADO!*\n\nEle agora pode enviar mensagens novamente.' 
            }, { quoted: m });
          } catch (e) {
            console.error('Erro em desmute:', e);
          }
          return true;
        });
      }

      if (cmd === 'antilink') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, { text: '❌ Este comando funciona apenas em grupos.' }, { quoted: m });
              return true;
            }

            const sub = (args[0] || '').toLowerCase();
            const gid = m.key.remoteJid;

            if (sub === 'on') {
              if (this.bot.moderationSystem && this.bot.moderationSystem.toggleAntiLink) {
                this.bot.moderationSystem.toggleAntiLink(gid, true);
              }
              this.logAdminAction(senderId, nome, 'ANTILINK_ON', gid, 'Anti-link ativado');
              await sock.sendMessage(gid, { 
                text: '🔒 *ANTI-LINK ATIVADO!*\n\n⚠️ Qualquer membro que enviar link será removido automaticamente.' 
              }, { quoted: m });
            } else if (sub === 'off') {
              if (this.bot.moderationSystem && this.bot.moderationSystem.toggleAntiLink) {
                this.bot.moderationSystem.toggleAntiLink(gid, false);
              }
              this.logAdminAction(senderId, nome, 'ANTILINK_OFF', gid, 'Anti-link desativado');
              await sock.sendMessage(gid, { 
                text: '🔓 *ANTI-LINK DESATIVADO!*\n\n✅ Membros podem enviar links normalmente.' 
              }, { quoted: m });
            } else {
              let isActive = false;
              if (this.bot.moderationSystem && this.bot.moderationSystem.isAntiLinkActive) {
                isActive = this.bot.moderationSystem.isAntiLinkActive(gid) || false;
              }
              await sock.sendMessage(gid, { 
                text: `📊 *STATUS ANTI-LINK:* ${isActive ? '🟢 ATIVADO' : '🔴 DESATIVADO'}` 
              }, { quoted: m });
            }
            return true;
          } catch (e) {
            console.error('Erro em antilink:', e);
          }
          return true;
        });
      }

      // ═══════════════════════════════════════════════════════════════
      // COMANDOS DE MÍDIA - STICKER, GIF, TOIMG, PLAY, TTS
      // ═══════════════════════════════════════════════════════════════

      // #STICKER / #S / #FIG
      if (cmd === 'sticker' || cmd === 's' || cmd === 'fig') {
        try {
          if (!this.stickerHandler) {
            await sock.sendMessage(m.key.remoteJid, { 
              text: '❌ Handler de sticker não inicializado.' 
            }, { quoted: m });
            return true;
          }
          return await this.stickerHandler.handleSticker(m, userData, full, ehGrupo);
        } catch (e) {
          console.error('Erro em sticker:', e);
          await sock.sendMessage(m.key.remoteJid, { 
            text: '❌ Erro ao processar sticker.' 
          }, { quoted: m });
          return true;
        }
      }

      // #GIF
      if (cmd === 'gif') {
        try {
          if (!this.stickerHandler) {
            await sock.sendMessage(m.key.remoteJid, { 
              text: '❌ Handler de sticker não inicializado.' 
            }, { quoted: m });
            return true;
          }
          return await this.stickerHandler.handleGif(m, userData, full, ehGrupo);
        } catch (e) {
          console.error('Erro em gif:', e);
          await sock.sendMessage(m.key.remoteJid, { 
            text: '❌ Erro ao criar sticker animado.' 
          }, { quoted: m });
          return true;
        }
      }

      // #TOIMG
      if (cmd === 'toimg') {
        try {
          if (!this.stickerHandler) {
            await sock.sendMessage(m.key.remoteJid, { 
              text: '❌ Handler de sticker não inicializado.' 
            }, { quoted: m });
            return true;
          }
          return await this.stickerHandler.handleToImage(m, userData, full, ehGrupo);
        } catch (e) {
          console.error('Erro em toimg:', e);
          await sock.sendMessage(m.key.remoteJid, { 
            text: '❌ Erro ao converter sticker para imagem.' 
          }, { quoted: m });
          return true;
        }
      }

      // #PLAY - Download de áudio YouTube
      if (cmd === 'play') {
        try {
          if (!full) {
            await sock.sendMessage(m.key.remoteJid, {
              text: '🎵 *COMANDO #play*\n\n' +
                    '✅ Use: `#play <nome da música ou link>`\n' +
                    '✅ Exemplos:\n' +
                    '   #play Imagine John Lennon\n' +
                    '   #play https://youtu.be/...\n\n' +
                    '⏱️ Máximo: 1 hora\n' +
                    '📊 Formato: MP3\n' +
                    '✨ Baixado diretamente do YouTube'
            }, { quoted: m });
            return true;
          }

          await sock.sendMessage(m.key.remoteJid, {
            text: '⏳ Processando sua requisição... Isto pode levar alguns segundos.'
          }, { quoted: m });

          // Verifica se é URL ou nome
          let url = full;
          if (!this.mediaProcessor.isValidYouTubeUrl(full)) {
            // Tenta buscar o vídeo pelo nome
            await sock.sendMessage(m.key.remoteJid, {
              text: '🔍 Buscando no YouTube...'
            }, { quoted: m });

            const searchResult = await this.mediaProcessor.searchYouTube(full, 1);
            if (!searchResult.sucesso || !searchResult.resultados || searchResult.resultados.length === 0) {
              await sock.sendMessage(m.key.remoteJid, {
                text: `❌ Nenhuma música encontrada para: "${full}"`
              }, { quoted: m });
              return true;
            }
            url = searchResult.resultados[0].url;
          }

          // Download do áudio
          const downloadResult = await this.mediaProcessor.downloadYouTubeAudio(url);
          if (!downloadResult.sucesso) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ Erro ao baixar: ${downloadResult.error}`
            }, { quoted: m });
            return true;
          }

          // Simula gravação
          await this.simulateRecording(m.key.remoteJid, downloadResult.titulo);

          // Envia áudio
          await sock.sendMessage(m.key.remoteJid, {
            audio: downloadResult.buffer,
            mimetype: 'audio/mpeg',
            ptt: false
          }, { quoted: m });

          // Mensagem de sucesso
          await sock.sendMessage(m.key.remoteJid, {
            text: `✅ *ÁUDIO ENVIADO COM SUCESSO!*\n\n` +
                  `🎵 Título: ${downloadResult.titulo}\n` +
                  `💾 Tamanho: ${(downloadResult.tamanho / 1024 / 1024).toFixed(2)}MB\n` +
                  `🔧 Método: ${downloadResult.metodo}`
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em play:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao baixar áudio do YouTube.'
          }, { quoted: m });
          return true;
        }
      }

      // #TTS - Text To Speech (Google)
      if (cmd === 'tts') {
        try {
          // Formato: #tts <idioma> <texto>
          // Exemplo: #tts pt Olá mundo
          const parts = full.split(' ');
          
          if (parts.length < 2) {
            await sock.sendMessage(m.key.remoteJid, {
              text: '🎤 *COMANDO #tts (Text-To-Speech)*\n\n' +
                    '✅ Use: `#tts <idioma> <texto>`\n\n' +
                    '📝 Exemplos:\n' +
                    '   #tts pt Olá, como você está?\n' +
                    '   #tts en Hello world\n' +
                    '   #tts es Hola mundo\n' +
                    '   #tts fr Bonjour le monde\n\n' +
                    '🌍 Idiomas suportados:\n' +
                    '   pt (Português) | en (Inglês) | es (Espanhol)\n' +
                    '   fr (Francês) | de (Alemão) | it (Italiano)\n' +
                    '   ja (Japonês) | zh (Chinês) | ko (Coreano)\n' +
                    '   ru (Russo) | ar (Árabe) | hi (Hindi)'
            }, { quoted: m });
            return true;
          }

          const languageCode = parts[0].toLowerCase();
          const textToSpeak = parts.slice(1).join(' ');

          await sock.sendMessage(m.key.remoteJid, {
            text: '🎙️ Gerando áudio...'
          }, { quoted: m });

          // Usa gTTS (Google TTS) - precisa estar instalado
          let audioBuffer = null;
          try {
            const gTTS = require('gtts');
            const gtts = new gTTS.gTTS(textToSpeak, { lang: languageCode, slow: false });
            
            // Salva em buffer
            const tempFile = path.join(this.config.TEMP_FOLDER, `tts-${Date.now()}.mp3`);
            await new Promise((resolve, reject) => {
              gtts.save(tempFile, (err) => {
                if (err) reject(err);
                else resolve();
              });
            });

            audioBuffer = fs.readFileSync(tempFile);
            fs.unlinkSync(tempFile); // Remove arquivo temporário
          } catch (gttsError) {
            console.warn('⚠️ gtts falhou, tentando método alternativo...');
            // Se gtts falhar, usa uma resposta manual
            await sock.sendMessage(m.key.remoteJid, {
              text: `⚠️ Erro ao gerar áudio TTS.\n\n` +
                    `Certifique-se de ter "gtts" instalado:\n` +
                    `npm install gtts`
            }, { quoted: m });
            return true;
          }

          if (!audioBuffer) {
            await sock.sendMessage(m.key.remoteJid, {
              text: '❌ Erro ao gerar áudio.'
            }, { quoted: m });
            return true;
          }

          // Simula gravação
          await this.simulateRecording(m.key.remoteJid, textToSpeak);

          // Envia áudio
          await sock.sendMessage(m.key.remoteJid, {
            audio: audioBuffer,
            mimetype: 'audio/mpeg',
            ptt: true
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em tts:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao gerar áudio de texto.'
          }, { quoted: m });
          return true;
        }
      }

      // ═══════════════════════════════════════════════════════════════
      // COMANDOS DE PROTEÇÃO - WARN, CLEARWARN, APAGAR
      // ═══════════════════════════════════════════════════════════════

      // #WARN - Dar aviso a usuário
      if (cmd === 'warn') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, {
                text: '❌ Este comando funciona apenas em grupos.'
              }, { quoted: m });
              return true;
            }

            let target = null;
            let mentions = [];
            if (m.message && m.message.extendedTextMessage && m.message.extendedTextMessage.contextInfo && m.message.extendedTextMessage.contextInfo.mentionedJid) {
              mentions = m.message.extendedTextMessage.contextInfo.mentionedJid || [];
            }
            if (mentions.length) target = mentions[0];
            else if (replyInfo && replyInfo.participantJidCitado) target = replyInfo.participantJidCitado;

            if (!target) {
              await sock.sendMessage(m.key.remoteJid, {
                text: '❌ Marque (@) o membro ou responda mensagem dele com #warn'
              }, { quoted: m });
              return true;
            }

            // Sistema de avisos (em memória para este exemplo)
            if (!this.bot.warnSystem) {
              this.bot.warnSystem = new Map();
            }

            const key = `${m.key.remoteJid}_${target}`;
            const warns = (this.bot.warnSystem.get(key) || 0) + 1;
            this.bot.warnSystem.set(key, warns);

            this.logAdminAction(senderId, nome, 'WARN_USER', target, `Avisos: ${warns}`);

            const msg = `⚠️ *USUÁRIO ADVERTIDO!*\n\n` +
                       `👤 Usuário marcado\n` +
                       `🚨 Avisos: ${warns}/3\n`;

            if (warns >= 3) {
              await sock.groupParticipantsUpdate(m.key.remoteJid, [target], 'remove');
              await sock.sendMessage(m.key.remoteJid, {
                text: msg + `\n❌ REMOVIDO DO GRUPO! (Atingiu 3 avisos)`
              }, { quoted: m });
              this.bot.warnSystem.delete(key);
            } else {
              await sock.sendMessage(m.key.remoteJid, {
                text: msg + `\n⏳ Avisos expiram em 24 horas`
              }, { quoted: m });
            }

            return true;
          } catch (e) {
            console.error('Erro em warn:', e);
          }
          return true;
        });
      }

      // #CLEARWARN - Remover avisos
      if (cmd === 'clearwarn') {
        return await ownerOnly(async () => {
          try {
            if (!ehGrupo) {
              await sock.sendMessage(m.key.remoteJid, {
                text: '❌ Este comando funciona apenas em grupos.'
              }, { quoted: m });
              return true;
            }

            let target = null;
            let mentions = [];
            if (m.message && m.message.extendedTextMessage && m.message.extendedTextMessage.contextInfo && m.message.extendedTextMessage.contextInfo.mentionedJid) {
              mentions = m.message.extendedTextMessage.contextInfo.mentionedJid || [];
            }
            if (mentions.length) target = mentions[0];
            else if (replyInfo && replyInfo.participantJidCitado) target = replyInfo.participantJidCitado;

            if (!target) {
              await sock.sendMessage(m.key.remoteJid, {
                text: '❌ Marque (@) o membro ou responda mensagem dele com #clearwarn'
              }, { quoted: m });
              return true;
            }

            if (!this.bot.warnSystem) {
              this.bot.warnSystem = new Map();
            }

            const key = `${m.key.remoteJid}_${target}`;
            const warns = this.bot.warnSystem.get(key) || 0;

            if (warns === 0) {
              await sock.sendMessage(m.key.remoteJid, {
                text: '✅ Este usuário não possui avisos.'
              }, { quoted: m });
              return true;
            }

            this.bot.warnSystem.delete(key);
            this.logAdminAction(senderId, nome, 'CLEARWARN_USER', target, `Avisos removidos (eram ${warns})`);

            await sock.sendMessage(m.key.remoteJid, {
              text: `✅ *AVISOS REMOVIDOS!*\n\n` +
                    `👤 Usuário marcado\n` +
                    `🗑️ Avisos removidos: ${warns}\n` +
                    `🆕 Avisos atuais: 0`
            }, { quoted: m });

            return true;
          } catch (e) {
            console.error('Erro em clearwarn:', e);
          }
          return true;
        });
      }

      // #APAGAR - Apagar mensagem (responder a ela)
      if (cmd === 'apagar' || cmd === 'delete' || cmd === 'del') {
        try {
          // Deve responder uma mensagem
          let quotedMsg = null;
          if (m.message && m.message.extendedTextMessage && m.message.extendedTextMessage.contextInfo && m.message.extendedTextMessage.contextInfo.quotedMessage) {
            quotedMsg = m.message.extendedTextMessage.contextInfo.quotedMessage;
          }
          
          if (!quotedMsg) {
            await sock.sendMessage(m.key.remoteJid, {
              text: '🗑️ *COMANDO #apagar*\n\n' +
                    '✅ Responda uma mensagem com `#apagar`\n' +
                    '✅ Apenas mensagens do próprio bot podem ser apagadas de forma segura\n\n' +
                    '⚠️ Uso: Responda a mensagem que deseja remover'
            }, { quoted: m });
            return true;
          }

          try {
            // Tenta apagar a mensagem citada
            await sock.sendMessage(m.key.remoteJid, {
              delete: m.message.extendedTextMessage.contextInfo.stanzaId
                ? {
                    remoteJid: m.key.remoteJid,
                    fromMe: true,
                    id: m.message.extendedTextMessage.contextInfo.stanzaId,
                    participant: m.message.extendedTextMessage.contextInfo.participant
                  }
                : null
            });

            // Confirma
            setTimeout(async () => {
              await sock.sendMessage(m.key.remoteJid, {
                text: '✅ Mensagem apagada com sucesso!'
              }, { quoted: m });
            }, 500);

            return true;
          } catch (deleteError) {
            console.log('Nota: Apagamento direto não funcionou. Mensagem de confirmação enviada.');
            await sock.sendMessage(m.key.remoteJid, {
              text: '✅ Comando processado.\n\n' +
                    '⚠️ Nota: WhatsApp permite apagar apenas mensagens recentes (até 2 dias)'
            }, { quoted: m });
            return true;
          }
        } catch (e) {
          console.error('Erro em apagar:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao processar comando.'
          }, { quoted: m });
          return true;
        }
      }

      // ═══════════════════════════════════════════════════════════════
      // 🔐 COMANDOS DE CYBERSECURITY - ENTERPRISE TOOLS
      // ═══════════════════════════════════════════════════════════════

      // #WHOIS - Investigação de domínios e IPs
      if (cmd === 'whois') {
        try {
          const permissao = this.subscriptionManager.canUseFeature(senderId, 'whois');
          
          if (!permissao.canUse && !isOwner()) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `🔒 *FEATURE RESTRITA*\n\nVocê atingiu seu limite mensal para #whois.\n\n${this.subscriptionManager.getUpgradeMessage(senderId, 'WHOIS')}`
            }, { quoted: m });
            return true;
          }

          if (!full) {
            await sock.sendMessage(m.key.remoteJid, {
              text: '🔍 *COMANDO #whois*\n\nUso: `#whois <domínio ou IP>`\n\nExemplos:\n#whois google.com\n#whois 8.8.8.8'
            }, { quoted: m });
            return true;
          }

          await sock.sendMessage(m.key.remoteJid, {
            text: '🔍 Investigando alvo...'
          }, { quoted: m });

          const whoIsResult = await this.cybersecurityToolkit.whoIs(full);
          
          if (!whoIsResult.sucesso) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ ${whoIsResult.erro}`
            }, { quoted: m });
            return true;
          }

          let response = `✅ *WHOIS - ${whoIsResult.tipo.toUpperCase()}*\n\n`;
          response += `🎯 Alvo: ${whoIsResult.alvo}\n\n`;
          response += `📋 Informações:\n`;
          
          for (const [key, val] of Object.entries(whoIsResult.dados)) {
            if (Array.isArray(val)) {
              response += `${key}: ${val.join(', ') || 'N/A'}\n`;
            } else {
              response += `${key}: ${val}\n`;
            }
          }

          this.securityLogger.logOperation({
            usuario: nome,
            tipo: 'WHOIS',
            alvo: full,
            resultado: whoIsResult.sucesso ? 'SUCESSO' : 'FALHA',
            risco: 'BAIXO'
          });

          await sock.sendMessage(m.key.remoteJid, {
            text: response
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em whois:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao investigar alvo.'
          }, { quoted: m });
          return true;
        }
      }

      // #DNS - Investigação DNS
      if (cmd === 'dns') {
        try {
          const permissao = this.subscriptionManager.canUseFeature(senderId, 'dns');
          
          if (!permissao.canUse && !isOwner()) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `🔒 *FEATURE RESTRITA*\n\n${this.subscriptionManager.getUpgradeMessage(senderId, 'DNS Recon')}`
            }, { quoted: m });
            return true;
          }

          if (!full) {
            await sock.sendMessage(m.key.remoteJid, {
              text: '📡 *COMANDO #dns*\n\nUso: `#dns <domínio>`\n\nExemplo: #dns google.com'
            }, { quoted: m });
            return true;
          }

          await sock.sendMessage(m.key.remoteJid, {
            text: '📡 Consultando DNS...'
          }, { quoted: m });

          const dnsResult = await this.cybersecurityToolkit.dnsRecon(full);
          
          if (!dnsResult.sucesso) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ ${dnsResult.erro}`
            }, { quoted: m });
            return true;
          }

          let response = `✅ *RECONHECIMENTO DNS*\n\n🎯 Domínio: ${dnsResult.dominio}\n\n`;
          response += `📋 Registros encontrados:\n`;

          for (const [tipo, registros] of Object.entries(dnsResult.registros)) {
            if (registros && registros.length > 0) {
              response += `\n${tipo}:\n`;
              registros.forEach(r => {
                response += `  • ${typeof r === 'object' ? JSON.stringify(r) : r}\n`;
              });
            }
          }

          response += `\n🔍 Subdomínios sugeridos:\n`;
          dnsResult.subdomainsSugeridos.forEach(sub => {
            response += `  • ${sub}\n`;
          });

          this.securityLogger.logOperation({
            usuario: nome,
            tipo: 'DNS_RECON',
            alvo: full,
            resultado: 'SUCESSO',
            risco: 'BAIXO',
            detalhes: { registrosTotais: Object.keys(dnsResult.registros).length }
          });

          await sock.sendMessage(m.key.remoteJid, {
            text: response
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em dns:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao consultar DNS.'
          }, { quoted: m });
          return true;
        }
      }

      // #NMAP - Port scanning
      if (cmd === 'nmap') {
        try {
          const permissao = this.subscriptionManager.canUseFeature(senderId, 'nmap');
          
          if (!permissao.canUse && !isOwner()) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `🔒 *FEATURE RESTRITA*\n\n${this.subscriptionManager.getUpgradeMessage(senderId, 'NMAP Scan')}`
            }, { quoted: m });
            return true;
          }

          if (!full) {
            await sock.sendMessage(m.key.remoteJid, {
              text: '📡 *COMANDO #nmap*\n\nUso: `#nmap <IP ou domínio>`\n\nExemplo: #nmap google.com'
            }, { quoted: m });
            return true;
          }

          await sock.sendMessage(m.key.remoteJid, {
            text: '⏳ Scanning de portas (isto pode levar um minuto)...'
          }, { quoted: m });

          const nmapResult = await this.cybersecurityToolkit.nmapScan(full);
          
          if (!nmapResult.sucesso) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ ${nmapResult.erro}`
            }, { quoted: m });
            return true;
          }

          let response = `✅ *NMAP SCAN COMPLETO*\n\n`;
          response += `🎯 Alvo: ${nmapResult.alvo}\n`;
          response += `📍 IP: ${nmapResult.targetIP}\n`;
          response += `📊 Portas abertas: ${nmapResult.portasAbertos}\n\n`;
          response += `🔌 Serviços detectados:\n`;

          for (const [porta, info] of Object.entries(nmapResult.portas)) {
            response += `  Porta ${porta}: ${info.servico} (${info.versao})\n`;
          }

          response += `\n${nmapResult.aviso}`;

          this.securityLogger.logOperation({
            usuario: nome,
            tipo: 'NMAP_SCAN',
            alvo: full,
            resultado: 'SUCESSO',
            risco: nmapResult.portasAbertos > 5 ? 'MÉDIO' : 'BAIXO',
            detalhes: { portasAbertos: nmapResult.portasAbertos }
          });

          await sock.sendMessage(m.key.remoteJid, {
            text: response
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em nmap:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao fazer scan.'
          }, { quoted: m });
          return true;
        }
      }

      // #SQLMAP - SQL Injection testing
      if (cmd === 'sqlmap') {
        try {
          const permissao = this.subscriptionManager.canUseFeature(senderId, 'sqlmap');
          
          if (!permissao.canUse && !isOwner()) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `🔒 *FEATURE RESTRITA - PREMIUM ONLY*\n\n${this.subscriptionManager.getUpgradeMessage(senderId, 'SQLMap Testing')}`
            }, { quoted: m });
            return true;
          }

          if (!full || !full.includes('http')) {
            await sock.sendMessage(m.key.remoteJid, {
              text: '💉 *COMANDO #sqlmap*\n\nUso: `#sqlmap <URL completa>`\n\n⚠️ APENAS PARA TESTE EM AMBIENTES AUTORIZADOS\n\nExemplo: #sqlmap https://example.com/search.php?id=1'
            }, { quoted: m });
            return true;
          }

          await sock.sendMessage(m.key.remoteJid, {
            text: '⏳ Testando vulnerabilidades de SQL Injection...'
          }, { quoted: m });

          const sqlmapResult = await this.cybersecurityToolkit.sqlmapTest(full);
          
          if (!sqlmapResult.sucesso) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ ${sqlmapResult.erro}`
            }, { quoted: m });
            return true;
          }

          let response = `*SQLMAP TEST RESULT*\n\n`;
          response += `🎯 Alvo: ${sqlmapResult.alvo}\n`;
          response += `⚠️ SQL Injection detectada: ${sqlmapResult.vulneravelSQLi ? '✅ SIM - CRÍTICO' : '❌ Não detectada'}\n\n`;

          if (sqlmapResult.vulnerabilidades.length > 0) {
            response += `🚨 Vulnerabilidades encontradas:\n`;
            sqlmapResult.vulnerabilidades.forEach((vuln, i) => {
              response += `\n  ${i+1}. Tipo: ${vuln.tipo}\n`;
              response += `     Payload: ${vuln.payload}\n`;
              response += `     Risco: ${vuln.risco}\n`;
            });
          }

          response += `\n💡 Recomendações:\n`;
          sqlmapResult.recomendacoes.forEach(rec => {
            response += `${rec}\n`;
          });

          this.securityLogger.logOperation({
            usuario: nome,
            tipo: 'SQLMAP_TEST',
            alvo: full,
            resultado: sqlmapResult.vulneravelSQLi ? 'VULNERÁVEL' : 'SEGURO',
            risco: sqlmapResult.vulneravelSQLi ? 'CRÍTICO' : 'BAIXO'
          });

          await sock.sendMessage(m.key.remoteJid, {
            text: response
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em sqlmap:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao testar vulnerabilidades.'
          }, { quoted: m });
          return true;
        }
      }

      // #OSINT - Open Source Intelligence gathering
      if (cmd === 'osint') {
        try {
          const sub = (args[0] || '').toLowerCase();
          const alvo = args.slice(1).join(' ') || full;

          if (!sub || !alvo || ['email', 'phone', 'username', 'domain', 'breach'].indexOf(sub) === -1) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `🕵️ *COMANDO #osint - OPEN SOURCE INTELLIGENCE*\n\n` +
                    `Subcomandos:\n` +
                    `  #osint email <email> - Pesquisar email\n` +
                    `  #osint phone <número> - Pesquisar telefone\n` +
                    `  #osint username <username> - Buscar em redes sociais\n` +
                    `  #osint domain <domínio> - Encontrar subdomínios\n` +
                    `  #osint breach <email> - Verificar vazamentos\n\n` +
                    `💎 Recursos premium disponíveis com assinatura`
            }, { quoted: m });
            return true;
          }

          const permissao = this.subscriptionManager.canUseFeature(senderId, `osint_${sub}`);
          
          if (!permissao.canUse && !isOwner()) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `🔒 *FEATURE RESTRITA*\n\n${this.subscriptionManager.getUpgradeMessage(senderId, `OSINT - ${sub.toUpperCase()}`)}`
            }, { quoted: m });
            return true;
          }

          await sock.sendMessage(m.key.remoteJid, {
            text: `🔍 Investigando ${sub}...`
          }, { quoted: m });

          let resultado;

          if (sub === 'email') {
            resultado = await this.osintFramework.emailReconnaissance(alvo);
          } else if (sub === 'phone') {
            resultado = await this.osintFramework.phoneNumberLookup(alvo);
          } else if (sub === 'username') {
            resultado = await this.osintFramework.usernameSearch(alvo);
          } else if (sub === 'domain') {
            resultado = await this.osintFramework.subdomainEnumeration(alvo);
          } else if (sub === 'breach') {
            resultado = await this.osintFramework.breachSearch(alvo);
          }

          if (!resultado.sucesso) {
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ ${resultado.erro}`
            }, { quoted: m });
            return true;
          }

          let response = `✅ *OSINT - ${sub.toUpperCase()}*\n\n`;

          if (sub === 'email') {
            response += `📧 Email: ${resultado.email}\n`;
            response += `✔️ Válido: ${resultado.valido ? 'Sim' : 'Não'}\n`;
            response += `🚨 Vazamentos: ${resultado.descobertas.vazamentosEncontrados}\n`;
            if (resultado.descobertas.breaches.length > 0) {
              response += `   - ${resultado.descobertas.breaches.map(b => b.nome).join('\n   - ')}\n`;
            }
          } else if (sub === 'phone') {
            response += `📱 Número: ${resultado.numero}\n`;
            response += `🌍 País: ${resultado.analise.pais}\n`;
            response += `📊 Operadora: ${resultado.analise.operadora}\n`;
            response += `📈 Tipo: ${resultado.analise.tipoLinha}\n`;
          } else if (sub === 'username') {
            response += `👤 Username: ${resultado.username}\n`;
            response += `🔗 Contas encontradas: ${resultado.encontrados}\n`;
            resultado.contas.forEach(conta => {
              response += `   ${conta.ícone} ${conta.plataforma}: ${conta.status}\n`;
            });
          } else if (sub === 'domain') {
            response += `🌐 Domínio: ${resultado.dominio}\n`;
            response += `🔍 Subdomínios encontrados: ${resultado.descobertos}\n`;
            resultado.subdomainios.slice(0, 5).forEach(sub => {
              response += `   • ${sub.subdominio} (${sub.ativo ? '✅ Ativo' : '❌ Inativo'})\n`;
            });
          } else if (sub === 'breach') {
            response += `🎯 Alvo: ${resultado.alvo}\n`;
            response += `🚨 Vazamentos: ${resultado.vazamentosEncontrados}\n`;
            resultado.breaches.forEach(breach => {
              response += `   🔴 ${breach.nome} - ${breach.dataVazamento}\n`;
            });
            response += `\n⚠️ Ações recomendadas:\n`;
            resultado.acoes.forEach(acao => {
              response += `${acao}\n`;
            });
          }

          this.securityLogger.logOperation({
            usuario: nome,
            tipo: `OSINT_${sub.toUpperCase()}`,
            alvo,
            resultado: resultado.sucesso ? 'SUCESSO' : 'FALHA',
            risco: 'BAIXO'
          });

          await sock.sendMessage(m.key.remoteJid, {
            text: response
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em osint:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao investigar alvo.'
          }, { quoted: m });
          return true;
        }
      }

      // #MODE - Modo ROOT (dono apenas)
      if (cmd === 'mode') {
        try {
          const modo = (args[0] || '').toLowerCase();

          if (modo === 'root') {
            if (!isOwner()) {
              await sock.sendMessage(m.key.remoteJid, {
                text: '🚫 *COMANDO RESTRITO*\n\nApenas o proprietário pode ativar modo ROOT.'
              }, { quoted: m });
              return true;
            }

            // Ativa modo root
            if (!this.bot.rootMode) {
              this.bot.rootMode = new Map();
            }

            const rootMode = !((this.bot.rootMode.get(senderId) || false));
            this.bot.rootMode.set(senderId, rootMode);

            const resposta = rootMode ?
              `🔓 *MODO ROOT ATIVADO*\n\n` +
              `⚠️ Você agora tem acesso ilimitado a:\n` +
              `• Ferramentas de cybersecurity\n` +
              `• Dark web monitoring\n` +
              `• Análise profunda\n` +
              `• Sem limites de taxa\n\n` +
              `🛡️ Todas as operações serão logadas.`
              :
              `🔒 *MODO ROOT DESATIVADO*\n\nVoltando aos limites normais.`;

            await sock.sendMessage(m.key.remoteJid, {
              text: resposta
            }, { quoted: m });

            this.logAdminAction(senderId, nome, `MODE_ROOT_${rootMode ? 'ON' : 'OFF'}`, 'N/A', '');
            return true;
          }

          if (modo === 'status') {
            const subInfo = this.subscriptionManager.getSubscriptionInfo(senderId);
            
            let response = `📊 *STATUS DO BOT*\n\n`;
            response += `🎭 Modo: ${isOwner() ? '👑 OWNER' : 'Usuário normal'}\n`;
            response += `💎 Tier: ${subInfo.tier}\n`;
            response += `📈 Status: ${subInfo.status}\n\n`;
            response += `✨ Recursos disponíveis:\n`;
            subInfo.recursos.forEach(rec => {
              response += `${rec}\n`;
            });

            if (subInfo.upgrade) {
              response += `\n${subInfo.upgrade}`;
            }

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });
            return true;
          }

          await sock.sendMessage(m.key.remoteJid, {
            text: `⚙️ *COMANDO #mode*\n\nSubcomandos:\n` +
                  `  #mode root - Ativar/desativar modo ROOT (dono)\n` +
                  `  #mode status - Ver status e limites`
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em mode:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao processar comando.'
          }, { quoted: m });
          return true;
        }
      }

      // #SECURITY - Relatórios de segurança
      if (cmd === 'security') {
        try {
          const sub = (args[0] || '').toLowerCase();

          if (sub === 'report' && isOwner()) {
            const report = this.securityLogger.getOperationReport();
            const alertReport = this.securityLogger.getAlertReport();

            let response = `📊 *RELATÓRIO DE SEGURANÇA*\n\n`;
            response += `📈 Operações registradas: ${report.totalOperacoes}\n`;
            response += `🚨 Alertas ativos: ${alertReport.alertasNovos}\n`;
            response += `✅ Alertas resolvidos: ${alertReport.alertasResolvidos}\n\n`;
            response += `📋 Operações por tipo:\n`;

            for (const [tipo, count] of Object.entries(report.resumoPorTipo)) {
              response += `   ${tipo}: ${count}\n`;
            }

            response += `\n🚨 Operações suspeitas: ${report.operaçõesSuspeitas}\n`;

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });

            return true;
          }

          await sock.sendMessage(m.key.remoteJid, {
            text: `🛡️ *COMANDO #security*\n\nSubcomandos (dono):\n` +
                  `  #security report - Ver relatório de segurança`
          }, { quoted: m });

          return true;
        } catch (e) {
          console.error('Erro em security:', e);
          return true;
        }
      }

      // ═══════════════════════════════════════════════════════════════════════
      // 🔴 FERRAMENTAS PENTESTING REAIS (ROOT ONLY - DONO)
      // ═══════════════════════════════════════════════════════════════════════
      
      // #NMAP - REAL Port scanning com ferramenta verdadeira
      if (cmd === 'nmap' && isOwner()) {
        return await ownerOnly(async () => {
          try {
            if (!full) {
              await sock.sendMessage(m.key.remoteJid, {
                text: `📡 *NMAP - REAL PORT SCANNING*\n\n` +
                      `✅ Ferramenta REAL: github.com/nmap/nmap\n\n` +
                      `Uso: #nmap <target>\n` +
                      `Exemplo: #nmap 192.168.1.1\n` +
                      `Exemplo: #nmap scanme.nmap.org\n\n` +
                      `⏱️ Timeout: 15 minutos (full range)\n` +
                      `🚀 Framework: child_process.spawn()`
              }, { quoted: m });
              return true;
            }

            await sock.sendMessage(m.key.remoteJid, {
              text: `⏳ Iniciando NMAP real em ${full}...\n\n⚠️ Isto pode levar alguns minutos.`
            }, { quoted: m });

            const AdvancedPentestingToolkit = require('./AdvancedPentestingToolkit');
            const toolkit = new AdvancedPentestingToolkit({ resultsDir: '/tmp/pentest_results' });
            const result = await toolkit.nmapScan(full);

            let response = `✅ *NMAP SCAN COMPLETO (REAL)*\n\n`;
            response += `🎯 Alvo: ${result.target}\n`;
            response += `📊 Portas abertas: ${result.openPorts.length}\n`;
            response += `⏱️ Duração: ${result.duration}s\n\n`;

            if (result.openPorts.length > 0) {
              response += `🔌 Serviços encontrados:\n`;
              result.openPorts.slice(0, 20).forEach(port => {
                response += `   ${port.port}/${port.protocol} - ${port.service} (${port.state})\n`;
              });
              if (result.openPorts.length > 20) {
                response += `   ... e mais ${result.openPorts.length - 20} portas\n`;
              }
            } else {
              response += `❌ Nenhuma porta aberta encontrada\n`;
            }

            response += `\n📁 Resultados salvos em: /tmp/pentest_results/\n`;
            response += `🔐 Operação logada para auditoria`;

            this.logAdminAction(senderId, nome, 'NMAP_SCAN_REAL', full, `Portas: ${result.openPorts.length}`);
            this.securityLogger.logOperation({
              usuario: nome,
              tipo: 'NMAP_REAL',
              alvo: full,
              resultado: 'COMPLETO',
              risco: 'MÉDIO',
              detalhes: { portas: result.openPorts.length }
            });

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });

            return true;
          } catch (e) {
            console.error('Erro em NMAP:', e);
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ Erro ao executar NMAP:\n\n${e.message}`
            }, { quoted: m });
            return true;
          }
        });
      }

      // #SQLMAP - REAL SQL Injection testing
      if (cmd === 'sqlmap' && isOwner()) {
        return await ownerOnly(async () => {
          try {
            if (!full || !full.startsWith('http')) {
              await sock.sendMessage(m.key.remoteJid, {
                text: `💉 *SQLMAP - REAL SQL INJECTION TESTING*\n\n` +
                      `✅ Ferramenta REAL: github.com/sqlmapproject/sqlmap\n\n` +
                      `Uso: #sqlmap <URL completa>\n` +
                      `Exemplo: #sqlmap http://target.com/search.php?id=1\n\n` +
                      `⚠️ APENAS EM ALVOS AUTORIZADOS!\n` +
                      `🔐 Modo: child_process.spawn() python3`
              }, { quoted: m });
              return true;
            }

            await sock.sendMessage(m.key.remoteJid, {
              text: `⏳ Testando SQL Injection em ${full}...\n\n⚠️ Timeout: 20 minutos`
            }, { quoted: m });

            const AdvancedPentestingToolkit = require('./AdvancedPentestingToolkit');
            const toolkit = new AdvancedPentestingToolkit({ resultsDir: '/tmp/pentest_results' });
            const result = await toolkit.sqlmapTest(full);

            let response = `✅ *SQLMAP TEST COMPLETO (REAL)*\n\n`;
            response += `🎯 Alvo: ${result.target}\n`;
            response += `⚠️ Vulnerável: ${result.vulnerable ? '🔴 SIM - CRÍTICO' : '✅ NÃO'}\n\n`;

            if (result.vulnerable && result.vulnerabilities.length > 0) {
              response += `🚨 Vulnerabilidades encontradas:\n`;
              result.vulnerabilities.slice(0, 10).forEach((vuln, i) => {
                response += `\n${i+1}. Tipo: ${vuln.type}\n`;
                response += `   Parameter: ${vuln.parameter}\n`;
                response += `   Risco: ${vuln.risk}\n`;
              });
            }

            response += `\n📁 Resultados: /tmp/pentest_results/sqlmap_results.json\n`;
            response += `🔐 Operação logada`;

            this.logAdminAction(senderId, nome, 'SQLMAP_REAL', full, `Vulnerável: ${result.vulnerable}`);
            this.securityLogger.logOperation({
              usuario: nome,
              tipo: 'SQLMAP_REAL',
              alvo: full,
              resultado: result.vulnerable ? 'VULNERÁVEL' : 'SEGURO',
              risco: result.vulnerable ? 'CRÍTICO' : 'BAIXO'
            });

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });

            return true;
          } catch (e) {
            console.error('Erro em SQLMAP:', e);
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ Erro ao executar SQLMAP:\n\n${e.message}`
            }, { quoted: m });
            return true;
          }
        });
      }

      // #HYDRA - REAL Password cracking
      if (cmd === 'hydra' && isOwner()) {
        return await ownerOnly(async () => {
          try {
            if (!full || !full.includes(' ')) {
              await sock.sendMessage(m.key.remoteJid, {
                text: `🔓 *HYDRA - REAL PASSWORD CRACKING*\n\n` +
                      `✅ Ferramenta REAL: github.com/vanhauser-thc/thc-hydra\n\n` +
                      `Uso: #hydra <alvo> <usuário> <arquivo_senhas>\n` +
                      `Exemplo: #hydra 192.168.1.1:22 root password_list.txt\n\n` +
                      `⚠️ LEGAL PURPOSES ONLY!\n` +
                      `⏱️ Timeout: 30 minutos`
              }, { quoted: m });
              return true;
            }

            const [target, user, ...passFile] = full.split(' ');
            await sock.sendMessage(m.key.remoteJid, {
              text: `⏳ Iniciando Hydra em ${target}...\n\n⚠️ Isto pode levar tempo`
            }, { quoted: m });

            const AdvancedPentestingToolkit = require('./AdvancedPentestingToolkit');
            const toolkit = new AdvancedPentestingToolkit({ resultsDir: '/tmp/pentest_results' });
            const result = await toolkit.hydraBrute(target, 'ssh', user, []);

            let response = `✅ *HYDRA BRUTE-FORCE COMPLETO (REAL)*\n\n`;
            response += `🎯 Alvo: ${target}\n`;
            response += `👤 Usuário: ${user}\n`;
            response += `🔓 Senha encontrada: ${result.found ? result.password : 'Não'}\n`;
            response += `⏱️ Tempo: ${result.duration}s\n\n`;
            response += `📊 Tentativas: ${result.attempts}`;

            this.logAdminAction(senderId, nome, 'HYDRA_REAL', target, `Tentativas: ${result.attempts}`);

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });

            return true;
          } catch (e) {
            console.error('Erro em HYDRA:', e);
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ Erro ao executar Hydra:\n\n${e.message}`
            }, { quoted: m });
            return true;
          }
        });
      }

      // #NUCLEI - REAL Vulnerability scanning
      if (cmd === 'nuclei' && isOwner()) {
        return await ownerOnly(async () => {
          try {
            if (!full) {
              await sock.sendMessage(m.key.remoteJid, {
                text: `🔍 *NUCLEI - REAL VULNERABILITY SCANNING*\n\n` +
                      `✅ Ferramenta REAL: github.com/projectdiscovery/nuclei\n\n` +
                      `Uso: #nuclei <target>\n` +
                      `Exemplo: #nuclei https://target.com\n` +
                      `Exemplo: #nuclei 192.168.1.1\n\n` +
                      `⏱️ Timeout: 10 minutos\n` +
                      `📊 Templates: Auto-detection`
              }, { quoted: m });
              return true;
            }

            await sock.sendMessage(m.key.remoteJid, {
              text: `⏳ Nuclei scanning em ${full}...\n\n⚠️ Verificando vulnerabilidades`
            }, { quoted: m });

            const AdvancedPentestingToolkit = require('./AdvancedPentestingToolkit');
            const toolkit = new AdvancedPentestingToolkit({ resultsDir: '/tmp/pentest_results' });
            const result = await toolkit.nucleiScan(full);

            let response = `✅ *NUCLEI SCAN COMPLETO (REAL)*\n\n`;
            response += `🎯 Alvo: ${full}\n`;
            response += `🔍 Vulnerabilidades encontradas: ${result.findings.length}\n\n`;

            if (result.findings.length > 0) {
              response += `🚨 Resultados:\n`;
              result.findings.slice(0, 15).forEach((finding, i) => {
                response += `\n${i+1}. ${finding.name}\n`;
                response += `   Severidade: ${finding.severity}\n`;
                response += `   CVSS: ${finding.cvss || 'N/A'}\n`;
              });
              if (result.findings.length > 15) {
                response += `\n... e mais ${result.findings.length - 15} vulnerabilidades\n`;
              }
            }

            response += `\n📁 Resultados: /tmp/pentest_results/nuclei_results.json`;

            this.logAdminAction(senderId, nome, 'NUCLEI_REAL', full, `Findings: ${result.findings.length}`);

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });

            return true;
          } catch (e) {
            console.error('Erro em NUCLEI:', e);
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ Erro ao executar Nuclei:\n\n${e.message}`
            }, { quoted: m });
            return true;
          }
        });
      }

      // #MASSCAN - REAL Ultra-fast port scanning
      if (cmd === 'masscan' && isOwner()) {
        return await ownerOnly(async () => {
          try {
            if (!full) {
              await sock.sendMessage(m.key.remoteJid, {
                text: `⚡ *MASSCAN - REAL ULTRA-FAST PORT SCANNING*\n\n` +
                      `✅ Ferramenta REAL: github.com/robertdavidgraham/masscan\n\n` +
                      `Uso: #masscan <target> [portas]\n` +
                      `Exemplo: #masscan 192.168.1.0/24\n` +
                      `Exemplo: #masscan 192.168.1.1 1-65535\n\n` +
                      `🚀 Velocidade: 1000+ req/s\n` +
                      `⏱️ Timeout: 5 minutos`
              }, { quoted: m });
              return true;
            }

            const [target, ports] = full.split(' ');
            await sock.sendMessage(m.key.remoteJid, {
              text: `⚡ Ultra-fast scanning em ${target}...\n\n🚀 1000+ req/s`
            }, { quoted: m });

            const AdvancedPentestingToolkit = require('./AdvancedPentestingToolkit');
            const toolkit = new AdvancedPentestingToolkit({ resultsDir: '/tmp/pentest_results' });
            const result = await toolkit.masscanScan(target, ports || '1-65535');

            let response = `✅ *MASSCAN SCAN COMPLETO (REAL)*\n\n`;
            response += `🎯 Alvo: ${target}\n`;
            response += `⚡ Velocidade: ${(result.packetsPerSecond || 1000).toLocaleString()} req/s\n`;
            response += `📊 Portas abertas: ${result.openPorts.length}\n`;
            response += `⏱️ Tempo: ${result.duration}s\n\n`;

            if (result.openPorts.length > 0) {
              response += `🔌 Top 10 portas:\n`;
              result.openPorts.slice(0, 10).forEach(port => {
                response += `   ${port}/tcp\n`;
              });
            }

            response += `\n📁 Resultados: /tmp/pentest_results/masscan_results.json`;

            this.logAdminAction(senderId, nome, 'MASSCAN_REAL', target, `Portas: ${result.openPorts.length}`);

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });

            return true;
          } catch (e) {
            console.error('Erro em MASSCAN:', e);
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ Erro ao executar Masscan:\n\n${e.message}`
            }, { quoted: m });
            return true;
          }
        });
      }

      // #NIKTO - REAL Web server scanning
      if (cmd === 'nikto' && isOwner()) {
        return await ownerOnly(async () => {
          try {
            if (!full || !full.startsWith('http')) {
              await sock.sendMessage(m.key.remoteJid, {
                text: `🌐 *NIKTO - REAL WEB SERVER SCANNING*\n\n` +
                      `✅ Ferramenta REAL: github.com/sullo/nikto\n\n` +
                      `Uso: #nikto <URL>\n` +
                      `Exemplo: #nikto http://target.com\n` +
                      `Exemplo: #nikto https://target.com:8080\n\n` +
                      `⏱️ Timeout: 10 minutos\n` +
                      `🔍 Detecta: CVEs, Configs, Plugins`
              }, { quoted: m });
              return true;
            }

            await sock.sendMessage(m.key.remoteJid, {
              text: `⏳ Nikto scanning em ${full}...\n\n🔍 Analisando servidor web`
            }, { quoted: m });

            const AdvancedPentestingToolkit = require('./AdvancedPentestingToolkit');
            const toolkit = new AdvancedPentestingToolkit({ resultsDir: '/tmp/pentest_results' });
            const result = await toolkit.niktoScan(full);

            let response = `✅ *NIKTO SCAN COMPLETO (REAL)*\n\n`;
            response += `🎯 Alvo: ${full}\n`;
            response += `🌐 Servidor: ${result.server || 'Desconhecido'}\n`;
            response += `🔍 Issues encontradas: ${result.issues.length}\n\n`;

            if (result.issues.length > 0) {
              response += `⚠️ Problemas:\n`;
              result.issues.slice(0, 10).forEach((issue, i) => {
                response += `\n${i+1}. ${issue.description}\n`;
                response += `   Severidade: ${issue.severity}\n`;
              });
              if (result.issues.length > 10) {
                response += `\n... e mais ${result.issues.length - 10} issues\n`;
              }
            }

            response += `\n📁 Resultados: /tmp/pentest_results/nikto_results.json`;

            this.logAdminAction(senderId, nome, 'NIKTO_REAL', full, `Issues: ${result.issues.length}`);

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });

            return true;
          } catch (e) {
            console.error('Erro em NIKTO:', e);
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ Erro ao executar Nikto:\n\n${e.message}`
            }, { quoted: m });
            return true;
          }
        });
      }

      // #PENTEST - Gerar relatório completo com todas as ferramentas
      if (cmd === 'pentest' && isOwner()) {
        return await ownerOnly(async () => {
          try {
            if (!full) {
              await sock.sendMessage(m.key.remoteJid, {
                text: `🎯 *PENTEST COMPLETO - TODAS AS FERRAMENTAS*\n\n` +
                      `Usa: NMAP + SQLMAP + Nuclei + Masscan + Nikto\n\n` +
                      `Uso: #pentest <target>\n` +
                      `Exemplo: #pentest https://target.com\n\n` +
                      `⏱️ Duração total: ~1 hora\n` +
                      `📊 Gera relatório consolidado`
              }, { quoted: m });
              return true;
            }

            await sock.sendMessage(m.key.remoteJid, {
              text: `🎯 PENTEST COMPLETO iniciado em ${full}\n\n` +
                    `⏳ Isto pode levar ~1 hora\n` +
                    `📊 Executando:\n` +
                    `   ✓ NMAP (ports)\n` +
                    `   ✓ Nuclei (vulns)\n` +
                    `   ✓ Masscan (fast)\n` +
                    `   ✓ Nikto (web)\n` +
                    `   ✓ Relatório\n\n` +
                    `Você será notificado quando terminar.`
            }, { quoted: m });

            const AdvancedPentestingToolkit = require('./AdvancedPentestingToolkit');
            const toolkit = new AdvancedPentestingToolkit({ resultsDir: '/tmp/pentest_results' });
            
            // Executa todas as ferramentas
            const reports = await toolkit.generateComprehensiveReport(full);

            let response = `✅ *PENTEST COMPLETO FINALIZADO*\n\n`;
            response += `🎯 Alvo: ${full}\n\n`;
            response += `📊 Resumo dos resultados:\n`;
            let nmapLength = 0;
            if (reports.nmap && reports.nmap.openPorts && reports.nmap.openPorts.length) {
              nmapLength = reports.nmap.openPorts.length;
            }
            let nucleiLength = 0;
            if (reports.nuclei && reports.nuclei.findings && reports.nuclei.findings.length) {
              nucleiLength = reports.nuclei.findings.length;
            }
            let masscanLength = 0;
            if (reports.masscan && reports.masscan.openPorts && reports.masscan.openPorts.length) {
              masscanLength = reports.masscan.openPorts.length;
            }
            let niktoLength = 0;
            if (reports.nikto && reports.nikto.issues && reports.nikto.issues.length) {
              niktoLength = reports.nikto.issues.length;
            }
            response += `   🔌 NMAP: ${nmapLength} portas\n`;
            response += `   🔍 Nuclei: ${nucleiLength} vulnerabilidades\n`;
            response += `   ⚡ Masscan: ${masscanLength} portas\n`;
            response += `   🌐 Nikto: ${niktoLength} issues\n\n`;
            response += `📁 Arquivo consolidado:\n`;
            response += `   /tmp/pentest_results/pentest_report.json\n\n`;
            response += `🔐 Todas as operações foram logadas para auditoria`;

            this.logAdminAction(senderId, nome, 'PENTEST_COMPLETO', full, 'Relatório gerado');
            this.securityLogger.logOperation({
              usuario: nome,
              tipo: 'PENTEST_COMPLETO',
              alvo: full,
              resultado: 'COMPLETO',
              risco: 'VARIÁVEL'
            });

            await sock.sendMessage(m.key.remoteJid, {
              text: response
            }, { quoted: m });

            return true;
          } catch (e) {
            console.error('Erro em PENTEST:', e);
            await sock.sendMessage(m.key.remoteJid, {
              text: `❌ Erro ao executar pentest completo:\n\n${e.message}`
            }, { quoted: m });
            return true;
          }
        });
      }

      // #PENTESTMENU - Menu de ferramentas pentesting
      if (cmd === 'pentestmenu' || cmd === 'toolsmenu' || cmd === 'ptstmenu') {
        try {
          const menuText = this.createMenuHeader('🔴', 'FERRAMENTAS DE PENTESTING - REAL') + `

${this.createMenuSection('🔐', 'STATUS DE ACESSO')}
${isOwner() ? '✅ ROOT ATIVADO - Acesso irrestrito' : '🔒 Permissão negada - Apenas dono (Isaac Quarenta)'}

${this.createMenuSection('⚙️', 'FERRAMENTAS DISPONÍVEIS (ROOT ONLY)')}

*1️⃣ #nmap <target>*
   📡 Port Scanning (Real)
   ✅ Ferramenta: github.com/nmap/nmap
   ⏱️ Timeout: 15 min
   Exemplo: #nmap 192.168.1.1

*2️⃣ #sqlmap <URL>*
   💉 SQL Injection Testing (Real)
   ✅ Ferramenta: github.com/sqlmapproject/sqlmap
   ⏱️ Timeout: 20 min
   Exemplo: #sqlmap http://target.com/search?id=1

*3️⃣ #hydra <target> <user> <file>*
   🔓 Password Cracking (Real)
   ✅ Ferramenta: github.com/vanhauser-thc/thc-hydra
   ⏱️ Timeout: 30 min
   Exemplo: #hydra 192.168.1.1:22 root passwords.txt

*4️⃣ #nuclei <target>*
   🔍 Vulnerability Scanning (Real)
   ✅ Ferramenta: github.com/projectdiscovery/nuclei
   ⏱️ Timeout: 10 min
   Exemplo: #nuclei https://target.com

*5️⃣ #masscan <target> [ports]*
   ⚡ Ultra-Fast Port Scanning (Real)
   ✅ Ferramenta: github.com/robertdavidgraham/masscan
   ⏱️ Timeout: 5 min
   📊 Velocidade: 1000+ req/s
   Exemplo: #masscan 192.168.1.0/24

*6️⃣ #nikto <URL>*
   🌐 Web Server Scanning (Real)
   ✅ Ferramenta: github.com/sullo/nikto
   ⏱️ Timeout: 10 min
   Exemplo: #nikto http://target.com

*7️⃣ #pentest <target>*
   🎯 Pentesting Completo (TODAS as ferramentas)
   ✅ Gera relatório consolidado
   ⏱️ Duração: ~1 hora
   Exemplo: #pentest https://target.com

${this.createMenuSection('📊', 'RESULTADOS')}
Todos os resultados são salvos em:
📁 /tmp/pentest_results/

Cada ferramenta gera um arquivo JSON:
• nmap_results.json
• sqlmap_results.json
• hydra_results.json
• nuclei_results.json
• masscan_results.json
• nikto_results.json
• pentest_report.json (consolidado)

${this.createMenuSection('🔐', 'SEGURANÇA E COMPLIANCE')}
✅ Todas as operações são logadas
✅ Auditoria completa em tiempo real
✅ Apenas para alvos autorizados
✅ ROOT ONLY - Máxima proteção

${this.createMenuSection('⚖️', 'AVISO LEGAL')}
⚠️ Estas ferramentas são REAIS e PODEROSAS
⚠️ Use APENAS em ambientes autorizados
⚠️ Acesso não autorizado é ILEGAL
⚠️ Todas as operações são rastreadas

${this.createMenuSection('💡', 'DICAS')}
🎯 Para teste completo, use: #pentest <target>
📊 Combinar resultados de múltiplas ferramentas
🔍 Analisar relatórios JSON para detalhes
🛡️ Sempre obter autorização antes

*Desenvolvido com ❤️ por Isaac Quarenta*
_AKIRA BOT v21 - Enterprise Grade Pentesting Suite_`;

          if (!isOwner()) {
            await sock.sendMessage(m.key.remoteJid, {
              text: menuText + `\n\n❌ Este menu é ROOT-ONLY\nApenas ${this.config.DONO} tem acesso`
            }, { quoted: m });
          } else {
            await sock.sendMessage(m.key.remoteJid, { text: menuText }, { quoted: m });
          }

          return true;
        } catch (e) {
          console.error('Erro em pentestmenu:', e);
          await sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao exibir menu.'
          }, { quoted: m });
          return true;
        }
      }

      // Default: Comando não encontrado
      return false;

    } catch (err) {
      console.error('❌ Erro geral no handler:', err);
      try { 
        await this.bot.sock.sendMessage(m.key.remoteJid, { 
          text: '❌ Erro ao processar comando.' 
        }, { quoted: m }); 
      } catch {}
      return true;
    }
  }
}

module.exports = CommandHandler;