File size: 68,400 Bytes
5b2fc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""
QuickVocabCapture - Từ điển Tiếng Anh (IELTS/CEFR) & Tiếng Pháp (DELF/DALF) - Giao diện MochiMochi Chuẩn
Tính năng nổi bật:
1. Giao diện chuẩn MochiMochi theo đúng mẫu thiết kế:
   - Thanh Header với Logo MochiMochi, nút Nghe 🎧, Sổ từ đã lưu 📓, nút chuyển ngôn ngữ En - Vi ▾ / Fr - Vi ▾, Avatar Mochi, Ghim ⚙️
   - Ô tìm kiếm bo tròn viền vàng cam kèm vạch ngăn cách và kính lúp 🔍
   - Thanh Tab loại từ (Noun / Verb / Adjective ▾ | CEFR / DELF Context | Definition | Word Forms)
   - Tiêu đề từ vựng chữ lớn màu xanh đậm (#1E3A8A) + từ loại in nghiêng + nút [⊕ Lưu từ]
   - Dòng phát âm EN / FR 🔊 /ipa/
   - Danh sách các phiên bản nghĩa (1., 2., 3....) kèm huy hiệu CEFR (A1..C2),
     nút [⊕ Lưu từ] riêng cho từng nghĩa, và câu ví dụ + dịch tiếng Việt in nghiêng bên dưới.
2. Hai bộ cơ sở dữ liệu từ điển độc lập:
   - Tiếng Anh (En - Vi): E:\\tools\\english_dictionary.db -> lưu vào deck "hoc_lom" & danh_sach_tu_en.txt -> đồng bộ Hugging Face hung9066/mochi-english-anki-data
   - Tiếng Pháp (Fr - Vi): E:\\tools\\french_dictionary.db -> lưu vào deck "french2" & danh_sach_tu.txt -> đồng bộ Hugging Face hung9066/mochi-french-anki-data
3. Tự động bắt từ khi BÔI ĐEN + NHẤN PHÍM CTRL 2 LẦN LIÊN TIẾP (Double-Ctrl) hoặc nhập trực tiếp vào ô tra cứu.
"""

import sys
import os
import re
import json
import io
import base64
import time
import html
import random
import sqlite3
import threading
import queue
import urllib.parse
import unicodedata
import winsound
import ctypes
import subprocess
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
from bs4 import BeautifulSoup

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8")

try:
    import requests
    import customtkinter as ctk
    import pyperclip
    from pynput import mouse, keyboard
except ImportError as e:
    print(f"[!] Thư viện còn thiếu: {e}. Vui lòng cài đặt: pip install customtkinter pyperclip pynput requests pillow beautifulsoup4")

# ==============================================================================
# ĐƯỜNG DẪN ỨNG DỤNG TRONG E:\tools
# ==============================================================================
if getattr(sys, "frozen", False):
    APP_DIR = os.path.dirname(os.path.abspath(sys.executable))
else:
    APP_DIR = os.path.dirname(os.path.abspath(__file__))

FR_SQLITE_DB_PATH = os.path.join(APP_DIR, "french_dictionary.db")
EN_SQLITE_DB_PATH = os.path.join(APP_DIR, "english_dictionary.db")
LANG_PREF_FILE = os.path.join(APP_DIR, "vocab_lang_pref.json")
LOGO_PATH = os.path.join(APP_DIR, "mochimochi_logo.png")
AVATAR_PATH = os.path.join(APP_DIR, "mochi_head.png")

PROJECT_QUEUE_DIR = r"E:\AnkiProject\queue"
FR_PROJECT_QUEUE = os.path.join(PROJECT_QUEUE_DIR, "danh_sach_tu.txt")
EN_PROJECT_QUEUE = os.path.join(PROJECT_QUEUE_DIR, "danh_sach_tu_en.txt")

FR_LOCAL_LIST_FILE = os.path.join(APP_DIR, "danh_sach_tu.txt")
EN_LOCAL_LIST_FILE = os.path.join(APP_DIR, "danh_sach_tu_en.txt")

FR_LIST_FILE = FR_PROJECT_QUEUE if os.path.exists(PROJECT_QUEUE_DIR) else FR_LOCAL_LIST_FILE
EN_LIST_FILE = EN_PROJECT_QUEUE if os.path.exists(PROJECT_QUEUE_DIR) else EN_LOCAL_LIST_FILE

CLOUD_CONFIG_PATH = r"C:\Users\ASUS\.gemini\antigravity\scratch\anki_web_server\cloud_config.json"
FR_HF_DATASET_REPO = "hung9066/mochi-french-anki-data"
EN_HF_DATASET_REPO = "hung9066/mochi-english-anki-data"

ANKI_URL = "http://127.0.0.1:8765"
ANKI_BAT_PATH = r"E:\Chay_Anki.bat"
ANKI_EXE_PATH = r"E:\AnkiPortable\AnkiProgram\Anki.exe"
ANKI_DATA_PATH = r"E:\AnkiPortable\AnkiData"

anki_session = requests.Session()

DISTRACTOR_POOL_FR = [
    "Cải thiện, làm cho tốt hơn", "Đòi hỏi, yêu cầu khắt khe", "Bồi thường, đền bù thiệt hại",
    "Phát triển, mở rộng quy mô", "Quan sát, theo dõi kỹ lưỡng", "Giải thích, làm sáng tỏ vấn đề",
    "Duy trì, bảo tồn lâu dài", "Thúc đẩy, khuyến khích phát triển", "Ngăn cản, cản trở tiến trình",
    "Đánh giá, phân tích chi tiết", "Thích nghi với hoàn cảnh mới", "Đạt được mục tiêu đề ra"
]
DISTRACTOR_POOL_EN = [
    "to make something less severe or painful", "to encourage or promote the development of",
    "to examine or inspect closely and thoroughly", "to confirm or give support to a statement",
    "to reduce in extent or quantity; restrict", "able to withstand or recover quickly from difficulty",
    "lasting for only a very short time", "present, appearing, or found everywhere",
    "to make a problem or bad situation worse", "based on observation or experience rather than theory",
    "to officially forbid something by law or rule", "to produce or provide a natural or industrial result"
]
DISTRACTOR_WORDS_FR = ["améliorer", "exiger", "compenser", "développer", "observer", "maintenir", "favoriser", "évaluer"]
DISTRACTOR_WORDS_EN = ["mitigate", "foster", "scrutinize", "corroborate", "curtail", "resilient", "ephemeral", "ubiquitous"]

ANKI_NOTES_CACHE = {"fr": {}, "en": {}}
ANKI_CACHE_READY = {"fr": False, "en": False}
SAVED_WORDS_SET = {"fr": set(), "en": set()}
WORD_LIST_LOCK = threading.Lock()


# ==============================================================================
# TIỆN ÍCH LÀM SẠCH TỪ & PHÂN LOẠI TRÌNH ĐỘ CEFR / DELF / IELTS
# ==============================================================================
def clean_word_stem(w, lang="fr"):
    w = unicodedata.normalize("NFC", (w or "").lower().strip())
    if lang == "en":
        w = re.sub(r"^(to |a |an |the )", "", w)
    else:
        w = re.sub(r"^(l'|d'|le |la |les |un |une |des |du |de la |de l'|se |s')", "", w)
    w = re.sub(r"\s*\([^)]*\)", "", w).strip()
    return w


def get_short_cefr(level_str):
    for code in ("A1", "A2", "B1", "B2", "C1", "C2"):
        if code in (level_str or ""):
            return code
    return "B2"


def estimate_delf_dalf_level(word, sense_idx=0):
    stem = clean_word_stem(word, "fr")
    levels = ["DELF A1", "DELF A2", "DELF B1", "DELF B2", "DALF C1", "DALF C2"]
    if any(stem.endswith(s) for s in ["isation", "isme", "ologie", "archie", "cratie", "phobie"]):
        base = 4
    elif any(stem.endswith(s) for s in ["ment", "tion", "sion", "ence", "ance", "ité", "able", "ible", "ique"]):
        base = 3 if len(stem) >= 9 else 2
    elif len(stem) <= 4:
        base = 0
    elif len(stem) <= 6:
        base = 1
    elif len(stem) <= 9:
        base = 2
    elif len(stem) <= 12:
        base = 3
    else:
        base = 4
    idx = min(5, base + (1 if sense_idx >= 2 and base < 4 else 0))
    return levels[idx]


def estimate_english_cefr_level(word, sense_idx=0):
    stem = clean_word_stem(word, "en")
    levels = ["CEFR A1", "CEFR A2", "CEFR B1", "IELTS 6.5 / B2", "IELTS 7.5 / C1", "IELTS 8.5 / C2"]
    if any(stem.endswith(s) for s in ["ization", "isation", "ology", "cracy", "phobia", "escence", "itious"]):
        base = 4
    elif any(stem.endswith(s) for s in ["ment", "tion", "sion", "ence", "ance", "ity", "able", "ible", "ous", "ive", "ate"]):
        base = 4 if len(stem) >= 10 else 3
    elif len(stem) <= 4:
        base = 1
    elif len(stem) <= 6:
        base = 2
    elif len(stem) <= 9:
        base = 3
    elif len(stem) <= 12:
        base = 4
    else:
        base = 5
    idx = min(5, base + (1 if sense_idx >= 2 and base < 4 else 0))
    return levels[idx]


# ==============================================================================
# QUẢN LÝ FILE DANH SÁCH TỪ ĐÃ LƯU & ĐỒNG BỘ ANKI + HUGGING FACE
# ==============================================================================
def init_saved_word_list():
    for lang, paths in (("fr", {FR_LIST_FILE, FR_LOCAL_LIST_FILE}), ("en", {EN_LIST_FILE, EN_LOCAL_LIST_FILE})):
        for path in paths:
            try:
                if not os.path.exists(path):
                    os.makedirs(os.path.dirname(path), exist_ok=True)
                    open(path, "w", encoding="utf-8").close()
                else:
                    with open(path, "r", encoding="utf-8", errors="ignore") as f:
                        for line in f:
                            s = line.strip().lower()
                            if s:
                                SAVED_WORDS_SET[lang].add(s)
                                if "\t" in s:
                                    SAVED_WORDS_SET[lang].add(s.split("\t")[0].strip())
            except Exception as e:
                print(f"[!] Lỗi đọc file từ vựng ({lang}): {e}")


def upload_word_list_to_hf_sync(lang="fr"):
    try:
        if lang == "en":
            src_path = EN_LOCAL_LIST_FILE if os.path.exists(EN_LOCAL_LIST_FILE) else EN_LIST_FILE
            repo_id = EN_HF_DATASET_REPO
            remote_name = "danh_sach_tu_en.txt"
        else:
            src_path = FR_LOCAL_LIST_FILE if os.path.exists(FR_LOCAL_LIST_FILE) else FR_LIST_FILE
            repo_id = FR_HF_DATASET_REPO
            remote_name = "danh_sach_tu.txt"

        if not os.path.exists(src_path) or not os.path.exists(CLOUD_CONFIG_PATH):
            return False
        with open(CLOUD_CONFIG_PATH, "r", encoding="utf-8-sig") as f:
            cfg = json.load(f)
        token = (cfg.get("token") or cfg.get("hf_token") or "").strip()
        if not token:
            return False
        with open(src_path, "rb") as f:
            raw_bytes = f.read()
        b64 = base64.b64encode(raw_bytes).decode("ascii")
        ndjson_body = (
            json.dumps({"key": "header", "value": {"summary": f"Sync {remote_name} from QuickVocabCapture"}}) + "\n" +
            json.dumps({"key": "file", "value": {"content": b64, "path": remote_name, "encoding": "base64"}}) + "\n"
        )
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/x-ndjson"
        }
        resp = requests.post(
            f"https://huggingface.co/api/datasets/{repo_id}/commit/main",
            data=ndjson_body.encode("utf-8"),
            headers=headers,
            timeout=6.0
        )
        return resp.status_code == 200
    except Exception:
        return False


def save_to_word_list(word_clean, level_text="", meaning_text="", example_text="", lang="fr"):
    with WORD_LIST_LOCK:
        line_to_write = f"{word_clean}\t{level_text}\t{meaning_text}\t{example_text}".strip()
        key = f"{word_clean.lower().strip()}\t{meaning_text.lower().strip()}"
        if key in SAVED_WORDS_SET[lang]:
            return
        paths = {EN_LIST_FILE, EN_LOCAL_LIST_FILE} if lang == "en" else {FR_LIST_FILE, FR_LOCAL_LIST_FILE}
        for path in paths:
            try:
                os.makedirs(os.path.dirname(path), exist_ok=True)
                with open(path, "a", encoding="utf-8") as f:
                    f.write(f"{line_to_write}\n")
                    f.flush()
            except Exception:
                pass
        SAVED_WORDS_SET[lang].add(key)
        SAVED_WORDS_SET[lang].add(word_clean.lower().strip())
    threading.Thread(target=upload_word_list_to_hf_sync, args=(lang,), daemon=True).start()


def anki_request(action, **params):
    try:
        payload = {"action": action, "params": params, "version": 6}
        resp = anki_session.post(ANKI_URL, json=payload, timeout=2.0)
        if resp.status_code == 200:
            return resp.json()
    except Exception:
        pass
    return None


def check_anki_connection():
    data = anki_request("version")
    return bool(data and data.get("result"))


def launch_anki_background():
    if check_anki_connection():
        return True
    try:
        if os.path.exists(ANKI_BAT_PATH):
            subprocess.Popen([ANKI_BAT_PATH], shell=True)
        elif os.path.exists(ANKI_EXE_PATH):
            subprocess.Popen([ANKI_EXE_PATH, "-b", ANKI_DATA_PATH])
        for _ in range(14):
            time.sleep(0.4)
            if check_anki_connection():
                init_anki_cache_background()
                return True
    except Exception as e:
        print(f"[!] Không thể mở Anki: {e}")
    return check_anki_connection()


def record_card_in_anki_cache(word, meaning, lang="fr"):
    w_k = clean_word_stem(word, lang)
    m_k = meaning.strip().lower()
    ANKI_NOTES_CACHE[lang].setdefault(w_k, set()).add(m_k)


def init_anki_cache_background():
    def worker():
        for lang, deck_name, pool_m, pool_w in (
            ("fr", "french2", DISTRACTOR_POOL_FR, DISTRACTOR_WORDS_FR),
            ("en", "hoc_lom", DISTRACTOR_POOL_EN, DISTRACTOR_WORDS_EN),
        ):
            try:
                data = anki_request("findNotes", query=f'deck:"{deck_name}"')
                if not data or not data.get("result"):
                    continue
                notes = data["result"]
                for i in range(0, len(notes), 500):
                    chunk = notes[i:i + 500]
                    info_data = anki_request("notesInfo", notes=chunk)
                    if info_data and info_data.get("result"):
                        for n in info_data["result"]:
                            w = n.get("fields", {}).get("word", {}).get("value", "").strip()
                            m = n.get("fields", {}).get("meaning", {}).get("value", "").strip()
                            if w and m:
                                record_card_in_anki_cache(w, m, lang)
                                if len(m) < 70 and m not in pool_m:
                                    pool_m.append(m)
                                if len(w) < 35 and w not in pool_w:
                                    pool_w.append(w)
                ANKI_CACHE_READY[lang] = True
            except Exception:
                pass
    threading.Thread(target=worker, daemon=True).start()


def is_card_already_in_anki(word, meaning, deck_name="french2", lang="fr"):
    w_k = clean_word_stem(word, lang)
    m_k = meaning.strip().lower()
    if ANKI_CACHE_READY.get(lang) and w_k in ANKI_NOTES_CACHE[lang]:
        return m_k in ANKI_NOTES_CACHE[lang][w_k]

    escaped = word.replace('"', '\\"')
    data = anki_request("findNotes", query=f'deck:"{deck_name}" "word:{escaped}"')
    if not data or not data.get("result"):
        return False
    info_data = anki_request("notesInfo", notes=data["result"])
    if not info_data or not info_data.get("result"):
        return False
    for n in info_data["result"]:
        m = n.get("fields", {}).get("meaning", {}).get("value", "").strip().lower()
        if m == m_k:
            record_card_in_anki_cache(word, meaning, lang)
            return True
    return False


def get_distractors(target_meaning, lang="fr", count=3):
    base_pool = DISTRACTOR_POOL_EN if lang == "en" else DISTRACTOR_POOL_FR
    pool = [d for d in base_pool if d.lower() != target_meaning.lower()]
    if len(pool) >= count:
        return random.sample(pool, count)
    return (pool + base_pool)[:count]


def get_word_distractors(target_word, lang="fr", count=3):
    base_pool = DISTRACTOR_WORDS_EN if lang == "en" else DISTRACTOR_WORDS_FR
    pool = [w for w in base_pool if w.lower() != target_word.lower()]
    if len(pool) >= count:
        return random.sample(pool, count)
    return (pool + base_pool)[:count]


def add_card_to_anki(word, sense_data, pos_text="Noun", ipa_text="", lang="fr"):
    deck_name = "hoc_lom" if lang == "en" else "french2"
    word_clean = word.strip()
    meaning_text = sense_data.get("meaning", "").strip()
    level_text = sense_data.get("level", "CEFR B2" if lang == "en" else "DELF B1").strip()
    ex_main = sense_data.get("example", "").strip()
    ex_vi = sense_data.get("example_vi", "").strip()
    if " — " in ex_main and not ex_vi:
        parts = ex_main.split(" — ", 1)
        ex_main, ex_vi = parts[0].strip(), parts[1].strip()

    # Luôn lưu vào danh sách từ đã lưu (danh_sach_tu_en.txt hoặc danh_sach_tu.txt) & đẩy lên Hugging Face
    save_to_word_list(word_clean, level_text, meaning_text, ex_main, lang=lang)

    if not check_anki_connection():
        return "SAVED_LOCAL", "Đã lưu vào danh sách từ"

    if is_card_already_in_anki(word_clean, meaning_text, deck_name, lang=lang):
        return "ALREADY_EXISTS", "Đã có thẻ với nghĩa này"

    distractors = get_distractors(meaning_text, lang, 3)
    choices = distractors + [meaning_text]
    random.shuffle(choices)
    correct_idx = str(choices.index(meaning_text) + 1)

    w_distractors = get_word_distractors(word_clean, lang, 3)
    w_choices = w_distractors + [word_clean]
    random.shuffle(w_choices)
    correct_w_idx = str(w_choices.index(word_clean) + 1)

    ipa_formatted = ipa_text if (ipa_text.startswith("/") and ipa_text.endswith("/")) else f"/{ipa_text.strip('/') or word_clean}/"

    note = {
        "deckName": deck_name,
        "modelName": "(Anki) Template học từ vựng của Admin Phúc [2026]",
        "fields": {
            "word": word_clean,
            "meaning": meaning_text,
            "pos": pos_text,
            "pronunciation": ipa_formatted,
            "explain": f"[{level_text}] {meaning_text}",
            "example": ex_main,
            "example_translated": ex_vi,
            "collocation": "",
            "synonym": "",
            "antonym": "",
            "image": "",
            "choice_1": choices[0] if len(choices) > 0 else "",
            "choice_2": choices[1] if len(choices) > 1 else "",
            "choice_3": choices[2] if len(choices) > 2 else "",
            "choice_4": choices[3] if len(choices) > 3 else "",
            "correct_choice": correct_idx,
            "choice_word_1": w_choices[0] if len(w_choices) > 0 else "",
            "choice_word_2": w_choices[1] if len(w_choices) > 1 else "",
            "choice_word_3": w_choices[2] if len(w_choices) > 2 else "",
            "choice_word_4": w_choices[3] if len(w_choices) > 3 else "",
            "correct_choice_word": correct_w_idx,
            "choice_audio_1": "",
            "choice_audio_2": "",
            "choice_audio_3": "",
            "choice_audio_4": "",
            "correct_choice_audio": correct_w_idx,
            "audio": "",
            "audio_word": "",
            "audio_meaning": ""
        },
        "options": {"allowDuplicate": True}
    }

    res_data = anki_request("addNote", note=note)
    if res_data and res_data.get("result"):
        record_card_in_anki_cache(word_clean, meaning_text, lang)
        return "SUCCESS", ""
    return "SAVED_LOCAL", "Đã lưu vào danh sách từ"


# ==============================================================================
# 1. ĐỘNG CƠ TRA CỨU TỪ ĐIỂN TIẾNG ANH - VIỆT (IELTS / CEFR + ONLINE FALLBACK)
# ==============================================================================
class EnglishCEFRDictionary:
    def __init__(self):
        self.web_session = requests.Session()
        self.web_session.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36"
        })

    def _query_sqlite(self, key):
        if not os.path.exists(EN_SQLITE_DB_PATH):
            return None
        try:
            with sqlite3.connect(EN_SQLITE_DB_PATH, timeout=2.0) as conn:
                row = conn.execute(
                    "SELECT word, level, pos, ipa, meanings_json FROM dictionary WHERE word_key = ? LIMIT 1",
                    (key.lower(),)
                ).fetchone()
                if row:
                    word_str, level_str, pos_str, ipa_str, meanings_json = row
                    senses = json.loads(meanings_json)
                    ipa_fmt = ipa_str if ipa_str.startswith("/") else f"/{ipa_str.strip('/') or word_str}/"
                    return {
                        "word": word_str,
                        "level": level_str if "CEFR" in level_str or "IELTS" in level_str else f"CEFR {level_str}",
                        "pos": (pos_str or "Noun").capitalize(),
                        "ipa": ipa_fmt,
                        "meanings": senses
                    }
        except Exception as e:
            print(f"[!] Lỗi đọc English SQLite: {e}")
        return None

    def get_candidate_stems(self, raw_word):
        w = unicodedata.normalize("NFC", raw_word.strip().lower())
        stem = clean_word_stem(w, "en")
        cands = []
        for c in [w, stem]:
            if c and c not in cands:
                cands.append(c)
        if len(stem) > 3:
            if stem.endswith("ies") and len(stem) > 4:
                cands.append(stem[:-3] + "y")
            if stem.endswith("es") and len(stem) > 4:
                cands.extend([stem[:-2], stem[:-1]])
            if stem.endswith("s") and not stem.endswith("ss"):
                cands.append(stem[:-1])
            if stem.endswith("ied") and len(stem) > 4:
                cands.append(stem[:-3] + "y")
            if stem.endswith("ed") and len(stem) > 4:
                cands.extend([stem[:-2], stem[:-1]])
                if len(stem) > 5 and stem[-3] == stem[-4]:
                    cands.append(stem[:-3])
            if stem.endswith("ing") and len(stem) > 5:
                cands.extend([stem[:-3], stem[:-3] + "e"])
                if len(stem) > 6 and stem[-4] == stem[-5]:
                    cands.append(stem[:-4])
            if stem.endswith("ly") and len(stem) > 4:
                cands.append(stem[:-2])
        return cands

    def lookup(self, word):
        word = unicodedata.normalize("NFC", (word or "").strip())
        if not word:
            return None

        for cand in self.get_candidate_stems(word):
            res = self._query_sqlite(cand)
            if res and res.get("meanings"):
                return res

        online_res = self.fetch_online_and_save(word)
        if online_res:
            return online_res

        lvl = estimate_english_cefr_level(word, 0)
        return {
            "word": word,
            "level": lvl,
            "pos": "Noun",
            "ipa": f"/{word}/",
            "meanings": [{
                "word": word,
                "level": lvl,
                "meaning": f"Từ vựng tiếng Anh: {word}",
                "example": f"Recent academic studies highlight the significance of {word} in modern society.",
                "example_vi": f"Các nghiên cứu học thuật gần đây làm nổi bật tầm quan trọng của “{word}” trong xã hội hiện đại."
            }]
        }

    def fetch_online_and_save(self, word):
        stem = clean_word_stem(word, "en")

        def fetch_free_dict():
            pos_out = "Noun"
            ipa_out = ""
            defs_out = []
            try:
                url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{urllib.parse.quote(stem)}"
                r = self.web_session.get(url, timeout=3.5)
                if r.status_code == 200:
                    arr = r.json()
                    if isinstance(arr, list) and arr:
                        entry = arr[0]
                        ipa_out = (entry.get("phonetic") or "").strip()
                        if not ipa_out:
                            for p in entry.get("phonetics", []):
                                if p.get("text"):
                                    ipa_out = p["text"].strip()
                                    break
                        meanings_list = entry.get("meanings", [])
                        if meanings_list:
                            pos_out = (meanings_list[0].get("partOfSpeech") or "Noun").capitalize()
                        for m_obj in meanings_list:
                            p_cur = (m_obj.get("partOfSpeech") or pos_out).capitalize()
                            for d_obj in m_obj.get("definitions", [])[:2]:
                                d_en = (d_obj.get("definition") or "").strip()
                                ex_en = (d_obj.get("example") or "").strip()
                                if d_en:
                                    defs_out.append({"pos": p_cur, "def_en": d_en, "ex_en": ex_en})
            except Exception:
                pass
            return pos_out, ipa_out, defs_out

        def fetch_google_vi():
            vi_terms = []
            main_trans = ""
            try:
                url = (
                    "https://translate.googleapis.com/translate_a/single?client=gtx"
                    f"&sl=en&tl=vi&dt=t&dt=bd&q={urllib.parse.quote(stem)}"
                )
                r = self.web_session.get(url, timeout=3.0)
                if r.status_code == 200:
                    data = r.json()
                    if data and data[0]:
                        main_trans = "".join(seg[0] for seg in data[0] if seg and seg[0]).strip()
                    if len(data) > 1 and data[1]:
                        for pos_block in data[1]:
                            if len(pos_block) > 1 and isinstance(pos_block[1], list):
                                for term in pos_block[1][:4]:
                                    if isinstance(term, str) and term.strip():
                                        t_clean = term.strip().capitalize()
                                        if t_clean.lower() not in [x.lower() for x in vi_terms]:
                                            vi_terms.append(t_clean)
            except Exception:
                pass
            if main_trans and main_trans.lower() != stem.lower():
                m_cap = main_trans[0].upper() + main_trans[1:]
                if m_cap.lower() not in [x.lower() for x in vi_terms]:
                    vi_terms.insert(0, m_cap)
            return vi_terms

        def translate_en_to_vi(text_en):
            if not text_en:
                return ""
            try:
                url = (
                    "https://translate.googleapis.com/translate_a/single?client=gtx"
                    f"&sl=en&tl=vi&dt=t&q={urllib.parse.quote(text_en)}"
                )
                r = self.web_session.get(url, timeout=2.5)
                if r.status_code == 200:
                    data = r.json()
                    if data and data[0]:
                        return "".join(seg[0] for seg in data[0] if seg and seg[0]).strip()
            except Exception:
                pass
            return ""

        with ThreadPoolExecutor(max_workers=2) as ex:
            f_dict = ex.submit(fetch_free_dict)
            f_vi = ex.submit(fetch_google_vi)
            pos, ipa, en_defs = f_dict.result()
            vi_terms = f_vi.result()

        if not vi_terms and not en_defs:
            return None

        ipa_fmt = ipa if (ipa.startswith("/") and ipa.endswith("/")) else f"/{ipa.strip('/') or stem}/"
        senses = []
        max_senses = max(len(vi_terms), len(en_defs), 1)
        for idx in range(min(4, max_senses)):
            lvl = estimate_english_cefr_level(stem, idx)
            vi_part = vi_terms[idx] if idx < len(vi_terms) else (vi_terms[0] if vi_terms else "")
            en_part = en_defs[idx]["def_en"] if idx < len(en_defs) else ""
            ex_en = en_defs[idx]["ex_en"] if idx < len(en_defs) and en_defs[idx]["ex_en"] else f"Academic studies frequently examine the role of {stem} in modern contexts."
            ex_vi = translate_en_to_vi(ex_en) or f"Các nghiên cứu học thuật thường xem xét vai trò của “{stem}” trong bối cảnh hiện đại."

            if vi_part and en_part:
                short_en = en_part if len(en_part) <= 75 else en_part[:72] + "..."
                meaning_combined = f"{vi_part} ({short_en})"
            else:
                meaning_combined = vi_part or en_part

            senses.append({
                "word": stem,
                "level": lvl,
                "meaning": meaning_combined,
                "example": ex_en,
                "example_vi": ex_vi
            })

        entry_data = {
            "word": stem,
            "level": senses[0]["level"],
            "pos": pos or "Noun",
            "ipa": ipa_fmt,
            "meanings": senses
        }

        try:
            with sqlite3.connect(EN_SQLITE_DB_PATH, timeout=2.0) as conn:
                conn.execute(
                    "INSERT OR REPLACE INTO dictionary (word_key, word, level, pos, ipa, meanings_json) VALUES (?, ?, ?, ?, ?, ?)",
                    (stem.lower(), stem, entry_data["level"], pos, ipa_fmt.strip("/"), json.dumps(senses, ensure_ascii=False))
                )
                conn.commit()
        except Exception:
            pass

        return entry_data


# ==============================================================================
# 2. ĐỘNG CƠ TRA CỨU TỪ ĐIỂN PHÁP - VIỆT DELF/DALF (SQLITE 48,000+ TỪ + ONLINE FALLBACK)
# ==============================================================================
class FrenchDELFDictionary:
    def __init__(self):
        self.web_session = requests.Session()
        self.web_session.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36"
        })

    def _query_sqlite(self, key):
        if not os.path.exists(FR_SQLITE_DB_PATH):
            return None
        try:
            with sqlite3.connect(FR_SQLITE_DB_PATH, timeout=2.0) as conn:
                row = conn.execute(
                    "SELECT word, level, pos, ipa, meanings_json FROM dictionary WHERE word_key = ? LIMIT 1",
                    (key.lower(),)
                ).fetchone()
                if row:
                    word_str, level_str, pos_str, ipa_str, meanings_json = row
                    senses = json.loads(meanings_json)
                    return {
                        "word": word_str,
                        "level": level_str,
                        "pos": pos_str or "Noun",
                        "ipa": ipa_str or f"/{word_str}/",
                        "meanings": senses
                    }
        except Exception as e:
            print(f"[!] Lỗi đọc SQLite: {e}")
        return None

    def get_candidate_stems(self, raw_word):
        w = unicodedata.normalize("NFC", raw_word.strip().lower())
        stem = clean_word_stem(w, "fr")
        cands = []
        for c in [w, stem]:
            if c and c not in cands:
                cands.append(c)

        if len(stem) > 3:
            if stem.endswith("aux"):
                cands.append(stem[:-3] + "al")
            if stem.endswith("eaux"):
                cands.append(stem[:-1])
            if stem.endswith("s") or stem.endswith("x"):
                cands.append(stem[:-1])
            if stem.endswith("es") and len(stem) > 4:
                cands.extend([stem[:-2], stem[:-1], stem[:-2] + "er"])
            if stem.endswith("e") and len(stem) > 4:
                cands.extend([stem[:-1], stem + "r"])
            if stem.endswith("ée") or stem.endswith("és") or stem.endswith("ées"):
                base = re.sub(r"(ée|és|ées)$", "", stem)
                cands.extend([base + "er", base + "é"])
            if stem.endswith("é") and len(stem) > 3:
                cands.append(stem[:-1] + "er")
            for v_end in ("ent", "ons", "ez", "ais", "ait", "aient", "era", "eront", "ant"):
                if stem.endswith(v_end) and len(stem) > len(v_end) + 2:
                    root = stem[:-len(v_end)]
                    cands.extend([root + "er", root + "ir", root + "re", root + "e"])
            if stem.endswith("issement") and len(stem) > 10:
                cands.append(stem[:-8] + "ir")
        return cands

    def lookup(self, word):
        word = unicodedata.normalize("NFC", (word or "").strip())
        if not word:
            return None

        for cand in self.get_candidate_stems(word):
            res = self._query_sqlite(cand)
            if res and res.get("meanings"):
                return res

        online_res = self.fetch_online_and_save(word)
        if online_res:
            return online_res

        lvl = estimate_delf_dalf_level(word, 0)
        return {
            "word": word,
            "level": lvl,
            "pos": "Noun",
            "ipa": f"/{word}/",
            "meanings": [{
                "word": word,
                "level": lvl,
                "meaning": f"Từ vựng tiếng Pháp: {word}",
                "example": f"On utilise souvent le terme « {word} » dans ce contexte.",
                "example_vi": f"Người ta thường sử dụng từ “{word}” trong ngữ cảnh này."
            }]
        }

    def fetch_online_and_save(self, word):
        stem = clean_word_stem(word, "fr")
        glosbe_means = []
        lar_defs = []
        pos = "Noun"
        ipa = f"/{stem}/"

        def fetch_glosbe():
            out = []
            try:
                url = f"https://glosbe.com/fr/vi/{urllib.parse.quote(stem)}"
                r = self.web_session.get(url, timeout=3.0)
                if r.status_code == 200:
                    soup = BeautifulSoup(r.text, "html.parser")
                    for tag in soup.find_all(class_=re.compile(r"translation__item__phar?se", re.I)):
                        t = tag.get_text(strip=True)
                        t = re.sub(r"FVDP[^\n]*", "", t).strip()
                        if t and len(t) < 60 and t.lower() not in [x.lower() for x in out]:
                            out.append(t[0].upper() + t[1:])
            except Exception:
                pass
            return out

        def fetch_larousse():
            defs = []
            p = "Noun"
            try:
                url = f"https://www.larousse.fr/dictionnaires/francais/{urllib.parse.quote(stem)}"
                r = self.web_session.get(url, timeout=3.0)
                if r.status_code == 200:
                    soup = BeautifulSoup(r.text, "html.parser")
                    cat = soup.find("p", class_="CatgramDefinition")
                    if cat:
                        c_txt = cat.get_text(strip=True).lower()
                        if "verbe" in c_txt:
                            p = "Verb"
                        elif "adjectif" in c_txt:
                            p = "Adjective"
                        elif "adverbe" in c_txt:
                            p = "Adverb"
                    for li in soup.find_all("li", class_="DivisionDefinition")[:4]:
                        ex = li.find("span", class_="ExempleDefinition")
                        ex_text = ex.get_text(strip=True) if ex else ""
                        defs.append({"ex": ex_text})
            except Exception:
                pass
            return defs, p

        def fetch_mymemory():
            try:
                url = f"https://api.mymemory.translated.net/get?q={urllib.parse.quote(stem)}&langpair=fr|vi"
                r = self.web_session.get(url, timeout=2.5)
                if r.status_code == 200:
                    t = r.json().get("responseData", {}).get("translatedText", "").strip()
                    if t and "MYMEMORY" not in t and t.lower() != stem.lower():
                        return t[0].upper() + t[1:]
            except Exception:
                pass
            return ""

        with ThreadPoolExecutor(max_workers=3) as ex:
            f1 = ex.submit(fetch_glosbe)
            f2 = ex.submit(fetch_larousse)
            f3 = ex.submit(fetch_mymemory)
            glosbe_means = f1.result()
            lar_defs, pos = f2.result()
            mm_vi = f3.result()

        if mm_vi and mm_vi.lower() not in [x.lower() for x in glosbe_means]:
            glosbe_means.insert(0, mm_vi)

        if not glosbe_means:
            return None

        senses = []
        for idx, m_txt in enumerate(glosbe_means[:4]):
            lvl = estimate_delf_dalf_level(stem, idx)
            ex_fr = lar_defs[idx]["ex"] if idx < len(lar_defs) and lar_defs[idx]["ex"] else f"Exemple avec le mot « {stem} » dans une phrase."
            ex_vi = f"Ví dụ sử dụng từ “{m_txt.lower()}” trong câu."
            senses.append({
                "word": stem,
                "level": lvl,
                "meaning": m_txt,
                "example": ex_fr,
                "example_vi": ex_vi
            })

        entry_data = {
            "word": stem,
            "level": senses[0]["level"],
            "pos": pos,
            "ipa": ipa,
            "meanings": senses
        }

        try:
            with sqlite3.connect(FR_SQLITE_DB_PATH, timeout=2.0) as conn:
                conn.execute(
                    "INSERT OR REPLACE INTO dictionary VALUES (?, ?, ?, ?, ?, ?)",
                    (stem.lower(), stem, entry_data["level"], pos, ipa, json.dumps(senses, ensure_ascii=False))
                )
                conn.commit()
        except Exception:
            pass

        return entry_data


# ==============================================================================
# GIAO DIỆN MOCHIMOCHI ĐA NGÔN NGỮ: ANH - VIỆT (hoc_lom) & PHÁP - VIỆT (french2)
# ==============================================================================
class MochiVocabCapture(ctk.CTk):
    def __init__(self):
        super().__init__()

        ctk.set_appearance_mode("Light")
        ctk.set_default_color_theme("green")

        self.current_lang = self._load_lang_pref()
        self.fr_engine = FrenchDELFDictionary()
        self.en_engine = EnglishCEFRDictionary()

        self.geometry("500x700")
        self.minsize(460, 560)
        self.configure(fg_color="#FFFFFF")

        self.is_pinned = True
        self.attributes("-topmost", True)

        init_saved_word_list()
        self.current_data = None
        self.queue = queue.Queue()

        # Trạng thái bắt phím Ctrl 2 lần liên tiếp (Double-Ctrl) & Giữ Ctrl bôi đen
        self.is_ctrl_down = False
        self.is_simulating_copy = False
        self.is_processing_copy = False
        self.last_ctrl_release_time = 0.0
        self.other_key_pressed_during_ctrl = False

        self._build_header()
        self._build_search_bar()
        self._build_category_tabs()
        self._build_scrollable_body()
        self._apply_lang_ui_state()

        self.after(80, self._process_queue)
        self.after(600, init_anki_cache_background)
        self._start_global_listener()

        # Hiển thị từ mẫu ngay khi mở ứng dụng
        sample_word = "mitigate" if self.current_lang == "en" else "améliorer"
        self.after(150, lambda: self.search_word(sample_word))
        self.protocol("WM_DELETE_WINDOW", self._on_close_app)

    def _load_lang_pref(self):
        try:
            if os.path.exists(LANG_PREF_FILE):
                with open(LANG_PREF_FILE, "r", encoding="utf-8") as f:
                    d = json.load(f)
                    if d.get("lang") in ("en", "fr"):
                        return d["lang"]
        except Exception:
            pass
        return "en"

    def _save_lang_pref(self):
        try:
            with open(LANG_PREF_FILE, "w", encoding="utf-8") as f:
                json.dump({"lang": self.current_lang}, f)
        except Exception:
            pass

    def toggle_language(self):
        self.current_lang = "fr" if self.current_lang == "en" else "en"
        self._save_lang_pref()
        self._apply_lang_ui_state()
        cur_query = (self.search_entry.get() or "").strip()
        if not cur_query or cur_query.lower() in ("améliorer", "compenser", "mitigate", "ubiquitous"):
            cur_query = "mitigate" if self.current_lang == "en" else "améliorer"
        self.search_word(cur_query)

    def _apply_lang_ui_state(self):
        if self.current_lang == "en":
            self.title("MochiMochi Dictionary - Tiếng Anh IELTS / CEFR (Deck: hoc_lom)")
            self.btn_lang.configure(text="En - Vi ▾", fg_color="#0284C7", hover_color="#0369A1")
            self.search_entry.configure(placeholder_text="Nhập từ tiếng Anh hoặc Bôi đen + Nhấn Ctrl 2 lần...")
            self.lbl_context_tab.configure(text="IELTS / CEFR")
        else:
            self.title("MochiMochi Dictionary - Tiếng Pháp DELF / DALF (Deck: french2)")
            self.btn_lang.configure(text="Fr - Vi ▾", fg_color="#2563EB", hover_color="#1D4ED8")
            self.search_entry.configure(placeholder_text="Nhập từ tiếng Pháp hoặc Bôi đen + Nhấn Ctrl 2 lần...")
            self.lbl_context_tab.configure(text="DELF Context")

    def _on_close_app(self):
        try:
            for local_f, proj_f, lg in (
                (FR_LOCAL_LIST_FILE, FR_LIST_FILE, "fr"),
                (EN_LOCAL_LIST_FILE, EN_LIST_FILE, "en")
            ):
                if os.path.exists(local_f) and proj_f != local_f:
                    os.makedirs(os.path.dirname(proj_f), exist_ok=True)
                    with open(local_f, "rb") as f_src:
                        data = f_src.read()
                    with open(proj_f, "wb") as f_dst:
                        f_dst.write(data)
                upload_word_list_to_hf_sync(lg)
        except Exception:
            pass
        self.destroy()
        os._exit(0)

    def _load_ctk_image(self, path, size):
        try:
            if os.path.exists(path):
                pil_img = Image.open(path)
                return ctk.CTkImage(light_image=pil_img, dark_image=pil_img, size=size)
        except Exception:
            pass
        return None

    # --------------------------------------------------------------------------
    # 1. THANH HEADER TRÊN CÙNG (GIỐNG HỆT HÌNH MẪU MOCHIMOCHI)
    # --------------------------------------------------------------------------
    def _build_header(self):
        header_wrap = ctk.CTkFrame(self, fg_color="#FFFFFF")
        header_wrap.pack(fill="x", padx=0, pady=0)

        header_frame = ctk.CTkFrame(header_wrap, fg_color="#FFFFFF", height=54)
        header_frame.pack(fill="x", padx=18, pady=(10, 8))

        # Logo MOCHIMOCHI bên trái
        self.logo_img = self._load_ctk_image(LOGO_PATH, (142, 28))
        if self.logo_img:
            self.logo_label = ctk.CTkLabel(header_frame, image=self.logo_img, text="")
        else:
            self.logo_label = ctk.CTkLabel(
                header_frame,
                text="MOCHIMOCHI",
                font=("Arial Rounded MT Bold", 20, "bold"),
                text_color="#F59E0B"
            )
        self.logo_label.pack(side="left", pady=4)

        # Cụm nút bên phải: 🎧 Xanh lá | 📓 Trắng viền | En - Vi ▾ / Fr - Vi ▾ | Avatar Mochi | ⚙️
        right_bar = ctk.CTkFrame(header_frame, fg_color="transparent")
        right_bar.pack(side="right")

        # Nút Tai nghe phát âm 🎧 (Tròn xanh lá #22C55E)
        self.btn_headphone = ctk.CTkButton(
            right_bar,
            text="🎧",
            width=38,
            height=38,
            corner_radius=19,
            fg_color="#22C55E",
            hover_color="#16A34A",
            text_color="#FFFFFF",
            font=("Segoe UI Emoji", 16),
            command=self.play_audio
        )
        self.btn_headphone.pack(side="left", padx=4)

        # Nút Sổ tay từ đã lưu 📓 (Tròn trắng viền xám nhạt)
        self.btn_notebook = ctk.CTkButton(
            right_bar,
            text="📕",
            width=38,
            height=38,
            corner_radius=19,
            fg_color="#FFFFFF",
            hover_color="#F8FAFC",
            border_color="#E2E8F0",
            border_width=1.5,
            text_color="#F43F5E",
            font=("Segoe UI Emoji", 15),
            command=self.open_saved_file
        )
        self.btn_notebook.pack(side="left", padx=4)

        # Vạch ngăn cách dọc mảnh
        sep1 = ctk.CTkFrame(right_bar, width=1, height=24, fg_color="#E2E8F0")
        sep1.pack(side="left", padx=6)

        # Nút pill chuyển ngôn ngữ "En - Vi ▾" / "Fr - Vi ▾"
        self.btn_lang = ctk.CTkButton(
            right_bar,
            text="En - Vi ▾",
            width=82,
            height=34,
            corner_radius=17,
            fg_color="#0284C7",
            hover_color="#0369A1",
            text_color="#FFFFFF",
            font=("Segoe UI", 13, "bold"),
            command=self.toggle_language
        )
        self.btn_lang.pack(side="left", padx=4)

        # Avatar Mochi tròn viền xanh lá
        self.avatar_img = self._load_ctk_image(AVATAR_PATH, (28, 28))
        self.btn_avatar = ctk.CTkButton(
            right_bar,
            image=self.avatar_img,
            text="" if self.avatar_img else "🍡",
            width=38,
            height=38,
            corner_radius=19,
            fg_color="#FFFFFF",
            hover_color="#F0FDF4",
            border_color="#22C55E",
            border_width=2,
            command=self._on_anki_status_click
        )
        self.btn_avatar.pack(side="left", padx=4)

        # Vạch ngăn cách dọc mảnh
        sep2 = ctk.CTkFrame(right_bar, width=1, height=24, fg_color="#E2E8F0")
        sep2.pack(side="left", padx=4)

        # Nút bánh răng cài đặt / Ghim cửa sổ ⚙️
        self.btn_gear = ctk.CTkButton(
            right_bar,
            text="⚙️",
            width=34,
            height=34,
            corner_radius=17,
            fg_color="transparent",
            hover_color="#F1F5F9",
            text_color="#64748B",
            font=("Segoe UI Emoji", 17),
            command=self.toggle_pin
        )
        self.btn_gear.pack(side="left", padx=(2, 0))

        # Đường kẻ ngang phân tách dưới Header
        header_line = ctk.CTkFrame(header_wrap, height=1, fg_color="#E2E8F0")
        header_line.pack(fill="x")

    # --------------------------------------------------------------------------
    # 2. Ô TÌM KIẾM BO TRÒN VIỀN VÀNG CAM + VẠCH DỌC + KÍNH LÚP
    # --------------------------------------------------------------------------
    def _build_search_bar(self):
        search_outer = ctk.CTkFrame(self, fg_color="#FFFFFF")
        search_outer.pack(fill="x", padx=22, pady=(16, 14))

        search_box = ctk.CTkFrame(
            search_outer,
            fg_color="#FFFFFF",
            border_color="#F59E0B",
            border_width=2,
            corner_radius=27,
            height=54
        )
        search_box.pack(fill="x")
        search_box.pack_propagate(False)

        self.search_entry = ctk.CTkEntry(
            search_box,
            placeholder_text="Nhập từ tiếng Anh hoặc Bôi đen + Nhấn Ctrl 2 lần...",
            fg_color="transparent",
            border_width=0,
            font=("Segoe UI", 17, "bold"),
            text_color="#0F172A"
        )
        self.search_entry.pack(side="left", fill="both", expand=True, padx=(22, 8), pady=6)
        self.search_entry.bind("<Return>", lambda e: self.search_word(self.search_entry.get()))

        # Nút kính lúp bên phải
        search_btn = ctk.CTkButton(
            search_box,
            text="🔍",
            width=48,
            height=40,
            corner_radius=20,
            fg_color="transparent",
            hover_color="#F1F5F9",
            text_color="#0284C7",
            font=("Segoe UI Emoji", 18),
            command=lambda: self.search_word(self.search_entry.get())
        )
        search_btn.pack(side="right", padx=(6, 12))

        # Vạch ngăn cách dọc trước kính lúp
        divider = ctk.CTkFrame(search_box, width=1.5, height=28, fg_color="#CBD5E1")
        divider.pack(side="right", pady=12)

    # --------------------------------------------------------------------------
    # 3. THANH TAB LOẠI TỪ (Verb / Noun ▾ | Context | Definition | Verb Forms)
    # --------------------------------------------------------------------------
    def _build_category_tabs(self):
        tabs_wrap = ctk.CTkFrame(self, fg_color="#FFFFFF")
        tabs_wrap.pack(fill="x")

        top_border = ctk.CTkFrame(tabs_wrap, height=1, fg_color="#F1F5F9")
        top_border.pack(fill="x")

        tabs_bar = ctk.CTkFrame(tabs_wrap, fg_color="#FFFFFF", height=42)
        tabs_bar.pack(fill="x", padx=6)
        tabs_bar.pack_propagate(False)

        self.tab_pos_btn = ctk.CTkLabel(
            tabs_bar,
            text="Verb ▾",
            font=("Segoe UI", 14, "bold"),
            fg_color="#FEF3C7",
            text_color="#0F172A",
            corner_radius=0,
            padx=18,
            pady=9
        )
        self.tab_pos_btn.pack(side="left", fill="y")

        self.lbl_context_tab = ctk.CTkLabel(
            tabs_bar,
            text="IELTS / CEFR",
            font=("Segoe UI", 13, "bold"),
            fg_color="transparent",
            text_color="#A1A1AA",
            padx=12
        )
        self.lbl_context_tab.pack(side="left", fill="y")

        for tab_name in ("Definition", "Word Forms"):
            lbl = ctk.CTkLabel(
                tabs_bar,
                text=tab_name,
                font=("Segoe UI", 13, "bold"),
                fg_color="transparent",
                text_color="#A1A1AA",
                padx=12
            )
            lbl.pack(side="left", fill="y")

        bottom_border = ctk.CTkFrame(tabs_wrap, height=1, fg_color="#F1F5F9")
        bottom_border.pack(fill="x")

    # --------------------------------------------------------------------------
    # 4. VÙNG NỘI DUNG CUỘN (TIÊU ĐỀ TỪ LỚN + IPA + CÁC PHIÊN BẢN NGHĨA 1., 2., 3.)
    # --------------------------------------------------------------------------
    def _build_scrollable_body(self):
        self.scroll_body = ctk.CTkScrollableFrame(
            self,
            fg_color="#FFFFFF",
            scrollbar_button_color="#CBD5E1",
            scrollbar_button_hover_color="#94A3B8"
        )
        self.scroll_body.pack(fill="both", expand=True, padx=8, pady=(4, 8))

    def _on_anki_status_click(self):
        if not check_anki_connection():
            threading.Thread(target=launch_anki_background, daemon=True).start()

    def search_word(self, word):
        word = (word or "").strip()
        if not word:
            return
        self.search_entry.delete(0, "end")
        self.search_entry.insert(0, word)
        threading.Thread(target=self._search_worker, args=(word, self.current_lang), daemon=True).start()

    def _search_worker(self, word, lang):
        engine = self.en_engine if lang == "en" else self.fr_engine
        data = engine.lookup(word)
        if data:
            data["lang"] = lang
        self.queue.put(("RENDER_WORD", data))

    def _process_queue(self):
        try:
            while True:
                msg_type, payload = self.queue.get_nowait()
                if msg_type == "RENDER_WORD":
                    self._render_word_data(payload)
                elif msg_type == "POPUP_WORD":
                    self.search_word(payload)
                    self.deiconify()
                    self.lift()
                    self.attributes("-topmost", True)
                    self.focus_force()
                    try:
                        winsound.Beep(1200, 90)
                    except Exception:
                        pass
        except queue.Empty:
            pass
        self.after(70, self._process_queue)

    def _render_word_data(self, data):
        self.current_data = data
        if not data:
            return

        pos_display = data.get("pos", "Noun")
        self.tab_pos_btn.configure(text=f"{pos_display} ▾")

        for child in self.scroll_body.winfo_children():
            child.destroy()

        word_str = data.get("word", "")
        ipa_str = data.get("ipa", f"/{word_str}/")
        lang = data.get("lang", self.current_lang)
        main_level = data.get("level", "CEFR B2" if lang == "en" else "DELF B1")
        meanings = data.get("meanings", [])

        # --- PHẦN ĐẦU: TỪ VỰNG CHỮ LỚN MÀU XANH ĐẬM + TỪ LOẠI IN NGHIÊNG + TRÌNH ĐỘ + NÚT LƯU TỪ ---
        word_header_row = ctk.CTkFrame(self.scroll_body, fg_color="transparent")
        word_header_row.pack(fill="x", padx=12, pady=(14, 4))

        lbl_word_title = ctk.CTkLabel(
            word_header_row,
            text=word_str,
            font=("Segoe UI", 28, "bold"),
            text_color="#1E3A8A"
        )
        lbl_word_title.pack(side="left", anchor="s")

        lbl_pos_italic = ctk.CTkLabel(
            word_header_row,
            text=f" {pos_display.lower()}",
            font=("Segoe UI", 16, "italic"),
            text_color="#94A3B8"
        )
        lbl_pos_italic.pack(side="left", anchor="s", padx=(4, 8), pady=(0, 3))

        # Huy hiệu trình độ CEFR / IELTS / DELF ngay sau từ chính
        lbl_word_delf = ctk.CTkLabel(
            word_header_row,
            text=main_level,
            font=("Segoe UI", 12, "bold"),
            fg_color="#EFF6FF",
            text_color="#1D4ED8",
            corner_radius=8,
            padx=8,
            pady=2
        )
        lbl_word_delf.pack(side="left", anchor="s", pady=(0, 5))

        # Nút [+ Lưu từ] bên cạnh từ chính (lưu nghĩa số 1 của từ)
        if meanings:
            btn_save_main = ctk.CTkButton(
                word_header_row,
                text="⊕ Lưu từ",
                width=94,
                height=34,
                corner_radius=17,
                fg_color="#22C55E",
                hover_color="#16A34A",
                text_color="#FFFFFF",
                font=("Segoe UI", 13, "bold"),
                command=lambda m0=meanings[0]: self._on_save_clicked(word_str, m0, pos_display, ipa_str, btn_save_main, lang)
            )
            btn_save_main.pack(side="right", anchor="center")

        # --- DÒNG PHÁT ÂM (EN / FR 🔊 /ipa/) ---
        pron_row = ctk.CTkFrame(self.scroll_body, fg_color="transparent")
        pron_row.pack(fill="x", padx=12, pady=(4, 14))

        lbl_lang_tag = ctk.CTkLabel(
            pron_row,
            text="EN" if lang == "en" else "FR",
            font=("Segoe UI", 13, "bold"),
            text_color="#0284C7" if lang == "en" else "#F87171"
        )
        lbl_lang_tag.pack(side="left", padx=(0, 8))

        btn_speaker = ctk.CTkButton(
            pron_row,
            text="🔊",
            width=36,
            height=36,
            corner_radius=18,
            fg_color="#FFFFFF",
            hover_color="#F1F5F9",
            border_color="#E2E8F0",
            border_width=1.5,
            text_color="#EF4444",
            font=("Segoe UI Emoji", 14),
            command=self.play_audio
        )
        btn_speaker.pack(side="left", padx=(0, 10))

        lbl_ipa = ctk.CTkLabel(
            pron_row,
            text=ipa_str,
            font=("Segoe UI", 15),
            text_color="#334155"
        )
        lbl_ipa.pack(side="left")

        # --- DANH SÁCH CÁC PHIÊN BẢN NGHĨA (1., 2., 3....) ---
        for idx, m_item in enumerate(meanings, start=1):
            self._render_meaning_block(idx, word_str, pos_display, ipa_str, m_item, lang)

    def _render_meaning_block(self, number, word_str, pos_display, ipa_str, m_item, lang):
        block = ctk.CTkFrame(self.scroll_body, fg_color="#FFFFFF")
        block.pack(fill="x", padx=10, pady=(6, 14))

        top_row = ctk.CTkFrame(block, fg_color="transparent")
        top_row.pack(fill="x")

        lbl_num = ctk.CTkLabel(
            top_row,
            text=f"{number}.",
            font=("Segoe UI", 15, "bold"),
            text_color="#0F172A"
        )
        lbl_num.pack(side="left", anchor="n", padx=(0, 6), pady=(2, 0))

        level_full = m_item.get("level") or self.current_data.get("level", "CEFR B2" if lang == "en" else "DELF B1")
        short_cefr = get_short_cefr(level_full)

        badge_cefr = ctk.CTkLabel(
            top_row,
            text=short_cefr,
            font=("Segoe UI", 12, "bold"),
            fg_color="#1D4ED8",
            text_color="#FFFFFF",
            corner_radius=9,
            padx=8,
            pady=1
        )
        badge_cefr.pack(side="left", anchor="n", padx=(0, 8), pady=(3, 0))

        btn_save = ctk.CTkButton(
            top_row,
            text="⊕ Lưu từ",
            width=94,
            height=34,
            corner_radius=17,
            fg_color="#22C55E",
            hover_color="#16A34A",
            text_color="#FFFFFF",
            font=("Segoe UI", 13, "bold")
        )
        btn_save.configure(command=lambda b=btn_save, m=m_item: self._on_save_clicked(word_str, m, pos_display, ipa_str, b, lang))
        btn_save.pack(side="right", anchor="n", padx=(8, 0), pady=(2, 0))

        meaning_txt = m_item.get("meaning", "")
        lbl_meaning = ctk.CTkLabel(
            top_row,
            text=meaning_txt,
            font=("Segoe UI", 15, "bold"),
            text_color="#0F172A",
            wraplength=265,
            justify="left"
        )
        lbl_meaning.pack(side="left", fill="x", expand=True, anchor="n")

        badge_row = ctk.CTkFrame(block, fg_color="transparent")
        badge_row.pack(fill="x", padx=(26, 0), pady=(4, 6))

        delf_pill = ctk.CTkFrame(
            badge_row,
            fg_color="#FFFFFF",
            border_color="#E11D48",
            border_width=1.5,
            corner_radius=10
        )
        delf_pill.pack(side="left", padx=(0, 6))

        pill_label = level_full if ("DELF" in level_full or "DALF" in level_full or "IELTS" in level_full or "CEFR" in level_full) else (f"IELTS / CEFR {level_full}" if lang == "en" else f"DELF {level_full}")
        lbl_delf_pill = ctk.CTkLabel(
            delf_pill,
            text=pill_label,
            font=("Segoe UI", 12, "bold"),
            text_color="#E11D48",
            padx=9,
            pady=1
        )
        lbl_delf_pill.pack()

        lbl_excl = ctk.CTkLabel(
            badge_row,
            text="ⓘ",
            font=("Segoe UI", 14),
            text_color="#94A3B8"
        )
        lbl_excl.pack(side="left")

        ex_main = m_item.get("example", "").strip()
        ex_vi = m_item.get("example_vi", "").strip()
        if " — " in ex_main and not ex_vi:
            parts = ex_main.split(" — ", 1)
            ex_main, ex_vi = parts[0].strip(), parts[1].strip()

        if ex_main:
            ex_row = ctk.CTkFrame(block, fg_color="transparent")
            ex_row.pack(fill="x", padx=(8, 4), pady=(2, 2))

            dot = ctk.CTkLabel(
                ex_row,
                text="•",
                font=("Segoe UI", 16, "bold"),
                text_color="#CBD5E1"
            )
            dot.pack(side="left", anchor="n", padx=(0, 8))

            ex_text_col = ctk.CTkFrame(ex_row, fg_color="transparent")
            ex_text_col.pack(side="left", fill="x", expand=True)

            lbl_ex_main = ctk.CTkLabel(
                ex_text_col,
                text=ex_main,
                font=("Segoe UI", 13.5),
                text_color="#1E293B",
                wraplength=410,
                justify="left"
            )
            lbl_ex_main.pack(anchor="w")

            if ex_vi:
                lbl_ex_vi = ctk.CTkLabel(
                    ex_text_col,
                    text=ex_vi,
                    font=("Segoe UI", 13, "italic"),
                    text_color="#64748B",
                    wraplength=410,
                    justify="left"
                )
                lbl_ex_vi.pack(anchor="w", pady=(1, 0))

    def _on_save_clicked(self, word_str, m_item, pos_display, ipa_str, btn_widget, lang):
        btn_widget.configure(text="Đang lưu...", state="disabled")

        def save_task():
            status, _ = add_card_to_anki(word_str, m_item, pos_display, ipa_str, lang=lang)

            def update_ui():
                if status in ("SUCCESS", "SAVED_LOCAL"):
                    btn_widget.configure(text="✓ Đã lưu", fg_color="#10B981", state="disabled")
                    try:
                        winsound.Beep(1200, 120)
                    except Exception:
                        pass
                elif status == "ALREADY_EXISTS":
                    btn_widget.configure(text="✓ Đã có thẻ", fg_color="#64748B", state="disabled")
                else:
                    btn_widget.configure(text="✓ Đã lưu", fg_color="#10B981", state="disabled")

            self.after(0, update_ui)

        threading.Thread(target=save_task, daemon=True).start()

    def play_audio(self):
        if not self.current_data:
            return
        raw_word = self.current_data.get("word", "")
        if not raw_word:
            return
        lang = self.current_data.get("lang", self.current_lang)
        word_to_speak = clean_word_stem(raw_word, lang)

        def audio_task():
            try:
                cache_dir = os.path.join(APP_DIR, "audio_cache")
                os.makedirs(cache_dir, exist_ok=True)
                safe_name = re.sub(r"[^\w\-]", "_", word_to_speak.lower()).strip("_") or "word"
                mp3_file = os.path.join(cache_dir, f"{safe_name}_{lang}.mp3")
                tl_code = "en" if lang == "en" else "fr"

                if not os.path.exists(mp3_file) or os.path.getsize(mp3_file) < 500:
                    url = f"https://translate.google.com/translate_tts?ie=UTF-8&q={urllib.parse.quote(word_to_speak)}&tl={tl_code}&client=tw-ob"
                    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
                    resp = requests.get(url, headers=headers, timeout=4)
                    if resp.status_code == 200 and len(resp.content) > 500:
                        with open(mp3_file, "wb") as f:
                            f.write(resp.content)

                if os.path.exists(mp3_file) and os.path.getsize(mp3_file) > 500:
                    alias = f"audio_{int(time.time() * 1000)}"
                    mci = ctypes.windll.winmm.mciSendStringW
                    mci("close all", None, 0, None)
                    mci(f'open "{mp3_file}" type mpegvideo alias {alias}', None, 0, None)
                    mci(f"play {alias} wait", None, 0, None)
                    mci(f"close {alias}", None, 0, None)
                    return
            except Exception:
                pass

            try:
                escaped = word_to_speak.replace("'", "''")
                culture_prefix = "en*" if lang == "en" else "fr*"
                ps_cmd = (
                    f"Add-Type -AssemblyName System.Speech; "
                    f"$s = New-Object System.Speech.Synthesis.SpeechSynthesizer; "
                    f"$v = $s.GetInstalledVoices() | Where-Object {{ $_.VoiceInfo.Culture.Name -like '{culture_prefix}' }} | Select-Object -First 1; "
                    f"if ($v) {{ $s.SelectVoice($v.VoiceInfo.Name) }}; "
                    f"$s.Speak('{escaped}')"
                )
                subprocess.run(
                    f'powershell -Command "{ps_cmd}"',
                    shell=True,
                    timeout=5,
                    creationflags=0x08000000 if os.name == "nt" else 0
                )
            except Exception:
                pass

        threading.Thread(target=audio_task, daemon=True).start()

    def toggle_pin(self):
        self.is_pinned = not self.is_pinned
        self.attributes("-topmost", self.is_pinned)
        self.btn_gear.configure(
            fg_color="#FEF3C7" if self.is_pinned else "transparent",
            text_color="#D97706" if self.is_pinned else "#64748B"
        )

    def open_saved_file(self):
        if self.current_lang == "en":
            target = EN_LOCAL_LIST_FILE if os.path.exists(EN_LOCAL_LIST_FILE) else EN_LIST_FILE
        else:
            target = FR_LOCAL_LIST_FILE if os.path.exists(FR_LOCAL_LIST_FILE) else FR_LIST_FILE
        if not os.path.exists(target):
            open(target, "w", encoding="utf-8").close()
        os.startfile(target)

    # --------------------------------------------------------------------------
    # 5. BẮT TỪ TOÀN CỤC KHI BÔI ĐEN + NHẤN CTRL 2 LẦN LIÊN TIẾP (DOUBLE-CTRL)
    # --------------------------------------------------------------------------
    def _start_global_listener(self):
        self.kb_controller = keyboard.Controller()
        self.mouse_pressed = False
        self.press_pos = (0, 0)
        self.ctrl_at_press = False
        self.last_mouse_release = 0.0

        def is_ctrl_pressed_win():
            return bool(ctypes.windll.user32.GetAsyncKeyState(0x11) & 0x8000)

        def on_key_press(key):
            if self.is_simulating_copy:
                return
            if key in (keyboard.Key.ctrl, keyboard.Key.ctrl_l, keyboard.Key.ctrl_r):
                if not self.is_ctrl_down:
                    self.is_ctrl_down = True
                    self.other_key_pressed_during_ctrl = False
            else:
                if self.is_ctrl_down:
                    self.other_key_pressed_during_ctrl = True

        def on_key_release(key):
            if self.is_simulating_copy:
                return
            if key in (keyboard.Key.ctrl, keyboard.Key.ctrl_l, keyboard.Key.ctrl_r):
                self.is_ctrl_down = False
                if not self.other_key_pressed_during_ctrl:
                    now = time.time()
                    delta = now - self.last_ctrl_release_time
                    if 0.04 <= delta <= 0.55:
                        self.last_ctrl_release_time = 0.0
                        threading.Timer(0.03, self._trigger_copy_and_capture).start()
                    else:
                        self.last_ctrl_release_time = now
                else:
                    self.last_ctrl_release_time = 0.0

        def on_mouse_click(x, y, button, pressed):
            if button != mouse.Button.left:
                return
            now = time.time()
            if pressed:
                self.mouse_pressed = True
                self.press_pos = (x, y)
                self.ctrl_at_press = self.is_ctrl_down or is_ctrl_pressed_win()
            else:
                ctrl_active = self.ctrl_at_press or self.is_ctrl_down or is_ctrl_pressed_win()
                if ctrl_active and not self.is_simulating_copy:
                    dist = ((x - self.press_pos[0]) ** 2 + (y - self.press_pos[1]) ** 2) ** 0.5
                    is_dbl = (now - self.last_mouse_release) < 0.45
                    self.last_mouse_release = now
                    if dist > 6 or is_dbl:
                        threading.Timer(0.05, self._trigger_copy_and_capture).start()
                self.mouse_pressed = False

        threading.Thread(
            target=lambda: keyboard.Listener(on_press=on_key_press, on_release=on_key_release).run(),
            daemon=True
        ).start()
        threading.Thread(
            target=lambda: mouse.Listener(on_click=on_mouse_click).run(),
            daemon=True
        ).start()

    def _trigger_copy_and_capture(self):
        if self.is_processing_copy:
            return
        threading.Thread(target=self._capture_worker, daemon=True).start()

    def _capture_worker(self):
        self.is_processing_copy = True
        self.is_simulating_copy = True
        try:
            time.sleep(0.04)
            with self.kb_controller.pressed(keyboard.Key.ctrl):
                self.kb_controller.press("c")
                self.kb_controller.release("c")

            time.sleep(0.10)
            raw_text = pyperclip.paste()
            if not raw_text:
                return

            text = raw_text.strip()
            clean = re.sub(r"^[^\w']+|[^\w']+$", "", text, flags=re.UNICODE)
            if 1 <= len(clean) <= 60 and "\n" not in clean:
                self.queue.put(("POPUP_WORD", clean))
        except Exception as e:
            print(f"[!] Lỗi bắt từ: {e}")
        finally:
            time.sleep(0.08)
            self.is_simulating_copy = False
            self.is_processing_copy = False


if __name__ == "__main__":
    app = MochiVocabCapture()
    app.mainloop()