aegis_vm 0.2.51

Advanced Rust code virtualization and obfuscation framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
//! Build script for anticheat-vm
//!
//! Generates compile-time constants including:
//! - BUILD_SEED: Unique per-build encryption key seed
//! - BUILD_ID: Derived from BUILD_SEED for watermarking
//! - BUILD_TIMESTAMP: Unix timestamp of build
//! - CUSTOMER_ID: Customer identifier for build tracking
//! - WATERMARK: 128-bit steganographic watermark
//! - OPCODE_TABLE: Shuffled opcode mapping for polymorphic VM

use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    // Generate build configuration
    let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest_path = Path::new(&out_dir).join("build_config.rs");
    let mut f = File::create(&dest_path).expect("Could not create build_config.rs");

    // Get build timestamp
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards")
        .as_secs();

    // Generate BUILD_SEED
    // In production: Use ANTICHEAT_BUILD_KEY environment variable
    // In dev: Generate from timestamp + random data
    let build_seed = generate_build_seed();

    // Derive BUILD_ID from seed (simple FNV-1a for build script)
    let build_id = derive_build_id(&build_seed);

    // Get customer ID for watermarking (identifies the SDK licensee)
    let customer_id = env::var("ANTICHEAT_CUSTOMER_ID")
        .unwrap_or_else(|_| "dev-customer".to_string());

    // Generate watermark from customer + build info
    let watermark = generate_watermark(&customer_id, &build_seed, timestamp);

    // Write generated constants
    writeln!(f, "/// Build timestamp (Unix epoch seconds)").unwrap();
    writeln!(f, "pub const BUILD_TIMESTAMP: u64 = {};", timestamp).unwrap();
    writeln!(f).unwrap();

    // --- DYNAMIC SEED GENERATION START ---
    // Instead of writing the seed directly, we generate a function to reconstruct it.
    // This prevents the seed from appearing as a contiguous block in .rodata.
    // Combined with OLLVM, this logic becomes extremely hard to reverse.

    // 1. Generate Entropy Pool (1024 bytes of junk)
    let mut entropy_pool = [0u8; 1024];
    let pool_seed = generate_random_seed(); // Seed for the pool itself
    let mut rng_state = pool_seed;
    for (i, byte) in entropy_pool.iter_mut().enumerate() {
        // Simple LCG for pool generation
        let mac = hmac_sha256(&rng_state, &(i as u32).to_le_bytes());
        *byte = mac[0];
        // Update state occasionally
        if i % 32 == 0 {
            rng_state = mac;
        }
    }

    // 2. Calculate Delta values to reconstruct the real seed
    // Algorithm: seed[i] = pool[(start + i * step) % 1024] ^ delta[i]
    // So: delta[i] = seed[i] ^ pool[(start + i * step) % 1024]
    
    // Generate random parameters for the access pattern
    let rnd = generate_random_seed();
    let start_offset = (u64::from_le_bytes(rnd[0..8].try_into().unwrap()) % 800) as usize;
    let step = (u64::from_le_bytes(rnd[8..16].try_into().unwrap()) % 20 + 1) as usize; // 1..21

    let mut deltas = [0u8; 32];
    for i in 0..32 {
        let pool_idx = (start_offset + i * step) % 1024;
        deltas[i] = build_seed[i] ^ entropy_pool[pool_idx];
    }

    // 3. Write the Entropy Pool constant
    writeln!(f, "/// Entropy pool for seed reconstruction").unwrap();
    writeln!(f, "const ENTROPY_POOL: [u8; 1024] = [").unwrap();
    for (i, byte) in entropy_pool.iter().enumerate() {
        if i % 16 == 0 { write!(f, "\n    ").unwrap(); }
        write!(f, "0x{:02x}, ", byte).unwrap();
    }
    writeln!(f, "\n];").unwrap();
    writeln!(f).unwrap();

    // 4. Write the Delta Array
    writeln!(f, "/// Delta values for seed reconstruction").unwrap();
    writeln!(f, "const SEED_DELTAS: [u8; 32] = [").unwrap();
    for (i, byte) in deltas.iter().enumerate() {
        if i > 0 { write!(f, ", ").unwrap(); }
        write!(f, "0x{:02x}", byte).unwrap();
    }
    writeln!(f, "];").unwrap();
    writeln!(f).unwrap();

    // 5. Write the Reconstruction Function
    // We use std::hint::black_box to prevent constant folding.
    // We mark it #[inline(always)] so OLLVM obfuscates it at every call site.
    writeln!(f, "/// Reconstruct the build seed at runtime").unwrap();
    writeln!(f, "/// This prevents the seed from existing plainly in binary").unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn get_build_seed() -> [u8; 32] {{").unwrap();
    writeln!(f, "    let mut seed = [0u8; 32];").unwrap();
    // Use black_box on the parameters
    writeln!(f, "    let start = core::hint::black_box({});", start_offset).unwrap();
    writeln!(f, "    let step = core::hint::black_box({});", step).unwrap();
    writeln!(f, "    ").unwrap();
    writeln!(f, "    for i in 0..32 {{").unwrap();
    writeln!(f, "        let idx = (start + i * step) % 1024;").unwrap();
    writeln!(f, "        // The XOR operation combined with table lookups").unwrap();
    writeln!(f, "        seed[i] = ENTROPY_POOL[idx] ^ SEED_DELTAS[i];").unwrap();
    writeln!(f, "    }}").unwrap();
    writeln!(f, "    seed").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
    
    // Note: We REMOVED the 'pub const BUILD_SEED' definition.
    // --- DYNAMIC SEED GENERATION END ---

    writeln!(f, "/// Build ID derived from BUILD_SEED (for watermarking)").unwrap();
    writeln!(f, "pub const BUILD_ID: u64 = 0x{:016x};", build_id).unwrap();
    writeln!(f).unwrap();

    // Customer ID
    writeln!(f, "/// Customer ID for build tracking (from ANTICHEAT_CUSTOMER_ID env)").unwrap();
    writeln!(f, "pub const CUSTOMER_ID: &str = \"{}\";", customer_id).unwrap();
    writeln!(f).unwrap();

    // Watermark (128-bit)
    writeln!(f, "/// 128-bit steganographic watermark derived from customer + build").unwrap();
    writeln!(f, "/// Used for identifying leaked builds").unwrap();
    write!(f, "pub const WATERMARK: [u8; 16] = [").unwrap();
    for (i, byte) in watermark.iter().enumerate() {
        if i > 0 {
            write!(f, ", ").unwrap();
        }
        write!(f, "0x{:02x}", byte).unwrap();
    }
    writeln!(f, "];").unwrap();
    writeln!(f).unwrap();

    // Watermark as two u64 for easy embedding
    let watermark_hi = u64::from_le_bytes([
        watermark[0], watermark[1], watermark[2], watermark[3],
        watermark[4], watermark[5], watermark[6], watermark[7],
    ]);
    let watermark_lo = u64::from_le_bytes([
        watermark[8], watermark[9], watermark[10], watermark[11],
        watermark[12], watermark[13], watermark[14], watermark[15],
    ]);
    writeln!(f, "/// Watermark high 64 bits").unwrap();
    writeln!(f, "pub const WATERMARK_HI: u64 = 0x{:016x};", watermark_hi).unwrap();
    writeln!(f, "/// Watermark low 64 bits").unwrap();
    writeln!(f, "pub const WATERMARK_LO: u64 = 0x{:016x};", watermark_lo).unwrap();
    writeln!(f).unwrap();

    // Git commit hash if available
    if let Some(git_hash) = get_git_hash() {
        writeln!(f, "/// Git commit hash (first 16 hex chars)").unwrap();
        writeln!(f, "pub const GIT_COMMIT: &str = \"{}\";", git_hash).unwrap();
    } else {
        writeln!(f, "/// Git commit hash (not available)").unwrap();
        writeln!(f, "pub const GIT_COMMIT: &str = \"unknown\";").unwrap();
    }
    writeln!(f).unwrap();

    // Protection level from environment
    let protection_level = env::var("ANTICHEAT_PROTECTION_LEVEL")
        .unwrap_or_else(|_| "medium".to_string());
    writeln!(f, "/// Protection level (from ANTICHEAT_PROTECTION_LEVEL env)").unwrap();
    writeln!(f, "pub const PROTECTION_LEVEL: &str = \"{}\";", protection_level).unwrap();
    writeln!(f).unwrap();

    // Build sequence number (for tracking multiple builds in same session)
    let build_seq = env::var("ANTICHEAT_BUILD_SEQ")
        .unwrap_or_else(|_| "0".to_string())
        .parse::<u32>()
        .unwrap_or(0);
    writeln!(f, "/// Build sequence number (from ANTICHEAT_BUILD_SEQ env)").unwrap();
    writeln!(f, "pub const BUILD_SEQ: u32 = {};", build_seq).unwrap();
    writeln!(f).unwrap();

    // Async VM yield mask (polymorphic per-build)
    // Lower bits = more frequent yields = more state transitions
    // Derived from build seed for per-build uniqueness
    let yield_mask = generate_yield_mask(&build_seed);
    writeln!(f, "/// Async VM yield mask (controls yield frequency)").unwrap();
    writeln!(f, "/// Lower value = more frequent yields = more obfuscation").unwrap();
    writeln!(f, "pub const YIELD_MASK: u64 = 0x{:02x};", yield_mask).unwrap();
    writeln!(f).unwrap();

    // Generate shuffled opcode table
    let opcode_table = generate_opcode_table(&build_seed);
    write_opcode_table(&mut f, &opcode_table);

    // CRITICAL: Write opcode table to shared file for vm-macro to read
    // This ensures Single Source of Truth - macro reads the same table build.rs generated
    write_shared_opcode_table(&opcode_table);

    // Generate randomized MAGIC bytes for bytecode header
    let magic_bytes = generate_magic_bytes(&build_seed);
    write_magic_bytes(&mut f, &magic_bytes);

    // Generate shuffled native function IDs
    let native_ids = generate_native_ids(&build_seed);
    write_native_ids(&mut f, &native_ids);

    // Generate shuffled register mapping
    let register_map = generate_register_map(&build_seed);
    write_register_map(&mut f, &register_map);

    // Generate custom FNV hash constants
    let fnv_constants = generate_fnv_constants(&build_seed);
    write_fnv_constants(&mut f, &fnv_constants);

    // Generate randomized XOR key for domain string obfuscation
    let xor_key = generate_xor_key(&build_seed);
    write_xor_key(&mut f, xor_key);

    // Generate shuffled flag bit positions
    let flag_bits = generate_flag_bits(&build_seed);
    write_flag_bits(&mut f, &flag_bits);

    // Generate mutated handlers
    let mutated_handlers_path = Path::new(&out_dir).join("mutated_handlers.rs");
    generate_mutated_handlers(&build_seed, &mutated_handlers_path);

    // Generate whitebox crypto key (if feature enabled)
    generate_whitebox_config(&mut f, &build_seed);

    // Write build history for debugging
    write_build_history(
        &build_seed, build_id, timestamp, &customer_id, &opcode_table,
        &magic_bytes, &native_ids, &register_map, &fnv_constants, xor_key, &flag_bits
    );

    // Rerun conditions
    println!("cargo:rerun-if-env-changed=ANTICHEAT_BUILD_KEY");
    println!("cargo:rerun-if-env-changed=ANTICHEAT_PROTECTION_LEVEL");
    println!("cargo:rerun-if-env-changed=ANTICHEAT_CUSTOMER_ID");
    println!("cargo:rerun-if-env-changed=ANTICHEAT_BUILD_SEQ");
    println!("cargo:rerun-if-changed=build.rs");

    // CRITICAL: Force rebuild when seed file changes
    // This ensures proc-macro output stays in sync with runtime
    if let Ok(out_dir) = env::var("OUT_DIR") {
        if let Some(target_dir) = Path::new(&out_dir)
            .ancestors()
            .find(|p| p.file_name().is_some_and(|n| n == "target"))
        {
            let seed_file = target_dir.join(".anticheat_build_seed");
            println!("cargo:rerun-if-changed={}", seed_file.display());
        }
    }
}

/// Generate watermark from customer ID, build seed, and timestamp
/// The watermark is designed to be:
/// 1. Unique per customer+build combination
/// 2. Verifiable server-side to identify leaked builds
/// 3. Spread across the binary via steganographic embedding
fn generate_watermark(customer_id: &str, build_seed: &[u8; 32], timestamp: u64) -> [u8; 16] {
    // Create watermark input: customer_id || build_seed || timestamp
    let mut input = Vec::new();
    input.extend_from_slice(customer_id.as_bytes());
    input.extend_from_slice(build_seed);
    input.extend_from_slice(&timestamp.to_le_bytes());
    input.extend_from_slice(b"watermark-v1");

    // Hash to get watermark
    let hash = sha256(&input);

    // Take first 16 bytes as watermark
    let mut watermark = [0u8; 16];
    watermark.copy_from_slice(&hash[..16]);
    watermark
}

/// Generate yield mask for async VM (polymorphic per-build)
/// Uses build seed to derive a unique mask value
/// Returns a value between 0x3F and 0xFF (64-256 instruction intervals)
fn generate_yield_mask(build_seed: &[u8; 32]) -> u64 {
    // Derive mask from build seed using a specific byte
    // Use byte 16 (middle of seed) XOR byte 31 for more entropy
    let base = (build_seed[16] ^ build_seed[31]) as u64;

    // Ensure mask is in valid range: 0x3F to 0xFF
    // This gives yield intervals of 64 to 256 instructions
    // Lower = more frequent = more obfuscation but slower
    0x3F | (base & 0xC0)
}

/// Generate build seed from environment or random
/// The seed is also written to a shared file so vm-macro can read it
fn generate_build_seed() -> [u8; 32] {
    // Check for explicit build key (for reproducible builds)
    if let Ok(key) = env::var("ANTICHEAT_BUILD_KEY") {
        // Use HMAC(build_key, seed_domain)
        // This ensures reproducible but secure seeds
        let seed = hmac_sha256(key.as_bytes(), b"anticheat-vm-seed-v1");
        write_shared_seed(&seed);
        return seed;
    }

    // No explicit key - generate random seed for this build
    // Each build will have unique opcodes, encryption, etc.
    let seed = generate_random_seed();
    write_shared_seed(&seed);
    seed
}

/// Write seed to shared location for vm-macro to read
fn write_shared_seed(seed: &[u8; 32]) {
    // Write to target directory so vm-macro can find it
    if let Ok(out_dir) = env::var("OUT_DIR") {
        // OUT_DIR is like:
        //   target/debug/build/anticheat-vm-xxx/out (native)
        //   target/aarch64-linux-android/debug/build/xxx/out (cross-compile)
        // Find the actual "target" directory (not debug/release inside it)
        let target_dir = Path::new(&out_dir)
            .ancestors()
            .find(|p| p.file_name().is_some_and(|n| n == "target"));

        if let Some(target) = target_dir {
            let seed_file = target.join(".anticheat_build_seed");
            if let Ok(mut f) = File::create(&seed_file) {
                // Write as hex
                for byte in seed {
                    let _ = write!(f, "{:02x}", byte);
                }
            }
        }
    }
}

/// Write opcode encode table to shared location for vm-macro to read
/// This ensures macro and runtime use EXACTLY the same opcode mapping
fn write_shared_opcode_table(table: &OpcodeTable) {
    if let Ok(out_dir) = env::var("OUT_DIR") {
        let target_dir = Path::new(&out_dir)
            .ancestors()
            .find(|p| p.file_name().is_some_and(|n| n == "target"));

        if let Some(target) = target_dir {
            let table_file = target.join(".anticheat_opcode_table");
            if let Ok(mut f) = File::create(&table_file) {
                // Write encode table as hex (256 bytes)
                for byte in &table.encode {
                    let _ = write!(f, "{:02x}", byte);
                }
            }
        }
    }
}

/// Write build history to file for debugging/inspection
#[allow(clippy::too_many_arguments)]
fn write_build_history(
    seed: &[u8; 32],
    build_id: u64,
    timestamp: u64,
    customer_id: &str,
    opcode_table: &OpcodeTable,
    magic_bytes: &[u8; 4],
    native_ids: &NativeIdMap,
    register_map: &RegisterMap,
    fnv_constants: &FnvConstants,
    xor_key: u8,
    flag_bits: &FlagBits,
) {
    use std::fs::OpenOptions;

    // Find project root (where Cargo.toml is)
    let history_path = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        Some(Path::new(&manifest_dir).join("build_history.txt"))
    } else {
        Some(Path::new("build_history.txt").to_path_buf())
    };

    let Some(history_path) = history_path else { return };

    let Ok(mut file) = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&history_path) else { return };

    // Format timestamp as human readable
    let datetime = format_timestamp(timestamp);

    writeln!(file, "================================================================================").ok();
    writeln!(file, "BUILD: {}", datetime).ok();
    writeln!(file, "================================================================================").ok();
    writeln!(file, "Timestamp:   {} ({})", timestamp, datetime).ok();
    writeln!(file, "Customer ID: {}", customer_id).ok();
    writeln!(file, "Build ID:    0x{:016x}", build_id).ok();
    writeln!(file).ok();

    // Seed as hex
    write!(file, "Seed: ").ok();
    for byte in seed {
        write!(file, "{:02x}", byte).ok();
    }
    writeln!(file).ok();
    writeln!(file).ok();

    // MAGIC bytes
    writeln!(file, "MAGIC Bytes: 0x{:02x} 0x{:02x} 0x{:02x} 0x{:02x}",
             magic_bytes[0], magic_bytes[1], magic_bytes[2], magic_bytes[3]).ok();
    writeln!(file).ok();

    // Important opcodes (shuffled values)
    writeln!(file, "Shuffled Opcodes (base -> shuffled):").ok();
    writeln!(file, "  PUSH_IMM8:  0x02 -> 0x{:02x}", opcode_table.encode[0x02]).ok();
    writeln!(file, "  PUSH_IMM:   0x01 -> 0x{:02x}", opcode_table.encode[0x01]).ok();
    writeln!(file, "  DROP:       0x07 -> 0x{:02x}", opcode_table.encode[0x07]).ok();
    writeln!(file, "  ADD:        0x20 -> 0x{:02x}", opcode_table.encode[0x20]).ok();
    writeln!(file, "  SUB:        0x21 -> 0x{:02x}", opcode_table.encode[0x21]).ok();
    writeln!(file, "  MUL:        0x22 -> 0x{:02x}", opcode_table.encode[0x22]).ok();
    writeln!(file, "  XOR:        0x23 -> 0x{:02x}", opcode_table.encode[0x23]).ok();
    writeln!(file, "  CMP:        0x30 -> 0x{:02x}", opcode_table.encode[0x30]).ok();
    writeln!(file, "  JMP:        0x31 -> 0x{:02x}", opcode_table.encode[0x31]).ok();
    writeln!(file, "  JZ:         0x32 -> 0x{:02x}", opcode_table.encode[0x32]).ok();
    writeln!(file, "  JNZ:        0x33 -> 0x{:02x}", opcode_table.encode[0x33]).ok();
    writeln!(file, "  NOP:        0x40 -> 0x{:02x}", opcode_table.encode[0x40]).ok();
    writeln!(file, "  HALT:       0xFF -> 0xff (fixed)").ok();
    writeln!(file).ok();

    // Handler Duplication aliases
    writeln!(file, "Handler Duplication (aliases that decode to same base):").ok();
    for &base in DUPLICATED_OPCODES {
        let base_name = match base {
            0x20 => "ADD",
            0x21 => "SUB",
            0x23 => "XOR",
            0x24 => "AND",
            0x25 => "OR",
            0x30 => "CMP",
            _ => "???",
        };
        let primary = opcode_table.encode[base as usize];
        if let Some(aliases) = opcode_table.aliases.get(&base) {
            let alias_str: Vec<String> = aliases.iter().map(|a| format!("0x{:02x}", a)).collect();
            writeln!(file, "  {}: primary=0x{:02x}, aliases=[{}]",
                     base_name, primary, alias_str.join(", ")).ok();
        }
    }
    writeln!(file).ok();

    // Native function IDs
    writeln!(file, "Native Function IDs:").ok();
    writeln!(file, "  CHECK_ROOT:      {}", native_ids.check_root).ok();
    writeln!(file, "  CHECK_EMULATOR:  {}", native_ids.check_emulator).ok();
    writeln!(file, "  CHECK_HOOKS:     {}", native_ids.check_hooks).ok();
    writeln!(file, "  CHECK_DEBUGGER:  {}", native_ids.check_debugger).ok();
    writeln!(file, "  CHECK_TAMPER:    {}", native_ids.check_tamper).ok();
    writeln!(file, "  GET_TIMESTAMP:   {}", native_ids.get_timestamp).ok();
    writeln!(file, "  HASH_FNV1A:      {}", native_ids.hash_fnv1a).ok();
    writeln!(file, "  READ_MEMORY:     {}", native_ids.read_memory).ok();
    writeln!(file, "  GET_DEVICE_HASH: {}", native_ids.get_device_hash).ok();
    writeln!(file).ok();

    // Register mapping
    writeln!(file, "Register Mapping (logical -> physical):").ok();
    for i in 0..8 {
        writeln!(file, "  R{} -> physical {}", i, register_map.map[i]).ok();
    }
    writeln!(file).ok();

    // FNV constants
    writeln!(file, "FNV Hash Constants:").ok();
    writeln!(file, "  BASIS_64: 0x{:016x}", fnv_constants.basis_64).ok();
    writeln!(file, "  PRIME_64: 0x{:016x}", fnv_constants.prime_64).ok();
    writeln!(file, "  BASIS_32: 0x{:08x}", fnv_constants.basis_32).ok();
    writeln!(file, "  PRIME_32: 0x{:08x}", fnv_constants.prime_32).ok();
    writeln!(file).ok();

    // XOR key
    writeln!(file, "XOR Obfuscation Key: 0x{:02x}", xor_key).ok();
    writeln!(file).ok();

    // Flag bits
    writeln!(file, "Flag Bit Positions:").ok();
    writeln!(file, "  ZERO:     0b{:08b}", flag_bits.zero).ok();
    writeln!(file, "  CARRY:    0b{:08b}", flag_bits.carry).ok();
    writeln!(file, "  OVERFLOW: 0b{:08b}", flag_bits.overflow).ok();
    writeln!(file, "  SIGN:     0b{:08b}", flag_bits.sign).ok();
    writeln!(file).ok();
    writeln!(file).ok();
}

/// Format unix timestamp as human readable string
fn format_timestamp(timestamp: u64) -> String {
    let secs = timestamp;
    let days_since_epoch = secs / 86400;
    let time_of_day = secs % 86400;

    let hours = time_of_day / 3600;
    let minutes = (time_of_day % 3600) / 60;
    let seconds = time_of_day % 60;

    // Simple date calculation (not accounting for leap seconds)
    let mut year = 1970;
    let mut remaining_days = days_since_epoch;

    loop {
        let days_in_year = if is_leap_year(year) { 366 } else { 365 };
        if remaining_days < days_in_year {
            break;
        }
        remaining_days -= days_in_year;
        year += 1;
    }

    let days_in_months: [u64; 12] = if is_leap_year(year) {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };

    let mut month = 1;
    for days in days_in_months.iter() {
        if remaining_days < *days {
            break;
        }
        remaining_days -= days;
        month += 1;
    }

    let day = remaining_days + 1;

    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC",
            year, month, day, hours, minutes, seconds)
}

fn is_leap_year(year: u64) -> bool {
    (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
}

/// Generate cryptographically random seed
fn generate_random_seed() -> [u8; 32] {
    use std::io::Read;

    let mut seed = [0u8; 32];

    // Try /dev/urandom first (Unix)
    if let Ok(mut file) = File::open("/dev/urandom") {
        if file.read_exact(&mut seed).is_ok() {
            return seed;
        }
    }

    // Fallback: combine multiple entropy sources
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();

    let mut entropy = Vec::new();
    entropy.extend_from_slice(&timestamp.as_nanos().to_le_bytes());
    entropy.extend_from_slice(&std::process::id().to_le_bytes());

    // Add some environment entropy
    if let Ok(pwd) = env::var("PWD") {
        entropy.extend_from_slice(pwd.as_bytes());
    }
    if let Ok(user) = env::var("USER") {
        entropy.extend_from_slice(user.as_bytes());
    }

    // Hash for uniform distribution
    sha256(&entropy)
}

/// Derive build ID from seed using HMAC-SHA256
/// Must match derive_build_id in vm-macro/src/crypto.rs
fn derive_build_id(seed: &[u8; 32]) -> u64 {
    // Domain string for build ID derivation
    const BUILDID_DOMAIN: &[u8] = b"anticheat-vm-build-id-v1";
    let hmac_result = hmac_sha256(seed, BUILDID_DOMAIN);
    u64::from_le_bytes([
        hmac_result[0], hmac_result[1], hmac_result[2], hmac_result[3],
        hmac_result[4], hmac_result[5], hmac_result[6], hmac_result[7],
    ])
}

/// Get git commit hash (first 16 chars)
fn get_git_hash() -> Option<String> {
    use std::process::Command;

    let output = Command::new("git")
        .args(["rev-parse", "--short=16", "HEAD"])
        .output()
        .ok()?;

    if output.status.success() {
        let hash = String::from_utf8_lossy(&output.stdout);
        Some(hash.trim().to_string())
    } else {
        None
    }
}

/// Simple SHA-256 implementation for build script (no external deps)
fn sha256(data: &[u8]) -> [u8; 32] {
    // Initial hash values (first 32 bits of fractional parts of square roots of first 8 primes)
    let mut h: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
        0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
    ];

    // Round constants
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
        0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
        0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
        0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
        0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
        0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
        0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
    ];

    // Pre-processing: adding padding bits
    let ml = (data.len() as u64) * 8;
    let mut padded = data.to_vec();
    padded.push(0x80);

    while (padded.len() % 64) != 56 {
        padded.push(0x00);
    }

    // Append original length in bits as 64-bit big-endian
    padded.extend_from_slice(&ml.to_be_bytes());

    // Process each 512-bit (64-byte) chunk
    for chunk in padded.chunks(64) {
        let mut w = [0u32; 64];

        // Break chunk into 16 32-bit big-endian words
        for i in 0..16 {
            w[i] = u32::from_be_bytes([
                chunk[i * 4],
                chunk[i * 4 + 1],
                chunk[i * 4 + 2],
                chunk[i * 4 + 3],
            ]);
        }

        // Extend the first 16 words into the remaining 48 words
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
        }

        // Initialize working variables
        let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh) =
            (h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);

        // Compression function main loop
        for i in 0..64 {
            let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
            let ch = (e & f) ^ ((!e) & g);
            let temp1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]);
            let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
            let maj = (a & b) ^ (a & c) ^ (b & c);
            let temp2 = s0.wrapping_add(maj);

            hh = g;
            g = f;
            f = e;
            e = d.wrapping_add(temp1);
            d = c;
            c = b;
            b = a;
            a = temp1.wrapping_add(temp2);
        }

        // Add compressed chunk to current hash value
        h[0] = h[0].wrapping_add(a);
        h[1] = h[1].wrapping_add(b);
        h[2] = h[2].wrapping_add(c);
        h[3] = h[3].wrapping_add(d);
        h[4] = h[4].wrapping_add(e);
        h[5] = h[5].wrapping_add(f);
        h[6] = h[6].wrapping_add(g);
        h[7] = h[7].wrapping_add(hh);
    }

    // Produce final hash value (big-endian)
    let mut result = [0u8; 32];
    for (i, &word) in h.iter().enumerate() {
        result[i * 4..(i + 1) * 4].copy_from_slice(&word.to_be_bytes());
    }
    result
}

/// Base opcode definitions (canonical values)
/// These are the "logical" opcodes that the compiler uses
#[rustfmt::skip]
const BASE_OPCODES: &[(& str, &str, u8)] = &[
    // Stack operations
    ("stack", "PUSH_IMM", 0x01),
    ("stack", "PUSH_IMM8", 0x02),
    ("stack", "PUSH_REG", 0x03),
    ("stack", "POP_REG", 0x04),
    ("stack", "DUP", 0x05),
    ("stack", "SWAP", 0x06),
    ("stack", "DROP", 0x07),
    ("stack", "PUSH_IMM16", 0x08),
    ("stack", "PUSH_IMM32", 0x09),
    // Register operations
    ("register", "MOV_IMM", 0x10),
    ("register", "MOV_REG", 0x11),
    ("register", "LOAD_MEM", 0x12),
    ("register", "STORE_MEM", 0x13),
    // Arithmetic operations
    ("arithmetic", "ADD", 0x20),
    ("arithmetic", "SUB", 0x21),
    ("arithmetic", "MUL", 0x22),
    ("arithmetic", "XOR", 0x23),
    ("arithmetic", "AND", 0x24),
    ("arithmetic", "OR", 0x25),
    ("arithmetic", "SHL", 0x26),
    ("arithmetic", "SHR", 0x27),
    ("arithmetic", "NOT", 0x28),
    ("arithmetic", "ROL", 0x29),
    ("arithmetic", "ROR", 0x2A),
    ("arithmetic", "INC", 0x2B),
    ("arithmetic", "DEC", 0x2C),
    ("arithmetic", "DIV", 0x46),
    ("arithmetic", "MOD", 0x47),
    ("arithmetic", "IDIV", 0x48),
    ("arithmetic", "IMOD", 0x49),
    // Control flow
    ("control", "CMP", 0x30),
    ("control", "JMP", 0x31),
    ("control", "JZ", 0x32),
    ("control", "JNZ", 0x33),
    ("control", "JGT", 0x34),
    ("control", "JLT", 0x35),
    ("control", "JGE", 0x36),
    ("control", "JLE", 0x37),
    ("control", "CALL", 0x38),
    ("control", "RET", 0x39),
    // Special operations
    ("special", "NOP", 0x40),
    ("special", "NOP_N", 0x41),
    ("special", "OPAQUE_TRUE", 0x42),
    ("special", "OPAQUE_FALSE", 0x43),
    ("special", "HASH_CHECK", 0x44),
    ("special", "TIMING_CHECK", 0x45),
    // Type conversion
    ("convert", "SEXT8", 0x50),
    ("convert", "SEXT16", 0x51),
    ("convert", "SEXT32", 0x52),
    ("convert", "TRUNC8", 0x53),
    ("convert", "TRUNC16", 0x54),
    ("convert", "TRUNC32", 0x55),
    // Memory operations
    ("memory", "LOAD8", 0x60),
    ("memory", "LOAD16", 0x61),
    ("memory", "LOAD32", 0x62),
    ("memory", "LOAD64", 0x63),
    ("memory", "STORE8", 0x64),
    ("memory", "STORE16", 0x65),
    ("memory", "STORE32", 0x66),
    ("memory", "STORE64", 0x67),
    // Heap operations
    ("heap", "HEAP_ALLOC", 0x70),
    ("heap", "HEAP_FREE", 0x71),
    ("heap", "HEAP_LOAD8", 0x72),
    ("heap", "HEAP_LOAD16", 0x73),
    ("heap", "HEAP_LOAD32", 0x74),
    ("heap", "HEAP_LOAD64", 0x75),
    ("heap", "HEAP_STORE8", 0x76),
    ("heap", "HEAP_STORE16", 0x77),
    ("heap", "HEAP_STORE32", 0x78),
    ("heap", "HEAP_STORE64", 0x79),
    ("heap", "HEAP_SIZE", 0x7A),
    // Vector operations
    ("vector", "VEC_NEW", 0x80),
    ("vector", "VEC_LEN", 0x81),
    ("vector", "VEC_CAP", 0x82),
    ("vector", "VEC_PUSH", 0x83),
    ("vector", "VEC_POP", 0x84),
    ("vector", "VEC_GET", 0x85),
    ("vector", "VEC_SET", 0x86),
    ("vector", "VEC_REPEAT", 0x87),
    ("vector", "VEC_CLEAR", 0x88),
    ("vector", "VEC_RESERVE", 0x89),
    // String operations
    ("string", "STR_NEW", 0x90),
    ("string", "STR_LEN", 0x91),
    ("string", "STR_PUSH", 0x92),
    ("string", "STR_GET", 0x93),
    ("string", "STR_SET", 0x94),
    ("string", "STR_CMP", 0x95),
    ("string", "STR_EQ", 0x96),
    ("string", "STR_HASH", 0x97),
    ("string", "STR_CONCAT", 0x98),
    // Native calls
    ("native", "NATIVE_CALL", 0xF0),
    ("native", "NATIVE_READ", 0xF1),
    ("native", "NATIVE_WRITE", 0xF2),
    ("native", "INPUT_LEN", 0xF3),
    // Execution control
    ("exec", "HALT", 0xFF),
    ("exec", "HALT_ERR", 0xFE),
];

/// Critical opcodes that get handler duplication (alias opcodes)
/// Each critical opcode gets 2 additional aliases that decode to the same base value
const DUPLICATED_OPCODES: &[u8] = &[
    0x20, // ADD - most common arithmetic
    0x21, // SUB
    0x23, // XOR - used heavily in MBA
    0x24, // AND
    0x25, // OR
    0x30, // CMP - control flow critical
];

/// Generate shuffled opcode table from build seed
/// Returns a mapping: shuffled_value -> base_value (for runtime decode)
/// And we also need: base_value -> shuffled_value (for compile-time encode)
///
/// Handler Duplication: Critical opcodes (ADD, SUB, XOR, CMP) get multiple
/// shuffled values that all decode to the same base opcode. This confuses
/// reverse engineers who see different opcodes doing the same thing.
fn generate_opcode_table(seed: &[u8; 32]) -> OpcodeTable {
    // Derive shuffle key from seed
    let shuffle_key = hmac_sha256(seed, b"opcode-shuffle-v1");

    // Create list of available byte values (0x00-0xFD, excluding 0xFE and 0xFF for HALT)
    // We keep HALT and HALT_ERR fixed for simplicity in error handling
    let mut available: Vec<u8> = (0x00..0xFE).collect();

    // Fisher-Yates shuffle using HMAC-derived randomness
    let mut rng_state = shuffle_key;
    for i in (1..available.len()).rev() {
        // Get next random index
        let rand_bytes = hmac_sha256(&rng_state, &(i as u32).to_le_bytes());
        rng_state = rand_bytes;
        let j = (u64::from_le_bytes([
            rand_bytes[0], rand_bytes[1], rand_bytes[2], rand_bytes[3],
            rand_bytes[4], rand_bytes[5], rand_bytes[6], rand_bytes[7],
        ]) as usize) % (i + 1);
        available.swap(i, j);
    }

    // Build the mapping tables
    let mut encode = [0u8; 256]; // base -> shuffled (primary)
    let mut decode = [0u8; 256]; // shuffled -> base

    // Initialize as identity mapping
    for i in 0..256 {
        encode[i] = i as u8;
        decode[i] = i as u8;
    }

    // Track alias opcodes for each duplicated base opcode
    // aliases[base_opcode] = [alias1, alias2] (additional shuffled values)
    let mut aliases: std::collections::HashMap<u8, Vec<u8>> = std::collections::HashMap::new();

    // Assign shuffled values to each base opcode (except HALT/HALT_ERR)
    let mut available_idx = 0;
    for (_, _, base_val) in BASE_OPCODES.iter() {
        if *base_val == 0xFF || *base_val == 0xFE {
            // Keep HALT and HALT_ERR fixed
            continue;
        }
        let shuffled_val = available[available_idx];
        available_idx += 1;

        encode[*base_val as usize] = shuffled_val;
        decode[shuffled_val as usize] = *base_val;
    }

    // Handler Duplication: Assign additional aliases for critical opcodes
    // These aliases also decode to the same base opcode
    for &base_val in DUPLICATED_OPCODES {
        let mut op_aliases = Vec::new();

        // Assign 2 additional aliases per critical opcode
        for _ in 0..2 {
            if available_idx < available.len() {
                let alias_shuffled = available[available_idx];
                available_idx += 1;

                // This alias decodes to the same base opcode
                decode[alias_shuffled as usize] = base_val;
                op_aliases.push(alias_shuffled);
            }
        }

        if !op_aliases.is_empty() {
            aliases.insert(base_val, op_aliases);
        }
    }

    OpcodeTable { encode, decode, aliases }
}

/// Opcode table with handler duplication support
struct OpcodeTable {
    encode: [u8; 256], // base opcode -> shuffled opcode (for compiler)
    decode: [u8; 256], // shuffled opcode -> base opcode (for runtime)
    aliases: std::collections::HashMap<u8, Vec<u8>>, // base -> additional shuffled values
}

/// Write opcode table to generated file
fn write_opcode_table(f: &mut File, table: &OpcodeTable) {
    writeln!(f, "/// Opcode encoding table (base -> shuffled)").unwrap();
    writeln!(f, "/// Used by vm-macro at compile time").unwrap();
    write!(f, "pub const OPCODE_ENCODE: [u8; 256] = [").unwrap();
    for (i, &val) in table.encode.iter().enumerate() {
        if i % 16 == 0 {
            write!(f, "\n    ").unwrap();
        }
        write!(f, "0x{:02x}, ", val).unwrap();
    }
    writeln!(f, "\n];").unwrap();
    writeln!(f).unwrap();

    writeln!(f, "/// Opcode decoding table (shuffled -> base)").unwrap();
    writeln!(f, "/// Used by VM engine at runtime").unwrap();
    writeln!(f, "/// Note: Multiple shuffled values may decode to the same base (handler duplication)").unwrap();
    write!(f, "pub const OPCODE_DECODE: [u8; 256] = [").unwrap();
    for (i, &val) in table.decode.iter().enumerate() {
        if i % 16 == 0 {
            write!(f, "\n    ").unwrap();
        }
        write!(f, "0x{:02x}, ", val).unwrap();
    }
    writeln!(f, "\n];").unwrap();
    writeln!(f).unwrap();

    // Write alias information for vm-macro to use during polymorphic code generation
    writeln!(f, "/// Handler duplication aliases (base opcode -> additional shuffled values)").unwrap();
    writeln!(f, "/// These decode to the same base opcode, confusing reverse engineers").unwrap();
    writeln!(f, "pub mod opcode_aliases {{").unwrap();

    // Get opcode name from base value
    let get_name = |base: u8| -> &'static str {
        for (_, name, val) in BASE_OPCODES.iter() {
            if *val == base { return name; }
        }
        "UNKNOWN"
    };

    for &base in DUPLICATED_OPCODES {
        if let Some(aliases) = table.aliases.get(&base) {
            let name = get_name(base);
            write!(f, "    pub const {}_ALIASES: &[u8] = &[", name).unwrap();
            for (i, &alias) in aliases.iter().enumerate() {
                if i > 0 { write!(f, ", ").unwrap(); }
                write!(f, "0x{:02x}", alias).unwrap();
            }
            writeln!(f, "];").unwrap();
        }
    }
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();

    // Also write individual opcode constants for the runtime
    writeln!(f, "/// Shuffled opcode values for this build").unwrap();
    writeln!(f, "pub mod opcodes {{").unwrap();

    let mut current_mod = "";
    for (module, name, base_val) in BASE_OPCODES.iter() {
        if *module != current_mod {
            if !current_mod.is_empty() {
                writeln!(f, "    }}").unwrap();
            }
            writeln!(f, "    pub mod {} {{", module).unwrap();
            current_mod = module;
        }
        let shuffled = table.encode[*base_val as usize];
        writeln!(f, "        pub const {}: u8 = 0x{:02x};", name, shuffled).unwrap();
    }
    if !current_mod.is_empty() {
        writeln!(f, "    }}").unwrap();
    }
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

/// HMAC-SHA256 for production key derivation
fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    const BLOCK_SIZE: usize = 64;

    // Prepare key
    let mut k = [0u8; BLOCK_SIZE];
    if key.len() > BLOCK_SIZE {
        let hashed = sha256(key);
        k[..32].copy_from_slice(&hashed);
    } else {
        k[..key.len()].copy_from_slice(key);
    }

    // Inner and outer pads
    let mut ipad = [0x36u8; BLOCK_SIZE];
    let mut opad = [0x5cu8; BLOCK_SIZE];
    for i in 0..BLOCK_SIZE {
        ipad[i] ^= k[i];
        opad[i] ^= k[i];
    }

    // Inner hash: H(ipad || data)
    let mut inner_data = ipad.to_vec();
    inner_data.extend_from_slice(data);
    let inner_hash = sha256(&inner_data);

    // Outer hash: H(opad || inner_hash)
    let mut outer_data = opad.to_vec();
    outer_data.extend_from_slice(&inner_hash);
    sha256(&outer_data)
}

// ============================================================================
// MAGIC BYTES - Randomized bytecode header magic
// ============================================================================

/// Generate random MAGIC bytes for bytecode header identification
fn generate_magic_bytes(seed: &[u8; 32]) -> [u8; 4] {
    let hash = hmac_sha256(seed, b"magic-bytes-v1");
    [hash[0], hash[1], hash[2], hash[3]]
}

fn write_magic_bytes(f: &mut File, magic: &[u8; 4]) {
    writeln!(f, "/// Randomized MAGIC bytes for bytecode header").unwrap();
    writeln!(f, "pub const MAGIC: [u8; 4] = [0x{:02x}, 0x{:02x}, 0x{:02x}, 0x{:02x}];",
             magic[0], magic[1], magic[2], magic[3]).unwrap();
    writeln!(f).unwrap();
}

// ============================================================================
// NATIVE FUNCTION IDs - Shuffled native call identifiers
// ============================================================================

/// Native function ID mapping
struct NativeIdMap {
    check_root: u8,
    check_emulator: u8,
    check_hooks: u8,
    check_debugger: u8,
    check_tamper: u8,
    get_timestamp: u8,
    hash_fnv1a: u8,
    read_memory: u8,
    get_device_hash: u8,
    custom_start: u8,
}

fn generate_native_ids(seed: &[u8; 32]) -> NativeIdMap {
    let hash = hmac_sha256(seed, b"native-ids-v1");

    // Use first 9 bytes of hash as shuffled IDs (0-8 range shuffled)
    let mut ids: Vec<u8> = (0..9).collect();

    // Fisher-Yates shuffle using hash bytes
    for i in (1..9).rev() {
        let j = (hash[i] as usize) % (i + 1);
        ids.swap(i, j);
    }

    NativeIdMap {
        check_root: ids[0],
        check_emulator: ids[1],
        check_hooks: ids[2],
        check_debugger: ids[3],
        check_tamper: ids[4],
        get_timestamp: ids[5],
        hash_fnv1a: ids[6],
        read_memory: ids[7],
        get_device_hash: ids[8],
        custom_start: 128, // Keep custom start fixed at 128
    }
}

fn write_native_ids(f: &mut File, ids: &NativeIdMap) {
    writeln!(f, "/// Shuffled native function IDs").unwrap();
    writeln!(f, "pub mod native_ids {{").unwrap();
    writeln!(f, "    pub const CHECK_ROOT: u8 = {};", ids.check_root).unwrap();
    writeln!(f, "    pub const CHECK_EMULATOR: u8 = {};", ids.check_emulator).unwrap();
    writeln!(f, "    pub const CHECK_HOOKS: u8 = {};", ids.check_hooks).unwrap();
    writeln!(f, "    pub const CHECK_DEBUGGER: u8 = {};", ids.check_debugger).unwrap();
    writeln!(f, "    pub const CHECK_TAMPER: u8 = {};", ids.check_tamper).unwrap();
    writeln!(f, "    pub const GET_TIMESTAMP: u8 = {};", ids.get_timestamp).unwrap();
    writeln!(f, "    pub const HASH_FNV1A: u8 = {};", ids.hash_fnv1a).unwrap();
    writeln!(f, "    pub const READ_MEMORY: u8 = {};", ids.read_memory).unwrap();
    writeln!(f, "    pub const GET_DEVICE_HASH: u8 = {};", ids.get_device_hash).unwrap();
    writeln!(f, "    pub const CUSTOM_START: u8 = {};", ids.custom_start).unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

// ============================================================================
// REGISTER MAPPING - Shuffled register indices
// ============================================================================

/// Register mapping (logical R0-R7 to physical indices)
struct RegisterMap {
    map: [u8; 8],      // logical -> physical
    reverse: [u8; 8],  // physical -> logical
}

fn generate_register_map(seed: &[u8; 32]) -> RegisterMap {
    let hash = hmac_sha256(seed, b"register-map-v1");

    // Shuffle 0-7
    let mut map: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];

    for i in (1..8).rev() {
        let j = (hash[i] as usize) % (i + 1);
        map.swap(i, j);
    }

    // Build reverse mapping
    let mut reverse = [0u8; 8];
    for (logical, &physical) in map.iter().enumerate() {
        reverse[physical as usize] = logical as u8;
    }

    RegisterMap { map, reverse }
}

fn write_register_map(f: &mut File, reg_map: &RegisterMap) {
    writeln!(f, "/// Shuffled register mapping (logical -> physical)").unwrap();
    write!(f, "pub const REGISTER_MAP: [u8; 8] = [").unwrap();
    for (i, &val) in reg_map.map.iter().enumerate() {
        if i > 0 { write!(f, ", ").unwrap(); }
        write!(f, "{}", val).unwrap();
    }
    writeln!(f, "];").unwrap();

    writeln!(f, "/// Reverse register mapping (physical -> logical)").unwrap();
    write!(f, "pub const REGISTER_REVERSE: [u8; 8] = [").unwrap();
    for (i, &val) in reg_map.reverse.iter().enumerate() {
        if i > 0 { write!(f, ", ").unwrap(); }
        write!(f, "{}", val).unwrap();
    }
    writeln!(f, "];").unwrap();
    writeln!(f).unwrap();
}

// ============================================================================
// FNV HASH CONSTANTS - Custom hash function parameters
// ============================================================================

/// FNV hash constants
struct FnvConstants {
    basis_64: u64,
    prime_64: u64,
    basis_32: u32,
    prime_32: u32,
}

fn generate_fnv_constants(seed: &[u8; 32]) -> FnvConstants {
    let hash = hmac_sha256(seed, b"fnv-constants-v1");

    // Generate random basis values (must be non-zero, odd for better distribution)
    let basis_64 = u64::from_le_bytes([
        hash[0], hash[1], hash[2], hash[3],
        hash[4], hash[5], hash[6], hash[7],
    ]) | 1; // Ensure odd

    let basis_32 = u32::from_le_bytes([
        hash[8], hash[9], hash[10], hash[11],
    ]) | 1; // Ensure odd

    // Generate primes - use well-known FNV-like primes with slight modification
    // Original FNV-1a prime for 64-bit: 0x100000001b3
    // Original FNV-1a prime for 32-bit: 0x01000193
    // We'll XOR with some seed bytes to vary them slightly while keeping good properties
    let prime_modifier = u64::from_le_bytes([
        hash[16], hash[17], hash[18], hash[19],
        hash[20], hash[21], hash[22], hash[23],
    ]);

    // Keep lower bits of original prime, modify upper bits
    let prime_64 = 0x100000001b3 ^ ((prime_modifier & 0xFFFF_0000_0000_0000) >> 8);
    let prime_32 = 0x01000193 ^ ((hash[24] as u32) << 24);

    FnvConstants {
        basis_64,
        prime_64,
        basis_32,
        prime_32,
    }
}

fn write_fnv_constants(f: &mut File, fnv: &FnvConstants) {
    writeln!(f, "/// Randomized FNV-1a hash constants").unwrap();
    writeln!(f, "pub const FNV_BASIS_64: u64 = 0x{:016x};", fnv.basis_64).unwrap();
    writeln!(f, "pub const FNV_PRIME_64: u64 = 0x{:016x};", fnv.prime_64).unwrap();
    writeln!(f, "pub const FNV_BASIS_32: u32 = 0x{:08x};", fnv.basis_32).unwrap();
    writeln!(f, "pub const FNV_PRIME_32: u32 = 0x{:08x};", fnv.prime_32).unwrap();
    writeln!(f).unwrap();
}

// ============================================================================
// XOR KEY - Randomized obfuscation key
// ============================================================================

fn generate_xor_key(seed: &[u8; 32]) -> u8 {
    let hash = hmac_sha256(seed, b"xor-key-v1");
    // Ensure non-zero XOR key
    if hash[0] == 0 { hash[1] | 1 } else { hash[0] }
}

fn write_xor_key(f: &mut File, key: u8) {
    writeln!(f, "/// Randomized XOR key for string obfuscation").unwrap();
    writeln!(f, "pub const XOR_KEY: u8 = 0x{:02x};", key).unwrap();
    writeln!(f).unwrap();
}

// ============================================================================
// FLAG BITS - Shuffled CPU flag bit positions
// ============================================================================

/// Flag bit positions
struct FlagBits {
    zero: u8,
    carry: u8,
    overflow: u8,
    sign: u8,
}

fn generate_flag_bits(seed: &[u8; 32]) -> FlagBits {
    let hash = hmac_sha256(seed, b"flag-bits-v1");

    // Shuffle bit positions 0-3
    let mut positions: [u8; 4] = [0, 1, 2, 3];
    for i in (1..4).rev() {
        let j = (hash[i] as usize) % (i + 1);
        positions.swap(i, j);
    }

    FlagBits {
        zero: 1 << positions[0],
        carry: 1 << positions[1],
        overflow: 1 << positions[2],
        sign: 1 << positions[3],
    }
}

fn write_flag_bits(f: &mut File, flags: &FlagBits) {
    writeln!(f, "/// Shuffled flag bit positions").unwrap();
    writeln!(f, "pub mod flags {{").unwrap();
    writeln!(f, "    pub const ZERO: u8 = 0b{:08b};", flags.zero).unwrap();
    writeln!(f, "    pub const CARRY: u8 = 0b{:08b};", flags.carry).unwrap();
    writeln!(f, "    pub const OVERFLOW: u8 = 0b{:08b};", flags.overflow).unwrap();
    writeln!(f, "    pub const SIGN: u8 = 0b{:08b};", flags.sign).unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

// ============================================================================
// HANDLER MUTATION - Generate polymorphic handler implementations
// ============================================================================

/// Generate mutated arithmetic handlers
/// Each build gets different implementations of the same operations
fn generate_mutated_handlers(seed: &[u8; 32], path: &Path) {
    let mut f = File::create(path).expect("Could not create mutated_handlers.rs");

    // Derive mutation selection key
    let mutation_key = hmac_sha256(seed, b"handler-mutation-v1");

    writeln!(f, "// Build-time generated mutated handlers").unwrap();
    writeln!(f, "// DO NOT EDIT - Generated by build.rs").unwrap();
    writeln!(f, "//").unwrap();
    writeln!(f, "// Each build produces different handler implementations").unwrap();
    writeln!(f, "// to confuse static analysis and pattern matching.").unwrap();
    writeln!(f).unwrap();
    writeln!(f, "use crate::error::VmResult;").unwrap();
    writeln!(f, "use crate::state::VmState;").unwrap();
    writeln!(f).unwrap();

    // Generate junk constants (will be used in junk code)
    let junk_consts = generate_junk_constants(&mutation_key);
    write_junk_constants(&mut f, &junk_consts);

    // Select and generate each mutated handler
    let mut rng_state = mutation_key;

    // ADD handler
    let add_variant = next_rand(&mut rng_state) % 3;
    generate_add_handler(&mut f, add_variant, &mut rng_state);

    // SUB handler
    let sub_variant = next_rand(&mut rng_state) % 3;
    generate_sub_handler(&mut f, sub_variant, &mut rng_state);

    // MUL handler (fewer variants, harder to transform)
    let mul_variant = next_rand(&mut rng_state) % 2;
    generate_mul_handler(&mut f, mul_variant, &mut rng_state);

    // XOR handler
    let xor_variant = next_rand(&mut rng_state) % 3;
    generate_xor_handler(&mut f, xor_variant, &mut rng_state);

    // AND handler
    let and_variant = next_rand(&mut rng_state) % 2;
    generate_and_handler(&mut f, and_variant, &mut rng_state);

    // OR handler
    let or_variant = next_rand(&mut rng_state) % 2;
    generate_or_handler(&mut f, or_variant, &mut rng_state);

    // NOT handler
    let not_variant = next_rand(&mut rng_state) % 3;
    generate_not_handler(&mut f, not_variant, &mut rng_state);

    // INC handler
    let inc_variant = next_rand(&mut rng_state) % 2;
    generate_inc_handler(&mut f, inc_variant, &mut rng_state);

    // DEC handler
    let dec_variant = next_rand(&mut rng_state) % 2;
    generate_dec_handler(&mut f, dec_variant, &mut rng_state);
}

/// Simple deterministic RNG for build-time mutation selection
fn next_rand(state: &mut [u8; 32]) -> u64 {
    *state = hmac_sha256(state, b"next");
    u64::from_le_bytes([
        state[0], state[1], state[2], state[3],
        state[4], state[5], state[6], state[7],
    ])
}

/// Generate random junk constants
fn generate_junk_constants(key: &[u8; 32]) -> [u64; 8] {
    let hash = hmac_sha256(key, b"junk-constants");
    [
        u64::from_le_bytes(hash[0..8].try_into().unwrap()),
        u64::from_le_bytes(hash[8..16].try_into().unwrap()),
        u64::from_le_bytes(hash[16..24].try_into().unwrap()),
        u64::from_le_bytes(hash[24..32].try_into().unwrap()),
        // Generate more from another round
        {
            let h2 = hmac_sha256(key, b"junk-constants-2");
            u64::from_le_bytes(h2[0..8].try_into().unwrap())
        },
        {
            let h2 = hmac_sha256(key, b"junk-constants-2");
            u64::from_le_bytes(h2[8..16].try_into().unwrap())
        },
        {
            let h2 = hmac_sha256(key, b"junk-constants-2");
            u64::from_le_bytes(h2[16..24].try_into().unwrap())
        },
        {
            let h2 = hmac_sha256(key, b"junk-constants-2");
            u64::from_le_bytes(h2[24..32].try_into().unwrap())
        },
    ]
}

fn write_junk_constants(f: &mut File, consts: &[u64; 8]) {
    writeln!(f, "// Junk constants for dead code insertion").unwrap();
    writeln!(f, "#[allow(dead_code)]").unwrap();
    writeln!(f, "const JUNK: [u64; 8] = [").unwrap();
    for c in consts {
        writeln!(f, "    0x{:016x},", c).unwrap();
    }
    writeln!(f, "];").unwrap();
    writeln!(f).unwrap();
}

/// Generate junk code line
fn generate_junk_line(rng: &mut [u8; 32], var_idx: usize) -> String {
    let op = next_rand(rng) % 4;
    let const_idx = (next_rand(rng) % 8) as usize;
    let const_idx2 = (next_rand(rng) % 8) as usize;

    match op {
        0 => format!("    let _j{} = JUNK[{}] ^ JUNK[{}];", var_idx, const_idx, const_idx2),
        1 => format!("    let _j{} = JUNK[{}].wrapping_add(JUNK[{}]);", var_idx, const_idx, const_idx2),
        2 => format!("    let _j{} = JUNK[{}].rotate_left({});", var_idx, const_idx, (next_rand(rng) % 64) as u32),
        _ => format!("    let _j{} = JUNK[{}].wrapping_mul(0x{:x});", var_idx, const_idx, next_rand(rng)),
    }
}

/// Insert junk code before/after main logic
fn insert_junk(f: &mut File, rng: &mut [u8; 32], count: usize, start_idx: usize) {
    for i in 0..count {
        writeln!(f, "{}", generate_junk_line(rng, start_idx + i)).unwrap();
    }
}

// ============================================================================
// Individual Handler Generators
// ============================================================================

fn generate_add_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// ADD: Pop 2, push sum (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_add(state: &mut VmState) -> VmResult<()> {{").unwrap();

    // Pre-junk
    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let b = state.pop()?;").unwrap();
    writeln!(f, "    let a = state.pop()?;").unwrap();

    // Mid-junk
    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct implementation
            writeln!(f, "    let result = a.wrapping_add(b);").unwrap();
        }
        1 => {
            // XOR + AND trick: a + b = (a ^ b) + 2*(a & b)
            writeln!(f, "    let xor_part = a ^ b;").unwrap();
            writeln!(f, "    let and_part = a & b;").unwrap();
            writeln!(f, "    let result = xor_part.wrapping_add(and_part << 1);").unwrap();
        }
        _ => {
            // SUB(-b): a + b = a - (-b) = a - (!b + 1)
            writeln!(f, "    let neg_b = (!b).wrapping_add(1);").unwrap();
            writeln!(f, "    let result = a.wrapping_sub(neg_b);").unwrap();
        }
    }

    // Post-junk
    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

fn generate_sub_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// SUB: Pop 2, push difference (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_sub(state: &mut VmState) -> VmResult<()> {{").unwrap();

    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let b = state.pop()?;").unwrap();
    writeln!(f, "    let a = state.pop()?;").unwrap();

    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct implementation
            writeln!(f, "    let result = a.wrapping_sub(b);").unwrap();
        }
        1 => {
            // ADD(-b): a - b = a + (-b) = a + (!b + 1)
            writeln!(f, "    let neg_b = (!b).wrapping_add(1);").unwrap();
            writeln!(f, "    let result = a.wrapping_add(neg_b);").unwrap();
        }
        _ => {
            // NOT+ADD+NOT: a - b = ~(~a + b)
            writeln!(f, "    let not_a = !a;").unwrap();
            writeln!(f, "    let sum = not_a.wrapping_add(b);").unwrap();
            writeln!(f, "    let result = !sum;").unwrap();
        }
    }

    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

fn generate_mul_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// MUL: Pop 2, push product (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_mul(state: &mut VmState) -> VmResult<()> {{").unwrap();

    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let b = state.pop()?;").unwrap();
    writeln!(f, "    let a = state.pop()?;").unwrap();

    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct
            writeln!(f, "    let result = a.wrapping_mul(b);").unwrap();
        }
        _ => {
            // Obfuscated with identity: a * b = (a * b) ^ 0 ^ 0
            writeln!(f, "    let product = a.wrapping_mul(b);").unwrap();
            writeln!(f, "    let result = product ^ (JUNK[0] ^ JUNK[0]);").unwrap();
        }
    }

    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

fn generate_xor_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// XOR: Pop 2, push XOR (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_xor(state: &mut VmState) -> VmResult<()> {{").unwrap();

    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let b = state.pop()?;").unwrap();
    writeln!(f, "    let a = state.pop()?;").unwrap();

    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct
            writeln!(f, "    let result = a ^ b;").unwrap();
        }
        1 => {
            // (a | b) & !(a & b) - but simpler: (a | b) ^ (a & b)
            // Actually a^b = (a|b) & !(a&b) = (a|b) ^ (a&b) is wrong
            // Correct: a^b = (a & !b) | (!a & b)
            writeln!(f, "    let part1 = a & !b;").unwrap();
            writeln!(f, "    let part2 = !a & b;").unwrap();
            writeln!(f, "    let result = part1 | part2;").unwrap();
        }
        _ => {
            // Double NOT cancellation: a ^ b = !!a ^ !!b = !(!a) ^ !(!b) ... doesn't help
            // Use: a ^ b = (a | b) & (!a | !b)
            writeln!(f, "    let or_part = a | b;").unwrap();
            writeln!(f, "    let nand_part = !a | !b;").unwrap();
            writeln!(f, "    let result = or_part & nand_part;").unwrap();
        }
    }

    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

fn generate_and_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// AND: Pop 2, push AND (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_and(state: &mut VmState) -> VmResult<()> {{").unwrap();

    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let b = state.pop()?;").unwrap();
    writeln!(f, "    let a = state.pop()?;").unwrap();

    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct
            writeln!(f, "    let result = a & b;").unwrap();
        }
        _ => {
            // De Morgan: a & b = !(!a | !b)
            writeln!(f, "    let not_a = !a;").unwrap();
            writeln!(f, "    let not_b = !b;").unwrap();
            writeln!(f, "    let result = !(not_a | not_b);").unwrap();
        }
    }

    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

fn generate_or_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// OR: Pop 2, push OR (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_or(state: &mut VmState) -> VmResult<()> {{").unwrap();

    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let b = state.pop()?;").unwrap();
    writeln!(f, "    let a = state.pop()?;").unwrap();

    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct
            writeln!(f, "    let result = a | b;").unwrap();
        }
        _ => {
            // De Morgan: a | b = !(!a & !b)
            writeln!(f, "    let not_a = !a;").unwrap();
            writeln!(f, "    let not_b = !b;").unwrap();
            writeln!(f, "    let result = !(not_a & not_b);").unwrap();
        }
    }

    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

fn generate_not_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// NOT: Pop 1, push NOT (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_not(state: &mut VmState) -> VmResult<()> {{").unwrap();

    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let a = state.pop()?;").unwrap();

    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct
            writeln!(f, "    let result = !a;").unwrap();
        }
        1 => {
            // XOR with MAX: !a = a ^ 0xFFFF...
            writeln!(f, "    let result = a ^ u64::MAX;").unwrap();
        }
        _ => {
            // SUB from MAX: !a = MAX - a (only works because !a = -a-1 = MAX-a in unsigned)
            // Actually: !a for unsigned is bitwise complement
            // !0 = MAX, MAX - 0 = MAX ✓
            // !1 = MAX-1, MAX - 1 = MAX-1 ✓
            // !MAX = 0, MAX - MAX = 0 ✓
            // So !a = MAX - a when wrapping_sub
            writeln!(f, "    let result = u64::MAX.wrapping_sub(a);").unwrap();
        }
    }

    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

fn generate_inc_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// INC: Increment top of stack (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_inc(state: &mut VmState) -> VmResult<()> {{").unwrap();

    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let a = state.pop()?;").unwrap();

    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct
            writeln!(f, "    let result = a.wrapping_add(1);").unwrap();
        }
        _ => {
            // SUB(-1): a + 1 = a - (-1) = a - MAX
            writeln!(f, "    let result = a.wrapping_sub(u64::MAX);").unwrap();
        }
    }

    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

fn generate_dec_handler(f: &mut File, variant: u64, rng: &mut [u8; 32]) {
    writeln!(f, "/// DEC: Decrement top of stack (Variant {})", variant).unwrap();
    writeln!(f, "#[inline(always)]").unwrap();
    writeln!(f, "pub fn mutated_dec(state: &mut VmState) -> VmResult<()> {{").unwrap();

    let pre_junk = (next_rand(rng) % 3) as usize;
    insert_junk(f, rng, pre_junk, 0);

    writeln!(f, "    let a = state.pop()?;").unwrap();

    let mid_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, mid_junk, 10);

    match variant {
        0 => {
            // Direct
            writeln!(f, "    let result = a.wrapping_sub(1);").unwrap();
        }
        _ => {
            // ADD(-1): a - 1 = a + (-1) = a + MAX
            writeln!(f, "    let result = a.wrapping_add(u64::MAX);").unwrap();
        }
    }

    let post_junk = (next_rand(rng) % 2) as usize;
    insert_junk(f, rng, post_junk, 20);

    writeln!(f, "    state.set_zero_flag(result);").unwrap();
    writeln!(f, "    state.push(result)").unwrap();
    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}

// ============================================================================
// WHITE-BOX CRYPTO - BUILD-TIME TABLE GENERATION
// ============================================================================
//
// WBC tables are generated at build-time and embedded with entropy pool protection.
// The AES key NEVER exists at runtime - it's only used during compilation.
// This provides true white-box security: key extraction is mathematically impossible.

// AES Constants for build-time table generation
const AES_SBOX: [u8; 256] = [
    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
];

const AES_RCON: [u8; 10] = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
const AES_MIX_COLS: [[u8; 4]; 4] = [[2, 3, 1, 1], [1, 2, 3, 1], [1, 1, 2, 3], [3, 1, 1, 2]];
const AES_SHIFT_ROWS: [usize; 16] = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11];

const AES_ROUNDS: usize = 10;
const AES_BLOCK_SIZE: usize = 16;

// Table sizes
const TBOX_SIZE: usize = AES_ROUNDS * AES_BLOCK_SIZE * 256; // 40,960 bytes
const TYBOX_SIZE: usize = 9 * AES_BLOCK_SIZE * 256 * 4;     // 147,456 bytes
const XOR_TABLE_SIZE: usize = 9 * 96 * 16 * 16;             // 221,184 bytes
const MBL_SIZE: usize = 9 * AES_BLOCK_SIZE * 256 * 4;       // 147,456 bytes
const TBOX_LAST_SIZE: usize = AES_BLOCK_SIZE * 256;         // 4,096 bytes

/// GF(2^8) multiplication
fn gf_mul(a: u8, b: u8) -> u8 {
    let mut result = 0u8;
    let mut aa = a;
    let mut bb = b;
    for _ in 0..8 {
        if bb & 1 != 0 { result ^= aa; }
        let hi_bit = aa & 0x80;
        aa <<= 1;
        if hi_bit != 0 { aa ^= 0x1b; }
        bb >>= 1;
    }
    result
}

/// AES key expansion
fn aes_key_expansion(key: &[u8; 16]) -> [[u8; 16]; 11] {
    let mut round_keys = [[0u8; 16]; 11];
    round_keys[0].copy_from_slice(key);

    for i in 1..11 {
        let prev = &round_keys[i - 1];
        let mut next = [0u8; 16];
        let rot = [prev[13], prev[14], prev[15], prev[12]];
        next[0] = prev[0] ^ AES_SBOX[rot[0] as usize] ^ AES_RCON[i - 1];
        next[1] = prev[1] ^ AES_SBOX[rot[1] as usize];
        next[2] = prev[2] ^ AES_SBOX[rot[2] as usize];
        next[3] = prev[3] ^ AES_SBOX[rot[3] as usize];
        for j in 4..16 {
            next[j] = prev[j] ^ next[j - 4];
        }
        round_keys[i] = next;
    }
    round_keys
}

/// Seeded RNG for deterministic table generation
struct BuildRng { state: u64 }

impl BuildRng {
    fn new(seed: &[u8]) -> Self {
        let mut state = 0x853c49e6748fea9bu64;
        for (i, &byte) in seed.iter().enumerate() {
            state ^= (byte as u64) << ((i % 8) * 8);
            state = state.wrapping_mul(0x5851f42d4c957f2d);
            state ^= state >> 33;
        }
        Self { state }
    }

    fn next_u64(&mut self) -> u64 {
        self.state ^= self.state >> 12;
        self.state ^= self.state << 25;
        self.state ^= self.state >> 27;
        self.state.wrapping_mul(0x2545f4914f6cdd1d)
    }

    fn random_permutation(&mut self, n: usize) -> Vec<u8> {
        // Build permutation manually to avoid u8 overflow for n=256
        let mut perm: Vec<u8> = Vec::with_capacity(n);
        for i in 0..n {
            perm.push(i as u8);
        }
        for i in (1..n).rev() {
            let j = (self.next_u64() as usize) % (i + 1);
            perm.swap(i, j);
        }
        perm
    }
}

/// 8-bit bijection
#[derive(Clone, Copy)]
struct Bijection8 { forward: [u8; 256], inverse: [u8; 256] }

impl Bijection8 {
    fn identity() -> Self {
        let mut forward = [0u8; 256];
        let mut inverse = [0u8; 256];
        for i in 0..256 { forward[i] = i as u8; inverse[i] = i as u8; }
        Self { forward, inverse }
    }
    fn encode(&self, x: u8) -> u8 { self.forward[x as usize] }
    fn decode(&self, x: u8) -> u8 { self.inverse[x as usize] }
}

/// 4-bit bijection
#[derive(Clone, Copy)]
struct Bijection4 { forward: [u8; 16], inverse: [u8; 16] }

impl Bijection4 {
    fn identity() -> Self {
        let mut forward = [0u8; 16];
        let mut inverse = [0u8; 16];
        for i in 0..16 { forward[i] = i as u8; inverse[i] = i as u8; }
        Self { forward, inverse }
    }
    fn encode(&self, x: u8) -> u8 { self.forward[(x & 0x0f) as usize] }
    fn decode(&self, x: u8) -> u8 { self.inverse[(x & 0x0f) as usize] }
}

/// 32x32 mixing bijection
struct MixingBijection32 { matrix: [[u8; 32]; 32], inverse: [[u8; 32]; 32] }

impl MixingBijection32 {
    fn identity() -> Self {
        let mut matrix = [[0u8; 32]; 32];
        let mut inverse = [[0u8; 32]; 32];
        for i in 0..32 { matrix[i][i] = 1; inverse[i][i] = 1; }
        Self { matrix, inverse }
    }

    fn apply(&self, input: u32) -> u32 {
        let mut result = 0u32;
        for i in 0..32 {
            let mut bit = 0u8;
            for j in 0..32 {
                if self.matrix[i][j] != 0 && (input >> j) & 1 != 0 { bit ^= 1; }
            }
            result |= (bit as u32) << i;
        }
        result
    }

    fn apply_inverse(&self, input: u32) -> u32 {
        let mut result = 0u32;
        for i in 0..32 {
            let mut bit = 0u8;
            for j in 0..32 {
                if self.inverse[i][j] != 0 && (input >> j) & 1 != 0 { bit ^= 1; }
            }
            result |= (bit as u32) << i;
        }
        result
    }
}

/// Internal encodings
struct InternalEncodings {
    round_output: [[Bijection8; AES_BLOCK_SIZE]; AES_ROUNDS],
    nibble_encodings: [[[Bijection4; 2]; 96]; 9],
}

/// Generated WBC tables (raw bytes for embedding)
struct WbcTables {
    tbox: Vec<u8>,       // 40,960 bytes
    tybox: Vec<u8>,      // 147,456 bytes
    xor_tables: Vec<u8>, // 221,184 bytes
    mbl: Vec<u8>,        // 147,456 bytes
    tbox_last: Vec<u8>,  // 4,096 bytes
}

/// Generate all WBC tables at build-time
#[allow(clippy::needless_range_loop)]
fn generate_wbc_tables(key: &[u8; 16], seed: &[u8]) -> WbcTables {
    let mut rng = BuildRng::new(seed);
    let round_keys = aes_key_expansion(key);

    // Generate encodings
    let encodings = generate_encodings(&mut rng);
    let mixing_bijections = generate_mixing_bijections(&mut rng);

    // Allocate tables
    let mut tbox = vec![0u8; TBOX_SIZE];
    let mut tybox = vec![0u8; TYBOX_SIZE];
    let mut xor_tables = vec![0u8; XOR_TABLE_SIZE];
    let mut mbl = vec![0u8; MBL_SIZE];
    let mut tbox_last = vec![0u8; TBOX_LAST_SIZE];

    // Generate T-boxes and Ty-boxes (rounds 0-8)
    for round in 0..9 {
        for col in 0..4 {
            for row in 0..4 {
                let pos = col * 4 + row;
                let shifted_pos = AES_SHIFT_ROWS[pos];

                for x in 0..256 {
                    let decoded = if round == 0 {
                        x as u8
                    } else {
                        encodings.round_output[round - 1][pos].decode(x as u8)
                    };

                    let after_key = decoded ^ round_keys[round][shifted_pos];
                    let after_sbox = AES_SBOX[after_key as usize];

                    // MixColumns contribution
                    let mut mc_out = [0u8; 4];
                    for out_row in 0..4 {
                        mc_out[out_row] = gf_mul(AES_MIX_COLS[out_row][row], after_sbox);
                    }

                    let packed = (mc_out[0] as u32)
                        | ((mc_out[1] as u32) << 8)
                        | ((mc_out[2] as u32) << 16)
                        | ((mc_out[3] as u32) << 24);

                    let mixed = mixing_bijections[round].apply(packed);

                    // Store tybox (u32 as 4 bytes LE)
                    let tybox_idx = (round * AES_BLOCK_SIZE * 256 + pos * 256 + x) * 4;
                    tybox[tybox_idx..tybox_idx + 4].copy_from_slice(&mixed.to_le_bytes());

                    // Store tbox
                    let tbox_idx = round * AES_BLOCK_SIZE * 256 + pos * 256 + x;
                    tbox[tbox_idx] = after_sbox;
                }
            }
        }
    }

    // Generate XOR tables
    for round in 0..9 {
        for table_idx in 0..96 {
            for a in 0..16u8 {
                for b in 0..16u8 {
                    let a_decoded = encodings.nibble_encodings[round][table_idx][0].decode(a);
                    let b_decoded = encodings.nibble_encodings[round][table_idx][1].decode(b);
                    let result = a_decoded ^ b_decoded;
                    let encoded_result = if table_idx + 1 < 96 {
                        encodings.nibble_encodings[round][(table_idx + 1) % 96][0].encode(result)
                    } else {
                        result
                    };
                    let idx = round * 96 * 16 * 16 + table_idx * 16 * 16 + (a as usize) * 16 + (b as usize);
                    xor_tables[idx] = encoded_result;
                }
            }
        }
    }

    // Generate MBL tables
    for (round, mb) in mixing_bijections.iter().enumerate().take(9) {
        for pos in 0..AES_BLOCK_SIZE {
            for x in 0..256 {
                let l_encoded = (x as u32) << ((pos % 4) * 8);
                let unmixed = mb.apply_inverse(l_encoded);

                let out_bytes = [
                    unmixed as u8,
                    (unmixed >> 8) as u8,
                    (unmixed >> 16) as u8,
                    (unmixed >> 24) as u8,
                ];

                let col_base = (pos / 4) * 4;
                let encoded_bytes = [
                    encodings.round_output[round][col_base].encode(out_bytes[0]),
                    encodings.round_output[round][col_base + 1].encode(out_bytes[1]),
                    encodings.round_output[round][col_base + 2].encode(out_bytes[2]),
                    encodings.round_output[round][col_base + 3].encode(out_bytes[3]),
                ];

                let packed = (encoded_bytes[0] as u32)
                    | ((encoded_bytes[1] as u32) << 8)
                    | ((encoded_bytes[2] as u32) << 16)
                    | ((encoded_bytes[3] as u32) << 24);

                let mbl_idx = (round * AES_BLOCK_SIZE * 256 + pos * 256 + x) * 4;
                mbl[mbl_idx..mbl_idx + 4].copy_from_slice(&packed.to_le_bytes());
            }
        }
    }

    // Generate last round T-boxes (round 9, no MixColumns)
    let round = AES_ROUNDS - 1;
    for pos in 0..AES_BLOCK_SIZE {
        let shifted_pos = AES_SHIFT_ROWS[pos];
        for x in 0..256 {
            let decoded = encodings.round_output[round - 1][pos].decode(x as u8);
            let after_key = decoded ^ round_keys[round][shifted_pos];
            let after_sbox = AES_SBOX[after_key as usize];
            let result = after_sbox ^ round_keys[AES_ROUNDS][shifted_pos];

            tbox_last[pos * 256 + x] = result;
            tbox[round * AES_BLOCK_SIZE * 256 + pos * 256 + x] = result;
        }
    }

    WbcTables { tbox, tybox, xor_tables, mbl, tbox_last }
}

fn generate_encodings(rng: &mut BuildRng) -> InternalEncodings {
    let mut encodings = InternalEncodings {
        round_output: [[Bijection8::identity(); AES_BLOCK_SIZE]; AES_ROUNDS],
        nibble_encodings: [[[Bijection4::identity(); 2]; 96]; 9],
    };

    for round in 0..AES_ROUNDS {
        for pos in 0..AES_BLOCK_SIZE {
            let perm = rng.random_permutation(256);
            let mut bij = Bijection8::identity();
            for (i, &p) in perm.iter().enumerate() {
                bij.forward[i] = p;
                bij.inverse[p as usize] = i as u8;
            }
            encodings.round_output[round][pos] = bij;
        }
    }

    for round in 0..9 {
        for table in 0..96 {
            for nibble in 0..2 {
                let perm = rng.random_permutation(16);
                let mut bij = Bijection4::identity();
                for (i, &p) in perm.iter().enumerate() {
                    bij.forward[i] = p;
                    bij.inverse[p as usize] = i as u8;
                }
                encodings.nibble_encodings[round][table][nibble] = bij;
            }
        }
    }

    encodings
}

fn generate_mixing_bijections(rng: &mut BuildRng) -> [MixingBijection32; 9] {
    let mut mbs: [MixingBijection32; 9] = core::array::from_fn(|_| MixingBijection32::identity());

    for mb in &mut mbs {
        for _ in 0..64 {
            let i = (rng.next_u64() as usize) % 32;
            let j = (rng.next_u64() as usize) % 32;
            if i != j {
                for k in 0..32 { mb.matrix[i][k] ^= mb.matrix[j][k]; }
                for k in 0..32 { mb.inverse[k][j] ^= mb.inverse[k][i]; }
            }
        }
    }

    mbs
}

/// Generate whitebox tables embedded with entropy pool protection
/// The AES key is ONLY used during build - it never exists at runtime!
fn generate_whitebox_config(f: &mut File, build_seed: &[u8; 32]) {
    // Derive WBC key and table seed
    let wbc_key_full = hmac_sha256(build_seed, b"whitebox-aes-key-v1");
    let table_seed = hmac_sha256(build_seed, b"whitebox-table-seed-v1");

    // Extract 16-byte AES key
    let mut wbc_key = [0u8; 16];
    wbc_key.copy_from_slice(&wbc_key_full[..16]);

    // Generate all WBC tables at BUILD TIME
    // After this, wbc_key is no longer needed - it's embedded in the tables!
    let tables = generate_wbc_tables(&wbc_key, &table_seed);

    // Generate shared entropy pool (64KB) for all tables
    const POOL_SIZE: usize = 65536;
    let mut entropy_pool = vec![0u8; POOL_SIZE];
    let pool_seed = hmac_sha256(build_seed, b"wbc-shared-pool-v2");
    let mut rng_state = pool_seed;
    for (i, byte) in entropy_pool.iter_mut().enumerate() {
        let mac = hmac_sha256(&rng_state, &(i as u32).to_le_bytes());
        *byte = mac[0];
        if i % 64 == 0 { rng_state = mac; }
    }

    // Generate per-table parameters and deltas
    let params_seed = hmac_sha256(build_seed, b"wbc-table-params-v2");

    writeln!(f, "// ============================================================================").unwrap();
    writeln!(f, "// WHITE-BOX CRYPTO TABLES - BUILD-TIME GENERATED").unwrap();
    writeln!(f, "// ============================================================================").unwrap();
    writeln!(f, "// AES key was used ONLY during compilation to generate these tables.").unwrap();
    writeln!(f, "// The key does NOT exist anywhere at runtime - true white-box security!").unwrap();
    writeln!(f, "// Tables are protected with entropy pool + delta XOR reconstruction.").unwrap();
    writeln!(f, "pub mod whitebox_config {{").unwrap();
    writeln!(f, "    #![allow(clippy::all)]").unwrap();
    writeln!(f, "    extern crate alloc;").unwrap();
    writeln!(f).unwrap();

    // Write shared entropy pool
    writeln!(f, "    /// Shared entropy pool for all table reconstruction (64KB)").unwrap();
    writeln!(f, "    const ENTROPY_POOL: [u8; {}] = [", POOL_SIZE).unwrap();
    for (i, byte) in entropy_pool.iter().enumerate() {
        if i % 32 == 0 { write!(f, "\n        ").unwrap(); }
        write!(f, "0x{:02x},", byte).unwrap();
    }
    writeln!(f, "\n    ];").unwrap();
    writeln!(f).unwrap();

    // Helper function to generate and write delta array for a table
    fn write_table_deltas(
        f: &mut File,
        name: &str,
        table_data: &[u8],
        entropy_pool: &[u8],
        params_seed: &[u8; 32],
        domain: &[u8],
    ) -> (usize, usize) {
        let params = hmac_sha256(params_seed, domain);
        let start = (u64::from_le_bytes(params[0..8].try_into().unwrap()) as usize) % entropy_pool.len();
        let step = (u64::from_le_bytes(params[8..16].try_into().unwrap()) as usize) % 31 + 1;

        // Calculate deltas
        let mut deltas = vec![0u8; table_data.len()];
        for (i, (&data_byte, delta_byte)) in table_data.iter().zip(deltas.iter_mut()).enumerate() {
            let pool_idx = (start + i * step) % entropy_pool.len();
            *delta_byte = data_byte ^ entropy_pool[pool_idx];
        }

        // Write delta array
        writeln!(f, "    /// Delta values for {} reconstruction ({} bytes)", name, deltas.len()).unwrap();
        writeln!(f, "    const {}_DELTAS: [u8; {}] = [", name, deltas.len()).unwrap();
        for (i, byte) in deltas.iter().enumerate() {
            if i % 32 == 0 { write!(f, "\n        ").unwrap(); }
            write!(f, "0x{:02x},", byte).unwrap();
        }
        writeln!(f, "\n    ];").unwrap();
        writeln!(f).unwrap();

        (start, step)
    }

    // Write deltas for each table
    let (tbox_start, tbox_step) = write_table_deltas(
        f, "TBOX", &tables.tbox, &entropy_pool, &params_seed, b"tbox-params"
    );
    let (tybox_start, tybox_step) = write_table_deltas(
        f, "TYBOX", &tables.tybox, &entropy_pool, &params_seed, b"tybox-params"
    );
    let (xor_start, xor_step) = write_table_deltas(
        f, "XOR_TABLES", &tables.xor_tables, &entropy_pool, &params_seed, b"xor-params"
    );
    let (mbl_start, mbl_step) = write_table_deltas(
        f, "MBL", &tables.mbl, &entropy_pool, &params_seed, b"mbl-params"
    );
    let (tbox_last_start, tbox_last_step) = write_table_deltas(
        f, "TBOX_LAST", &tables.tbox_last, &entropy_pool, &params_seed, b"tbox-last-params"
    );

    // Write table size constants
    writeln!(f, "    // Table sizes").unwrap();
    writeln!(f, "    pub const TBOX_SIZE: usize = {};", TBOX_SIZE).unwrap();
    writeln!(f, "    pub const TYBOX_SIZE: usize = {};", TYBOX_SIZE).unwrap();
    writeln!(f, "    pub const XOR_TABLE_SIZE: usize = {};", XOR_TABLE_SIZE).unwrap();
    writeln!(f, "    pub const MBL_SIZE: usize = {};", MBL_SIZE).unwrap();
    writeln!(f, "    pub const TBOX_LAST_SIZE: usize = {};", TBOX_LAST_SIZE).unwrap();
    writeln!(f, "    pub const POOL_SIZE: usize = {};", POOL_SIZE).unwrap();
    writeln!(f).unwrap();

    // Write reconstruction functions
    writeln!(f, "    /// Reconstruct T-boxes from entropy pool + deltas").unwrap();
    writeln!(f, "    #[inline(never)]").unwrap();
    writeln!(f, "    pub fn reconstruct_tbox() -> alloc::boxed::Box<[[[u8; 256]; 16]; 10]> {{").unwrap();
    writeln!(f, "        let mut tbox = alloc::boxed::Box::new([[[0u8; 256]; 16]; 10]);").unwrap();
    writeln!(f, "        let start = core::hint::black_box({});", tbox_start).unwrap();
    writeln!(f, "        let step = core::hint::black_box({});", tbox_step).unwrap();
    writeln!(f, "        for i in 0..TBOX_SIZE {{").unwrap();
    writeln!(f, "            let round = i / (16 * 256);").unwrap();
    writeln!(f, "            let pos = (i / 256) % 16;").unwrap();
    writeln!(f, "            let x = i % 256;").unwrap();
    writeln!(f, "            let pool_idx = (start + i * step) % POOL_SIZE;").unwrap();
    writeln!(f, "            tbox[round][pos][x] = ENTROPY_POOL[pool_idx] ^ TBOX_DELTAS[i];").unwrap();
    writeln!(f, "        }}").unwrap();
    writeln!(f, "        tbox").unwrap();
    writeln!(f, "    }}").unwrap();
    writeln!(f).unwrap();

    writeln!(f, "    /// Reconstruct Ty-boxes from entropy pool + deltas").unwrap();
    writeln!(f, "    #[inline(never)]").unwrap();
    writeln!(f, "    pub fn reconstruct_tybox() -> alloc::boxed::Box<[[[u32; 256]; 16]; 9]> {{").unwrap();
    writeln!(f, "        let mut tybox = alloc::boxed::Box::new([[[0u32; 256]; 16]; 9]);").unwrap();
    writeln!(f, "        let start = core::hint::black_box({});", tybox_start).unwrap();
    writeln!(f, "        let step = core::hint::black_box({});", tybox_step).unwrap();
    writeln!(f, "        for i in 0..(TYBOX_SIZE / 4) {{").unwrap();
    writeln!(f, "            let round = i / (16 * 256);").unwrap();
    writeln!(f, "            let pos = (i / 256) % 16;").unwrap();
    writeln!(f, "            let x = i % 256;").unwrap();
    writeln!(f, "            let base = i * 4;").unwrap();
    writeln!(f, "            let mut bytes = [0u8; 4];").unwrap();
    writeln!(f, "            for j in 0..4 {{").unwrap();
    writeln!(f, "                let pool_idx = (start + (base + j) * step) % POOL_SIZE;").unwrap();
    writeln!(f, "                bytes[j] = ENTROPY_POOL[pool_idx] ^ TYBOX_DELTAS[base + j];").unwrap();
    writeln!(f, "            }}").unwrap();
    writeln!(f, "            tybox[round][pos][x] = u32::from_le_bytes(bytes);").unwrap();
    writeln!(f, "        }}").unwrap();
    writeln!(f, "        tybox").unwrap();
    writeln!(f, "    }}").unwrap();
    writeln!(f).unwrap();

    writeln!(f, "    /// Reconstruct XOR tables from entropy pool + deltas").unwrap();
    writeln!(f, "    #[inline(never)]").unwrap();
    writeln!(f, "    pub fn reconstruct_xor_tables() -> alloc::boxed::Box<[[[[u8; 16]; 16]; 96]; 9]> {{").unwrap();
    writeln!(f, "        let mut xor_tables = alloc::boxed::Box::new([[[[0u8; 16]; 16]; 96]; 9]);").unwrap();
    writeln!(f, "        let start = core::hint::black_box({});", xor_start).unwrap();
    writeln!(f, "        let step = core::hint::black_box({});", xor_step).unwrap();
    writeln!(f, "        for i in 0..XOR_TABLE_SIZE {{").unwrap();
    writeln!(f, "            let round = i / (96 * 16 * 16);").unwrap();
    writeln!(f, "            let table = (i / (16 * 16)) % 96;").unwrap();
    writeln!(f, "            let a = (i / 16) % 16;").unwrap();
    writeln!(f, "            let b = i % 16;").unwrap();
    writeln!(f, "            let pool_idx = (start + i * step) % POOL_SIZE;").unwrap();
    writeln!(f, "            xor_tables[round][table][a][b] = ENTROPY_POOL[pool_idx] ^ XOR_TABLES_DELTAS[i];").unwrap();
    writeln!(f, "        }}").unwrap();
    writeln!(f, "        xor_tables").unwrap();
    writeln!(f, "    }}").unwrap();
    writeln!(f).unwrap();

    writeln!(f, "    /// Reconstruct MBL tables from entropy pool + deltas").unwrap();
    writeln!(f, "    #[inline(never)]").unwrap();
    writeln!(f, "    pub fn reconstruct_mbl() -> alloc::boxed::Box<[[[u32; 256]; 16]; 9]> {{").unwrap();
    writeln!(f, "        let mut mbl = alloc::boxed::Box::new([[[0u32; 256]; 16]; 9]);").unwrap();
    writeln!(f, "        let start = core::hint::black_box({});", mbl_start).unwrap();
    writeln!(f, "        let step = core::hint::black_box({});", mbl_step).unwrap();
    writeln!(f, "        for i in 0..(MBL_SIZE / 4) {{").unwrap();
    writeln!(f, "            let round = i / (16 * 256);").unwrap();
    writeln!(f, "            let pos = (i / 256) % 16;").unwrap();
    writeln!(f, "            let x = i % 256;").unwrap();
    writeln!(f, "            let base = i * 4;").unwrap();
    writeln!(f, "            let mut bytes = [0u8; 4];").unwrap();
    writeln!(f, "            for j in 0..4 {{").unwrap();
    writeln!(f, "                let pool_idx = (start + (base + j) * step) % POOL_SIZE;").unwrap();
    writeln!(f, "                bytes[j] = ENTROPY_POOL[pool_idx] ^ MBL_DELTAS[base + j];").unwrap();
    writeln!(f, "            }}").unwrap();
    writeln!(f, "            mbl[round][pos][x] = u32::from_le_bytes(bytes);").unwrap();
    writeln!(f, "        }}").unwrap();
    writeln!(f, "        mbl").unwrap();
    writeln!(f, "    }}").unwrap();
    writeln!(f).unwrap();

    writeln!(f, "    /// Reconstruct last round T-boxes from entropy pool + deltas").unwrap();
    writeln!(f, "    #[inline(never)]").unwrap();
    writeln!(f, "    pub fn reconstruct_tbox_last() -> [[u8; 256]; 16] {{").unwrap();
    writeln!(f, "        let mut tbox_last = [[0u8; 256]; 16];").unwrap();
    writeln!(f, "        let start = core::hint::black_box({});", tbox_last_start).unwrap();
    writeln!(f, "        let step = core::hint::black_box({});", tbox_last_step).unwrap();
    writeln!(f, "        for i in 0..TBOX_LAST_SIZE {{").unwrap();
    writeln!(f, "            let pos = i / 256;").unwrap();
    writeln!(f, "            let x = i % 256;").unwrap();
    writeln!(f, "            let pool_idx = (start + i * step) % POOL_SIZE;").unwrap();
    writeln!(f, "            tbox_last[pos][x] = ENTROPY_POOL[pool_idx] ^ TBOX_LAST_DELTAS[i];").unwrap();
    writeln!(f, "        }}").unwrap();
    writeln!(f, "        tbox_last").unwrap();
    writeln!(f, "    }}").unwrap();
    writeln!(f).unwrap();

    // ============================================================================
    // PRE-COMPUTED DOMAIN HASHES
    // ============================================================================
    // Domain strings are hashed at BUILD TIME using FNV-1a.
    // Runtime only sees 32 random-looking bytes, not the actual string!
    // This eliminates strings like "aegis-bytecode-encryption-v1" from the binary.

    // FNV-1a hash function (same as in whitebox/mod.rs)
    fn fnv_hash_domain(domain: &[u8]) -> [u8; 32] {
        let mut hash1 = 0xcbf29ce484222325u64;
        let mut hash2 = 0x84222325cbf29ce4u64;

        for &byte in domain {
            hash1 ^= byte as u64;
            hash1 = hash1.wrapping_mul(0x100000001b3);
            hash2 = hash2.wrapping_mul(0x100000001b3);
            hash2 ^= byte as u64;
        }

        // Create 32-byte hash (matches derive_key_with_tables logic)
        let hash3 = hash1.rotate_left(13) ^ hash2;
        let hash4 = hash2.rotate_right(17) ^ hash1;

        let mut result = [0u8; 32];
        result[0..8].copy_from_slice(&hash1.to_le_bytes());
        result[8..16].copy_from_slice(&hash2.to_le_bytes());
        result[16..24].copy_from_slice(&hash3.to_le_bytes());
        result[24..32].copy_from_slice(&hash4.to_le_bytes());
        result
    }

    // Compute hashes for all domain strings at build-time
    let bytecode_domain_hash = fnv_hash_domain(b"aegis-bytecode-encryption-v1");
    let smc_domain_hash = fnv_hash_domain(b"aegis-smc-key-v1");
    let nonce_domain_hash = fnv_hash_domain(b"wbc-nonce\x00\x00\x00\x00\x00\x00\x00"); // Padded to 16 bytes

    // Write domain hash constants with entropy pool protection
    writeln!(f, "    // ========================================================================").unwrap();
    writeln!(f, "    // PRE-COMPUTED DOMAIN HASHES (strings eliminated from binary!)").unwrap();
    writeln!(f, "    // ========================================================================").unwrap();
    writeln!(f).unwrap();

    // Protect bytecode domain hash
    let (bc_hash_start, bc_hash_step) = {
        let params = hmac_sha256(&params_seed, b"bytecode-hash-params");
        let start = (u64::from_le_bytes(params[0..8].try_into().unwrap()) as usize) % POOL_SIZE;
        let step = (u64::from_le_bytes(params[8..16].try_into().unwrap()) as usize) % 31 + 1;

        let mut deltas = [0u8; 32];
        for i in 0..32 {
            let pool_idx = (start + i * step) % POOL_SIZE;
            deltas[i] = bytecode_domain_hash[i] ^ entropy_pool[pool_idx];
        }

        writeln!(f, "    /// Bytecode domain hash deltas (32 bytes)").unwrap();
        writeln!(f, "    const BYTECODE_DOMAIN_HASH_DELTAS: [u8; 32] = [").unwrap();
        write!(f, "        ").unwrap();
        for (i, byte) in deltas.iter().enumerate() {
            write!(f, "0x{:02x},", byte).unwrap();
            if i == 15 { write!(f, "\n        ").unwrap(); }
        }
        writeln!(f, "\n    ];").unwrap();
        (start, step)
    };

    // Protect SMC domain hash
    let (smc_hash_start, smc_hash_step) = {
        let params = hmac_sha256(&params_seed, b"smc-hash-params");
        let start = (u64::from_le_bytes(params[0..8].try_into().unwrap()) as usize) % POOL_SIZE;
        let step = (u64::from_le_bytes(params[8..16].try_into().unwrap()) as usize) % 31 + 1;

        let mut deltas = [0u8; 32];
        for i in 0..32 {
            let pool_idx = (start + i * step) % POOL_SIZE;
            deltas[i] = smc_domain_hash[i] ^ entropy_pool[pool_idx];
        }

        writeln!(f, "    /// SMC domain hash deltas (32 bytes)").unwrap();
        writeln!(f, "    const SMC_DOMAIN_HASH_DELTAS: [u8; 32] = [").unwrap();
        write!(f, "        ").unwrap();
        for (i, byte) in deltas.iter().enumerate() {
            write!(f, "0x{:02x},", byte).unwrap();
            if i == 15 { write!(f, "\n        ").unwrap(); }
        }
        writeln!(f, "\n    ];").unwrap();
        (start, step)
    };

    // Protect nonce domain hash
    let (nonce_hash_start, nonce_hash_step) = {
        let params = hmac_sha256(&params_seed, b"nonce-hash-params");
        let start = (u64::from_le_bytes(params[0..8].try_into().unwrap()) as usize) % POOL_SIZE;
        let step = (u64::from_le_bytes(params[8..16].try_into().unwrap()) as usize) % 31 + 1;

        let mut deltas = [0u8; 32];
        for i in 0..32 {
            let pool_idx = (start + i * step) % POOL_SIZE;
            deltas[i] = nonce_domain_hash[i] ^ entropy_pool[pool_idx];
        }

        writeln!(f, "    /// Nonce domain hash deltas (32 bytes)").unwrap();
        writeln!(f, "    const NONCE_DOMAIN_HASH_DELTAS: [u8; 32] = [").unwrap();
        write!(f, "        ").unwrap();
        for (i, byte) in deltas.iter().enumerate() {
            write!(f, "0x{:02x},", byte).unwrap();
            if i == 15 { write!(f, "\n        ").unwrap(); }
        }
        writeln!(f, "\n    ];").unwrap();
        (start, step)
    };

    writeln!(f).unwrap();

    // Write reconstruction functions for domain hashes
    writeln!(f, "    /// Reconstruct bytecode domain hash from entropy pool + deltas").unwrap();
    writeln!(f, "    #[inline(never)]").unwrap();
    writeln!(f, "    pub fn get_bytecode_domain_hash() -> [u8; 32] {{").unwrap();
    writeln!(f, "        let mut hash = [0u8; 32];").unwrap();
    writeln!(f, "        let start = core::hint::black_box({});", bc_hash_start).unwrap();
    writeln!(f, "        let step = core::hint::black_box({});", bc_hash_step).unwrap();
    writeln!(f, "        for i in 0..32 {{").unwrap();
    writeln!(f, "            let pool_idx = (start + i * step) % POOL_SIZE;").unwrap();
    writeln!(f, "            hash[i] = ENTROPY_POOL[pool_idx] ^ BYTECODE_DOMAIN_HASH_DELTAS[i];").unwrap();
    writeln!(f, "        }}").unwrap();
    writeln!(f, "        hash").unwrap();
    writeln!(f, "    }}").unwrap();
    writeln!(f).unwrap();

    writeln!(f, "    /// Reconstruct SMC domain hash from entropy pool + deltas").unwrap();
    writeln!(f, "    #[inline(never)]").unwrap();
    writeln!(f, "    pub fn get_smc_domain_hash() -> [u8; 32] {{").unwrap();
    writeln!(f, "        let mut hash = [0u8; 32];").unwrap();
    writeln!(f, "        let start = core::hint::black_box({});", smc_hash_start).unwrap();
    writeln!(f, "        let step = core::hint::black_box({});", smc_hash_step).unwrap();
    writeln!(f, "        for i in 0..32 {{").unwrap();
    writeln!(f, "            let pool_idx = (start + i * step) % POOL_SIZE;").unwrap();
    writeln!(f, "            hash[i] = ENTROPY_POOL[pool_idx] ^ SMC_DOMAIN_HASH_DELTAS[i];").unwrap();
    writeln!(f, "        }}").unwrap();
    writeln!(f, "        hash").unwrap();
    writeln!(f, "    }}").unwrap();
    writeln!(f).unwrap();

    writeln!(f, "    /// Reconstruct nonce domain hash from entropy pool + deltas").unwrap();
    writeln!(f, "    #[inline(never)]").unwrap();
    writeln!(f, "    pub fn get_nonce_domain_hash() -> [u8; 32] {{").unwrap();
    writeln!(f, "        let mut hash = [0u8; 32];").unwrap();
    writeln!(f, "        let start = core::hint::black_box({});", nonce_hash_start).unwrap();
    writeln!(f, "        let step = core::hint::black_box({});", nonce_hash_step).unwrap();
    writeln!(f, "        for i in 0..32 {{").unwrap();
    writeln!(f, "            let pool_idx = (start + i * step) % POOL_SIZE;").unwrap();
    writeln!(f, "            hash[i] = ENTROPY_POOL[pool_idx] ^ NONCE_DOMAIN_HASH_DELTAS[i];").unwrap();
    writeln!(f, "        }}").unwrap();
    writeln!(f, "        hash").unwrap();
    writeln!(f, "    }}").unwrap();

    writeln!(f, "}}").unwrap();
    writeln!(f).unwrap();
}