File size: 87,450 Bytes
0789398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09e59d
 
 
 
 
 
 
 
4d3bb7c
 
 
 
 
 
 
 
 
 
 
e2266ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2621817
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0789398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78b72a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0789398
78b72a5
 
0789398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ================================================================
# ural_code_engine.py — MASTER CODE ENGINE v3.0
# Nâng cấp toàn diện để đạt Claude-level programming
#
# 12 CƠ CHẾ CỐT LÕI:
# [1]  Semantic Code Detector     — nhận biết request thông minh
# [2]  Intent Decomposer          — hiểu YÊU CẦU THẬT trước khi code
# [3]  Pre-Code Reasoning Engine  — suy nghĩ trước, code sau
# [4]  Language & Framework Aware — context đúng ngôn ngữ/framework
# [5]  Anti-Hallucination Guard   — không bịa API, không bịa syntax
# [6]  Self-Verification Layer    — tự tìm bug trước khi trả lời
# [7]  Completeness Enforcer      — không TODO, không placeholder
# [8]  Algorithm Master           — biết thuật toán tối ưu cho bài toán
# [9]  Complexity Analyzer        — phân tích Big-O trước khi code
# [10] Architecture Advisor       — design pattern đúng context
# [11] Debug Pattern Matcher      — nhận diện lỗi phổ biến
# [12] Problem Decomposer         — chia bài khó thành bước nhỏ
# ================================================================

import os, sys, re, time, random, threading
from typing import Optional


# ══════════════════════════════════════════════════════════════════
# [1] SEMANTIC CODE DETECTOR
# ══════════════════════════════════════════════════════════════════
def is_code_request(text: str) -> bool:
    t = text.lower().strip()
    if "```" in text or re.search(r"\bdef \w+\(|\bclass \w+[:(]|\bfunction\s+\w+\(", text):
        return True
    _action = r"(viết|tạo|làm|build|code|implement|xây dựng|thiết kế|lập trình|tối ưu|fix|sửa|debug|refactor)"
    _obj    = r"(hàm|function|class|api|endpoint|bot|script|tool|app|website|game|module|plugin|component|server|database|query|thuật toán|algorithm|code|chương trình|ứng dụng)"
    if re.search(f"{_action}.{{0,30}}{_obj}", t) or re.search(f"{_obj}.{{0,20}}{_action}", t):
        return True
    if re.search(r"(debug|fix|sửa|repair).{0,20}(lỗi|bug|error|code|này|đây)", t):
        return True
    _langs = r"(python|javascript|typescript|html|css|sql|java|kotlin|swift|go|rust|php|c\+\+|c#|bash|shell|react|vue|angular|flutter|dart|nodejs|fastapi|django|flask)"
    _acts  = r"(viết|code|làm|build|tạo|sử dụng|dùng|cài|deploy|chạy|run|debug|fix|test|implement)"
    if re.search(f"{_langs}.{{0,20}}{_acts}", t) or re.search(f"{_acts}.{{0,20}}{_langs}", t):
        return True
    if re.search(r"(error|exception|traceback|syntax error|runtime error|import error|typeerror|valueerror|keyerror|indexerror|attributeerror|nameerror)", t):
        return True
    if re.search(r"(dockerfile|requirements\.txt|package\.json|setup\.py|\.env|config\.yaml|ci/cd|github action|pipeline)", t):
        return True
    if re.search(r"(tối ưu|optimize|refactor|cải thiện performance|nhanh hơn|giảm độ phức tạp).{0,30}(code|hàm|thuật toán|query|loop)", t):
        return True
    if re.search(r"(sort|search|tree|graph|dp|dynamic.programming|recursion|memoization|backtracking|binary.search|hash|heap|trie|queue|stack|linked.list)", t):
        return True
    if re.search(r"(thuật toán|algorithm|data structure|cấu trúc dữ liệu|độ phức tạp|big.?o|time.complexity|space.complexity)", t):
        return True
    return False


# ══════════════════════════════════════════════════════════════════
# [2] LANGUAGE DETECTOR + FRAMEWORK AWARE
# ══════════════════════════════════════════════════════════════════
def detect_code_language(text: str) -> str:
    t = text.lower()
    lang_map = [
        ("TypeScript",  [r"typescript", r"\.tsx?", r"\bts\b", r"type\s+\w+\s*=", r"interface\s+\w+", r"generic", r"<T>"]),
        ("React/JSX",   [r"react", r"jsx", r"usestate", r"useeffect", r"usememo", r"component", r"props\.", r"useState", r"redux", r"zustand"]),
        ("Vue.js",      [r"vue", r"v-model", r"v-for", r"v-if", r"<template>", r"vuex", r"pinia"]),
        ("Node.js",     [r"nodejs", r"node\.js", r"express", r"nestjs", r"npm ", r"require\(", r"module\.exports"]),
        ("JavaScript",  [r"\bjavascript\b", r"\bjs\b", r"vanilla js", r"dom", r"fetch\("]),
        ("Python",      [r"\bpython\b", r"\.py\b", r"pip ", r"django", r"flask", r"fastapi", r"pandas", r"numpy", r"async def", r"asyncio", r"pydantic"]),
        ("SQL",         [r"\bsql\b", r"select .+ from", r"insert into", r"mysql", r"postgresql", r"sqlite", r"orm", r"migration"]),
        ("HTML/CSS",    [r"\bhtml\b", r"\bcss\b", r"<div", r"stylesheet", r"flexbox", r"grid", r"animation", r"tailwind"]),
        ("Kotlin",      [r"\bkotlin\b", r"android", r"jetpack", r"coroutine"]),
        ("Swift",       [r"\bswift\b", r"\bios\b", r"swiftui", r"uikit"]),
        ("Go",          [r"\bgolang\b", r"\bgo\b.*\bserver\b", r"goroutine", r"channel\b", r"go func"]),
        ("Rust",        [r"\brust\b", r"\bcargo\b", r"ownership", r"borrowing", r"lifetime"]),
        ("C++",         [r"c\+\+", r"#include", r"std::", r"vector<", r"template<", r"pointer"]),
        ("C#",          [r"c#", r"\.net", r"csharp", r"linq", r"aspnet", r"unity"]),
        ("Java",        [r"\bjava\b", r"spring", r"maven", r"gradle", r"arraylist", r"hashmap"]),
        ("PHP",         [r"\bphp\b", r"laravel", r"composer", r"artisan"]),
        ("Bash/Shell",  [r"\bbash\b", r"\bshell\b", r"#!/bin", r"\bgrep\b", r"\bawk\b", r"\bsed\b"]),
        ("Docker",      [r"dockerfile", r"\bdocker\b", r"docker-compose", r"container", r"image build"]),
    ]
    for lang, patterns in lang_map:
        if any(re.search(p, t) for p in patterns):
            return lang
    return "Python"


def detect_code_task(text: str) -> str:
    t = text.lower()
    patterns = [
        ("Debug/Sửa lỗi",        [r"(fix|sửa|debug).{0,20}(bug|lỗi|error)", r"lỗi này", r"bị lỗi", r"không chạy", r"traceback"]),
        ("Tối ưu hiệu năng",     [r"(tối ưu|optimize|nhanh hơn|performance|chậm)", r"big.?o", r"complexity", r"memory leak"]),
        ("Thuật toán & DS",      [r"(sort|search|tree|graph|dp|dynamic.prog|recursion|heap|trie|hash)", r"thuật toán", r"algorithm", r"data structure"]),
        ("Giải thích code",      [r"(giải thích|explain|code này làm gì|đọc code|ý nghĩa)", r"how does"]),
        ("Refactor/Clean",       [r"refactor", r"clean code", r"viết lại", r"đẹp hơn", r"readable"]),
        ("Viết test",            [r"(unit test|test case|pytest|jest|mock|coverage|tdd)", r"kiểm thử"]),
        ("Xây dựng API",         [r"(api|endpoint|route|rest|graphql|webhook|http method)", r"crud"]),
        ("Database/Query",       [r"(database|sql|query|migration|schema|orm|index|join)", r"cơ sở dữ liệu"]),
        ("Bot/Automation",       [r"(bot|discord|telegram|automation|scheduler|cron|scrape)"]),
        ("ML/Data Science",      [r"(machine learning|deep learning|neural network|model|train|dataset|pandas|numpy|sklearn|pytorch|tensorflow|predict|classify|cluster|regression|epoch|batch|gradient|embedding|transformer|llm|fine.?tun)"]),
        ("Web Scraping",         [r"(scrape|crawl|beautifulsoup|selenium|playwright|requests.*html|lấy dữ liệu web|cào dữ liệu|extract.*website|parse.*html)"]),
        ("Game Dev",             [r"(game|pygame|phaser|game loop|collision|sprite|player|enemy|score|level|jump|shoot|pixel|canvas game|vật lý game|trò chơi)"]),
        ("CLI/Script",           [r"(cli|command.?line|argparse|click|typer|script|bash|shell script|tool dòng lệnh|terminal|stdin|stdout|pipe)"]),
        ("Data Visualization",   [r"(matplotlib|seaborn|plotly|chart|biểu đồ|dashboard|visualization|đồ thị|vẽ chart|heatmap|histogram|scatter)"]),
        ("Simulation/Visual",    [r"(mô phỏng|simulation|dao động|lò xo|hành tinh|orbit|particle|physics|vật lý|canvas|three.?js|wave|sóng|vật nặng|pendulum|solar|galaxy|fluid|ripple|firework|bounce|gravity|trọng lực|spring|oscillat)"]),
        ("Frontend/UI",          [r"(giao diện|frontend|ui|component|layout|responsive|css|html|animation)"]),
        ("System Design",        [r"(kiến trúc|architecture|design pattern|microservice|scalab|distributed|load balanc)"]),
        ("Deploy/DevOps",        [r"(deploy|docker|ci/cd|github action|server|nginx|kubernetes|cloud)"]),
        ("Security",             [r"(bảo mật|security|xss|csrf|injection|auth|jwt|oauth|encrypt)"]),
        ("Concurrent/Async",     [r"(async|await|concurrent|thread|process|race condition|deadlock|asyncio)"]),
    ]
    for name, pats in patterns:
        if any(re.search(p, t) for p in pats):
            return name
    return "Viết code mới"


# ══════════════════════════════════════════════════════════════════
# [8] ALGORITHM MASTER — biết thuật toán tối ưu cho từng bài
# ══════════════════════════════════════════════════════════════════
_ALGORITHM_MASTER = """
╔══════════════════════════════════════════════════════════╗
║  ALGORITHM MASTER — CHỌN THUẬT TOÁN TỐI ƯU              ║
╚══════════════════════════════════════════════════════════╝

[SORTING — Khi nào dùng gì]
• Quicksort O(n log n) avg: mảng lớn, random data — unstable nhưng cache-friendly
• Mergesort O(n log n) worst: cần stable sort, linked list, external sort
• Heapsort O(n log n) guaranteed: cần worst-case đảm bảo, không cần stable
• Timsort (Python sorted()): real-world data (gần sorted) — tốt nhất thực tế
• Counting/Radix Sort O(n+k): integer trong range nhỏ — cực nhanh
• Insertion Sort O(n²): mảng nhỏ (<20 phần tử) hoặc almost-sorted

[SEARCHING]
• Binary Search O(log n): mảng đã sort — LUÔN dùng khi data sorted
• Hash Table O(1): lookup/insert/delete nhanh nhất — trade space for time
• BFS O(V+E): shortest path unweighted, level-by-level traversal
• DFS O(V+E): connected components, cycle detection, topological sort
• A* O(E log V): shortest path với heuristic (pathfinding, maps)
• Dijkstra O((V+E) log V): shortest path weighted graph, non-negative edges
• Bellman-Ford O(VE): shortest path với negative edges, detect negative cycle

[DYNAMIC PROGRAMMING — Nhận dạng bài DP]
Dấu hiệu: "tối ưu", "đếm số cách", "min/max", "có thể chia thành subproblem"
• 1D DP: Fibonacci, climbing stairs, coin change, house robber
• 2D DP: LCS, Edit distance, Knapsack, Matrix chain
• DP on Tree: diameter, max path sum
• Bitmask DP: traveling salesman, assignment problem
Template: dp[state] = optimal_value, build từ base case lên

[GRAPH PATTERNS]
• Union-Find (DSU): connected components, cycle detection, Kruskal MST
• Topological Sort: dependency resolution, course schedule
• Strongly Connected Components (Tarjan/Kosaraju): find cycles in directed graph
• Minimum Spanning Tree: Kruskal (sort edges) hoặc Prim (priority queue)

[TWO POINTERS & SLIDING WINDOW]
• Two Pointers: sorted array pair sum, palindrome check — O(n) thay O(n²)
• Sliding Window: max/min subarray of size k, substring problems — O(n)
• Fast/Slow Pointers: cycle detection in linked list (Floyd's algorithm)

[DIVIDE & CONQUER]
• Merge Sort, Quick Sort, Binary Search đều là D&C
• Closest pair of points, Strassen matrix multiply
• Khi bài có dạng T(n) = 2T(n/2) + O(n) → O(n log n)

[GREEDY — Khi nào dùng được]
Chỉ dùng khi: local optimal = global optimal (cần chứng minh)
• Activity Selection, Interval Scheduling: sort by end time
• Huffman Coding: frequency-based compression
• Fractional Knapsack: sort by value/weight ratio
• Coin change (với mệnh giá chuẩn): greedy OK, nhưng thường cần DP

[BACKTRACKING]
• Permutation, Combination, Subset generation
• N-Queens, Sudoku solver, Word search
• Template: choose → explore → unchoose (prune khi không thể)

[COMPLEXITY GUIDE]
O(1) < O(log n) < O(√n) < O(n) < O(n log n) < O(n²) < O(2ⁿ) < O(n!)
Với n=10⁶: O(n log n) OK, O(n²) = 10¹² = quá chậm
"""

# ══════════════════════════════════════════════════════════════════
# [9] COMPLEXITY ANALYZER
# ══════════════════════════════════════════════════════════════════
_COMPLEXITY_RULES = """
[PHÂN TÍCH ĐỘ PHỨC TẠP — BẮT BUỘC với mọi thuật toán]

Trước khi code, phân tích:
1. TIME COMPLEXITY: O(?) — worst case
2. SPACE COMPLEXITY: O(?) — extra space
3. Có thể tối ưu không? Trade-off space/time?

VÍ DỤ PHÂN TÍCH:
• for i in range(n): O(n)
• for i in range(n): for j in range(n): O(n²) — thường cần tối ưu
• Binary search: O(log n)
• Hash lookup: O(1) amortized
• Sorting: O(n log n) minimum (comparison-based)
• Recursive với memo: phụ thuộc số state × thời gian mỗi state

KHI NÀO CẦN TỐI ƯU:
• n > 10⁴ và code là O(n²) → cần xuống O(n log n) hoặc O(n)
• n > 10⁶ và code là O(n log n) → cân nhắc O(n)
• Memory > 256MB → cần space optimization
"""

# ══════════════════════════════════════════════════════════════════
# [10] ARCHITECTURE ADVISOR — Design patterns đúng context
# ══════════════════════════════════════════════════════════════════
_ARCHITECTURE_GUIDE = """
[DESIGN PATTERNS — CHỌN ĐÚNG CHO BÀI TOÁN]

CREATIONAL (Tạo object):
• Singleton: DB connection pool, Config, Logger — chỉ 1 instance
• Factory: tạo object không biết class cụ thể (plugin system, DI)
• Builder: object phức tạp nhiều optional params (query builder)

STRUCTURAL (Cấu trúc):
• Adapter: kết nối 2 interface không tương thích (legacy code, 3rd party)
• Decorator: thêm tính năng không sửa class gốc (@timer, @cache, @auth)
• Proxy: lazy loading, caching, access control

BEHAVIORAL (Hành vi):
• Observer/Event: UI events, pub-sub, webhook notification
• Strategy: thuật toán hoán đổi được (payment method, sorting strategy)
• Command: undo/redo, queue operations, transaction
• Iterator: duyệt collection mà không expose internal structure

ARCHITECTURAL PATTERNS:
• MVC/MVP/MVVM: tách data, logic, UI
• Repository Pattern: tách business logic khỏi data access
• CQRS: tách read/write operations (scale riêng biệt)
• Event Sourcing: log mọi change như events

ANTI-PATTERNS CẦN TRÁNH:
• God Object: class làm quá nhiều thứ → chia nhỏ
• Magic Numbers: dùng constants có tên
• Copy-Paste Code → extract function
• Premature Optimization → profile trước, optimize sau
• Deep Nesting → early return, extract function
"""

# ══════════════════════════════════════════════════════════════════
# [11] DEBUG PATTERN MATCHER
# ══════════════════════════════════════════════════════════════════
_DEBUG_PATTERNS = """
[NHẬN DIỆN & FIX LỖI PHỔ BIẾN]

PYTHON COMMON BUGS:
• NameError: biến chưa define → check scope, typo
• TypeError: wrong type → check isinstance(), type conversion
• AttributeError: method/attr không tồn tại → check class definition, None check
• KeyError: key không tồn tại → dùng dict.get(key, default)
• IndexError: out of range → check len(), range bounds
• RecursionError: đệ quy không có base case → kiểm tra termination condition
• ImportError: module sai → pip install, check name
• IndentationError: tab/space mix → dùng nhất quán (4 spaces PEP8)
• Race Condition: async code → asyncio.Lock(), threading.Lock()
• Memory Leak: circular reference → gc.collect(), weak reference
• Off-by-one: range(n) vs range(n+1), < vs <=

JAVASCRIPT COMMON BUGS:
• undefined vs null → strict equality ===
• this binding → arrow functions, .bind()
• async/await not awaited → missing await keyword
• Promise rejection unhandled → .catch() or try/catch
• Closure in loop → let vs var, IIFE
• NaN comparison → Number.isNaN() not ===
• Prototype mutation → spread operator, Object.assign()

HTML/CSS COMMON BUGS:
• Blank page → check console error, script type="module" on local file
• CSS not applying → specificity, check selector, !important abuse
• Layout broken on mobile → viewport meta, overflow:hidden, flexbox
• Z-index not working → check stacking context (position:relative needed)

DEBUGGING PROCESS:
1. READ lỗi đầy đủ — đừng bỏ qua stack trace
2. REPRODUCE minimum case
3. ISOLATE — comment out code để tìm đoạn gây lỗi
4. INSPECT — print/log giá trị tại điểm nghi ngờ
5. HYPOTHESIS → TEST → CONCLUDE
6. FIX root cause, không chỉ symptom
"""

# ══════════════════════════════════════════════════════════════════
# [12] PROBLEM SOLVING FRAMEWORK
# ══════════════════════════════════════════════════════════════════
_PROBLEM_SOLVING_FRAMEWORK = """
╔══════════════════════════════════════════════════════════╗
║  PROBLEM SOLVING FRAMEWORK — 7 BƯỚC GIẢI MỌI BÀI       ║
╚══════════════════════════════════════════════════════════╝

BƯỚC 1 — HIỂU BÀI (Understand):
• Input là gì? Kiểu gì? Range? Có thể null/empty?
• Output là gì? Format? Chính xác hay xấp xỉ?
• Constraints? Time/Space limit?
• Test cases: bình thường, edge cases, corner cases

BƯỚC 2 — ĐẶT VÍ DỤ CỤ THỂ (Examples):
• Tự tạo 2-3 ví dụ với tay
• Input rỗng, 1 phần tử, số âm, số lớn
• Tìm pattern từ ví dụ

BƯỚC 3 — BRAINSTORM APPROACH (Brute Force → Optimize):
• Brute force approach là gì? O(?) 
• Có thể dùng sorting để đơn giản hóa không?
• Hash table để O(1) lookup?
• Two pointer nếu array/string sorted?
• DP nếu có overlapping subproblems?
• Greedy nếu local optimal = global optimal?

BƯỚC 4 — PHÂN TÍCH COMPLEXITY:
• Time: O(?) — acceptable không?
• Space: O(?) — trong giới hạn không?
• Nếu không OK → tối ưu approach

BƯỚC 5 — CODE (Structure First):
• Viết outline/pseudocode trước
• Core logic → Error handling → Edge cases
• Hàm nhỏ, tên rõ nghĩa

BƯỚC 6 — TỰ TEST (Trace Through):
• Chạy thử code trong đầu với ví dụ nhỏ
• Test edge case: empty, single, max
• Check boundary conditions

BƯỚC 7 — OPTIMIZE (If Needed):
• Còn loop lồng nhau không cần thiết?
• Dùng built-in functions (sort, set, dict) thay tự implement?
• Có thể cache/memoize gì không?
"""

# ══════════════════════════════════════════════════════════════════
# SOLID PRINCIPLES + DESIGN PATTERNS + CODE QUALITY
# ══════════════════════════════════════════════════════════════════
_SOLID_PRINCIPLES = """
[SOLID PRINCIPLES — Áp dụng khi code OOP hoặc module lớn]
• S — Single Responsibility: 1 class/function làm 1 việc, 1 lý do để thay đổi
  ❌ class UserManager: login() + sendEmail() + generateReport()
  ✅ class AuthService, class EmailService, class ReportService
• O — Open/Closed: Mở để extend, đóng để modify
  ❌ if type == "A": ... elif type == "B": ...  (thêm type phải sửa code cũ)
  ✅ class Animal(ABC): def speak() — subclass override
• L — Liskov Substitution: Subclass phải dùng được chỗ của parent
  ❌ class Square(Rectangle): setWidth phá vỡ invariant của Rectangle
  ✅ Thiết kế hierarchy đúng, không override phá vỡ contract
• I — Interface Segregation: Interface nhỏ, specific — không force implement method không cần
  ❌ class IWorker: work() + eat() + sleep() — Robot không cần eat()
  ✅ class IWorkable: work() | class IFeedable: eat()
• D — Dependency Inversion: Depend on abstraction, không depend on concrete
  ❌ class OrderService: self.db = MySQLDatabase()
  ✅ class OrderService: def __init__(self, db: Database): self.db = db
"""

_DESIGN_PATTERNS = """
[DESIGN PATTERNS — Dùng đúng chỗ, không over-engineer]
CREATIONAL (Tạo object):
• Factory: tạo object mà không biết class cụ thể — get_payment("stripe"/"paypal")
• Singleton: chỉ 1 instance — DB connection, config, logger
• Builder: tạo object phức tạp step by step — QueryBuilder().select().where().limit()

STRUCTURAL (Cấu trúc):
• Adapter: wrap interface không tương thích — OpenAIAdapter(GoogleAIClient)
• Decorator: thêm tính năng không sửa code gốc — @cache, @retry, @log_time
• Facade: interface đơn giản cho subsystem phức tạp — EmailService.send()

BEHAVIORAL (Hành vi):
• Observer: event system — on("message", handler), pub/sub
• Strategy: thay đổi algorithm runtime — sort(strategy=QuickSort/MergeSort)
• Command: encapsulate request — undo/redo, queue operations
• State Machine: manage states — IDLE→LOADING→SUCCESS/ERROR

KHI NÀO DÙNG:
• Factory: nhiều loại object cùng interface
• Decorator: cross-cutting concerns (logging, auth, cache)
• Observer: loose coupling giữa components
• Strategy: nhiều cách giải quyết 1 bài toán
TRÁNH: Singleton quá nhiều (global state khó test), premature abstraction
"""

_CODE_QUALITY = """
[CODE QUALITY STANDARDS — Mã nguồn sạch như Claude]
NAMING (Đặt tên):
• Variable/function: snake_case (Python), camelCase (JS) — KHÔNG a, b, tmp, foo
• Boolean: is_valid, has_data, can_access — bắt đầu bằng is/has/can/should
• Function: verb + noun — get_user(), calculate_total(), validate_email()
• Constant: UPPER_SNAKE_CASE — MAX_RETRY, DEFAULT_TIMEOUT
• Class: PascalCase — UserRepository, PaymentProcessor

STRUCTURE (Cấu trúc):
• Function: tối đa 20-30 dòng — nếu dài hơn → tách function
• Nesting: tối đa 3-4 level — nếu sâu hơn → early return hoặc extract function
• DRY: code lặp 2+ lần → extract function/constant
• Magic numbers: KHÔNG 86400 trực tiếp → SECONDS_PER_DAY = 86400
• Comments: giải thích WHY, không giải thích WHAT (code đã tự nói)

DOCUMENTATION:
• Docstring cho mọi public function: Args, Returns, Raises, Example
• README cho project: mô tả, cài đặt, usage, example
• Type hints đầy đủ (Python), JSDoc (JavaScript)

CODE SMELLS CẦN TRÁNH:
• Long Parameter List: >4 params → dùng dataclass/dict
• Feature Envy: method dùng data của class khác nhiều hơn class mình
• Dead Code: code không dùng → xóa
• Duplicated Code: copy-paste → extract
• God Class: class biết quá nhiều → tách ra
• Primitive Obsession: dùng string/int cho domain concepts → tạo class/enum
"""

# ══════════════════════════════════════════════════════════════════
# [4] LANGUAGE RULES — Expanded
# ══════════════════════════════════════════════════════════════════
_LANG_RULES = {
    "Python": """PYTHON BEST PRACTICES:
• Type hints đầy đủ: def func(x: int, data: list[str]) -> dict[str, int]
• f-string thay % và .format(): f"Hello {name!r}"
• Context manager: with open() as f, with lock:
• Exception cụ thể: except (ValueError, TypeError) as e:
• Dataclass cho data containers: @dataclass class Point: x: float; y: float
• List/dict/set comprehension khi ngắn gọn hơn for loop
• Generator cho large data: (x for x in data) tiết kiệm memory
• Walrus operator :=  cho while loops
• @functools.lru_cache cho memoization
• asyncio.gather() để run tasks parallel
• pathlib.Path thay os.path
• logging thay print() cho production
TRÁNH: bare except, global variables, mutable default arguments (def f(x=[]))""",

    "JavaScript": """JAVASCRIPT BEST PRACTICES:
• const/let, tuyệt đối không var
• async/await thay .then().catch() — dễ đọc, debug dễ hơn
• Optional chaining: user?.profile?.avatar
• Nullish coalescing: name ?? 'Anonymous'
• Destructuring + default: const { a = 0, b = '' } = obj
• Spread operator: [...arr1, ...arr2], {...obj1, ...obj2}
• Array: .map, .filter, .reduce, .find, .some, .every (tránh for loop thuần)
• Template literals cho string phức tạp
• Modules: import/export (ES modules, không CommonJS trong modern JS)
• Error handling: try/catch/finally hoặc Promise.allSettled()
• Set/Map cho unique values và key-value pairs tốt hơn Object
TRÁNH: == (dùng ===), var, callback hell, không xử lý Promise rejection""",

    "TypeScript": """TYPESCRIPT BEST PRACTICES:
• Interface cho object shapes, type alias cho union/intersection
• Không dùng 'any' — dùng 'unknown' rồi narrow type
• Generic types: function identity<T>(arg: T): T
• Utility types: Partial<T>, Required<T>, Pick<T, K>, Omit<T, K>, Record<K, V>
• Discriminated unions cho state machines: type State = {kind: 'loading'} | {kind: 'data', data: T}
• as const cho literal types
• Strict mode trong tsconfig
• Enums ít dùng — thay bằng const object hoặc union literal types
TRÁNH: any, type casting không cần thiết, ignore ts errors""",

    "React/JSX": """REACT BEST PRACTICES:
• Functional component + hooks, không class component
• Key prop phải unique và stable (không dùng index làm key nếu list thay đổi)
• useEffect: cleanup function khi có subscription/timer
• useMemo cho expensive computation, useCallback cho function props
• Custom hooks để reuse stateful logic
• Context + useReducer cho global state phức tạp
• React.memo() cho component optimization khi parent re-render nhiều
• Error Boundary để catch runtime errors
• Lazy loading: React.lazy() + Suspense
• Form: controlled components hoặc React Hook Form
TRÁNH: prop drilling sâu quá 3 level, useEffect chạy mỗi render, setState trong render""",

    "SQL": """SQL BEST PRACTICES:
• Parameterized query LUÔN LUÔN — KHÔNG string concatenation
• INDEX cho column thường dùng trong WHERE, JOIN, ORDER BY
• Tránh SELECT * — chỉ lấy column cần
• EXPLAIN/EXPLAIN ANALYZE trước khi optimize
• JOIN thay subquery khi có thể (thường nhanh hơn)
• Tránh function trong WHERE clause (vô hiệu hóa index): WHERE YEAR(date) = 2024
  Thay bằng: WHERE date >= '2024-01-01' AND date < '2025-01-01'
• N+1 query problem: dùng JOIN hoặc IN() thay loop query
• Transaction cho multiple related writes
• Connection pooling cho production
• Pagination: LIMIT + OFFSET hoặc cursor-based pagination
TRÁNH: SELECT * trong subquery, correlated subquery trong loop, implicit conversion""",

    "Node.js": """NODE.JS BEST PRACTICES:
• async/await với proper error handling: try/catch
• Express: middleware pipeline, error handler middleware cuối cùng
• Environment variables: dotenv, không hardcode
• Rate limiting: express-rate-limit
• Helmet.js cho security headers
• Morgan cho logging
• Input validation: joi, zod, express-validator
• NEVER block event loop: không sync I/O, không heavy computation trong main thread
• Worker threads cho CPU-intensive tasks
• Cluster mode để tận dụng multiple cores
TRÁNH: sync file operations, blocking loops, unhandled promise rejections""",

    "HTML/CSS": """HTML/CSS BEST PRACTICES:
• KHÔNG dùng <script type="module"> trong file local (blank page!)
• Mobile-first: media query từ nhỏ lên lớn
• Flexbox cho 1D layout, Grid cho 2D layout
• CSS variables: --primary-color: #007bff
• Semantic HTML: <header>, <nav>, <main>, <section>, <article>
• Alt text cho img, aria-label cho icon buttons
• Fonts: preconnect Google Fonts, font-display: swap
• Animation: prefer CSS animations, requestAnimationFrame cho JS
• Performance: lazy loading images, minimize reflow/repaint
TRÁNH: !important abuse, inline styles, fixed width px (dùng %, rem, clamp())""",

    "Go": """GO BEST PRACTICES:
• Error handling explicit: if err != nil { return err }
• Goroutines với WaitGroup, Channel, Mutex
• Interface implicit — duck typing
• defer cho cleanup (close file, unlock, disconnect)
• Pointer cho large structs, value cho small
• go vet + golint + gofmt
• Context cho cancellation và timeout
• Table-driven tests
TRÁNH: panic() trong library code, global state, ignoring errors với _""",

    "Rust": """RUST BEST PRACTICES:
• Ownership: mỗi value có 1 owner
• Borrowing: &T immutable, &mut T mutable (chỉ 1 mutable borrow tại một thời điểm)
• Result<T, E> cho error handling, ? operator để propagate
• Option<T> thay null
• match exhaustive cho enum
• Iterator adapters: .map(), .filter(), .collect()
• Lifetimes khi cần reference trong struct
TRÁNH: unwrap() trong production (dùng expect() với message hoặc handle properly), clone() quá nhiều""",

    "Bash/Shell": """BASH BEST PRACTICES:
• Shebang: #!/usr/bin/env bash
• set -euo pipefail ở đầu script (exit on error, undefined var, pipe fail)
• Dùng [[ ]] thay [ ] cho conditionals (bash-specific, safer)
• Quote mọi variable: "$var", "${var}", không bỏ quote
• Check file existence: [[ -f "$file" ]], [[ -d "$dir" ]]
• Dùng $() thay backtick cho command substitution
• Local variables trong function: local var=value
• Error messages → stderr: echo "Error: ..." >&2
• Exit codes: 0=success, 1=general error, 2=misuse
• readonly cho constants: readonly CONFIG_FILE="/etc/app.conf"
• Trap để cleanup: trap 'rm -f "$tmpfile"' EXIT
• Array: arr=("a" "b" "c"), loop: for item in "${arr[@]}"
TRÁNH: parsing ls output, unquoted variables, cd trong subshell""",

    "Python/ML": """PYTHON ML/DATA SCIENCE BEST PRACTICES:
• NumPy: vectorized operations, tránh Python loops trên array lớn
  - np.where() thay if/else trên array
  - Broadcasting: shape (3,1) * (1,4) = (3,4) — không cần tile
  - dtype rõ ràng: np.float32 tiết kiệm memory hơn float64
• Pandas:
  - .loc[], .iloc[] thay chained indexing (tránh SettingWithCopyWarning)
  - .apply() chậm — dùng vectorized pandas/numpy khi có thể
  - .groupby().agg() cho aggregation phức tạp
  - pd.NA cho missing values thay np.nan với nullable dtypes
  - .read_csv(dtype={...}) để đúng type từ đầu
• Scikit-learn:
  - Pipeline để chain preprocessing + model (tránh data leakage)
  - cross_val_score thay train/test split đơn thuần
  - GridSearchCV/RandomizedSearchCV cho hyperparameter tuning
  - StandardScaler FIT trên train, TRANSFORM trên test (không fit lại)
• PyTorch/TensorFlow:
  - model.eval() + torch.no_grad() khi inference
  - .detach().cpu().numpy() để convert tensor
  - DataLoader với num_workers cho training nhanh
  - Gradient clipping: nn.utils.clip_grad_norm_()
• Data Viz:
  - Matplotlib: fig, ax = plt.subplots() thay plt.xxx() trực tiếp
  - Seaborn cho statistical plots
  - Plotly cho interactive charts
  - Luôn đặt title, xlabel, ylabel, legend
TRÁNH: fit scaler/encoder trên test set, for loop trên DataFrame rows, memory leak với GPU tensor""",
}

# ══════════════════════════════════════════════════════════════════
# [2] INTENT DECOMPOSER
# ══════════════════════════════════════════════════════════════════
def decompose_intent(user_query: str) -> dict:
    t = user_query.lower()
    constraints = []
    if re.search(r"không (dùng|import|cài) (thư viện|library|lib)", t):
        constraints.append("không dùng thư viện ngoài — stdlib only")
    if re.search(r"\basync\b|\bawait\b|bất đồng bộ|concurrent|thread", t):
        constraints.append("async/concurrent — cần xử lý race condition")
    if re.search(r"production|deploy thật|môi trường thật", t):
        constraints.append("production-ready — cần logging, error handling đầy đủ")
    if re.search(r"typescript|\bts\b|type hint", t):
        constraints.append("strict typing — type hints/interfaces đầy đủ")
    if re.search(r"\btest\b|unit test|tdd", t):
        constraints.append("có unit tests — arrange/act/assert pattern")
    if re.search(r"free|miễn phí|huggingface|render|không tốn tiền", t):
        constraints.append("free tier compatible — nhẹ, ít RAM, không tốn quota")
    if re.search(r"mobile|android|điện thoại", t):
        constraints.append("mobile-first — test trên thiết bị nhỏ")

    risks = []
    if re.search(r"\bfile\b|đọc file|ghi file|\bio\b", t):
        risks.append("I/O: try/except, encoding='utf-8', context manager")
    if re.search(r"\bapi\b|request|http|fetch", t):
        risks.append("Network: timeout, retry logic, check status code, rate limit")
    if re.search(r"database|sql|query|\bdb\b", t):
        risks.append("DB: parameterized query, close connection, transaction")
    if re.search(r"login|auth|password|token|secret", t):
        risks.append("Security: hash password, không hardcode secret, JWT expiry")
    if re.search(r"vòng lặp|loop|đệ quy|recursion|list|array", t):
        risks.append("Logic: off-by-one, infinite loop, missing base case")
    if re.search(r"\basync\b|\bawait\b|concurrent|thread", t):
        risks.append("Async: race condition, proper await chain, error propagation")
    if re.search(r"html|web|file:/|local file|android|điện thoại", t):
        risks.append("HTML: KHÔNG dùng type='module' cho local file — trang trắng!")
    if re.search(r"recursion|đệ quy|recursive", t):
        risks.append("Recursion: phải có base case rõ ràng, tránh stack overflow (n>1000)")
    if re.search(r"scrape|crawl|cào dữ liệu|lấy dữ liệu web", t):
        risks.append("Scraping: check robots.txt, rate limit, User-Agent header")
    if re.search(r"train|fit|model|dataset|pandas|numpy|sklearn", t):
        risks.append("ML: fit scaler/encoder CHỈ trên train set, tránh data leakage")
    if re.search(r"game|pygame|canvas game|collision|sprite", t):
        risks.append("Game: delta time cho physics, object pooling cho bullets/particles")

    return {
        "lang": detect_code_language(user_query),
        "task": detect_code_task(user_query),
        "constraints": constraints,
        "risks": risks,
    }


# ══════════════════════════════════════════════════════════════════
# [3] ENHANCED TASK RULES
# ══════════════════════════════════════════════════════════════════
_TASK_RULES = {
    "Debug/Sửa lỗi": """DEBUG RULES:
• Tìm ROOT CAUSE — không chỉ fix symptom
• Giải thích TẠI SAO lỗi xảy ra (mechanism) trước khi đưa fix
• Verify fix không tạo regression/bug mới
• Nếu lỗi logic: trace qua từng bước với ví dụ cụ thể
• Nếu lỗi import/dependency: kiểm tra version compatibility
• Nếu lỗi async: vẽ execution flow ra""",

    "Tối ưu hiệu năng": """OPTIMIZATION RULES:
• NÊU ĐỘ PHỨC TẠP O(n) trước và sau khi tối ưu
• Profile trước: xác định bottleneck thực sự (đừng optimize mù)
• Trade-off: time vs space, readability vs speed
• Python: set/dict lookup O(1) thay list O(n), generator thay list
• SQL: thêm index đúng chỗ, tránh function trong WHERE
• Đo benchmark: timeit, cProfile, EXPLAIN ANALYZE""",

    "Thuật toán & DS": """ALGORITHM RULES:
• Phân tích time/space complexity rõ ràng
• So sánh ít nhất 2 approach: brute force vs optimal
• Chứng minh tính đúng đắn (hoặc test cases đa dạng)
• Implement sạch, có comment giải thích bước quan trọng
• Include test cases: empty, single, large, negative, boundary""",

    "Xây dựng API": """API RULES:
• RESTful: GET/POST/PUT/PATCH/DELETE đúng semantics
• Validate input (400 nếu sai) → Process → Return (200/201/204)
• Response format nhất quán: {"status": "ok", "data": ..., "error": null}
• HTTP status codes đúng: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error
• Rate limiting cho endpoint public
• Pagination cho endpoint trả list lớn
• API versioning: /api/v1/...""",

    "Database/Query": """DATABASE RULES:
• Parameterized queries — KHÔNG string format/concatenation
• N+1 query: dùng JOIN hoặc batch thay vì query trong loop
• Index: WHERE, JOIN ON, ORDER BY columns
• Connection pooling — không tạo connection mới mỗi request
• Transaction cho multiple writes
• Migration files cho schema changes""",

    "Viết test": """TEST RULES:
• Arrange-Act-Assert (AAA) pattern
• Test cases: happy path + edge cases + error cases + boundary
• Mock external dependencies (API, DB, file system)
• Tên test rõ nghĩa: test_should_return_zero_when_input_is_empty
• Không test implementation detail — test behavior
• Coverage target: 80%+ for critical paths""",

    "Security": """SECURITY RULES:
• Hash passwords: bcrypt (min cost=12), argon2 — KHÔNG md5/sha1
• JWT: set expiry, validate signature, không lưu sensitive data trong payload
• SQL: parameterized query — ngăn SQL injection
• XSS: sanitize HTML output, Content-Security-Policy header
• CSRF: CSRF token hoặc SameSite cookie
• Rate limiting: ngăn brute force
• Secrets: environment variables, không hardcode, không commit vào git
• HTTPS only in production
• Input validation: whitelist approach, check type + length + format""",

    "Concurrent/Async": """ASYNC RULES:
• asyncio.gather() để run nhiều coroutines parallel
• asyncio.Semaphore để limit concurrent requests
• asyncio.Queue cho producer/consumer pattern
• asyncio.Lock cho shared state
• Proper error handling: asyncio.gather(*tasks, return_exceptions=True)
• Timeout: asyncio.wait_for(coro, timeout=30)
• Thread-safe: Queue thay shared list, Lock trước khi modify
• Avoid blocking calls trong async context (dùng loop.run_in_executor)""",

    "Simulation/Visual": """SIMULATION RULES — BẮT BUỘC CHO MỌI MÔ PHỎNG:

╔══════════════════════════════════════════════════════════════╗
║  ANTI-PATTERNS ĐÃ BIẾT — TUYỆT ĐỐI KHÔNG LÀM              ║
╚══════════════════════════════════════════════════════════════╝
❌ LÒ XO — LỖI PHỔ BIẾN (đã quan sát):
  • KHÔNG canh giữa: `x = SPACING * (i + 1)` → tràn ra ngoài màn hình
    ✅ FIX: const totalW = spacing*(N-1); const startX = (W-totalW)/2; const x = startX + i*spacing;
  • KHÔNG dùng frame count cho state machine (phụ thuộc FPS, 60FPS ≠ 30FPS)
    ✅ FIX: dùng performance.now()/1000 (giây thật), KHÔNG stateTimer++ theo frame
  • KHÔNG lerp phase mà thiếu wrap-around → phase nhảy loạn
    ✅ FIX: let diff = target - current; while(diff>PI) diff-=2*PI; while(diff<-PI) diff+=2*PI; phase += diff*0.02;
  • KHÔNG khởi tạo `spring.y = canvas.height/2` ngay lúc tạo (canvas chưa có kích thước)
    ✅ FIX: tính y trong animation loop từ canvas.height tại thời điểm vẽ
  • KHÔNG bỏ qua trần (ceiling bar) — lò xo phải treo vào đâu đó!
    ✅ FIX: vẽ thanh kim loại ngang, bolt tại mỗi điểm treo lò xo

❌ THREE.JS SOLAR SYSTEM — LỖI PHỔ BIẾN (đã quan sát):
  • KHÔNG để camera bất động — user cần xoay/zoom
    ✅ FIX: implement mouse drag orbit (xem code mẫu bên dưới)
  • KHÔNG bỏ Saturn rings — Saturn PHẢI có vành đai
    ✅ FIX: RingGeometry(inner, outer, 64), rotation.x = -PI/2 + tilt, mesh.add(ring)
  • KHÔNG dùng MeshBasicMaterial cho hành tinh — trông plastic/flat
    ✅ FIX: MeshStandardMaterial + roughness:0.8 + emissive cho depth
  • KHÔNG để Mặt Trời flat — phải có glow layers
    ✅ FIX: 2-3 sphere lồng nhau, BackSide material, opacity giảm dần
  • KHÔNG bỏ label tên hành tinh
    ✅ FIX: Sprite với CanvasTexture, position.y = radius + offset, mesh.add(sprite)
  • KHÔNG bỏ speed control slider
    ✅ FIX: <input type="range">, speedMult = parseFloat(slider.value), dt * speedMult

[VẬT LÝ THẬT — không fake]:
• Lò xo: y(t) = A·sin(2π·f·t + φ), vẽ CUỘN lò xo thật bằng quadraticCurveTo
• Con lắc: θ'' = -(g/L)sin(θ), vẽ dây + bob
• Hành tinh: Kepler — v ∝ 1/√r, hành tinh gần mặt trời đi NHANH hơn
• Sóng: superposition, damping term e^(-γt)

[VISUAL QUALITY — bắt buộc]:
• Glow: ctx.shadowBlur = 12-20; ctx.shadowColor = color; (trước khi stroke/fill)
• Gradient weight: ctx.createLinearGradient → highlight trên, shadow dưới
• Background: không clearRect trắng → ctx.fillStyle='rgba(R,G,B,0.85)'; ctx.fillRect (motion blur)
• Labels: state name, fps counter, physical values lên màn hình
• Color per spring: hue = (i/N)*360 → rainbow gradient

[ANIMATION CYCLE — TIME-BASED, không frame-based]:
```javascript
// ✅ ĐÚNG — time-based state machine (performance.now)
const STATES = [
  { name: 'SYNCHRONIZED', dur: 3.0 },   // giây, không phải frames
  { name: 'DISPERSING',   dur: 4.0 },
  { name: 'WAVE PATTERN', dur: 4.0 },
  { name: 'RESYNCING',    dur: 3.0 },
];
let stateIdx = 0, stateStart = 0;

function tickState(nowSec) {
  if (nowSec - stateStart >= STATES[stateIdx].dur) {
    stateIdx = (stateIdx + 1) % STATES.length;
    stateStart = nowSec;
    applyStateTargets(stateIdx);
  }
  // Lerp với wrap-around — BẮT BUỘC
  springs.forEach(s => {
    let diff = s.targetPhase - s.phase;
    while (diff >  Math.PI) diff -= Math.PI * 2;
    while (diff < -Math.PI) diff += Math.PI * 2;
    s.phase += diff * 0.02;
  });
}

// Layout canh giữa — BẮT BUỘC
function getSpringX(i, N, W) {
  const spacing = Math.min(80, (W - 80) / N);
  const totalW  = spacing * (N - 1);
  const startX  = (W - totalW) / 2;
  return startX + i * spacing;
}
```

[CODE MẪU — Lò xo đầy đủ]:
```javascript
// VẼ LÒ XO — quadraticCurveTo, glow, coil width thay đổi theo stretch
function drawSpring(ctx, x, topY, botY, coils, stretch) {
  const h   = botY - topY;
  const ch  = h / coils;
  const w   = 12 + stretch * 5;   // cuộn rộng khi giãn
  const hue = 180 + stretch * 60; // màu thay đổi theo stretch
  const col = `hsl(${hue},100%,65%)`;
  ctx.save();
  ctx.shadowBlur = 14; ctx.shadowColor = col;
  ctx.strokeStyle = col; ctx.lineWidth = 2.5; ctx.lineCap = 'round';
  ctx.beginPath(); ctx.moveTo(x, topY); ctx.lineTo(x, topY + ch*0.3);
  for (let i = 0; i < coils; i++) {
    const y0 = topY + ch*(i+0.3);
    ctx.quadraticCurveTo(x+w, y0+ch*0.25, x, y0+ch*0.5);
    ctx.quadraticCurveTo(x-w, y0+ch*0.75, x, y0+ch);
  }
  ctx.lineTo(x, botY); ctx.stroke(); ctx.restore();
}

// VẼ TRẦN + BOLT
function drawCeiling(ctx, xs, spacing, ceilY) {
  const x0 = xs[0] - spacing*0.5, x1 = xs[xs.length-1] + spacing*0.5;
  const g = ctx.createLinearGradient(0,ceilY-8,0,ceilY+8);
  g.addColorStop(0,'#2a2a3a'); g.addColorStop(0.5,'#7a7a9a'); g.addColorStop(1,'#1a1a2a');
  ctx.fillStyle = g; ctx.fillRect(x0, ceilY-8, x1-x0, 16);
  xs.forEach(x => {
    ctx.beginPath(); ctx.arc(x,ceilY,5,0,Math.PI*2);
    ctx.fillStyle='#888'; ctx.fill();
    ctx.beginPath(); ctx.arc(x,ceilY,3,0,Math.PI*2);
    ctx.fillStyle='#ddd'; ctx.fill();
  });
}

// VẬT NẶNG — gradient 3D + glow
function drawWeight(ctx, x, y, idx, N) {
  const w=32, h=26, hue=(idx/N)*300;
  ctx.save();
  ctx.shadowBlur=20; ctx.shadowColor=`hsl(${hue},90%,55%)`;
  const g = ctx.createLinearGradient(x-w/2,y,x+w/2,y+h);
  g.addColorStop(0,`hsl(${hue},80%,65%)`);
  g.addColorStop(1,`hsl(${hue},50%,20%)`);
  ctx.fillStyle=g;
  ctx.beginPath(); ctx.roundRect(x-w/2,y,w,h,5); ctx.fill();
  ctx.fillStyle='rgba(255,255,255,0.2)';
  ctx.beginPath(); ctx.roundRect(x-w/2+4,y+3,w/2,6,3); ctx.fill();
  ctx.restore();
}
```

[CODE MẪU — Three.js Solar System đầy đủ]:
```javascript
// CDN: https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
// KHÔNG type="module", KHÔNG OrbitControls

// ── MOUSE ORBIT CONTROLS (thủ công) ─────────────────
const sph = { theta:0.5, phi:0.9, r:200 };
const tSph = {...sph};
let isDrag=false, prev={x:0,y:0};
renderer.domElement.addEventListener('mousedown', e=>{isDrag=true;prev={x:e.clientX,y:e.clientY};});
window.addEventListener('mouseup', ()=>isDrag=false);
window.addEventListener('mousemove', e=>{
  if(!isDrag)return;
  tSph.theta -= (e.clientX-prev.x)*0.006;
  tSph.phi = Math.max(0.1,Math.min(Math.PI-0.1,tSph.phi-(e.clientY-prev.y)*0.006));
  prev={x:e.clientX,y:e.clientY};
});
renderer.domElement.addEventListener('wheel',e=>{
  tSph.r=Math.max(15,Math.min(500,tSph.r+e.deltaY*0.2));
},{passive:true});

// Trong animate loop:
sph.theta+=(tSph.theta-sph.theta)*0.08;
sph.phi  +=(tSph.phi  -sph.phi  )*0.08;
sph.r    +=(tSph.r    -sph.r    )*0.08;
camera.position.set(
  sph.r*Math.sin(sph.phi)*Math.cos(sph.theta),
  sph.r*Math.cos(sph.phi),
  sph.r*Math.sin(sph.phi)*Math.sin(sph.theta)
);
camera.lookAt(0,0,0);

// ── SUN GLOW (layers) ────────────────────────────────
[[11,0xff8800,0.14],[15,0xff4400,0.07],[20,0xff2200,0.03]].forEach(([r,c,o])=>{
  scene.add(new THREE.Mesh(
    new THREE.SphereGeometry(r,32,32),
    new THREE.MeshBasicMaterial({color:c,transparent:true,opacity:o,side:THREE.BackSide})
  ));
});

// ── SATURN RINGS ─────────────────────────────────────
function addSaturnRings(mesh, planetR) {
  [[planetR*1.35,planetR*2.2,0xc8a86b,0.72],[planetR*1.55,planetR*1.9,0x9a7a40,0.45]].forEach(([i,o,c,op])=>{
    const ring = new THREE.Mesh(
      new THREE.RingGeometry(i,o,64),
      new THREE.MeshBasicMaterial({color:c,side:THREE.DoubleSide,transparent:true,opacity:op})
    );
    ring.rotation.x = -Math.PI/2 + 0.45;
    mesh.add(ring);
  });
}

// ── PLANET LABEL (canvas texture) ────────────────────
function createLabel(name) {
  const c=document.createElement('canvas'); c.width=256; c.height=56;
  const cx=c.getContext('2d');
  cx.font='bold 28px Arial'; cx.fillStyle='rgba(255,255,255,0.85)'; cx.textAlign='center';
  cx.fillText(name.toUpperCase(),128,40);
  const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:new THREE.CanvasTexture(c),transparent:true}));
  sp.scale.set(7,1.8,1);
  return sp;
}

// ── PIVOT PATTERN (revolution orbit) ─────────────────
// pivot → mesh (tại planet.dist từ gốc) → rings/moon/label
const pivot = new THREE.Object3D();
pivot.rotation.y = Math.random()*Math.PI*2;
scene.add(pivot);
const mesh = new THREE.Mesh(geo, mat);
mesh.position.x = planet.dist;
pivot.add(mesh);
// Label gắn vào mesh (theo planet tự động)
mesh.add(createLabel(planet.name));
// Orbit trong animate: pivot.rotation.y += planet.speed * dt * 30;

// ── SPEED CONTROL ─────────────────────────────────────
// HTML: <input type="range" id="spd" min="0" max="8" step="0.1" value="1">
let speed = 1;
document.getElementById('spd').addEventListener('input', e => speed = parseFloat(e.target.value));
// trong animate: pivot.rotation.y += planet.orbitSpeed * dt * speed * 30;

// ── MOON ─────────────────────────────────────────────
const moonPivot = new THREE.Object3D(); // pivot gắn vào planet mesh
mesh.add(moonPivot);
const moonMesh = new THREE.Mesh(new THREE.SphereGeometry(0.27,24,24), moonMat);
moonMesh.position.x = 4.5;
moonPivot.add(moonMesh);
// animate: moonPivot.rotation.y += moonSpeed * dt * speed * 30;

// ── KEPLER SPEEDS ─────────────────────────────────────
const planets = [
  {name:'Mercury',dist:20, r:0.4, color:0x9b9b9b, speed:1.607},
  {name:'Venus',  dist:30, r:0.9, color:0xe8cda0, speed:1.174},
  {name:'Earth',  dist:42, r:1.0, color:0x2266cc, speed:1.000},
  {name:'Mars',   dist:56, r:0.53,color:0xcc4422, speed:0.802},
  {name:'Jupiter',dist:78, r:3.0, color:0xc88b3a, speed:0.434},
  {name:'Saturn', dist:100,r:2.6, color:0xe4d191, speed:0.323, rings:true},
  {name:'Uranus', dist:122,r:1.6, color:0x7de8e8, speed:0.228},
  {name:'Neptune',dist:142,r:1.5, color:0x3355ee, speed:0.182},
];
```

[COMPLETENESS CHECKLIST]:
✦ Lò xo: N lò xo canh giữa màn hình | ceiling bar + bolt | state machine TIME-BASED | phase lerp có wrap | weight có gradient + glow
✦ Solar: 8 hành tinh đúng màu | Saturn rings | Earth moon | mouse drag orbit | scroll zoom | speed slider | planet labels | sun glow | starfield
✦ Cả hai: responsive resize | requestAnimationFrame | info panel/HUD""",

    "ML/Data Science": """ML/DATA SCIENCE RULES:
• Pipeline bắt buộc: Load → Clean → EDA → Feature Eng → Split → Scale → Train → Eval → Save
• DATA LEAKAGE: fit scaler/encoder CHỈ trên train set, KHÔNG trên toàn bộ data
• KHÔNG dùng test set để tune hyperparameter → dùng validation set
• Class imbalance: kiểm tra class distribution trước, dùng SMOTE/class_weight nếu cần
• Metric phù hợp: accuracy chỉ tốt khi balanced; F1/AUC-ROC cho imbalanced
• Reproducibility: set random seed (np.random.seed, torch.manual_seed)
• Model save: pickle/joblib cho sklearn, torch.save() cho PyTorch
• EDA bắt buộc: df.info(), df.describe(), df.isnull().sum(), correlation matrix
• Feature importance sau khi train để giải thích model
• Cross-validation: StratifiedKFold cho classification, KFold cho regression""",

    "Web Scraping": """WEB SCRAPING RULES:
• robots.txt: kiểm tra trước, tôn trọng Disallow
• Rate limiting: time.sleep(1-3s) giữa requests, tránh DDoS
• Headers: dùng User-Agent thật (Chrome/Firefox), Referer khi cần
• Session: requests.Session() để tái dùng connection, cookie
• BeautifulSoup: find()/find_all() với CSS selector hoặc tag + attrs
• Playwright/Selenium: chỉ dùng khi cần JavaScript rendering
• Retry logic: tenacity hoặc tự code retry với exponential backoff
• Error handling: 403 (blocked), 429 (rate limit → sleep), 503 (maintenance)
• Lưu data: pandas DataFrame → CSV/JSON, SQLite cho lớn hơn
• Anti-detection: random delay, rotate User-Agent, proxy pool nếu cần
TRÁNH: scrape quá nhanh, parse HTML bằng regex, bỏ qua SSL errors""",

    "Game Dev": """GAME DEVELOPMENT RULES:
• Game loop: update() → draw() tách biệt rõ ràng, fixed timestep cho physics
• requestAnimationFrame cho browser games — KHÔNG setInterval
• Delta time: dt = currentTime - lastTime → physics nhân dt để framerate-independent
• Collision detection: AABB cho hình chữ nhật, circle collision, SAT cho polygon
• Entity-Component pattern cho game objects lớn
• Object pooling: tái dùng objects thay create/destroy liên tục (đặc biệt bullets, particles)
• State machine cho game states: MENU → PLAYING → PAUSED → GAME_OVER
• Input handling: keydown/keyup dict (không dùng event-only), touch support
• Sprite animation: spritesheet, frame counter, fps animation
• Pixel-perfect collision: tránh float position → round() khi vẽ
• Sound: AudioContext Web API, preload sounds
• Score/HUD: vẽ lên canvas layer riêng, font rõ ràng""",

    "CLI/Script": """CLI/SCRIPT RULES:
• argparse/click/typer: help text rõ ràng cho mỗi argument
• Subcommands cho tool phức tạp: app add, app remove, app list
• Exit codes: sys.exit(0) success, sys.exit(1) error — scripts khác check được
• stderr cho error messages: print(..., file=sys.stderr)
• stdin support: nếu không có argument → đọc từ pipe (sys.stdin)
• Progress: tqdm cho long operations
• Color output: rich/colorama, nhưng detect isatty() — tắt màu khi pipe
• Config file: ~/.config/appname/config.toml hoặc .env
• Verbose mode: -v/--verbose flag → logging.DEBUG
• Dry run: --dry-run flag để test trước khi thực hiện
• Idempotent: chạy nhiều lần không gây hại
TRÁNH: hardcode paths, không có --help, crash mà không có error message""",

    "Data Visualization": """DATA VISUALIZATION RULES:
• Matplotlib: LUÔN dùng fig, ax = plt.subplots(figsize=(10,6))
• Title + xlabel + ylabel + legend bắt buộc
• plt.tight_layout() trước khi save
• Chọn chart đúng:
  - Bar chart: so sánh category
  - Line chart: trend theo thời gian
  - Scatter: correlation giữa 2 biến
  - Heatmap (seaborn): correlation matrix, confusion matrix
  - Histogram: distribution
  - Box plot: distribution + outliers
• Màu sắc: colorblind-friendly palette (seaborn: 'colorblind', matplotlib: 'tab10')
• Annotation: ax.annotate() cho điểm quan trọng
• Plotly Interactive: px.line/bar/scatter + hover_data + layout update
• Save: plt.savefig('output.png', dpi=150, bbox_inches='tight')
• Dark theme: plt.style.use('dark_background') hoặc seaborn dark
TRÁNH: pie chart cho >5 categories, 3D chart khi không cần, quá nhiều màu""",

    "System Design": """SYSTEM DESIGN RULES:
• Clarify requirements trước: scale, availability, consistency
• Estimate scale: DAU, QPS, storage
• High-level: client → CDN → Load Balancer → App servers → Cache → DB
• Database: SQL vs NoSQL theo use case
• Caching: Redis cho session, computed results, rate limiting
• Message Queue: async processing, decouple services
• Monitoring: metrics, logging, alerting""",
}


# ══════════════════════════════════════════════════════════════════
# [5] ANTI-HALLUCINATION GUARD — Expanded
# ══════════════════════════════════════════════════════════════════
_HALLUCINATION_PATTERNS = [
    (r"requests\.get_json\(",         "requests không có .get_json() — dùng response.json()"),
    (r"import requests_async",         "thư viện này không tồn tại — dùng aiohttp hoặc httpx"),
    (r"from fast_api import",          "sai package — phải là 'from fastapi import'"),
    (r"import pandas as pd\n.*pd\.read_excel.*without openpyxl",
                                       "pandas cần 'openpyxl' cho .xlsx files"),
    (r'(api_key|password|secret|token)\s*=\s*["\'][^"\']{8,}["\']',
                                       "⚠️ HARDCODED CREDENTIAL — dùng os.getenv()"),
    (r"THREE\.OrbitControls",          "OrbitControls không có trong three.min.js — implement mouse events thuần"),
    (r"three\.min\.js.*r(?!128)\d{2,3}", "Dùng Three.js r128: cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"),
    (r"three@0\.1(?!28)\d\d",           "Dùng Three.js r128: cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"),
    (r'<script type=["\']module["\']', "⛔ type='module' gây blank page khi mở local file!"),
    (r"import \* as THREE from",       "⛔ ES import không chạy được file local — dùng <script src=three.min.js>"),
    # ── SIMULATION-SPECIFIC — từ lỗi đã quan sát trong output thực tế ──
    (r"stateTimer\+\+",                "⚠️ FRAME-BASED state machine! Dùng performance.now()/1000 (giây thật) thay vì frame count — FPS khác nhau timing khác nhau"),
    (r"SPACING\s*\*\s*\(\s*i\s*\+\s*1\s*\)", "⚠️ Lò xo KHÔNG canh giữa màn hình! Đúng: const totalW=spacing*(N-1); const startX=(W-totalW)/2; x=startX+i*spacing"),
    (r"\.y\s*=\s*canvas\.height\s*/\s*2(?=.*spring|.*Spring)", "⚠️ Khởi tạo spring.y=canvas.height/2 tại lúc tạo object (canvas chưa đúng kích thước) → tính trong animate loop"),
    (r"s\.phase\s*\+=\s*\([^)]*target[Pp]hase[^)]*\)\s*\*\s*0\.\d+\s*;(?!\s*\n.*wrap|\s*//.*PI)", "⚠️ Lerp phase THIẾU wrap [-π,+π]! Cần: while(diff>Math.PI)diff-=2*Math.PI; while(diff<-Math.PI)diff+=2*Math.PI"),
    (r"new THREE\.MeshBasicMaterial\(\{.*color.*\}\)(?=.*planet|.*Planet|.*hành tinh)", "⚠️ MeshBasicMaterial cho hành tinh trông flat plastic! Dùng MeshStandardMaterial+roughness:0.8+emissive"),
    (r"clearRect\(0,\s*0,\s*canvas\.width,\s*canvas\.height\)\s*;?\s*\n(?!.*fillStyle.*rgba)", "⚠️ clearRect trắng hoàn toàn mất motion trail — dùng ctx.fillStyle='rgba(0,0,0,0.82)'; ctx.fillRect(0,0,W,H) để tạo blur effect"),
    (r"new THREE\.RingGeometry[^;]+\)\s*;?\s*\n[^;]*orbit(?!.*Saturn|.*ring|.*saturn|.*Ring)", "⚠️ RingGeometry cho orbit path trông xấu — dùng LineLoop với Points array"),
    # ── BUG từ code__82_.html (lò xo) ──────────────────────────────
    (r"new Spring\([^)]*canvas\.height\s*\*\s*0\.", "⚠️ spring.y=canvas.height*0.5 trong constructor bị cố định khi resize! Tính botY từ canvas.height trực tiếp trong draw()"),
    (r"const w\s*=\s*12\s*\+\s*Math\.abs\(this\.amplitude\)\s*\*\s*5", "⚠️ Coil width=12+amplitude*5=262px quá rộng! Dùng stretch(-1→1): const w=12+stretch*6"),
    (r"resizeCanvas\(\)[^\n]*\n(?![^\n]*initSprings|[^\n]*springs)", "⚠️ Thiếu gọi reinitSprings() sau resizeCanvas() → springs.x bị lệch khi resize"),
        (r"\.then\(.*\)\.catch\(.*\)(?!.*async)", "Promise chain phức tạp — cân nhắc chuyển sang async/await"),
    (r"var\s+\w+\s*=",                 "var bị hoisting — dùng const/let"),
    (r"== null|== undefined",          "Dùng === null hoặc == null (chỉ trường hợp muốn check cả undefined)"),
    (r"catch\s*\(\s*\)\s*\{\s*\}",    "Empty catch block — ít nhất cần log error"),
    (r"SELECT \*",                     "Tránh SELECT * trong production — chỉ lấy columns cần"),
    (r"sha1|md5.*password",            "MD5/SHA1 không đủ mạnh cho password — dùng bcrypt/argon2"),
]

def check_hallucinations(code_response: str) -> list:
    return [msg for pat, msg in _HALLUCINATION_PATTERNS
            if re.search(pat, code_response, re.IGNORECASE)]


# ══════════════════════════════════════════════════════════════════
# BUILD SYSTEM PROMPT
# ══════════════════════════════════════════════════════════════════
def build_code_system_prompt(user_query: str, context: str = "") -> str:
    intent = decompose_intent(user_query)
    lang   = intent["lang"]
    task   = intent["task"]
    c_str  = "\n".join(f"  • {c}" for c in intent["constraints"]) or "  • (không có)"
    r_str  = "\n".join(f"  ⚠️ {r}" for r in intent["risks"])     or "  • (không có)"
    lang_r = _LANG_RULES.get(lang, f"• Best practices của {lang}\n• Xử lý lỗi đầy đủ")
    task_r = _TASK_RULES.get(task, "• Làm đúng và đầy đủ yêu cầu\n• Test edge cases")

    # Add UI/UX Design Sense for visual tasks
    uiux_section = ""
    if task in ("Frontend/UI", "Simulation/Visual") or any(
        k in user_query.lower() for k in ["giao diện", "ui", "ux", "css", "layout", "responsive", "mobile", "button", "màu sắc", "design", "card", "navbar"]
    ):
        uiux_section = f"\n{_UIUX_SENSE}\n"

    # Add simulation guide
    sim_section = ""
    if task == "Simulation/Visual" or any(
        k in user_query.lower() for k in [
            "mô phỏng", "simulation", "dao động", "lò xo", "canvas",
            "three.js", "hành tinh", "orbit", "solar", "particle", "sóng", "wave",
            "pendulum", "con lắc", "spring", "physics", "vật lý",
        ]
    ):
        sim_section = f"\n{_TASK_RULES.get('Simulation/Visual', '')}\n"

    # Add ML/Data Science guide
    ml_section = ""
    if task == "ML/Data Science":
        ml_section = f"\n{_TASK_RULES.get('ML/Data Science', '')}\n"

    # Add Game Dev guide
    game_section = ""
    if task == "Game Dev":
        game_section = f"\n{_TASK_RULES.get('Game Dev', '')}\n"

    # Add scraping/CLI/dataviz guide
    misc_section = ""
    if task in ("Web Scraping", "CLI/Script", "Data Visualization"):
        misc_section = f"\n{_TASK_RULES.get(task, '')}\n"

    # Add SOLID + Code Quality for complex tasks
    quality_section = ""
    if task in ("System Design", "Xây dựng API", "Refactor/Clean", "ML/Data Science",
                "Bot/Automation", "Game Dev") or len(user_query) > 200:
        quality_section = f"\n{_SOLID_PRINCIPLES}\n{_CODE_QUALITY}\n"

    # Add algorithm guide for algorithm tasks
    algo_section = ""
    if task in ("Thuật toán & DS", "Tối ưu hiệu năng") or any(
        k in user_query.lower() for k in ["sort", "search", "graph", "dp", "algorithm", "thuật toán"]
    ):
        algo_section = f"\n{_ALGORITHM_MASTER}\n{_COMPLEXITY_RULES}"

    # Add architecture guide for system design
    arch_section = ""
    if task in ("System Design", "Xây dựng API", "Bot/Automation"):
        arch_section = f"\n{_ARCHITECTURE_GUIDE}"

    # Add debug guide
    debug_section = ""
    if task == "Debug/Sửa lỗi":
        debug_section = f"\n{_DEBUG_PATTERNS}"

    # Detect nếu là code file dài (HTML/JS simulation, game, full app)
    _is_long_code = task in ("Simulation/Visual", "Game Dev", "Frontend/UI", "Xây dựng API") or any(
        k in user_query.lower() for k in [
            "three.js", "solar", "hệ mặt trời", "canvas", "mô phỏng", "simulation",
            "full", "hoàn chỉnh", "toàn bộ", "game", "phần mềm", "app", "website"
        ]
    )

    _multipart_rule = ""
    if _is_long_code:
        _multipart_rule = """
[MULTIPART OUTPUT — BẮT BUỘC KHI CODE > 200 DÒNG]
Nếu code cần > 200 dòng, BẮT BUỘC chia thành nhiều phần như sau:

Phần 1: Viết phần HTML structure + CSS + khai báo biến + data arrays
Kết thúc phần 1 bằng comment: // ===PART_END:1===

Phần 2: Viết phần khởi tạo scene/canvas/renderer + tạo objects + lighting
Kết thúc phần 2 bằng comment: // ===PART_END:2===

Phần 3: Viết phần animate loop + event handlers + controls + </script></body></html>
Kết thúc phần 3 bằng comment: // ===PART_END:3=== ===COMPLETE===

Mỗi phần phải là code liền mạch, có thể ghép trực tiếp.
KHÔNG viết giải thích giữa các phần. KHÔNG lặp lại code đã viết ở phần trước.
"""

    return f"""[CHẾ ĐỘ CHUYÊN GIA CODE v3.0 — ĐỘ CHÍNH XÁC CAO NHẤT]

PHÂN TÍCH: {lang} | {task}
Ràng buộc:    {c_str}
Rủi ro cần chú ý: {r_str}

QUY TẮC BẮT BUỘC:
[COMPLETENESS] KHÔNG: # TODO, # ..., pass rỗng, "tương tự như trên", placeholder
[COMPLETENESS] Sửa code cũ → IN TOÀN BỘ FILE, không dùng "# giữ nguyên phần trên"
[COMPLETENESS] Code dài → PAGINATION, không cắt bớt logic quan trọng
[ACCURACY] KHÔNG bịa tên thư viện, API, method không tồn tại
[ACCURACY] Không chắc syntax → nói thẳng "cần kiểm tra lại"
[ERROR] Mọi I/O → try/except | Mọi network → timeout, check status
[SECURITY] KHÔNG hardcode API key/password/secret → os.getenv()
[FORMAT] Bọc code: ```{lang.lower().split('/')[0]} ... ```
[TRANSPARENCY] 🆕 Nếu code tính ra 1 kết quả số học/tài chính/thống kê cụ thể
(VD lãi kép, mật độ, xác suất, trung bình...), BẮT BUỘC in kèm CÔNG THỨC và
CÁC SỐ LIỆU ĐẦU VÀO đã dùng trong CHÍNH output — không chỉ in mỗi con số kết
quả cuối cùng. Ví dụ SAI: `print(f"Kết quả: {{total}}")`. Ví dụ ĐÚNG:
`print(f"A = P×(1+r)^t = {{P}}×(1+{{r}})^{{t}} = {{total}}")`. Lý do: đây là
phần output DUY NHẤT được xác minh 100% qua sandbox thật — nếu công thức chỉ
nằm trong lời văn giải thích (không qua sandbox), không có cách nào kiểm
chứng công thức đó có đúng khớp với code thật hay không.
[FACTOR-BUG] 🆕 (2026-07-29, phát hiện qua bug thật) Khi viết vòng lặp tìm
ước số / phân tích thừa số (VD kiểm tra số nguyên tố, phân tích n = a×b),
BẮT BUỘC lưu ĐÚNG biến vòng lặp (`i`) và thương số (`num // i`) vào 2 biến
RIÊNG BIỆT ngay khi tìm thấy — ví dụ SAI (đã xảy ra thật, in ra
"1681 = 1681 × 1681" — SAI, đúng ra là 41×41): gán cả 2 biến factor bằng
chính `num` thay vì bằng `i` và `num // i`. Trước khi in bất kỳ dòng nào
dạng "X = a × b", TỰ KIỂM TRA lại bằng phép nhân a×b có thực sự bằng X hay
không — đây là loại lỗi logic sandbox KHÔNG THỂ phát hiện được (code chạy
không crash, con số vẫn "khớp" vì chính code tự in ra con số sai đó), nên
phải tự tránh ngay từ lúc viết, không thể trông chờ bước xác minh sau bắt
được.
[WEIGHTED-AVG] 🆕 (2026-07-31, phát hiện qua Gemini + bug thật) Khi tính
MẬT ĐỘ/TỈ LỆ/TỐC ĐỘ TRUNG BÌNH cho NHIỀU NHÓM CÓ TRỌNG SỐ KHÁC NHAU (VD mật
độ dân số trung bình của nhiều tỉnh có DIỆN TÍCH khác nhau, tốc độ trung
bình của nhiều đoạn đường có QUÃNG ĐƯỜNG khác nhau, lãi suất trung bình của
nhiều khoản vay có SỐ TIỀN khác nhau), TUYỆT ĐỐI KHÔNG lấy trung bình cộng
đơn thuần của các tỉ lệ thành phần — VD SAI: mật độ_TB =
(mật_độ_HCM + mật_độ_BD + mật_độ_HN) / 3. Đây là lỗi thống kê thật, sandbox
KHÔNG THỂ phát hiện được (phép chia (a+b+c)/3 tự nó không hề sai cú pháp
hay logic nội bộ) và MathVerifier cũng không bắt được (nó chỉ xác nhận
"code tính đúng theo chính công thức đã viết", không biết công thức đó có
đúng bài toán thống kê gốc hay không). BẮT BUỘC dùng công thức tổng tích
lũy (weighted average): mật_độ_TB = (Tổng dân số của MỌI nhóm) / (Tổng diện
tích của MỌI nhóm) — tức Σ(giá_trị_i × trọng_số_i) / Σ(trọng_số_i), KHÔNG
PHẢI Σ(tỉ_lệ_i) / n. Áp dụng tương tự cho mọi bài toán "trung bình của các
tỉ lệ" khi mẫu số (trọng số) của từng nhóm khác nhau.
[EQUATION-CHECK] 🆕 (2026-08-01, phát hiện qua bug thật) Khi được yêu cầu
SỬA BÀI/TÌM LỖI SAI/KIỂM TRA NGHIỆM của 1 phương trình cụ thể (VD "học sinh
giải sai ở đâu, nghiệm đúng là gì"), TUYỆT ĐỐI KHÔNG chỉ dựa vào suy luận
bằng lời — BẮT BUỘC viết kèm 1 đoạn code Python NGẮN để TỰ KIỂM CHỨNG từng
nghiệm ứng viên bằng cách THAY SỐ TRỰC TIẾP VÀO PHƯƠNG TRÌNH GỐC (không phải
phương trình đã biến đổi/bình phương — phải là phương trình BAN ĐẦU trước
khi biến đổi) và so sánh 2 vế bằng math.isclose(). Đây chính là bug thật đã
xảy ra: model kết luận "x=3 đúng, x=6 sai" — NGƯỢC HOÀN TOÀN với việc thay
số thật (x=6: √(6-2)=2 và 6-4=2, khớp; x=3: √(3-2)=1 và 3-4=-1, KHÔNG khớp)
— dù suy luận bằng lời (nói về điều kiện miền) nghe có vẻ hợp lý, kết luận
cuối lại sai. KHÔNG dùng sympy (KHÔNG có sẵn trong sandbox này) — chỉ cần
thay số trực tiếp bằng math thuần túy, ví dụ:
```python
import math
def check(x):
    lhs = math.sqrt(x - 2) if x - 2 >= 0 else None
    rhs = x - 4
    return lhs is not None and math.isclose(lhs, rhs, abs_tol=1e-9)
for x in [3, 6]:
    print(f"x={{x}}: thỏa mãn phương trình gốc = {{check(x)}}")
```
Chỉ kết luận nghiệm nào đúng SAU KHI đã in ra kết quả kiểm chứng bằng code
— không kết luận trước rồi mới viết code minh họa.
{_multipart_rule}

QUY TẮC — {lang.upper()}:
{lang_r}

QUY TẮC — {task.upper()}:
{task_r}
{uiux_section}{sim_section}{ml_section}{game_section}{misc_section}{quality_section}{algo_section}{arch_section}{debug_section}
FORMAT TRẢ LỜI:
1. Approach (2-3 câu): làm gì, tại sao chọn cách này, complexity là O(?)
2. Code đầy đủ (trong code block có tên file)
3. Giải thích điểm logic quan trọng
4. Cách test/chạy
5. Edge cases cần lưu ý

Xưng "mình", gọi người dùng là "Boss".
{f"CONTEXT:{chr(10)}{context[:500]}" if context else ""}"""


# ══════════════════════════════════════════════════════════════════
# [3] PRE-CODE REASONING
# ══════════════════════════════════════════════════════════════════
_PRE_CODE_REASONING = f"""
[INTERNAL REASONING — CHỈ DÙNG NỘI BỘ, KHÔNG OUTPUT 7 BƯỚC NÀY RA NGOÀI]
Trước khi viết code, suy nghĩ thầm qua các bước sau trong đầu:
{_PROBLEM_SOLVING_FRAMEWORK}
[KẾT THÚC INTERNAL REASONING]

⚡ OUTPUT RULE: Viết code NGAY lập tức sau khi suy nghĩ xong.
- KHÔNG output kế hoạch, KHÔNG liệt kê các bước phân tích ra ngoài
- Bắt đầu bằng code block (```lang ... ```) NGAY, giải thích ngắn SAU code (nếu cần)
- Nếu code dài → dùng MULTIPART (xem quy tắc bên dưới)
"""

# ══════════════════════════════════════════════════════════════════
# [6] SELF-VERIFICATION
# ══════════════════════════════════════════════════════════════════
_UIUX_SENSE = """
[UI/UX DESIGN SENSE — Áp dụng khi làm giao diện, web, app, HTML]
MÀU SẮC:
• Contrast ratio tối thiểu 4.5:1 (text trên nền) — không đặt chữ xanh lá trên nền đỏ
• Primary + Secondary + Neutral palette — tối đa 3-4 màu chính
• Dark mode: background #0f0f0f, surface #1a1a1a, text #e5e5e5 — không pure black/white
• Màu nền sáng + chữ tối, hoặc ngược lại — không bao giờ chữ cùng tone với nền

TYPOGRAPHY:
• Font size: body 14-16px, heading 20-32px, không dưới 12px
• Line height: 1.5-1.7 cho body text — không 1.0 (quá chật)
• Đọc được: Inter, Roboto, system-ui cho UI; JetBrains Mono cho code
• Hierarchy rõ: h1 > h2 > body > caption (không phẳng)

SPACING & LAYOUT:
• 8px grid system: padding/margin bội số của 4 hoặc 8
• Mobile first: touch targets tối thiểu 44x44px (ngón tay cái với tới)
• Breathing room: không nhồi nhét — whitespace = không gian thở
• Cards: border-radius 8-12px, shadow nhẹ (0 2px 8px rgba(0,0,0,0.1))

INTERACTIONS:
• Hover/active states cho mọi clickable element
• Loading states — không để UI freeze không feedback
• Error states rõ ràng — đỏ nhẹ, icon cảnh báo, message thân thiện
• Transitions: 150-300ms, ease-out (không quá nhanh, không quá chậm)

MOBILE UX:
• Nút quan trọng ở dưới (thumb zone) — không ở góc trên
• Bottom navigation cho app mobile
• Swipe gestures thay double-tap khi có thể
• Font tối thiểu 16px trên mobile (tránh zoom tự động iOS)

ACCESSIBILITY:
• alt text cho images
• aria-label cho icon buttons
• Focus visible (outline khi dùng keyboard)
• Không dùng màu duy nhất để convey thông tin (color blind)

CHECKLIST TRƯỚC KHI OUTPUT UI:
✦ Contrast đủ không?
✦ Mobile friendly không? (touch target đủ lớn?)
✦ Loading/error state có không?
✦ Màu sắc hài hòa, không chói mắt?
✦ Spacing đều, không nhồi nhét?
✦ Font đủ lớn đọc được?
"""



_SELF_VERIFY = """
[SELF-VERIFY CHECKLIST — BẮT BUỘC TRƯỚC KHI OUTPUT]
✦ CORRECTNESS: chạy thử trong đầu với ví dụ — đúng không?
✦ EDGE CASES: input rỗng/null/0/âm → crash không?
✦ IMPORTS: đủ và đúng? Thư viện tồn tại thật?
✦ COMPLETENESS: còn TODO/placeholder không? → XÓA HẾT
✦ SECURITY: hardcode secret không? → os.getenv()
✦ HTML: có type='module' không? → XÓA ĐI nếu local file
✦ COMPLEXITY: O(?) — có thể tối ưu hơn không?
✦ ERROR HANDLING: try/except cho I/O, network?

[SIMULATION/VISUAL — Nếu là mô phỏng hoặc HTML/Canvas/Three.js]
✦ PHYSICS: có phương trình vật lý thật không (F=ma, v=√(GM/r)...)? Nếu không → thêm vào
✦ SPRING/PENDULUM: vẽ cuộn lò xo/dây thật, không phải đường thẳng?
✦ THREE.JS CDN: dùng r128 (cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js)?
✦ ORBIT CONTROLS: KHÔNG dùng OrbitControls → implement thủ công?
✦ VISUAL QUALITY: có màu, glow (shadowBlur), labels, background không?
✦ ANIMATION CYCLE: nếu yêu cầu sync→desync→sync → có state machine không?
✦ CANVAS RESIZE: canvas.width = window.innerWidth khi resize?
✦ 60FPS: chỉ dùng requestAnimationFrame, không setInterval?
✦ ALL FEATURES: đọc lại yêu cầu — đã implement ĐẦY ĐỦ mọi tính năng được yêu cầu?

Nếu tất cả OK → kết thúc bằng: ✅ Code đã self-reviewed."""


def build_enhanced_query(user_query: str) -> str:
    intent = decompose_intent(user_query)
    risks  = intent["risks"]
    r_note = ""
    if risks:
        r_note = "\n\n⚠️ ĐẶC BIỆT CHÚ Ý:\n" + "\n".join(f"• {r}" for r in risks)
    return f"""{_PRE_CODE_REASONING}

YÊU CẦU: {user_query}{r_note}

⚡ BẮT BUỘC: Suy nghĩ qua 7 bước trong đầu (KHÔNG in ra) → viết code hoàn chỉnh NGAY → self-review sau code."""


# ══════════════════════════════════════════════════════════════════
# [7] COMPLETENESS ENFORCER
# ══════════════════════════════════════════════════════════════════
def enforce_completeness(response: str, original_query: str) -> str:
    _incomplete = [
        r"#\s*TODO", r"#\s*\.\.\.", r"#\s*(rest|phần còn lại|remaining)",
        r"#\s*(your code|code here|implement here|viết tiếp)",
        r"#\s*tương tự (như trên|bên trên)",
        r"raise NotImplementedError",
        r"pass\s*#\s*implement",
        r"// TODO", r"// \.\.\.", r"// implement",
    ]
    if any(re.search(p, response, re.IGNORECASE | re.MULTILINE) for p in _incomplete):
        response += "\n\n⚠️ **Cảnh báo:** Code có phần chưa hoàn thiện. Boss nhắn `viết đầy đủ phần [X]` để mình hoàn thiện nha!"
    return response


def build_code_context(history: list, brain_memory=None, user_query: str = "") -> str:
    parts = []
    if history:
        recent = []
        for turn in reversed(history[-6:]):
            if isinstance(turn, (list, tuple)) and len(turn) >= 2:
                blocks = re.findall(r'```(\w+)?\n(.*?)```', str(turn[1]), re.DOTALL)
                for lang, code in blocks:
                    if len(code.strip()) > 30:
                        recent.append(f"[Code đã viết - {lang or 'code'}]:\n{code[:800]}")
        if recent:
            parts.append("**Code trong hội thoại:**\n" + "\n\n".join(recent[-2:]))
    return "\n\n".join(parts) if parts else ""


def enhance_code_request(user_query, history=None, brain_memory=None, is_admin=True):
    if not is_code_request(user_query):
        return user_query, ""
    context  = build_code_context(history or [], brain_memory, user_query)

    # ── CODEGRAPH: Bổ sung context từ Knowledge Graph ─────────────
    graph_context = ""
    try:
        from yui_code_graph import query_graph
        graph_context = query_graph(user_query, max_tokens=1200)
        if graph_context:
            context = graph_context + "\n\n" + context
            print(f"[CODEGRAPH] ✅ Injected {len(graph_context)} chars context")
    except Exception as _cg_err:
        pass  # CodeGraph optional — không crash nếu thiếu
    # ──────────────────────────────────────────────────────────────

    system   = build_code_system_prompt(user_query, context)
    enhanced = build_enhanced_query(user_query) + _SELF_VERIFY
    return enhanced, system


# ══════════════════════════════════════════════════════════════════
# HOOK INTO APP.PY
# ══════════════════════════════════════════════════════════════════
_patched = False

def _patch_ask_logic_brain():
    global _patched
    if _patched: return True
    target = None
    for mod in sys.modules.values():
        if hasattr(mod, "ask_logic_brain") and hasattr(mod, "COHERE_KEYS"):
            target = mod; break
    if not target: return False

    _orig = target.ask_logic_brain

    def _enhanced(user_query, context_info, history, username, force_model=None, request=None):
        if not is_code_request(user_query):
            try: return _orig(user_query, context_info, history, username, force_model=force_model, request=request)
            except TypeError: return _orig(user_query, context_info, history, username, force_model)

        enhanced_query, code_system = enhance_code_request(
            user_query, history, getattr(target, "brain_memory", None))
        # 🐛 FIX (2026-07-29) BUG THẬT (xác nhận qua log thật): TRƯỚC ĐÂY gọi
        # _orig(enhanced_query, ...) — enhanced_query chứa TOÀN BỘ
        # _PRE_CODE_REASONING (khối "[INTERNAL REASONING — 7 BƯỚC]" dài hàng
        # nghìn ký tự) + _SELF_VERIFY, THAY THẾ hẳn user_query gốc. Nhưng
        # bên trong ask_logic_brain, tham số đầu tiên KHÔNG chỉ dùng để gửi
        # cho model sinh code — nó còn được dùng làm "câu hỏi gốc" cho
        # _ai_search_decision() (quyết định có cần tra web) và các bước
        # phân loại khác. Hậu quả xác nhận qua log thật:
        #   (1) _ai_search_decision nhúng NGUYÊN VĂN câu hỏi (không giới
        #       hạn độ dài) vào prompt quyết định — khi câu hỏi thực chất
        #       là cả khối "[INTERNAL REASONING...]" dài dằng dặc, model
        #       quyết định bị rối, TỰ TRẢ VỀ CODE PYTHON thay vì JSON
        #       ("JSON lỗi, không sửa được: '{}\\n    for city in
        #       cities:...'").
        #   (2) Ở lần khác, toàn bộ khối "[INTERNAL REASONING...]" còn bị
        #       dùng thẳng làm QUERY TÌM KIẾM THẬT gửi cho Tavily.
        #
        # Sửa: gọi _orig với user_query GỐC (để mọi logic phía dưới — search
        # decision, task detection — thấy đúng câu hỏi thật), và chuyển nội
        # dung hướng dẫn 7-bước + self-verify sang SYSTEM PROMPT thay vì
        # nhúng vào user_query — system prompt không bao giờ bị dùng làm
        # search query hay lộ vào bước quyết định nào khác.
        combined = (
            _PRE_CODE_REASONING + "\n\n" + code_system + _SELF_VERIFY
            + (f"\n\n[CONTEXT]:\n{context_info[:600]}" if context_info else "")
        )
        print(f"[CodeEngine v3.0] ✅ {detect_code_task(user_query)} | {detect_code_language(user_query)} | {user_query[:40]}...")
        try: result = _orig(user_query, combined, history, username, force_model=force_model, request=request)
        except TypeError: result = _orig(user_query, combined, history, username, force_model)

        if result:
            warns = check_hallucinations(result)
            if warns:
                result += "\n\n⚠️ **Phát hiện vấn đề trong code:**\n" + "\n".join(f"• {w}" for w in warns)
            result = enforce_completeness(result, user_query)
        return result

    target.ask_logic_brain = _enhanced
    _patched = True
    print("[Code Engine v3.0] ✅ Hook vào ask_logic_brain thành công!")
    return True


class _CodeHook:
    def __init__(self):
        self._done = False
    def install(self):
        if _patch_ask_logic_brain():
            self._done = True; return
        import builtins
        _orig = builtins.__import__
        outer = self
        def _hooked(name, *a, **kw):
            mod = _orig(name, *a, **kw)
            if not outer._done:
                try:
                    if hasattr(mod, "ask_logic_brain") and hasattr(mod, "COHERE_KEYS"):
                        if _patch_ask_logic_brain():
                            outer._done = True
                            builtins.__import__ = _orig
                except Exception: pass
            return mod
        builtins.__import__ = _hooked
        print("[Code Engine v3.0] Đang chờ app.py load...")


_hook = _CodeHook()
_hook.install()

print("""
╔══════════════════════════════════════════════════════════════╗
║   URAL CODE ENGINE v3.0 — CLAUDE-LEVEL PROGRAMMING         ║
║   [1]  Semantic Detector    [7]  Completeness Enforcer      ║
║   [2]  Intent Decomposer    [8]  Algorithm Master           ║
║   [3]  Pre-Code Reasoning   [9]  Complexity Analyzer        ║
║   [4]  Language Framework   [10] Architecture Advisor       ║
║   [5]  Anti-Hallucinate     [11] Debug Pattern Matcher      ║
║   [6]  Self-Verification    [12] Problem Solving Framework  ║
╚══════════════════════════════════════════════════════════════╝
""")

if __name__ == "__main__":
    tests = [
        ("viết hàm fibonacci python có cache", True),
        ("fix lỗi TypeError trong đoạn code này", True),
        ("build REST API với FastAPI và JWT", True),
        ("tối ưu SQL query đang chạy chậm", True),
        ("thuật toán dijkstra graph python", True),
        ("implement binary search tree", True),
        ("hôm nay thời tiết thế nào", False),
        ("bạn khỏe không", False),
        ("mình đang buồn quá", False),
    ]
    print("Testing semantic detector:")
    passed = 0
    for q, exp in tests:
        got = is_code_request(q)
        ok = got == exp
        passed += ok
        print(f"  {'✅' if ok else '❌'} [{got}] {q}")
    print(f"\n{passed}/{len(tests)} passed")

    print("\nTesting intent decomposer:")
    sample = "viết binary search tree python với insert, delete, search"
    intent = decompose_intent(sample)
    print(f"  Lang: {intent['lang']}, Task: {intent['task']}")
    print(f"  Risks: {intent['risks']}")