File size: 51,023 Bytes
889dfbb
71eef32
d6732c4
750d4eb
889dfbb
750d4eb
d6732c4
 
71eef32
599fabc
85b104e
 
60496de
90a3599
e6f85fa
750d4eb
d6732c4
 
0e4bcf7
85b104e
 
d6732c4
 
85b104e
 
599fabc
922fb3e
e6f85fa
1b61d51
599fabc
85b104e
d6732c4
 
e6f85fa
85b104e
d6732c4
 
 
 
 
85b104e
3601233
922fb3e
85b104e
 
 
90a3599
 
 
 
 
599fabc
85b104e
 
599fabc
922fb3e
 
 
 
 
 
85b104e
90a3599
85b104e
 
d6732c4
85b104e
922fb3e
d6732c4
922fb3e
85b104e
 
750d4eb
422f85a
 
 
 
750d4eb
422f85a
 
 
 
 
 
 
 
 
 
 
 
 
d6732c4
422f85a
 
 
 
 
 
d6732c4
422f85a
 
 
 
 
fa34f3f
 
 
889dfbb
fa34f3f
d6732c4
422f85a
 
 
d6732c4
 
 
 
422f85a
d6732c4
 
422f85a
 
fa34f3f
422f85a
 
 
d6732c4
422f85a
 
 
750d4eb
 
 
 
 
 
 
 
 
 
 
 
889dfbb
 
 
 
 
 
d6732c4
422f85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6732c4
422f85a
 
 
d6732c4
422f85a
 
 
 
 
 
 
 
 
 
fa34f3f
889dfbb
422f85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6732c4
422f85a
d6732c4
422f85a
d6732c4
 
 
 
fa34f3f
889dfbb
d6732c4
 
 
 
 
 
 
 
 
422f85a
 
 
d6732c4
422f85a
 
 
 
 
 
 
fa34f3f
 
889dfbb
422f85a
 
 
 
 
 
 
 
 
d6732c4
422f85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6732c4
422f85a
 
 
 
 
 
 
 
 
 
 
 
 
 
d6732c4
422f85a
 
 
 
 
 
 
 
 
 
 
 
fa34f3f
 
 
 
 
 
 
 
 
 
889dfbb
fa34f3f
 
 
 
 
 
 
 
422f85a
889dfbb
422f85a
 
 
 
 
d6732c4
 
599fabc
 
 
 
d6732c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa34f3f
 
 
889dfbb
 
599fabc
 
d6732c4
599fabc
d6732c4
 
 
599fabc
fa34f3f
 
 
889dfbb
 
fa34f3f
 
 
 
 
 
 
 
 
 
 
889dfbb
 
fa34f3f
 
 
 
 
 
 
 
 
 
889dfbb
 
fa34f3f
 
 
 
 
 
 
 
889dfbb
 
 
 
 
 
 
 
 
 
 
599fabc
 
 
750d4eb
599fabc
d6732c4
889dfbb
d6732c4
599fabc
d6732c4
 
 
 
 
 
 
 
 
fa34f3f
 
889dfbb
 
d6732c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
889dfbb
922fb3e
d6732c4
 
599fabc
d6732c4
 
 
 
fa34f3f
 
 
 
 
5ede139
 
 
 
 
 
 
 
 
 
 
 
 
 
fa34f3f
d6732c4
750d4eb
 
 
599fabc
fa34f3f
750d4eb
 
599fabc
750d4eb
 
 
 
 
 
 
889dfbb
 
 
 
750d4eb
 
 
 
 
 
 
fa34f3f
889dfbb
 
750d4eb
 
 
 
 
 
 
 
 
889dfbb
750d4eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
889dfbb
 
 
 
750d4eb
 
 
 
 
 
 
fa34f3f
889dfbb
 
750d4eb
 
 
 
 
 
 
 
 
 
 
 
599fabc
922fb3e
d6732c4
 
3006661
d6732c4
 
 
fa34f3f
889dfbb
d6732c4
 
 
 
 
 
889dfbb
922fb3e
d6732c4
 
599fabc
922fb3e
 
d6732c4
fa34f3f
889dfbb
fa34f3f
889dfbb
922fb3e
d6732c4
 
889dfbb
 
 
d6732c4
922fb3e
 
 
889dfbb
d6732c4
922fb3e
d6732c4
 
 
 
fa34f3f
 
889dfbb
fa34f3f
d6732c4
 
 
889dfbb
d6732c4
 
 
922fb3e
 
d6732c4
fa34f3f
889dfbb
 
 
922fb3e
d6732c4
 
889dfbb
 
fa34f3f
d6732c4
922fb3e
 
 
889dfbb
d6732c4
 
 
 
 
922fb3e
d6732c4
 
599fabc
d6732c4
 
 
 
 
599fabc
d6732c4
 
 
 
 
 
 
 
 
599fabc
 
 
d6732c4
 
 
 
 
 
 
 
 
 
 
 
922fb3e
d6732c4
 
922fb3e
fa34f3f
889dfbb
fa34f3f
 
 
 
889dfbb
 
 
fa34f3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
889dfbb
 
fa34f3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
889dfbb
 
fa34f3f
 
 
 
 
 
 
889dfbb
fa34f3f
 
 
 
 
 
 
889dfbb
fa34f3f
 
 
 
 
 
 
 
 
 
 
 
889dfbb
fa34f3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
889dfbb
 
 
 
fa34f3f
 
 
 
 
 
 
889dfbb
fa34f3f
 
 
 
 
 
 
 
 
d6732c4
 
 
599fabc
922fb3e
599fabc
922fb3e
 
 
d6732c4
889dfbb
3601233
922fb3e
3601233
922fb3e
 
 
 
 
599fabc
922fb3e
d6732c4
922fb3e
 
599fabc
e6f85fa
d6732c4
922fb3e
d6732c4
922fb3e
 
 
 
 
 
 
 
 
d6732c4
922fb3e
d6732c4
922fb3e
 
 
 
 
 
 
 
 
d6732c4
fa34f3f
 
 
 
 
 
 
 
 
 
 
 
889dfbb
 
 
 
 
 
 
 
 
 
 
 
d6732c4
 
922fb3e
d6732c4
922fb3e
d6732c4
fa34f3f
889dfbb
d6732c4
 
 
922fb3e
 
d6732c4
922fb3e
 
599fabc
922fb3e
 
 
 
 
 
fa34f3f
889dfbb
 
 
d6732c4
 
 
922fb3e
599fabc
922fb3e
d6732c4
599fabc
 
922fb3e
599fabc
 
 
 
 
 
 
 
 
 
922fb3e
599fabc
922fb3e
fa34f3f
889dfbb
fa34f3f
 
 
 
 
 
889dfbb
fa34f3f
 
 
 
889dfbb
fa34f3f
 
 
 
 
 
 
 
889dfbb
 
fa34f3f
 
 
889dfbb
 
fa34f3f
 
 
 
889dfbb
fa34f3f
 
 
 
 
d6732c4
 
 
599fabc
d6732c4
 
61db3f0
d6732c4
 
 
 
599fabc
d6732c4
 
922fb3e
d6732c4
 
 
cb0b72e
 
d6732c4
 
cb0b72e
 
d6732c4
 
 
 
 
 
 
 
599fabc
 
 
d6732c4
 
 
599fabc
750d4eb
 
599fabc
 
 
 
d6732c4
 
 
 
1b61d51
d6732c4
 
599fabc
d6732c4
599fabc
d6732c4
1b61d51
d6732c4
 
922fb3e
 
1b61d51
d6732c4
599fabc
d6732c4
922fb3e
d6732c4
 
922fb3e
 
 
d6732c4
599fabc
d6732c4
 
599fabc
922fb3e
d6732c4
 
3601233
d6732c4
 
 
599fabc
d6732c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb0b72e
d6732c4
602591b
 
d6732c4
602591b
 
599fabc
 
 
 
d6732c4
599fabc
 
 
 
d6732c4
599fabc
 
fa34f3f
889dfbb
fa34f3f
599fabc
 
 
 
fa34f3f
 
889dfbb
599fabc
 
d6732c4
599fabc
 
d6732c4
92a163a
 
5ec5232
d6732c4
 
599fabc
d6732c4
 
599fabc
d6732c4
 
 
 
 
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
# modules/database.py — AKIRA V21 FINAL CORRIGIDO (Dezembro 2025) - CORREÇÃO: Com suporte a nivel_transicao, desc_transicao e usuario_privilegiado
"""
✅ TOTALMENTE ADAPTADO ao index.js atualizado
✅ CORREÇÃO: Problema com message_id UNIQUE resolvido
✅ CORREÇÃO: Suporte para nivel_transicao, desc_transicao e usuario_privilegiado adicionado
✅ Métodos corretos para api.py, contexto.py, treinamento.py
✅ Estrutura completa com reply_metadata
✅ Todos os métodos necessários implementados
"""

import sqlite3
import time
import os
import json
import hashlib
import random
from datetime import datetime
from typing import Optional, List, Dict, Any, Tuple
from loguru import logger

class Database:
    def __init__(self, db_path: str = "akira.db"):
        self.db_path = db_path
        self.max_retries = 5
        self.retry_delay = 0.1
        
        db_dir = os.path.dirname(self.db_path)
        if db_dir:
            os.makedirs(db_dir, exist_ok=True)
        
        self._init_db()
        self._ensure_columns()
        logger.info(f"✅ Database inicializado: {self.db_path}")

    def _get_connection(self) -> sqlite3.Connection:
        conn = sqlite3.connect(self.db_path, timeout=30.0, check_same_thread=False)
        conn.execute('PRAGMA journal_mode=WAL')
        conn.execute('PRAGMA synchronous=NORMAL')
        conn.execute('PRAGMA cache_size=2000')
        return conn

    def _execute_with_retry(self, query: str, params: Optional[tuple] = None,
                           commit: bool = False, fetch: bool = True):
        for attempt in range(self.max_retries):
            try:
                with self._get_connection() as conn:
                    c = conn.cursor()
                    if params:
                        c.execute(query, params)
                    else:
                        c.execute(query)
                    
                    if commit:
                        conn.commit()
                    
                    if fetch and query.strip().upper().startswith('SELECT'):
                        return c.fetchall()
                    elif fetch:
                        return c.fetchall() if c.description else []
                    else:
                        return c.lastrowid
            except sqlite3.OperationalError as e:
                if "database is locked" in str(e) and attempt < self.max_retries - 1:
                    time.sleep(self.retry_delay * (2 ** attempt))
                    continue
                logger.error(f"Erro SQL: {e}")
                raise
            except Exception as e:
                logger.error(f"Erro na query: {e}")
                raise

    def _init_db(self):
        """Cria todas as tabelas necessárias - CORREÇÃO: message_id sem UNIQUE"""
        try:
            with self._get_connection() as conn:
                c = conn.cursor()
                
                # Tabela principal de mensagens - CORREÇÃO: message_id sem UNIQUE
                c.execute('''
                    CREATE TABLE IF NOT EXISTS mensagens (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        usuario TEXT NOT NULL,
                        usuario_nome TEXT DEFAULT '',
                        numero TEXT NOT NULL,
                        mensagem TEXT NOT NULL,
                        resposta TEXT NOT NULL,
                        contexto_id TEXT NOT NULL,
                        tipo_contexto TEXT DEFAULT 'pv',
                        tipo_conversa TEXT DEFAULT 'pv',
                        tipo_mensagem TEXT DEFAULT 'texto',
                        
                        -- Reply info
                        is_reply BOOLEAN DEFAULT 0,
                        mensagem_original TEXT,
                        mensagem_citada_limpa TEXT,
                        reply_to_bot BOOLEAN DEFAULT 0,
                        reply_info_json TEXT,
                        
                        -- Estado
                        humor TEXT DEFAULT 'normal_ironico',
                        modo_resposta TEXT DEFAULT 'normal_ironico',
                        emocao_detectada TEXT,
                        confianca_emocao REAL DEFAULT 0.5,
                        
                        -- Transição
                        nivel_transicao INTEGER DEFAULT 0,
                        info_transicao_json TEXT,
                        usuario_privilegiado BOOLEAN DEFAULT 0,
                        
                        -- Grupo
                        grupo_id TEXT DEFAULT '',
                        grupo_nome TEXT DEFAULT '',
                        
                        -- Audio
                        audio_transcricao TEXT,
                        fonte_stt TEXT DEFAULT 'deepgram',
                        confianca_stt REAL DEFAULT 0.0,
                        
                        -- Meta
                        comando_executado TEXT,
                        has_media BOOLEAN DEFAULT 0,
                        media_type TEXT DEFAULT '',
                        message_id TEXT,
                        bot_response_time_ms INTEGER DEFAULT 0,
                        is_mention BOOLEAN DEFAULT 0,
                        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
                        deletado BOOLEAN DEFAULT 0
                    )
                ''')
                
                # Índice para message_id para performance (sem UNIQUE)
                c.execute('''
                    CREATE INDEX IF NOT EXISTS idx_mensagens_message_id 
                    ON mensagens(message_id)
                ''')
                
                # Índice para busca por número
                c.execute('''
                    CREATE INDEX IF NOT EXISTS idx_mensagens_numero 
                    ON mensagens(numero)
                ''')
                
                # Índice para usuario_privilegiado
                c.execute('''
                    CREATE INDEX IF NOT EXISTS idx_mensagens_usuario_privilegiado 
                    ON mensagens(usuario_privilegiado)
                ''')
                
                # Usuários privilegiados
                c.execute('''
                    CREATE TABLE IF NOT EXISTS usuarios_privilegiados (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        numero TEXT UNIQUE NOT NULL,
                        nome TEXT NOT NULL,
                        nome_curto TEXT,
                        tom_inicial TEXT DEFAULT 'formal',
                        pode_dar_ordens BOOLEAN DEFAULT 0,
                        pode_usar_reset BOOLEAN DEFAULT 0,
                        pode_forcar_modo BOOLEAN DEFAULT 0,
                        pode_apagar_mensagens BOOLEAN DEFAULT 0,
                        pode_moderar_grupos BOOLEAN DEFAULT 0,
                        nivel_acesso TEXT DEFAULT 'vip',
                        ultimo_comando TEXT,
                        timestamp_comando DATETIME,
                        comandos_executados INTEGER DEFAULT 0,
                        comandos_falhos INTEGER DEFAULT 0,
                        config_personalizada TEXT DEFAULT '{}',
                        data_criacao DATETIME DEFAULT CURRENT_TIMESTAMP,
                        data_atualizacao DATETIME DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
                
                # Contexto
                c.execute('''
                    CREATE TABLE IF NOT EXISTS contexto (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        numero TEXT UNIQUE NOT NULL,
                        contexto_id TEXT NOT NULL,
                        tipo_contexto TEXT DEFAULT 'pv',
                        historico TEXT,
                        humor_atual TEXT DEFAULT 'normal_ironico',
                        modo_resposta TEXT DEFAULT 'normal_ironico',
                        nivel_transicao INTEGER DEFAULT 0,
                        info_transicao_json TEXT,
                        usuario_privilegiado BOOLEAN DEFAULT 0,
                        humor_alvo TEXT DEFAULT 'normal_ironico',
                        termos TEXT,
                        girias TEXT,
                        tom TEXT DEFAULT 'normal',
                        emocao_tendencia TEXT DEFAULT 'neutral',
                        volatilidade REAL DEFAULT 0.5,
                        nome_usuario TEXT DEFAULT '',
                        ultima_mensagem_audio BOOLEAN DEFAULT 0,
                        frequencia_audio INTEGER DEFAULT 0,
                        prefere_audio BOOLEAN DEFAULT 0,
                        nivel_confianca_stt REAL DEFAULT 0.0,
                        configuracao_reply TEXT DEFAULT '{}',
                        estatisticas_interacao TEXT DEFAULT '{}',
                        ultimo_contato DATETIME,
                        data_criacao DATETIME DEFAULT CURRENT_TIMESTAMP,
                        data_atualizacao DATETIME DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
                
                # Training examples
                c.execute('''
                    CREATE TABLE IF NOT EXISTS training_examples (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        input_text TEXT NOT NULL,
                        output_text TEXT NOT NULL,
                        humor TEXT DEFAULT 'normal_ironico',
                        modo_resposta TEXT DEFAULT 'normal_ironico',
                        nivel_transicao INTEGER DEFAULT 0,
                        usuario_privilegiado BOOLEAN DEFAULT 0,
                        emocao_contexto TEXT,
                        contexto_super_claro TEXT,
                        tipo_interacao TEXT DEFAULT 'normal',
                        score_relevancia REAL DEFAULT 1.0,
                        tags TEXT DEFAULT '',
                        qualidade_score REAL DEFAULT 1.0,
                        usado BOOLEAN DEFAULT 0,
                        usado_para_finetuning BOOLEAN DEFAULT 0,
                        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
                
                # Transições de humor
                c.execute('''
                    CREATE TABLE IF NOT EXISTS transicoes_humor (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        numero TEXT NOT NULL,
                        contexto_id TEXT NOT NULL,
                        humor_anterior TEXT NOT NULL,
                        humor_novo TEXT NOT NULL,
                        nivel_transicao_anterior INTEGER DEFAULT 0,
                        nivel_transicao_novo INTEGER DEFAULT 0,
                        usuario_privilegiado BOOLEAN DEFAULT 0,
                        emocao_trigger TEXT,
                        confianca_emocao REAL,
                        razao TEXT,
                        intensidade REAL DEFAULT 0.5,
                        contexto_mensagem TEXT,
                        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
                
                # Gírias
                c.execute('''
                    CREATE TABLE IF NOT EXISTS girias_aprendidas (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        numero TEXT NOT NULL,
                        contexto_id TEXT NOT NULL,
                        giria TEXT NOT NULL,
                        significado TEXT NOT NULL,
                        contexto TEXT,
                        frequencia INTEGER DEFAULT 1,
                        ultimo_uso DATETIME DEFAULT CURRENT_TIMESTAMP,
                        data_criacao DATETIME DEFAULT CURRENT_TIMESTAMP,
                        UNIQUE(numero, giria)
                    )
                ''')
                
                # Comandos executados
                c.execute('''
                    CREATE TABLE IF NOT EXISTS comandos_executados (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        numero TEXT NOT NULL,
                        comando TEXT NOT NULL,
                        parametros TEXT,
                        sucesso BOOLEAN DEFAULT 1,
                        resposta TEXT,
                        tipo_conversa TEXT DEFAULT 'pv',
                        grupo_id TEXT DEFAULT '',
                        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
                
                # Reset log
                c.execute('''
                    CREATE TABLE IF NOT EXISTS reset_log (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        numero TEXT NOT NULL,
                        tipo_reset TEXT NOT NULL,
                        itens_apagados INTEGER DEFAULT 0,
                        motivo TEXT,
                        sucesso BOOLEAN DEFAULT 1,
                        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
                
                # Interações (para treinamento)
                c.execute('''
                    CREATE TABLE IF NOT EXISTS interacoes (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        numero TEXT NOT NULL,
                        mensagem TEXT NOT NULL,
                        resposta TEXT NOT NULL,
                        humor TEXT DEFAULT 'normal_ironico',
                        modo_resposta TEXT DEFAULT 'normal_ironico',
                        nivel_transicao INTEGER DEFAULT 0,
                        usuario_privilegiado BOOLEAN DEFAULT 0,
                        emocao_detectada TEXT,
                        tipo_conversa TEXT DEFAULT 'pv',
                        reply_info_json TEXT,
                        qualidade_score REAL DEFAULT 1.0,
                        data_criacao DATETIME DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
                
                conn.commit()
                logger.info("✅ Tabelas criadas/verificadas com suporte a nivel_transicao e usuario_privilegiado")
                
        except Exception as e:
            logger.error(f"❌ Erro ao criar tabelas: {e}")
            raise

    def _ensure_columns(self):
        """Garante que todas as colunas existam"""
        try:
            with self._get_connection() as conn:
                c = conn.cursor()
                
                # Colunas para mensagens
                novas_colunas = [
                    ("tipo_mensagem", "TEXT DEFAULT 'texto'"),
                    ("reply_info_json", "TEXT"),
                    ("usuario_nome", "TEXT DEFAULT ''"),
                    ("grupo_id", "TEXT DEFAULT ''"),
                    ("grupo_nome", "TEXT DEFAULT ''"),
                    ("audio_transcricao", "TEXT"),
                    ("fonte_stt", "TEXT DEFAULT 'deepgram'"),
                    ("confianca_stt", "REAL DEFAULT 0.0"),
                    ("comando_executado", "TEXT"),
                    ("tipo_conversa", "TEXT DEFAULT 'pv'"),
                    ("is_mention", "BOOLEAN DEFAULT 0"),
                    ("has_media", "BOOLEAN DEFAULT 0"),
                    ("media_type", "TEXT DEFAULT ''"),
                    ("message_id", "TEXT"),
                    ("bot_response_time_ms", "INTEGER DEFAULT 0"),
                    ("nivel_transicao", "INTEGER DEFAULT 0"),
                    ("info_transicao_json", "TEXT"),
                    ("usuario_privilegiado", "BOOLEAN DEFAULT 0")
                ]
                
                for col_name, col_def in novas_colunas:
                    try:
                        c.execute(f"ALTER TABLE mensagens ADD COLUMN {col_name} {col_def}")
                    except sqlite3.OperationalError:
                        pass
                
                # Colunas para contexto
                contexto_colunas = [
                    ("info_transicao_json", "TEXT"),
                    ("nivel_transicao", "INTEGER DEFAULT 0"),
                    ("usuario_privilegiado", "BOOLEAN DEFAULT 0")
                ]
                
                for col_name, col_def in contexto_colunas:
                    try:
                        c.execute(f"ALTER TABLE contexto ADD COLUMN {col_name} {col_def}")
                    except sqlite3.OperationalError:
                        pass
                
                # Colunas para transições
                transicoes_colunas = [
                    ("nivel_transicao_anterior", "INTEGER DEFAULT 0"),
                    ("nivel_transicao_novo", "INTEGER DEFAULT 0"),
                    ("usuario_privilegiado", "BOOLEAN DEFAULT 0")
                ]
                
                for col_name, col_def in transicoes_colunas:
                    try:
                        c.execute(f"ALTER TABLE transicoes_humor ADD COLUMN {col_name} {col_def}")
                    except sqlite3.OperationalError:
                        pass
                
                # Colunas para training_examples
                training_colunas = [
                    ("nivel_transicao", "INTEGER DEFAULT 0"),
                    ("usuario_privilegiado", "BOOLEAN DEFAULT 0")
                ]
                
                for col_name, col_def in training_colunas:
                    try:
                        c.execute(f"ALTER TABLE training_examples ADD COLUMN {col_name} {col_def}")
                    except sqlite3.OperationalError:
                        pass
                
                # Colunas para interacoes
                interacoes_colunas = [
                    ("usuario_privilegiado", "BOOLEAN DEFAULT 0")
                ]
                
                for col_name, col_def in interacoes_colunas:
                    try:
                        c.execute(f"ALTER TABLE interacoes ADD COLUMN {col_name} {col_def}")
                    except sqlite3.OperationalError:
                        pass
                
                conn.commit()
                
        except Exception as e:
            logger.warning(f"⚠️ Erro ao verificar colunas: {e}")

    # ========================================================================
    # MÉTODOS DE SALVAMENTO (ADAPTADOS AO INDEX.JS) - CORRIGIDOS COM TODOS PARÂMETROS
    # ========================================================================
    
    def salvar_mensagem(self, usuario: str, mensagem: str, resposta: str,
                       numero: str = '', is_reply: bool = False,
                       mensagem_original: str = None,
                       mensagem_citada_limpa: str = None,
                       reply_to_bot: bool = False,
                       humor: str = 'normal_ironico',
                       modo_resposta: str = 'normal_ironico',
                       emocao_detectada: str = None,
                       confianca_emocao: float = 0.5,
                       nivel_transicao: int = 0,
                       info_transicao: dict = None,
                       desc_transicao: str = None,
                       usuario_privilegiado: bool = False,  # NOVO PARÂMETRO ADICIONADO
                       tipo_mensagem: str = 'texto',
                       reply_info_json: str = None,
                       usuario_nome: str = '',
                       grupo_id: str = '',
                       grupo_nome: str = '',
                       tipo_conversa: str = 'pv',
                       audio_transcricao: str = None,
                       fonte_stt: str = 'deepgram',
                       confianca_stt: float = 0.0,
                       comando_executado: str = None,
                       has_media: bool = False,
                       media_type: str = '',
                       message_id: str = None,
                       bot_response_time_ms: int = 0,
                       is_mention: bool = False) -> bool:
        """Salva mensagem no banco - COM SUPORTE A TODOS PARÂMETROS"""
        try:
            numero_final = str(numero or usuario).strip()
            contexto_id = self._gerar_contexto_id(numero_final, tipo_conversa)
            
            # Converte reply_info para JSON se for dict
            if isinstance(reply_info_json, dict):
                reply_info_json = json.dumps(reply_info_json, ensure_ascii=False)
            
            # Converte info_transicao para JSON se for dict
            info_transicao_json = None
            if info_transicao:
                info_transicao_json = json.dumps(info_transicao, ensure_ascii=False)
            
            # Se desc_transicao for fornecida, adiciona ao info_transicao
            if desc_transicao:
                if info_transicao_json:
                    try:
                        info_transicao_dict = json.loads(info_transicao_json) if isinstance(info_transicao_json, str) else info_transicao_json
                        info_transicao_dict['desc_transicao'] = desc_transicao
                        info_transicao_json = json.dumps(info_transicao_dict, ensure_ascii=False)
                    except:
                        # Cria novo info_transicao se não conseguir parsear
                        info_transicao_json = json.dumps({'desc_transicao': desc_transicao}, ensure_ascii=False)
                else:
                    # Cria info_transicao com desc_transicao
                    info_transicao_json = json.dumps({'desc_transicao': desc_transicao}, ensure_ascii=False)
            
            # Gera message_id único se não fornecido
            if not message_id:
                timestamp = int(time.time() * 1000)
                random_suffix = random.randint(1000, 9999)
                message_id = f"{numero_final}_{timestamp}_{random_suffix}"
            
            # Adiciona um sufixo aleatório extra para garantir unicidade
            unique_suffix = random.randint(100, 999)
            message_id = f"{message_id}_{unique_suffix}"
            
            try:
                self._execute_with_retry(
                    """
                    INSERT INTO mensagens
                    (usuario, usuario_nome, mensagem, resposta, numero, contexto_id, tipo_contexto,
                     tipo_conversa, tipo_mensagem, is_reply, mensagem_original, mensagem_citada_limpa,
                     reply_to_bot, reply_info_json, humor, modo_resposta, emocao_detectada, 
                     confianca_emocao, nivel_transicao, info_transicao_json, usuario_privilegiado,
                     grupo_id, grupo_nome, audio_transcricao, fonte_stt, confianca_stt, comando_executado, 
                     has_media, media_type, message_id, bot_response_time_ms, is_mention)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (
                        usuario[:50], usuario_nome[:100] or usuario[:100], 
                        mensagem[:4000], resposta[:4000], numero_final,
                        contexto_id, tipo_conversa, tipo_conversa, tipo_mensagem,
                        int(is_reply), mensagem_original, mensagem_citada_limpa,
                        int(reply_to_bot), reply_info_json, humor, modo_resposta,
                        emocao_detectada, confianca_emocao, nivel_transicao,
                        info_transicao_json, int(usuario_privilegiado),  # ADICIONADO
                        grupo_id[:50], grupo_nome[:100],
                        audio_transcricao[:2000] if audio_transcricao else None,
                        fonte_stt[:50], confianca_stt, comando_executado[:100] if comando_executado else None,
                        int(has_media), media_type[:50], message_id[:200],
                        bot_response_time_ms, int(is_mention)
                    ),
                    commit=True,
                    fetch=False
                )
                
                logger.debug(f"✅ Mensagem salva: {numero_final} | Nível: {nivel_transicao} | Privilegiado: {usuario_privilegiado}")
                return True
                
            except sqlite3.IntegrityError as e:
                # CORREÇÃO: Se ainda houver erro de UNIQUE (pode ser de outra coluna)
                if "UNIQUE constraint failed" in str(e):
                    logger.warning(f"🔄 Erro de UNIQUE, gerando novo message_id")
                    # Gera um novo message_id completamente diferente
                    new_message_id = f"{numero_final}_{int(time.time() * 1000)}_{random.randint(10000, 99999)}"
                    
                    self._execute_with_retry(
                        """
                        INSERT INTO mensagens
                        (usuario, usuario_nome, mensagem, resposta, numero, contexto_id, tipo_contexto,
                         tipo_conversa, tipo_mensagem, is_reply, mensagem_original, mensagem_citada_limpa,
                         reply_to_bot, reply_info_json, humor, modo_resposta, emocao_detectada, 
                         confianca_emocao, nivel_transicao, info_transicao_json, usuario_privilegiado,
                         grupo_id, grupo_nome, audio_transcricao, fonte_stt, confianca_stt, comando_executado, 
                         has_media, media_type, message_id, bot_response_time_ms, is_mention)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        """,
                        (
                            usuario[:50], usuario_nome[:100] or usuario[:100], 
                            mensagem[:4000], resposta[:4000], numero_final,
                            contexto_id, tipo_conversa, tipo_conversa, tipo_mensagem,
                            int(is_reply), mensagem_original, mensagem_citada_limpa,
                            int(reply_to_bot), reply_info_json, humor, modo_resposta,
                            emocao_detectada, confianca_emocao, nivel_transicao,
                            info_transicao_json, int(usuario_privilegiado),  # ADICIONADO
                            grupo_id[:50], grupo_nome[:100],
                            audio_transcricao[:2000] if audio_transcricao else None,
                            fonte_stt[:50], confianca_stt, comando_executado[:100] if comando_executado else None,
                            int(has_media), media_type[:50], new_message_id[:200],
                            bot_response_time_ms, int(is_mention)
                        ),
                        commit=True,
                        fetch=False
                    )
                    logger.debug(f"✅ Mensagem salva com novo message_id: {new_message_id}")
                    return True
                else:
                    raise
            
        except Exception as e:
            logger.error(f"❌ Erro ao salvar mensagem: {e}")
            return False

    def salvar_training_example(self, input_text: str, output_text: str,
                               humor: str = "normal_ironico",
                               modo_resposta: str = "normal_ironico",
                               nivel_transicao: int = 0,
                               usuario_privilegiado: bool = False,  # NOVO PARÂMETRO
                               emocao_contexto: str = None,
                               qualidade_score: float = 1.0,
                               contexto_super_claro: Dict = None,
                               tipo_interacao: str = "normal",
                               score_relevancia: float = 1.0,
                               tags: List[str] = None) -> bool:
        """Salva exemplo de treinamento - COM usuario_privilegiado"""
        try:
            contexto_json = json.dumps(contexto_super_claro, ensure_ascii=False) if contexto_super_claro else None
            tags_str = ",".join(tags) if tags else ""
            
            self._execute_with_retry(
                """
                INSERT INTO training_examples
                (input_text, output_text, humor, modo_resposta, nivel_transicao,
                 usuario_privilegiado, emocao_contexto, qualidade_score, contexto_super_claro, 
                 tipo_interacao, score_relevancia, tags)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    input_text[:2000], output_text[:2000], humor, modo_resposta,
                    nivel_transicao, int(usuario_privilegiado), emocao_contexto, 
                    qualidade_score, contexto_json, tipo_interacao, score_relevancia, 
                    tags_str[:200]
                ),
                commit=True,
                fetch=False
            )
            logger.debug(f"✅ Training example salvo | Nível: {nivel_transicao} | Privilegiado: {usuario_privilegiado}")
            return True
        except Exception as e:
            logger.error(f"❌ Erro ao salvar training: {e}")
            return False

    def salvar_transicao_humor(self, numero: str, humor_anterior: str,
                              humor_novo: str, nivel_transicao_anterior: int = 0,
                              nivel_transicao_novo: int = 0,
                              usuario_privilegiado: bool = False,  # NOVO PARÂMETRO
                              emocao_trigger: str = None,
                              confianca_emocao: float = 0.5,
                              razao: str = "", intensidade: float = 0.5,
                              contexto_mensagem: str = None):
        """Salva transição de humor - COM usuario_privilegiado"""
        try:
            contexto_id = self._gerar_contexto_id(numero, 'auto')
            
            self._execute_with_retry(
                """
                INSERT INTO transicoes_humor
                (numero, contexto_id, humor_anterior, humor_novo, 
                 nivel_transicao_anterior, nivel_transicao_novo, usuario_privilegiado,
                 emocao_trigger, confianca_emocao, razao, intensidade, contexto_mensagem)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    str(numero).strip(), contexto_id, humor_anterior, humor_novo,
                    nivel_transicao_anterior, nivel_transicao_novo, int(usuario_privilegiado),
                    emocao_trigger, confianca_emocao, razao[:200], intensidade, 
                    contexto_mensagem[:500] if contexto_mensagem else None
                ),
                commit=True,
                fetch=False
            )
            logger.debug(f"🎭 Transição salva: {humor_anterior}{humor_novo} | Nível: {nivel_transicao_anterior}{nivel_transicao_novo} | Privilegiado: {usuario_privilegiado}")
        except Exception as e:
            logger.error(f"❌ Erro ao salvar transição: {e}")

    def salvar_giria(self, numero: str, giria: str, significado: str, contexto: str = ""):
        """Salva gíria aprendida"""
        try:
            numero_final = str(numero).strip()
            contexto_id = self._gerar_contexto_id(numero_final, 'auto')
            
            result = self._execute_with_retry(
                "SELECT id, frequencia FROM girias_aprendidas WHERE numero = ? AND giria = ?",
                (numero_final, giria),
                fetch=True
            )
            
            if result:
                self._execute_with_retry(
                    """
                    UPDATE girias_aprendidas
                    SET frequencia = frequencia + 1,
                        ultimo_uso = CURRENT_TIMESTAMP
                    WHERE numero = ? AND giria = ?
                    """,
                    (numero_final, giria),
                    commit=True,
                    fetch=False
                )
            else:
                self._execute_with_retry(
                    """
                    INSERT INTO girias_aprendidas
                    (numero, contexto_id, giria, significado, contexto)
                    VALUES (?, ?, ?, ?, ?)
                    """,
                    (numero_final, contexto_id, giria, significado, contexto[:100]),
                    commit=True,
                    fetch=False
                )
            return True
        except Exception as e:
            logger.error(f"❌ Erro ao salvar gíria: {e}")
            return False

    # ========================================================================
    # MÉTODOS DE CONTEXTO - COM usuario_privilegiado
    # ========================================================================
    
    def atualizar_contexto(self, numero: str, humor_atual: str = None,
                          modo_resposta: str = None, nivel_transicao: int = None,
                          info_transicao: dict = None, usuario_privilegiado: bool = False,
                          tom: str = None, emocao_tendencia: str = None) -> bool:
        """Atualiza contexto do usuário - COM usuario_privilegiado"""
        try:
            numero_final = str(numero).strip()
            contexto_id = self._gerar_contexto_id(numero_final, 'auto')
            
            # Verifica se contexto existe
            result = self._execute_with_retry(
                "SELECT 1 FROM contexto WHERE numero = ?",
                (numero_final,),
                fetch=True
            )
            
            info_transicao_json = None
            if info_transicao:
                info_transicao_json = json.dumps(info_transicao, ensure_ascii=False)
            
            if result:
                # Atualiza existente
                updates = []
                params = []
                
                if humor_atual:
                    updates.append("humor_atual = ?")
                    params.append(humor_atual)
                if modo_resposta:
                    updates.append("modo_resposta = ?")
                    params.append(modo_resposta)
                if nivel_transicao is not None:
                    updates.append("nivel_transicao = ?")
                    params.append(nivel_transicao)
                if info_transicao_json:
                    updates.append("info_transicao_json = ?")
                    params.append(info_transicao_json)
                updates.append("usuario_privilegiado = ?")
                params.append(int(usuario_privilegiado))
                if tom:
                    updates.append("tom = ?")
                    params.append(tom)
                if emocao_tendencia:
                    updates.append("emocao_tendencia = ?")
                    params.append(emocao_tendencia)
                
                updates.append("ultimo_contato = CURRENT_TIMESTAMP")
                updates.append("data_atualizacao = CURRENT_TIMESTAMP")
                
                if updates:
                    query = f"UPDATE contexto SET {', '.join(updates)} WHERE numero = ?"
                    params.append(numero_final)
                    self._execute_with_retry(query, tuple(params), commit=True, fetch=False)
            else:
                # Cria novo contexto
                self._execute_with_retry(
                    """
                    INSERT INTO contexto
                    (numero, contexto_id, humor_atual, modo_resposta, nivel_transicao,
                     info_transicao_json, usuario_privilegiado, tom, emocao_tendencia, ultimo_contato)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
                    """,
                    (
                        numero_final, contexto_id,
                        humor_atual or 'normal_ironico',
                        modo_resposta or 'normal_ironico',
                        nivel_transicao or 0,
                        info_transicao_json,
                        int(usuario_privilegiado),
                        tom or 'normal',
                        emocao_tendencia or 'neutral'
                    ),
                    commit=True,
                    fetch=False
                )
            
            logger.debug(f"✅ Contexto atualizado: {numero_final} | Nível: {nivel_transicao} | Privilegiado: {usuario_privilegiado}")
            return True
            
        except Exception as e:
            logger.error(f"❌ Erro ao atualizar contexto: {e}")
            return False

    def recuperar_contexto(self, numero: str) -> Dict[str, Any]:
        """Recupera contexto completo do usuário"""
        try:
            result = self._execute_with_retry(
                """
                SELECT humor_atual, modo_resposta, nivel_transicao, info_transicao_json,
                       usuario_privilegiado, tom, emocao_tendencia, ultimo_contato
                FROM contexto WHERE numero = ?
                """,
                (str(numero).strip(),),
                fetch=True
            )
            
            if result:
                row = result[0]
                info_transicao = {}
                if row[3]:
                    try:
                        info_transicao = json.loads(row[3])
                    except:
                        pass
                
                return {
                    "humor_atual": row[0] or "normal_ironico",
                    "modo_resposta": row[1] or "normal_ironico",
                    "nivel_transicao": row[2] or 0,
                    "info_transicao": info_transicao,
                    "usuario_privilegiado": bool(row[4]) if row[4] is not None else False,
                    "tom": row[5] or "normal",
                    "emocao_tendencia": row[6] or "neutral",
                    "ultimo_contato": row[7]
                }
            
            return {
                "humor_atual": "normal_ironico",
                "modo_resposta": "normal_ironico",
                "nivel_transicao": 0,
                "info_transicao": {},
                "usuario_privilegiado": False,
                "tom": "normal",
                "emocao_tendencia": "neutral",
                "ultimo_contato": None
            }
            
        except Exception as e:
            logger.error(f"❌ Erro ao recuperar contexto: {e}")
            return {}

    # ========================================================================
    # MÉTODOS DE RECUPERAÇÃO
    # ========================================================================
    
    def recuperar_mensagens(self, numero: str, limite: int = 10) -> List[Tuple]:
        """Recupera mensagens do usuário"""
        try:
            results = self._execute_with_retry(
                """
                SELECT mensagem, resposta, is_reply, mensagem_original, 
                       reply_to_bot, humor, modo_resposta, nivel_transicao, usuario_privilegiado, timestamp
                FROM mensagens
                WHERE numero = ? AND deletado = 0
                ORDER BY timestamp DESC
                LIMIT ?
                """,
                (str(numero).strip(), limite),
                fetch=True
            )
            
            if results:
                return results[::-1]  # Reverter para ordem cronológica
            return []
        except Exception as e:
            logger.error(f"❌ Erro ao recuperar mensagens: {e}")
            return []

    def recuperar_humor_atual(self, numero: str) -> str:
        """Recupera humor atual"""
        try:
            result = self._execute_with_retry(
                "SELECT humor_atual FROM contexto WHERE numero = ?",
                (str(numero).strip(),),
                fetch=True
            )
            return result[0][0] if result else "normal_ironico"
        except Exception:
            return "normal_ironico"

    def recuperar_modo_resposta(self, numero: str) -> str:
        """Recupera modo de resposta"""
        try:
            result = self._execute_with_retry(
                "SELECT modo_resposta FROM contexto WHERE numero = ?",
                (str(numero).strip(),),
                fetch=True
            )
            return result[0][0] if result else "normal_ironico"
        except Exception:
            return "normal_ironico"

    def recuperar_nivel_transicao(self, numero: str) -> int:
        """Recupera nível de transição"""
        try:
            result = self._execute_with_retry(
                "SELECT nivel_transicao FROM contexto WHERE numero = ?",
                (str(numero).strip(),),
                fetch=True
            )
            return result[0][0] if result else 0
        except Exception:
            return 0

    def recuperar_usuario_privilegiado(self, numero: str) -> bool:
        """Recupera se usuário é privilegiado"""
        try:
            result = self._execute_with_retry(
                "SELECT usuario_privilegiado FROM contexto WHERE numero = ?",
                (str(numero).strip(),),
                fetch=True
            )
            return bool(result[0][0]) if result else False
        except Exception:
            return False

    def recuperar_training_examples(self, limite: int = 100, usado: bool = False) -> List[Dict]:
        """Recupera exemplos de treinamento"""
        try:
            where_clause = "WHERE usado = 0" if not usado else ""
            results = self._execute_with_retry(
                f"""
                SELECT input_text, output_text, humor, modo_resposta, nivel_transicao,
                       usuario_privilegiado, qualidade_score, tipo_interacao
                FROM training_examples
                {where_clause}
                ORDER BY qualidade_score DESC
                LIMIT ?
                """,
                (limite,),
                fetch=True
            )
            
            return [
                {
                    "input": r[0],
                    "output": r[1],
                    "humor": r[2],
                    "modo": r[3],
                    "nivel_transicao": r[4],
                    "usuario_privilegiado": bool(r[5]) if r[5] is not None else False,
                    "score": r[6],
                    "tipo": r[7]
                }
                for r in results
            ]
        except Exception as e:
            logger.error(f"❌ Erro ao recuperar exemplos: {e}")
            return []

    def marcar_examples_como_usados(self, ids: List[int] = None):
        """Marca exemplos como usados"""
        try:
            if ids:
                placeholders = ','.join(['?'] * len(ids))
                query = f"UPDATE training_examples SET usado = 1 WHERE id IN ({placeholders})"
                self._execute_with_retry(query, tuple(ids), commit=True, fetch=False)
            else:
                self._execute_with_retry(
                    "UPDATE training_examples SET usado = 1 WHERE usado = 0",
                    commit=True,
                    fetch=False
                )
        except Exception as e:
            logger.error(f"❌ Erro ao marcar exemplos: {e}")

    # ========================================================================
    # MÉTODO PARA REGISTRAR INTERAÇÃO (PARA TREINAMENTO) - COM usuario_privilegiado
    # ========================================================================
    
    def registrar_interacao(self, numero: str, mensagem: str, resposta: str,
                           humor: str = 'normal_ironico',
                           modo_resposta: str = 'normal_ironico',
                           nivel_transicao: int = 0,
                           usuario_privilegiado: bool = False,  # NOVO PARÂMETRO
                           emocao_detectada: str = None,
                           tipo_conversa: str = 'pv',
                           reply_info_json: str = None,
                           qualidade_score: float = 1.0) -> bool:
        """Registra interação para treinamento - COM usuario_privilegiado"""
        try:
            if isinstance(reply_info_json, dict):
                reply_info_json = json.dumps(reply_info_json, ensure_ascii=False)
            
            self._execute_with_retry(
                """
                INSERT INTO interacoes
                (numero, mensagem, resposta, humor, modo_resposta, nivel_transicao,
                 usuario_privilegiado, emocao_detectada, tipo_conversa, reply_info_json, qualidade_score)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    str(numero).strip(), mensagem[:2000], resposta[:2000], humor, modo_resposta,
                    nivel_transicao, int(usuario_privilegiado), emocao_detectada, 
                    tipo_conversa, reply_info_json, qualidade_score
                ),
                commit=True,
                fetch=False
            )
            logger.debug(f"✅ Interação registrada: {numero} | Nível: {nivel_transicao} | Privilegiado: {usuario_privilegiado}")
            return True
        except Exception as e:
            logger.error(f"❌ Erro ao registrar interação: {e}")
            return False

    # ========================================================================
    # PRIVILÉGIOS
    # ========================================================================
    
    def is_usuario_privilegiado(self, numero: str) -> bool:
        """Verifica se usuário é privilegiado"""
        try:
            result = self._execute_with_retry(
                "SELECT 1 FROM usuarios_privilegiados WHERE numero = ?",
                (str(numero).strip(),),
                fetch=True
            )
            return bool(result)
        except Exception:
            return False

    def pode_usar_reset(self, numero: str) -> bool:
        """Verifica se pode usar reset"""
        try:
            result = self._execute_with_retry(
                "SELECT pode_usar_reset FROM usuarios_privilegiados WHERE numero = ?",
                (str(numero).strip(),),
                fetch=True
            )
            return bool(result and result[0][0])
        except Exception:
            return False

    def registrar_comando(self, numero: str, comando: str, parametros: str = None,
                         sucesso: bool = True, resposta: str = None,
                         tipo_conversa: str = 'pv', grupo_id: str = ''):
        """Registra comando executado"""
        try:
            self._execute_with_retry(
                """
                INSERT INTO comandos_executados
                (numero, comando, parametros, sucesso, resposta, tipo_conversa, grupo_id)
                VALUES (?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    str(numero).strip(), comando, parametros, int(sucesso), resposta, tipo_conversa, grupo_id),
                commit=True,
                fetch=False
            )
        except Exception as e:
            logger.error(f"❌ Erro ao registrar comando: {e}")

    def resetar_contexto_usuario(self, numero: str, tipo: str = "completo") -> Dict:
        """Reseta contexto do usuário"""
        try:
            if not self.pode_usar_reset(numero):
                return {"sucesso": False, "erro": "Sem permissão", "itens_apagados": 0}
            
            itens = 0
            
            # Remove mensagens
            self._execute_with_retry(
                "DELETE FROM mensagens WHERE numero = ?",
                (str(numero).strip(),),
                commit=True,
                fetch=False
            )
            itens += 1
            
            # Remove contexto
            self._execute_with_retry(
                "DELETE FROM contexto WHERE numero = ?",
                (str(numero).strip(),),
                commit=True,
                fetch=False
            )
            itens += 1
            
            logger.info(f"✅ Reset completo para {numero}: {itens} itens")
            return {"sucesso": True, "itens_apagados": itens}
            
        except Exception as e:
            logger.error(f"❌ Erro ao resetar: {e}")
            return {"sucesso": False, "erro": str(e), "itens_apagados": 0}

    # ========================================================================
    # AUXILIARES
    # ========================================================================
    
    def _gerar_contexto_id(self, numero: str, tipo: str = 'auto') -> str:
        """Gera ID único para contexto"""
        if tipo == 'auto':
            num_str = str(numero).lower()
            if "@g.us" in num_str or "grupo_" in num_str or "120363" in num_str:
                tipo = "grupo"
            else:
                tipo = "pv"
        
        data_semana = datetime.now().strftime("%Y-%W")
        salt = f"AKIRA_V21_{data_semana}_ISOLATION"
        raw = f"{str(numero).strip()}|{tipo}|{salt}"
        return hashlib.sha256(raw.encode()).hexdigest()[:32]

    def registrar_tom_usuario(self, numero: str, tom: str, confianca: float = 0.6,
                             mensagem_contexto: str = None) -> bool:
        """Registra tom detectado"""
        try:
            logger.info(f"✅ Tom registrado: {tom} ({confianca:.2f}) para {numero}")
            return True
        except Exception as e:
            logger.error(f"❌ Erro ao registrar tom: {e}")
            return False

    def salvar_aprendizado_detalhado(self, input_text: str, output_text: str,
                                    contexto: Dict, qualidade_score: float = 1.0,
                                    tipo_aprendizado: str = "reply_padrao",
                                    metadata: Dict = None) -> bool:
        """Salva aprendizado detalhado"""
        try:
            contexto_super_claro = {
                'tipo_aprendizado': tipo_aprendizado,
                'metadata': metadata or {},
                'timestamp': time.time()
            }
            
            nivel_transicao = contexto.get('nivel_transicao', 0)
            usuario_privilegiado = contexto.get('usuario_privilegiado', False)
            
            return self.salvar_training_example(
                input_text=input_text,
                output_text=output_text,
                humor=contexto.get("humor_atualizado", "normal_ironico"),
                modo_resposta=contexto.get("modo_resposta", "normal_ironico"),
                nivel_transicao=nivel_transicao,
                usuario_privilegiado=usuario_privilegiado,
                qualidade_score=qualidade_score,
                contexto_super_claro=contexto_super_claro,
                tipo_interacao=tipo_aprendizado
            )
        except Exception as e:
            logger.error(f"❌ Erro ao salvar aprendizado: {e}")
            return False

    def close(self):
        """Fecha conexão"""
        logger.info("✅ Database fechado")

# Singleton
_db_instance = None

def get_database(db_path: str = "akira.db") -> Database:
    global _db_instance
    if _db_instance is None:
        _db_instance = Database(db_path)
    return _db_instance