polyplug_abi 0.1.1

ABI type definitions for the polyplug plugin runtime
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
//! SDK generation module — integrates language generators from polyplug_codegen.
//!
//! This module provides functions to generate SDK bindings for all supported
//! languages (C++, C#, Python, Lua, JavaScript) from extracted ABI types.
//! After code generation, it preserves hand-written helper method bodies from
//! existing helper files by merging them into the generated output.

#![allow(clippy::std_instead_of_core)]

use crate::mapper::map_all_abi_types;
use crate::types::AbiTypes;
use polyplug_codegen::data::Item;
use polyplug_codegen::languages::{
    CSharpGenerator, CodeGenerator, CppGenerator, ForwardKind, GenerationContext, JsGenerator,
    LuaGenerator, PythonGenerator,
};
use std::fs;
use std::path::{Path, PathBuf};

/// Target language for SDK generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetLang {
    /// C++ (C++17 headers).
    Cpp,
    /// C# (.NET bindings).
    CSharp,
    /// Python (ctypes bindings).
    Python,
    /// Lua (LuaJIT FFI bindings).
    Lua,
    /// JavaScript/TypeScript.
    JavaScript,
}

impl TargetLang {
    /// Return the language name for directory structure.
    pub const fn language_name(&self) -> &'static str {
        match self {
            TargetLang::Cpp => "cpp",
            TargetLang::CSharp => "csharp",
            TargetLang::Python => "python",
            TargetLang::Lua => "lua",
            TargetLang::JavaScript => "js",
        }
    }

    /// Return the output filename for the generated SDK.
    pub const fn output_filename(&self) -> &'static str {
        match self {
            TargetLang::Cpp => "abi.hpp",
            TargetLang::CSharp => "Abi.cs",
            TargetLang::Python => "abi.py",
            TargetLang::Lua => "abi.lua",
            TargetLang::JavaScript => "abi.ts",
        }
    }

    /// Return the subdirectory path for the generated SDK.
    pub const fn subdir(&self) -> &'static str {
        match self {
            TargetLang::Cpp => "polyplug",
            TargetLang::CSharp => "",
            TargetLang::Python => "",
            TargetLang::Lua => "",
            TargetLang::JavaScript => "",
        }
    }
}

/// Patterns in rust_type strings that indicate types which cannot be represented
/// in target languages. Simple generics (Array<T>, Option<...>) and tuples are allowed.
const UNREPRESENTABLE_PATTERNS: &[&str] = &["dyn ", "impl ", "for<", "where "];

// ─── Inline Helper Method Source (per language) ───────────────────────────────
//
// Per D-12: Helper methods are embedded as const strings so they survive across
// rebuilds without relying on external files that get deleted after merge.

/// C# StringViewHelper and PinnedUtf8 class bodies (no namespace wrapper, no
/// using statements). Merged into Abi.cs inside the Polyplug.Abi namespace.
/// Requires `using System.Runtime.InteropServices;` and `using System.Text;`
/// which are included in the generated Abi.cs header.
const HELPER_CSHARP_STRING_VIEW: &str = r#"
/// <summary>
/// Helpers for constructing and converting StringViews at the ABI boundary.
/// This is the unified implementation used by both host and guest.
/// </summary>
public static class StringViewHelper
{
    /// <summary>
    /// Returns a StringView pointing at the pinned byte array via a GCHandle.
    /// Caller owns the GCHandle and must keep it alive while the StringView is in use.
    /// </summary>
    public static StringView FromPinnedHandle(GCHandle handle, int length) =>
        new StringView { Ptr = handle.AddrOfPinnedObject(), Len = (nuint)length };

    /// <summary>
    /// Returns a StringView pointing at a pre-pinned IntPtr. Caller ensures ptr validity.
    /// </summary>
    public static StringView FromPtr(IntPtr ptr, int length) =>
        new StringView { Ptr = ptr, Len = (nuint)length };

    /// <summary>
    /// Creates a StringView from a .NET string by pinning it in memory.
    /// The GCHandle must be kept alive while the StringView is in use.
    /// For guest plugins, return strings should use host allocation via registrar.
    /// </summary>
    public static (StringView View, GCHandle Handle) FromStringPinned(string str)
    {
        if (string.IsNullOrEmpty(str))
            return (new StringView { Ptr = IntPtr.Zero, Len = 0 }, default);

        byte[] bytes = Encoding.UTF8.GetBytes(str);
        GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
        StringView sv = new StringView { Ptr = handle.AddrOfPinnedObject(), Len = (nuint)bytes.Length };
        return (sv, handle);
    }

    /// <summary>
    /// Converts a StringView to a .NET string by decoding the UTF-8 bytes
    /// directly from the native pointer (no intermediate byte[] copy).
    /// A null/zero-length view decodes to the empty string. A non-null view
    /// whose bytes are NOT valid UTF-8 throws <see cref="DecoderFallbackException"/>
    /// — the helper never silently substitutes replacement characters for a
    /// readable-but-invalid view.
    /// </summary>
    public static unsafe string ToString(this StringView sv)
    {
        if (sv.Ptr == IntPtr.Zero || sv.Len == 0)
            return string.Empty;

        return s_strictUtf8.GetString((byte*)sv.Ptr, (int)sv.Len);
    }

    /// <summary>
    /// Converts a StringView to a .NET string. Alias for ToString.
    /// </summary>
    public static string ToStr(StringView sv) => ToString(sv);

    /// <summary>
    /// Checks if a StringView starts with the given prefix.
    /// </summary>
    public static bool StartsWith(StringView sv, string prefix)
    {
        if (string.IsNullOrEmpty(prefix))
            return true;
        if (sv.Ptr == IntPtr.Zero || sv.Len == 0)
            return false;

        string str = ToString(sv);
        return str.StartsWith(prefix);
    }

    /// <summary>
    /// Checks if a StringView ends with the given suffix.
    /// </summary>
    public static bool EndsWith(StringView sv, string suffix)
    {
        if (string.IsNullOrEmpty(suffix))
            return true;
        if (sv.Ptr == IntPtr.Zero || sv.Len == 0)
            return false;

        string str = ToString(sv);
        return str.EndsWith(suffix);
    }

    /// <summary>
    /// Strips the prefix from a StringView if it starts with it.
    /// Returns the original string if the prefix is not present.
    /// </summary>
    public static string StripPrefix(StringView sv, string prefix)
    {
        if (string.IsNullOrEmpty(prefix))
            return ToString(sv);

        string str = ToString(sv);
        if (str.StartsWith(prefix))
            return str.Substring(prefix.Length);
        return str;
    }

    /// <summary>
    /// Splits a StringView by the given delimiter and returns an array of strings.
    /// </summary>
    public static string[] Split(StringView sv, string delimiter)
    {
        if (sv.Ptr == IntPtr.Zero || sv.Len == 0)
            return System.Array.Empty<string>();

        string str = ToString(sv);
        if (string.IsNullOrEmpty(delimiter))
            return new[] { str };

        return str.Split(new[] { delimiter }, System.StringSplitOptions.None);
    }

    /// <summary>
    /// Returns a process-lifetime <see cref="StringView"/> for a string that
    /// crosses the ABI boundary as an <see cref="AbiError.Message"/>.
    /// </summary>
    /// <remarks>
    /// Per the ABI ownership contract, an AbiError.Message is a static or
    /// runtime-owned string that the receiver MUST NEVER free. This helper pins
    /// the UTF-8 bytes for the lifetime of the process (equivalent to .rodata),
    /// caching one buffer per distinct string so repeated errors never leak a new
    /// GCHandle. It is the only sound way to hand the host a borrowed message that
    /// nobody frees. Use it for fixed error literals — NOT for per-call argument
    /// strings (use <see cref="PinnedUtf8"/> for those).
    /// </remarks>
    public static StringView StaticMessage(string value)
    {
        if (string.IsNullOrEmpty(value))
            return new StringView { Ptr = IntPtr.Zero, Len = 0 };

        lock (s_staticMessages)
        {
            if (s_staticMessages.TryGetValue(value, out StringView cached))
                return cached;

            byte[] bytes = Encoding.UTF8.GetBytes(value);
            // Never freed: pinned for the process lifetime, mirroring .rodata.
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            StringView view = new StringView
            {
                Ptr = handle.AddrOfPinnedObject(),
                Len = (nuint)bytes.Length,
            };
            s_staticMessages[value] = view;
            return view;
        }
    }

    private static readonly System.Collections.Generic.Dictionary<string, StringView> s_staticMessages =
        new System.Collections.Generic.Dictionary<string, StringView>();

    // Strict UTF-8 decoder: throws DecoderFallbackException on invalid bytes
    // instead of emitting U+FFFD replacement characters. Every StringView decode
    // (ToString and the helpers built on it) routes through this so a
    // readable-but-invalid view is surfaced as an error, never silently mangled.
    private static readonly UTF8Encoding s_strictUtf8 =
        new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
}

/// <summary>
/// Call-scoped pin of a .NET string's UTF-8 bytes, exposing a borrowed
/// <see cref="StringView"/> for passing a string ARGUMENT across the ABI
/// boundary. The argument is borrowed for the duration of the call only:
/// construct a <see cref="PinnedUtf8"/>, pass <see cref="View"/> into the call,
/// then dispose to release the pin.
/// </summary>
/// <remarks>
/// This is the correct mechanism for argument strings. It pins managed bytes
/// only for the call and frees the <see cref="GCHandle"/> on <see cref="Dispose"/>,
/// so there is no per-call leak. The host never frees this memory — it only reads
/// it for the duration of the call. For AbiError.Message values, use
/// <see cref="StringViewHelper.StaticMessage"/> instead.
/// </remarks>
public sealed class PinnedUtf8 : IDisposable
{
    private GCHandle _handle;
    private bool _pinned;

    /// <summary>
    /// The borrowed <see cref="StringView"/> over the pinned UTF-8 bytes. Valid
    /// only until <see cref="Dispose"/> is called.
    /// </summary>
    public StringView View { get; }

    public PinnedUtf8(string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            View = new StringView { Ptr = IntPtr.Zero, Len = 0 };
            return;
        }

        byte[] bytes = Encoding.UTF8.GetBytes(value);
        _handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
        _pinned = true;
        View = new StringView
        {
            Ptr = _handle.AddrOfPinnedObject(),
            Len = (nuint)bytes.Length,
        };
    }

    public void Dispose()
    {
        if (_pinned)
        {
            _handle.Free();
            _pinned = false;
        }
    }
}
"#;

/// Lua contract-ID / hash helper function definitions (function M.* only).
///
/// Provenance: mirrors the canonical FNV-1a 64-bit scheme implemented in
/// `crates/polyplug_utils/src/{lib,guest_contract_id,host_contract_id,bundle_id}.rs`.
/// Each function is self-contained (no shared module-level locals) because the
/// Lua helper extractor only preserves `function M.*` blocks.
const HELPER_LUA_HASHING: &str = r#"
--- Compute FNV-1a 64-bit hash of a Lua string.
-- @param str string Input string.
-- @return cdata uint64_t FNV-1a 64-bit hash.
function M.fnv1a_64(str)
    local bit = require("bit")
    local h = 0xcbf29ce484222325ULL
    for i = 1, #str do
        h = bit.bxor(h, str:byte(i))
        h = h * 0x00000100000001B3ULL
    end
    return h
end

--- Compute a bundle ID from its name using FNV-1a 64-bit hash.
-- @param name string     Bundle name.
-- @return cdata uint64_t Bundle ID hash.
function M.bundle_id(name)
    return M.fnv1a_64(name)
end

--- Calculate guest contract ID from name and major version.
-- @param name string          Contract name.
-- @param major_version number Major version.
-- @return cdata uint64_t      Guest contract ID hash.
function M.guest_contract_id(name, major_version)
    return M.fnv1a_64("guest_contract:" .. name .. "@" .. tostring(major_version))
end

--- Calculate host contract ID from name and major version.
-- @param name string          Contract name.
-- @param major_version number Major version.
-- @return cdata uint64_t      Host contract ID hash.
function M.host_contract_id(name, major_version)
    return M.fnv1a_64("host_contract:" .. name .. "@" .. tostring(major_version))
end
"#;

/// Python contract-ID / hash helper definitions appended to abi.py.
///
/// Provenance: mirrors the canonical FNV-1a 64-bit scheme implemented in
/// `crates/polyplug_utils/src/{lib,guest_contract_id,host_contract_id,bundle_id}.rs`.
const HELPER_PYTHON_HASHING: &str = r#"
# ─── FNV-1a 64-bit Hash / Contract-ID Helpers ─────────────────────────────────

FNV_OFFSET: int = 0xCBF29CE484222325
FNV_PRIME: int = 0x00000100000001B3


def fnv1a_64(data: bytes) -> int:
    """Compute FNV-1a 64-bit hash of a byte sequence."""
    hash_val: int = FNV_OFFSET
    for byte in data:
        hash_val ^= byte
        hash_val = (hash_val * FNV_PRIME) & 0xFFFFFFFFFFFFFFFF
    return hash_val


def guest_contract_id(name: str, major_version: int) -> int:
    """Calculate guest contract ID from name and major version."""
    return fnv1a_64(f"guest_contract:{name}@{major_version}".encode("utf-8"))


def host_contract_id(name: str, major_version: int) -> int:
    """Calculate host contract ID from name and major version."""
    return fnv1a_64(f"host_contract:{name}@{major_version}".encode("utf-8"))


def bundle_id(name: str) -> int:
    """Compute a bundle ID from its name using FNV-1a 64-bit hash."""
    return fnv1a_64(name.encode("utf-8"))
"#;

/// C# contract-ID / hash helper class merged into the generated Abi.cs namespace.
///
/// Provenance: mirrors the canonical FNV-1a 64-bit scheme implemented in
/// `crates/polyplug_utils/src/{lib,guest_contract_id,host_contract_id,bundle_id}.rs`.
/// Method names are PascalCase to match the C# naming convention validated by
/// `sdk_validator.yaml` (`fnv1a_64` -> `Fnv1a64`, etc.).
const HELPER_CSHARP_HASHING: &str = r#"
/// <summary>
/// FNV-1a 64-bit hashing and contract/bundle ID computation helpers.
/// Mirrors the canonical scheme in crates/polyplug_utils.
/// </summary>
public static class ContractId
{
    private const ulong FnvOffset = 0xCBF29CE484222325UL;
    private const ulong FnvPrime = 0x00000100000001B3UL;

    /// <summary>Compute the FNV-1a 64-bit hash of the UTF-8 bytes of <paramref name="data"/>.</summary>
    public static ulong Fnv1a64(string data)
    {
        ulong hash = FnvOffset;
        foreach (byte b in System.Text.Encoding.UTF8.GetBytes(data))
        {
            hash ^= b;
            hash *= FnvPrime;
        }
        return hash;
    }

    /// <summary>Compute a bundle ID from its name using FNV-1a 64-bit.</summary>
    public static ulong BundleId(string name) => Fnv1a64(name);

    /// <summary>Compute a guest contract ID from name and major version.</summary>
    public static ulong GuestContractId(string name, uint majorVersion) =>
        Fnv1a64($"guest_contract:{name}@{majorVersion}");

    /// <summary>Compute a host contract ID from name and major version.</summary>
    public static ulong HostContractId(string name, uint majorVersion) =>
        Fnv1a64($"host_contract:{name}@{majorVersion}");
}
"#;

/// Lua helper function definitions (function M.* only, no module boilerplate).
/// Merged into abi.lua before `return M`.
const HELPER_LUA: &str = r#"
--- Convert StringView to Lua string.
-- @param sv StringView from polyplug ABI (ffi.cdata), or nil for a null view
-- @return string Lua string (UTF-8), empty string if nil/empty
-- Raises if given anything other than a StringView cdata or nil — most often a
-- Lua string that was already converted (double-conversion), which would
-- otherwise silently yield "" because a Lua string has no `.ptr` field.
-- Raises if the viewed bytes are not valid UTF-8: LuaJIT's ffi.string copies
-- raw bytes without checking, so a readable-but-invalid view is validated here
-- (a manual scan — LuaJIT 5.1 has no utf8 library) and surfaced as an error
-- rather than silently yielding mojibake. The validation is inline because the
-- Lua helper extractor only preserves `function M.*` blocks (no module locals).
function M.to_str(sv)
    if sv == nil then
        return ""
    end
    if type(sv) ~= "cdata" then
        error("polyplug.to_str: expected a StringView cdata (or nil), got a " ..
            type(sv) .. " — did you already convert it to a Lua string? " ..
            "Pass the original StringView, not its to_str() result.", 2)
    end
    if sv.ptr == nil or sv.len == 0 then
        return ""
    end
    local s = ffi.string(sv.ptr, sv.len)
    local i, n = 1, #s
    while i <= n do
        local c = string.byte(s, i)
        if c < 0x80 then
            i = i + 1
        else
            local extra, min_cp, cp
            if c >= 0xC0 and c < 0xE0 then
                extra, min_cp, cp = 1, 0x80, c % 0x20
            elseif c >= 0xE0 and c < 0xF0 then
                extra, min_cp, cp = 2, 0x800, c % 0x10
            elseif c >= 0xF0 and c < 0xF8 then
                extra, min_cp, cp = 3, 0x10000, c % 0x08
            else
                error("polyplug.to_str: StringView contains invalid UTF-8 " ..
                    "(invalid lead byte)", 2)
            end
            if i + extra > n then
                error("polyplug.to_str: StringView contains invalid UTF-8 " ..
                    "(truncated sequence)", 2)
            end
            for k = 1, extra do
                local cc = string.byte(s, i + k)
                if cc < 0x80 or cc >= 0xC0 then
                    error("polyplug.to_str: StringView contains invalid UTF-8 " ..
                        "(bad continuation byte)", 2)
                end
                cp = cp * 0x40 + (cc % 0x40)
            end
            if cp < min_cp or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then
                error("polyplug.to_str: StringView contains invalid UTF-8 " ..
                    "(overlong, surrogate, or out-of-range code point)", 2)
            end
            i = i + extra + 1
        end
    end
    return s
end

--- Check if StringView starts with prefix.
-- @param sv StringView from polyplug ABI
-- @param prefix string Prefix string to check for
-- @return boolean True if the string starts with the prefix
function M.starts_with(sv, prefix)
    local s = M.to_str(sv)
    return s:sub(1, #prefix) == prefix
end

--- Check if StringView ends with suffix.
-- @param sv StringView from polyplug ABI
-- @param suffix string Suffix string to check for
-- @return boolean True if the string ends with the suffix
function M.ends_with(sv, suffix)
    local s = M.to_str(sv)
    if #suffix > #s then
        return false
    end
    return s:sub(-#suffix) == suffix
end

--- Strip prefix from StringView if present.
-- @param sv StringView from polyplug ABI
-- @param prefix string Prefix string to strip
-- @return string String with prefix removed if present, otherwise original
function M.strip_prefix(sv, prefix)
    local s = M.to_str(sv)
    if s:sub(1, #prefix) == prefix then
        return s:sub(#prefix + 1)
    end
    return s
end

--- Split StringView by a literal delimiter, keeping empty segments.
-- The delimiter is matched literally (plain find), never as a Lua pattern.
-- @param sv StringView from polyplug ABI
-- @param delimiter string Literal delimiter string to split by
-- @return table {} for a nil/empty view, { s } for a nil/empty delimiter,
--         otherwise the segments around every occurrence (empties kept)
function M.split(sv, delimiter)
    local s = M.to_str(sv)
    if s == "" then
        return {}
    end
    if delimiter == nil or delimiter == "" then
        return { s }
    end

    local result = {}
    local start = 1
    while true do
        local i, j = string.find(s, delimiter, start, true)
        if i == nil then
            table.insert(result, s:sub(start))
            break
        end
        table.insert(result, s:sub(start, i - 1))
        start = j + 1
    end

    return result
end
"#;

/// JavaScript/TypeScript helper function definitions (no import lines).
/// Merged into abi.ts after generated type definitions.
const HELPER_JS: &str = r#"
/**
 * Convert a StringView to a JavaScript string.
 *
 * Reads the viewed bytes through Deno's FFI pointer view (this abi mirror runs
 * in the Deno host environment) and decodes them as UTF-8.
 * @param sv - The StringView to convert.
 * @returns The decoded string, or empty string for a null/zero-length view.
 * @throws Error when no Deno FFI environment is available — never silently
 *          returns '' for a readable view.
 * @throws TypeError when the viewed bytes are not valid UTF-8 — the fatal
 *          decoder never substitutes U+FFFD for a readable-but-invalid view.
 */
export function stringViewToString(sv: StringView | null | undefined): string {
    if (!sv || sv.ptr === 0n || sv.len === 0) return '';
    const deno = (globalThis as {
        Deno?: {
            UnsafePointer: { create(value: bigint): unknown };
            UnsafePointerView: new (pointer: unknown) => {
                getArrayBuffer(byteLength: number): ArrayBuffer;
            };
        };
    }).Deno;
    if (deno === undefined) {
        throw new Error(
            'stringViewToString: no Deno FFI environment is available to read StringView memory ' +
            '(Deno.UnsafePointerView is required; refusing to silently return an empty string)',
        );
    }
    const pointer: unknown = deno.UnsafePointer.create(sv.ptr);
    if (pointer === null) return '';
    const bytes: ArrayBuffer = new deno.UnsafePointerView(pointer).getArrayBuffer(Number(sv.len));
    return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
}

/**
 * Strip a prefix from a string.
 * @param sv - The input StringView or string.
 * @param prefix - The prefix to strip.
 * @returns The string without prefix, or original if prefix not present.
 */
export function stripPrefix(sv: StringView | string, prefix: string): string {
    const s: string = typeof sv === 'string' ? sv : stringViewToString(sv);
    if (s.startsWith(prefix)) {
        return s.slice(prefix.length);
    }
    return s;
}

/**
 * Check if a string starts with a prefix.
 * @param sv - The input StringView or string.
 * @param prefix - The prefix to check.
 * @returns True if the string starts with the prefix.
 */
export function startsWith(sv: StringView | string, prefix: string): boolean {
    const s: string = typeof sv === 'string' ? sv : stringViewToString(sv);
    return s.startsWith(prefix);
}

/**
 * Check if a string ends with a suffix.
 * @param sv - The input StringView or string.
 * @param suffix - The suffix to check.
 * @returns True if the string ends with the suffix.
 */
export function endsWith(sv: StringView | string, suffix: string): boolean {
    const s: string = typeof sv === 'string' ? sv : stringViewToString(sv);
    return s.endsWith(suffix);
}

/**
 * Convert a StringView to a JavaScript string (shorthand alias).
 * @param sv - The StringView to convert.
 * @returns The JavaScript string, or empty string if null/empty.
 */
export function toStr(sv: StringView | null | undefined): string {
    return stringViewToString(sv);
}

/**
 * Split a string by a literal delimiter, keeping empty segments.
 * @param sv - The input StringView or string.
 * @param delimiter - The literal delimiter to split by.
 * @returns An array of strings: [] for a null/empty input, [s] for an empty delimiter.
 */
export function split(sv: StringView | string, delimiter: string): string[] {
    const s: string = typeof sv === 'string' ? sv : stringViewToString(sv);
    if (s.length === 0) return [];
    if (delimiter.length === 0) return [s];
    return s.split(delimiter);
}

/** FNV-1a 64-bit offset basis (matches polyplug_utils::fnv1a_64). */
const FNV_OFFSET_BASIS_64: bigint = 0xcbf29ce484222325n;
/** FNV-1a 64-bit prime (matches polyplug_utils::fnv1a_64). */
const FNV_PRIME_64: bigint = 0x00000100000001b3n;
/** 64-bit wrap mask applied after every FNV-1a round. */
const U64_WRAP_MASK: bigint = 0xffffffffffffffffn;
/** Shared UTF-8 encoder for hashing string inputs. */
const ID_TEXT_ENCODER: TextEncoder = new TextEncoder();

/**
 * Compute the FNV-1a 64-bit hash of UTF-8 bytes or a string.
 *
 * This is the canonical ID primitive mirrored from `polyplug_utils::fnv1a_64`;
 * `bundleId`, `guestContractId`, and `hostContractId` are all derived from it so
 * every language computes byte-identical identifiers.
 * @param data - The bytes to hash, or a string encoded as UTF-8 first.
 * @returns The 64-bit hash as a bigint.
 */
export function fnv1a64(data: Uint8Array | string): bigint {
    const bytes: Uint8Array = typeof data === 'string' ? ID_TEXT_ENCODER.encode(data) : data;
    let h: bigint = FNV_OFFSET_BASIS_64;
    for (const b of bytes) {
        h = (h ^ BigInt(b)) * FNV_PRIME_64;
        h = h & U64_WRAP_MASK;
    }
    return h;
}

/**
 * Compute a guest contract ID (matches polyplug_utils::guest_contract_id).
 *
 * Guest contract IDs use a distinct prefix to avoid collisions with host contracts.
 * @param name - Contract name (e.g., "pipeline.Decoder").
 * @param majorVersion - Major version number.
 * @returns The 64-bit contract ID as a bigint.
 */
export function guestContractId(name: string, majorVersion: number): bigint {
    return fnv1a64(`guest_contract:${name}@${majorVersion}`);
}

/**
 * Compute a host contract ID (matches polyplug_utils::host_contract_id).
 *
 * Host contract IDs use a distinct prefix to avoid collisions with guest contracts.
 * @param name - Host contract name (must start with "host.", e.g., "host.logger").
 * @param majorVersion - Major version number.
 * @returns The 64-bit host contract ID as a bigint.
 */
export function hostContractId(name: string, majorVersion: number): bigint {
    return fnv1a64(`host_contract:${name}@${majorVersion}`);
}

/**
 * Compute a bundle ID (matches polyplug_utils::bundle_id).
 * @param name - Bundle name.
 * @returns The 64-bit bundle ID as a bigint.
 */
export function bundleId(name: string): bigint {
    return fnv1a64(name);
}
"#;

/// C++ helper function definitions (no #pragma once, no #include directives).
/// Includes namespace wrappers since merge_cpp_helpers appends at end of file
/// and the generated abi.hpp has a closing namespace brace already.
const HELPER_CPP: &str = r#"

namespace polyplug {
namespace abi {

/// Convert StringView to std::string_view (zero-copy).
/// This is the raw byte primitive: it does NOT validate UTF-8 (it is the
/// explicit escape hatch for callers that knowingly want the bytes). Helpers
/// that decode — to_string / to_str / starts_with / ends_with / strip_prefix /
/// split — validate and throw on invalid UTF-8.
inline std::string_view to_string_view(StringView sv) noexcept {
    if (!sv.ptr || sv.len == 0) return {};
    return {reinterpret_cast<const char*>(sv.ptr), sv.len};
}

/// Returns true if every byte of `s` is part of a well-formed UTF-8 sequence
/// (rejecting overlong forms, surrogates, and code points above U+10FFFF) —
/// matching Rust's core::str::from_utf8 strictness. C++ has no standard UTF-8
/// validator, so this scan is the cross-language floor.
inline bool is_valid_utf8(std::string_view s) noexcept {
    size_t i = 0, n = s.size();
    while (i < n) {
        unsigned char c = static_cast<unsigned char>(s[i]);
        if (c < 0x80) { i++; continue; }
        size_t extra;
        unsigned int min_cp, cp;
        if ((c & 0xE0) == 0xC0) { extra = 1; min_cp = 0x80; cp = c & 0x1F; }
        else if ((c & 0xF0) == 0xE0) { extra = 2; min_cp = 0x800; cp = c & 0x0F; }
        else if ((c & 0xF8) == 0xF0) { extra = 3; min_cp = 0x10000; cp = c & 0x07; }
        else { return false; }
        if (i + extra >= n) return false;
        for (size_t k = 1; k <= extra; k++) {
            unsigned char cc = static_cast<unsigned char>(s[i + k]);
            if ((cc & 0xC0) != 0x80) return false;
            cp = (cp << 6) | (cc & 0x3F);
        }
        if (cp < min_cp || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) return false;
        i += extra + 1;
    }
    return true;
}

/// Throws std::runtime_error if `s` is not valid UTF-8. Used by every decoding
/// helper so a readable-but-invalid view surfaces an error instead of mojibake.
inline void require_utf8(std::string_view s) {
    if (!is_valid_utf8(s)) {
        throw std::runtime_error("polyplug: StringView contains invalid UTF-8");
    }
}

/// Convert StringView to std::string (copies data).
/// Throws std::runtime_error if the viewed bytes are not valid UTF-8.
inline std::string to_string(StringView sv) {
    if (!sv.ptr || sv.len == 0) return {};
    std::string_view s = to_string_view(sv);
    require_utf8(s);
    return {s.data(), s.size()};
}

/// Convert StringView to std::string (alias for to_string).
/// Throws std::runtime_error on invalid UTF-8.
inline std::string to_str(StringView sv) {
    return to_string(sv);
}

/// Strip prefix from a string.
/// @param sv The input StringView.
/// @param prefix The prefix to strip.
/// @return std::string_view without prefix if it starts with prefix, otherwise original.
inline std::string_view strip_prefix(StringView sv, std::string_view prefix) {
    auto s = to_string_view(sv);
    require_utf8(s);
    if (s.size() >= prefix.size() && s.substr(0, prefix.size()) == prefix) {
        return s.substr(prefix.size());
    }
    return s;
}

/// Check if string starts with prefix.
/// @param sv The input StringView.
/// @param prefix The prefix to check.
/// @return true if string starts with prefix.
inline bool starts_with(StringView sv, std::string_view prefix) {
    auto s = to_string_view(sv);
    require_utf8(s);
    return s.size() >= prefix.size() && s.substr(0, prefix.size()) == prefix;
}

/// Check if string ends with suffix.
/// @param sv The input StringView.
/// @param suffix The suffix to check.
/// @return true if string ends with suffix.
inline bool ends_with(StringView sv, std::string_view suffix) {
    auto s = to_string_view(sv);
    require_utf8(s);
    if (s.size() < suffix.size()) return false;
    return s.substr(s.size() - suffix.size()) == suffix;
}

/// Split string by a literal delimiter, keeping empty segments.
/// @param sv The input StringView.
/// @param delimiter The literal delimiter string.
/// @return Vector of string_views: {} for a null/empty view, {s} for an empty
///         delimiter, otherwise the segments around every occurrence (empties kept).
inline std::vector<std::string_view> split(StringView sv, std::string_view delimiter) {
    auto s = to_string_view(sv);
    require_utf8(s);
    std::vector<std::string_view> result;
    if (s.empty()) {
        return result;
    }
    if (delimiter.empty()) {
        result.push_back(s);
        return result;
    }

    size_t start = 0;
    while (true) {
        size_t pos = s.find(delimiter, start);
        if (pos == std::string_view::npos) {
            result.push_back(s.substr(start));
            break;
        }
        result.push_back(s.substr(start, pos - start));
        start = pos + delimiter.size();
    }

    return result;
}

/// Create StringView from string literal (borrowed)
inline StringView string_view(const char* s) noexcept {
    return {reinterpret_cast<const uint8_t*>(s), std::strlen(s)};
}

/// Create StringView from std::string (borrowed - ensure string outlives view)
inline StringView string_view(const std::string& s) noexcept {
    return {reinterpret_cast<const uint8_t*>(s.data()), s.size()};
}

/// Create StringView from std::string_view (borrowed)
inline StringView string_view(std::string_view s) noexcept {
    return {reinterpret_cast<const uint8_t*>(s.data()), s.size()};
}

// NOTE: cross-boundary allocation (alloc_string) lives in the guest SDK
// (polyplug::alloc_string in guest.hpp), which routes through the stored
// HostApi. abi.hpp stays pure ABI with no link-time host dependency.

} // namespace abi
} // namespace polyplug
"#;

/// Known struct sizes from Rust layout.
///
/// MAINTENANCE: Update this table when Rust struct layouts change.
/// See polyplug_abi layout tests (test_*_size) for canonical sizes.
/// Each size is verified by `static_assert`/`ctypes.sizeof` in generated SDK files,
/// so a stale table causes layout test failures, not silent corruption.
const KNOWN_SIZES: &[(&str, usize)] = &[
    ("StringView", 16),
    ("Buffer", 24),
    ("CallArena", 40),
    ("ArenaOverflowBlock", 24),
    ("Version", 12),
    ("AbiError", 24),
    ("DependencyInfo", 24),
    ("DispatchMechanisms", 16),
    ("GuestContractInterface", 56),
    ("GuestContractInstance", 16),
    ("HostApi", 184),
    ("HostContractInterface", 80),
    ("HostContractInstance", 8),
    ("GuestContractHandle", 8),
    ("PluginDescriptor", 48),
    ("BundleInitContext", 24),
    ("RuntimeConfig", 48),
    ("ReloadPhase", 48),
    ("NativeDispatch", 16),
    ("VmDispatch", 16),
    ("VmLoaderData", 8),
];

/// Populate `size_hint` fields on `AbiStruct` entries using the known size table.
fn populate_size_hints(abi_types: &mut AbiTypes) {
    for struct_info in &mut abi_types.structs {
        if struct_info.size_hint.is_none() {
            for (name, size) in KNOWN_SIZES {
                if struct_info.name == *name {
                    struct_info.size_hint = Some(*size);
                    break;
                }
            }
        }
    }
}

/// Validate that all field types can be represented in target languages.
///
/// Per D-09: Build fails with clear error if a type cannot be represented.
fn validate_representable_types(abi_types: &AbiTypes) -> Result<(), String> {
    for struct_info in &abi_types.structs {
        for field in &struct_info.fields {
            for pattern in UNREPRESENTABLE_PATTERNS {
                if field.rust_type.contains(pattern) {
                    return Err(format!(
                        "Cannot represent type '{}' field '{}' with type '{}' in target languages. \
                         Consider simplifying the type or adding codegen support.",
                        struct_info.name, field.name, field.rust_type
                    ));
                }
            }
        }
    }
    Ok(())
}

/// Auto-generated file header for each target language.
///
/// Per D-10: Every generated abi.* file starts with a header stating it is
/// auto-generated, where the embedded helper methods come from, and the
/// manual editing policy.
fn generate_auto_header(lang: TargetLang) -> String {
    match lang {
        TargetLang::Python => [
            "# THIS FILE IS AUTO-GENERATED BY polyplug_abi build script.",
            "# DO NOT EDIT STRUCT/FIELD DEFINITIONS.",
            "# Helper methods are embedded by the build script (see crates/polyplug_abi/build/generate.rs).",
            "",
        ]
        .join("\n"),
        TargetLang::CSharp => [
            "// THIS FILE IS AUTO-GENERATED BY polyplug_abi build script.",
            "// DO NOT EDIT STRUCT/FIELD DEFINITIONS.",
            "// Helper methods are embedded by the build script (see crates/polyplug_abi/build/generate.rs).",
            "",
        ]
        .join("\n"),
        TargetLang::Lua => [
            "-- THIS FILE IS AUTO-GENERATED BY polyplug_abi build script.",
            "-- DO NOT EDIT STRUCT/FIELD DEFINITIONS.",
            "-- Helper methods are embedded by the build script (see crates/polyplug_abi/build/generate.rs).",
            "",
        ]
        .join("\n"),
        TargetLang::JavaScript => [
            "// THIS FILE IS AUTO-GENERATED BY polyplug_abi build script.",
            "// DO NOT EDIT STRUCT/FIELD DEFINITIONS.",
            "// Helper methods are embedded by the build script (see crates/polyplug_abi/build/generate.rs).",
            "",
        ]
        .join("\n"),
        TargetLang::Cpp => [
            "// THIS FILE IS AUTO-GENERATED BY polyplug_abi build script.",
            "// DO NOT EDIT STRUCT/FIELD DEFINITIONS.",
            "// Helper methods are embedded by the build script (see crates/polyplug_abi/build/generate.rs).",
            "",
        ]
        .join("\n"),
    }
}

/// Generate SDK for a specific language.
///
/// # Arguments
/// * `lang` - Target language.
/// * `abi_types` - Extracted ABI types.
///
/// # Returns
/// Generated SDK code as a string.
pub fn generate_language_sdk(lang: TargetLang, abi_types: &AbiTypes) -> String {
    let all_items: Vec<Item> = map_all_abi_types(&abi_types.types());

    let generator: Box<dyn CodeGenerator> = match lang {
        TargetLang::Cpp => Box::new(CppGenerator::new()),
        TargetLang::CSharp => Box::new(CSharpGenerator::new()),
        TargetLang::Python => Box::new(PythonGenerator::new()),
        TargetLang::Lua => Box::new(LuaGenerator::new()),
        TargetLang::JavaScript => Box::new(JsGenerator::new()),
    };

    // Map every enum name to its Rust `repr` so generators that reference enum
    // fields by their underlying integer type (Python ctypes) can size them.
    let enum_reprs: std::collections::HashMap<String, String> = all_items
        .iter()
        .filter_map(|item| match item {
            Item::Enum(e) => Some((e.name.clone(), e.repr.clone())),
            _ => None,
        })
        .collect();

    let ctx: GenerationContext = GenerationContext::new().with_enum_reprs(enum_reprs);
    let mut output: String = String::new();

    // Prepend auto-generated header before the codegen header.
    output.push_str(&generate_auto_header(lang));
    output.push_str(&generator.generate_header(&ctx));

    // Languages whose bindings reference types eagerly at definition time
    // (C++ by-value fields, Python ctypes CFUNCTYPE/Structure references)
    // require every referenced aggregate to be defined before use.
    //
    // * C++ emits forward declarations and dependency-sorts definitions.
    // * Python has no forward-declaration mechanism for ctypes, so it relies
    //   solely on dependency-ordered emission.
    let emit_items: Vec<Item> = match lang {
        TargetLang::Cpp => {
            output.push_str(&cpp_forward_declarations(&all_items));
            cpp_dependency_ordered(all_items)
        }
        TargetLang::Python => python_dependency_ordered(all_items),
        TargetLang::Lua => {
            // LuaJIT's cdef parser requires every aggregate to be declared
            // before it is referenced (in a typedef, by value, or by pointer).
            // Emit forward declarations for all aggregates so function-pointer
            // typedefs and pointer fields may reference any type, then
            // dependency-sort the definitions so every by-value field
            // references an already-completed type.
            output.push_str(&lua_forward_declarations(&all_items));
            lua_dependency_ordered(all_items)
        }
        _ => all_items,
    };

    // Lua emits all C declarations inside a single `ffi.cdef[[ ... ]]` block,
    // while constants are plain Lua statements (`M.X = ffi.cast(...)`) that must
    // live OUTSIDE that block. Emit aggregates first, close the cdef block, then
    // emit constants in module scope.
    let lua_consts: &mut Vec<&Item> = &mut Vec::new();

    for item in &emit_items {
        if lang == TargetLang::Lua && matches!(item, Item::Const(_)) {
            lua_consts.push(item);
            continue;
        }
        let code: String = match item {
            Item::Const(c) => generator.generate_const(c, &ctx),
            Item::Struct(s) => generator.generate_struct(s, &ctx),
            Item::Enum(e) => generator.generate_enum(e, &ctx),
            Item::Union(u) => generator.generate_union(u, &ctx),
            // Function items are no longer generated from ABI extraction.
            // The Function variant remains in codegen for use by polyplugc CLI.
            Item::Function(_) => String::new(),
        };
        output.push_str(&code);
    }

    if lang == TargetLang::Lua {
        // Close the ffi.cdef block opened by the header before emitting Lua
        // statements (constants) in module scope.
        output.push_str("]]\n\n");
        for item in lua_consts.iter() {
            if let Item::Const(c) = item {
                output.push_str(&generator.generate_const(c, &ctx));
            }
        }
        output.push('\n');
    }

    output.push_str(&generator.generate_footer(&ctx));
    output
}

/// Emit C++ forward declarations for every struct, union, and enum item.
///
/// Forward declarations resolve all pointer and function-pointer references,
/// leaving only by-value field dependencies for `cpp_dependency_ordered` to
/// satisfy via emission order.
fn cpp_forward_declarations(items: &[Item]) -> String {
    let mut output = String::from("// ─── Forward declarations ───\n");
    for item in items {
        let decl = match item {
            Item::Struct(s) => CppGenerator::forward_declaration(&s.name, ForwardKind::Struct),
            Item::Union(u) => CppGenerator::forward_declaration(&u.name, ForwardKind::Union),
            Item::Enum(e) => {
                CppGenerator::forward_declaration(&e.name, ForwardKind::Enum(e.repr.clone()))
            }
            Item::Const(_) | Item::Function(_) => continue,
        };
        output.push_str(&decl);
    }
    output.push('\n');
    output
}

/// Emit LuaJIT-cdef forward declarations for every struct, union, and enum.
///
/// LuaJIT's cdef parser is not lazy: a type must be declared before it is named
/// in a typedef, by value, or by pointer. A forward `typedef struct X X;` (and
/// the enum/union equivalents) declares the tag and aliases it so any later
/// reference resolves, and the subsequent combined `typedef struct X { ... } X;`
/// completes the type without conflict.
fn lua_forward_declarations(items: &[Item]) -> String {
    let mut output = String::from("    // ─── Forward declarations ───\n");
    for item in items {
        let decl: String = match item {
            Item::Struct(s) => format!("    typedef struct {} {};\n", s.name, s.name),
            Item::Union(u) => format!("    typedef union {} {};\n", u.name, u.name),
            Item::Enum(e) => format!("    typedef enum {} {};\n", e.name, e.name),
            Item::Const(_) | Item::Function(_) => continue,
        };
        output.push_str(&decl);
    }
    output.push('\n');
    output
}

/// Order LuaJIT-cdef items so every by-value field references an
/// already-completed type.
///
/// Forward declarations (emitted by `lua_forward_declarations`) resolve all
/// pointer and function-pointer references, leaving only by-value struct,
/// union, and enum fields to satisfy via emission order. Constants and
/// definitions with satisfied dependencies keep their relative source order.
fn lua_dependency_ordered(items: Vec<Item>) -> Vec<Item> {
    use std::collections::HashSet;

    // Aggregates that can complete a by-value dependency: structs, unions, and
    // enums (an enum field needs its size, i.e. its definition, first).
    let aggregate_names: HashSet<String> = items
        .iter()
        .filter_map(|item| match item {
            Item::Struct(s) => Some(s.name.clone()),
            Item::Union(u) => Some(u.name.clone()),
            Item::Enum(e) => Some(e.name.clone()),
            _ => None,
        })
        .collect();

    let dependencies = |item: &Item| -> Vec<String> {
        let field_types: Vec<&str> = match item {
            Item::Struct(s) => s.fields.iter().map(|f| f.rust_type.as_str()).collect(),
            Item::Union(u) => u.variants.iter().map(|v| v.type_name.as_str()).collect(),
            _ => Vec::new(),
        };
        field_types
            .iter()
            .filter_map(|rust_type| LuaGenerator::value_dependency(rust_type))
            .filter(|dep| aggregate_names.contains(dep))
            .collect()
    };

    let mut ordered: Vec<Item> = Vec::with_capacity(items.len());
    let mut emitted: HashSet<String> = HashSet::new();
    let mut pending: Vec<Item> = items;

    loop {
        let mut progressed = false;
        let mut next_pending: Vec<Item> = Vec::new();

        for item in pending {
            let name: Option<String> = match &item {
                Item::Struct(s) => Some(s.name.clone()),
                Item::Union(u) => Some(u.name.clone()),
                Item::Enum(e) => Some(e.name.clone()),
                _ => None,
            };

            let ready: bool = dependencies(&item).iter().all(|dep| emitted.contains(dep));
            if ready {
                if let Some(name) = name {
                    emitted.insert(name);
                }
                ordered.push(item);
                progressed = true;
            } else {
                next_pending.push(item);
            }
        }

        if next_pending.is_empty() {
            break;
        }
        if !progressed {
            // A dependency cycle (or unresolved dependency) remains. Emit the
            // rest in source order rather than dropping items.
            ordered.extend(next_pending);
            break;
        }
        pending = next_pending;
    }

    ordered
}

/// Order C++ items so that every by-value field dependency is defined before
/// the struct or union that uses it.
///
/// Enums and constants carry no aggregate dependencies and keep their relative
/// order. Structs and unions are topologically sorted by their by-value field
/// dependencies (resolved via `CppGenerator::value_dependency`).
fn cpp_dependency_ordered(items: Vec<Item>) -> Vec<Item> {
    use std::collections::HashSet;

    // Names of aggregates whose definitions still need to be emitted.
    let aggregate_names: HashSet<String> = items
        .iter()
        .filter_map(|item| match item {
            Item::Struct(s) => Some(s.name.clone()),
            Item::Union(u) => Some(u.name.clone()),
            _ => None,
        })
        .collect();

    // By-value dependencies for each struct/union, restricted to aggregates we
    // are emitting (enums are satisfied by their forward declaration).
    let dependencies = |item: &Item| -> Vec<String> {
        let fields: Vec<&str> = match item {
            Item::Struct(s) => s.fields.iter().map(|f| f.rust_type.as_str()).collect(),
            Item::Union(u) => u.variants.iter().map(|v| v.type_name.as_str()).collect(),
            _ => Vec::new(),
        };
        fields
            .iter()
            .filter_map(|rust_type| CppGenerator::value_dependency(rust_type))
            .filter(|dep| aggregate_names.contains(dep))
            .collect()
    };

    let mut ordered: Vec<Item> = Vec::with_capacity(items.len());
    let mut emitted: HashSet<String> = HashSet::new();
    let mut pending: Vec<Item> = items;

    // Stable topological emission: repeatedly emit every item whose aggregate
    // dependencies are already emitted. Non-aggregate items and aggregates with
    // satisfied dependencies flush in source order each pass.
    loop {
        let mut progressed = false;
        let mut next_pending: Vec<Item> = Vec::new();

        for item in pending {
            let name = match &item {
                Item::Struct(s) => Some(s.name.clone()),
                Item::Union(u) => Some(u.name.clone()),
                _ => None,
            };

            let ready = dependencies(&item).iter().all(|dep| emitted.contains(dep));
            if ready {
                if let Some(name) = name {
                    emitted.insert(name);
                }
                ordered.push(item);
                progressed = true;
            } else {
                next_pending.push(item);
            }
        }

        if next_pending.is_empty() {
            break;
        }
        if !progressed {
            // A dependency cycle (or unresolved dependency) remains. Emit the
            // rest in source order rather than dropping items.
            ordered.extend(next_pending);
            break;
        }
        pending = next_pending;
    }

    ordered
}

/// Order Python items so that every name referenced eagerly by ctypes is
/// defined before use.
///
/// Python's ctypes has no forward-declaration mechanism: a `Structure`
/// `_fields_` entry referencing another aggregate, and a `CFUNCTYPE` typedef
/// referencing its return/parameter types, all evaluate those names at
/// definition time. Constants carry no dependencies and keep their relative
/// order. Structs, enums, and unions are topologically sorted by the named
/// aggregates they reference by value (resolved via
/// `PythonGenerator::type_dependencies`). Pointer fields impose no constraint.
fn python_dependency_ordered(items: Vec<Item>) -> Vec<Item> {
    use std::collections::HashSet;

    let aggregate_names: HashSet<String> = items
        .iter()
        .filter_map(|item| match item {
            Item::Struct(s) => Some(s.name.clone()),
            Item::Enum(e) => Some(e.name.clone()),
            Item::Union(u) => Some(u.name.clone()),
            _ => None,
        })
        .collect();

    let dependencies = |item: &Item| -> Vec<String> {
        let field_types: Vec<&str> = match item {
            Item::Struct(s) => s.fields.iter().map(|f| f.rust_type.as_str()).collect(),
            Item::Union(u) => u.variants.iter().map(|v| v.type_name.as_str()).collect(),
            _ => Vec::new(),
        };
        field_types
            .iter()
            .flat_map(|rust_type| PythonGenerator::type_dependencies(rust_type))
            .filter(|dep| aggregate_names.contains(dep))
            .collect()
    };

    let mut ordered: Vec<Item> = Vec::with_capacity(items.len());
    let mut emitted: HashSet<String> = HashSet::new();
    let mut pending: Vec<Item> = items;

    // Stable topological emission: repeatedly emit every item whose aggregate
    // dependencies are already emitted. Constants and aggregates with satisfied
    // dependencies flush in source order each pass.
    loop {
        let mut progressed = false;
        let mut next_pending: Vec<Item> = Vec::new();

        for item in pending {
            let name: Option<String> = match &item {
                Item::Struct(s) => Some(s.name.clone()),
                Item::Enum(e) => Some(e.name.clone()),
                Item::Union(u) => Some(u.name.clone()),
                _ => None,
            };

            let ready: bool = dependencies(&item).iter().all(|dep| emitted.contains(dep));
            if ready {
                if let Some(name) = name {
                    emitted.insert(name);
                }
                ordered.push(item);
                progressed = true;
            } else {
                next_pending.push(item);
            }
        }

        if next_pending.is_empty() {
            break;
        }
        if !progressed {
            // A dependency cycle (or unresolved dependency) remains. Emit the
            // rest in source order rather than dropping items.
            ordered.extend(next_pending);
            break;
        }
        pending = next_pending;
    }

    ordered
}

impl TargetLang {
    /// Return files in the abi directory that should be deleted before regeneration
    /// (the generated abi.* file itself).
    fn generated_filenames(&self) -> Vec<&'static str> {
        vec![self.output_filename()]
    }
}

/// Return inline helper method content for a given language.
///
/// Per D-12: Helper methods are embedded as const strings so they survive
/// across consecutive rebuilds without relying on external helper files.
fn get_inline_helpers(lang: TargetLang) -> Vec<(String, String)> {
    match lang {
        TargetLang::CSharp => vec![
            (
                "StringViewHelper.cs".to_string(),
                HELPER_CSHARP_STRING_VIEW.to_string(),
            ),
            ("Hashing.cs".to_string(), HELPER_CSHARP_HASHING.to_string()),
        ],
        TargetLang::Lua => vec![
            ("string_view_helper.lua".to_string(), HELPER_LUA.to_string()),
            ("hashing.lua".to_string(), HELPER_LUA_HASHING.to_string()),
        ],
        TargetLang::JavaScript => {
            vec![("string_view_helper.ts".to_string(), HELPER_JS.to_string())]
        }
        TargetLang::Cpp => vec![("string_view_helper.hpp".to_string(), HELPER_CPP.to_string())],
        TargetLang::Python => vec![("hashing.py".to_string(), HELPER_PYTHON_HASHING.to_string())],
    }
}

/// Delete old generated abi.* files before writing fresh ones.
///
/// Per D-11: Delete all broken/old abi.* files before codegen writes fresh ones.
/// Helper files are NOT deleted here -- they are consumed by the merge step.
fn delete_old_generated_files(lang: TargetLang, abi_dir: &Path) {
    for filename in lang.generated_filenames() {
        let path = abi_dir.join(filename);
        if path.exists() {
            if let Err(e) = fs::remove_file(&path) {
                println!(
                    "cargo:warning=Failed to delete old file {}: {}",
                    path.display(),
                    e
                );
            }
        }
    }
}

/// Strip the auto-generated header from helper file contents.
///
/// Helper files may have their own "AUTO-GENERATED" headers that should be
/// removed when merging, since the merged file has its own header.
fn strip_auto_generated_header(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let mut start = 0;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("// THIS FILE IS AUTO-GENERATED")
            || trimmed.starts_with("-- THIS FILE IS AUTO-GENERATED")
            || trimmed.starts_with("# THIS FILE IS AUTO-GENERATED")
            || trimmed.starts_with("// DO NOT EDIT")
            || trimmed.starts_with("-- DO NOT EDIT")
            || trimmed.starts_with("# DO NOT EDIT")
            || (trimmed.is_empty() && start == i)
        {
            start = i + 1;
            continue;
        }
        // Stop stripping once we hit real content (non-header lines).
        if !trimmed.is_empty()
            && !trimmed.starts_with("///")
            && !trimmed.starts_with("/**")
            && !trimmed.starts_with("// @")
            && !trimmed.starts_with("-- @")
            && !trimmed.starts_with("* @")
            && !trimmed.starts_with(" *")
        {
            break;
        }
    }
    lines[start..].join("\n")
}

/// Extract method/function bodies from a Lua helper file using regex.
///
/// Per D-14 research: ast-grep has limited Lua support, so we use a simple
/// regex-based extractor for Lua helper files. Looks for `function` patterns
/// that define methods on the module table.
fn extract_lua_helper_methods(content: &str) -> String {
    let mut methods = Vec::new();
    let mut in_function = false;
    let mut depth = 0;
    let mut current = String::new();

    for line in content.lines() {
        if !in_function {
            // Detect function start: `function M.name(...)` or `function M.name(`
            let trimmed = line.trim();
            if trimmed.starts_with("function M.") || trimmed.starts_with("function M ") {
                in_function = true;
                depth = 0;
                current.clear();
                current.push_str(line);
                current.push('\n');
                // Count opening/closing keywords for depth tracking
                depth += count_lua_openers(trimmed);
            }
        } else {
            current.push_str(line);
            current.push('\n');
            let trimmed = line.trim();
            depth += count_lua_openers(trimmed);
            if trimmed == "end" || trimmed.starts_with("end ") || trimmed.starts_with("end--") {
                depth = depth.saturating_sub(1);
            }
            if depth == 0 {
                methods.push(current.trim().to_string());
                current.clear();
                in_function = false;
            }
        }
    }

    if in_function && !current.trim().is_empty() {
        methods.push(current.trim().to_string());
    }

    methods.join("\n\n")
}

/// Count Lua block-opening keywords in a line.
///
/// # Limitations
/// Only tracks keywords at the start of a line (`starts_with`). Nested constructs
/// where keywords appear mid-line are not tracked. This is sufficient for the
/// inline helper methods in `HELPER_LUA`, which are simple top-level functions.
fn count_lua_openers(line: &str) -> i32 {
    let mut count = 0i32;
    let trimmed = line.trim();
    if trimmed.starts_with("function ") || trimmed.starts_with("function(") {
        count += 1;
    }
    if trimmed.starts_with("if ") || trimmed == "if" {
        count += 1;
    }
    if trimmed.starts_with("for ") || trimmed == "for" {
        count += 1;
    }
    if trimmed.starts_with("while ") || trimmed == "while" {
        count += 1;
    }
    // `end` at EOL doesn't count as opener, but `then` is part of `if`
    if trimmed.contains(" do") || trimmed.ends_with(" do") {
        count += 1;
    }
    if trimmed.contains(" then") || trimmed.ends_with(" then") {
        // `if ... then` already counted above, but elseif needs extra
    }
    count
}

/// Merge helper file contents into the generated code for a specific language.
///
/// Per D-12: Helper files (StringViewHelper.cs, string_view_helper.lua, etc.)
/// merge into abi.* files. The helper methods are appended at the end of the
/// generated file in a language-appropriate location.
fn merge_helpers_into_generated(
    lang: TargetLang,
    generated_code: &str,
    helpers: &[(String, String)],
) -> String {
    if helpers.is_empty() {
        return generated_code.to_string();
    }

    match lang {
        TargetLang::CSharp => merge_csharp_helpers(generated_code, helpers),
        TargetLang::Lua => merge_lua_helpers(generated_code, helpers),
        TargetLang::JavaScript => merge_js_helpers(generated_code, helpers),
        TargetLang::Cpp => merge_cpp_helpers(generated_code, helpers),
        TargetLang::Python => merge_python_helpers(generated_code, helpers),
    }
}

/// Merge Python helper functions into the generated abi.py.
///
/// The helper content is module-level Python (constants + functions). It is
/// appended after the generated type definitions; import lines are stripped
/// because all required imports already live at the top of the generated file.
fn merge_python_helpers(generated_code: &str, helpers: &[(String, String)]) -> String {
    let mut result: String = generated_code.to_string();
    result.push_str("\n\n# ─── Helper Methods (embedded by the build script) ───\n");

    for (_filename, contents) in helpers {
        let cleaned: String = strip_auto_generated_header(contents);
        let trimmed: &str = cleaned.trim();
        if trimmed.is_empty() {
            continue;
        }
        let body: String = trimmed
            .lines()
            .filter(|line| {
                let lt: &str = line.trim();
                !lt.starts_with("import ") && !lt.starts_with("from ")
            })
            .collect::<Vec<&str>>()
            .join("\n");
        result.push('\n');
        result.push_str(&body);
        result.push('\n');
    }

    result
}

/// Merge C# helper classes into the generated Abi.cs namespace.
///
/// The helper content contains static classes like StringViewHelper and PinnedUtf8.
/// They are appended inside the namespace block before the closing brace.
fn merge_csharp_helpers(generated_code: &str, helpers: &[(String, String)]) -> String {
    let mut merged = generated_code.to_string();

    // Find the last closing brace of the namespace block.
    // C# generated code ends with "}\n" for the namespace.
    if let Some(pos) = merged.rfind('}') {
        let mut helper_block =
            String::from("\n// ─── Helper Methods (embedded by the build script) ───\n\n");

        for (_filename, contents) in helpers {
            let cleaned = strip_auto_generated_header(contents);
            let trimmed = cleaned.trim();
            if !trimmed.is_empty() {
                // The helper classes use `namespace Polyplug.Abi;` or
                // `namespace Polyplug.Abi` with braces. We need to strip
                // the namespace wrapper and `using` statements that are
                // already in the generated file.
                let body = extract_csharp_class_body(trimmed);
                helper_block.push_str(&body);
                helper_block.push('\n');
            }
        }

        merged.insert_str(pos, &helper_block);
    }

    merged
}

/// Extract the class/struct body from a C# helper file, removing namespace
/// wrappers and using statements that duplicate the generated file.
fn extract_csharp_class_body(content: &str) -> String {
    let mut result = String::new();
    let mut in_namespace_brace = false;
    let mut brace_depth = 0;
    let mut skip_block = false;
    let mut using_lines = String::new();

    for line in content.lines() {
        let trimmed = line.trim();

        // Collect using statements separately.
        if trimmed.starts_with("using ") && !in_namespace_brace {
            // Only include usings not already in generated code
            if !trimmed.contains("System.Runtime.InteropServices")
                && !trimmed.contains("System.Text")
            {
                using_lines.push_str(line);
                using_lines.push('\n');
            }
            continue;
        }

        // Skip namespace declaration lines.
        if trimmed.starts_with("namespace ") {
            if trimmed.ends_with('{') {
                in_namespace_brace = true;
                brace_depth = 1;
            }
            // file-scoped namespace (ends with ;) -- skip, body follows
            continue;
        }

        if in_namespace_brace {
            // Count braces to find end of namespace
            for ch in line.chars() {
                match ch {
                    '{' => brace_depth += 1,
                    '}' => {
                        brace_depth -= 1;
                        if brace_depth == 0 {
                            in_namespace_brace = false;
                            skip_block = true;
                        }
                    }
                    _ => {}
                }
            }
            if skip_block {
                skip_block = false;
                continue;
            }
        }

        // Skip empty lines at start of content (before class definition)
        if result.is_empty() && trimmed.is_empty() {
            continue;
        }

        result.push_str(line);
        result.push('\n');
    }

    let body = result.trim();
    if body.is_empty() {
        return String::new();
    }

    // Prepend any extra using statements needed by helpers
    if using_lines.trim().is_empty() {
        body.to_string()
    } else {
        format!("{}\n{}", using_lines.trim(), body)
    }
}

/// Merge Lua helper functions into the generated abi.lua module.
///
/// The generated abi.lua has structure:
///   local ffi = require("ffi")
///   local M = {}
///   <ffi.cdef typedefs>
///   M.CONST = value
///   return M
///
/// Helper functions like `function M.to_str(sv)` are appended before `return M`.
fn merge_lua_helpers(generated_code: &str, helpers: &[(String, String)]) -> String {
    let mut helper_block = String::new();
    helper_block.push_str("\n-- ─── Helper Methods (embedded by the build script) ───\n\n");

    for (_filename, contents) in helpers {
        let cleaned = strip_auto_generated_header(contents);
        // Extract only the function definitions (skip module boilerplate)
        let methods = extract_lua_helper_methods(&cleaned);
        if !methods.trim().is_empty() {
            helper_block.push_str(&methods);
            helper_block.push_str("\n\n");
        }
    }

    // Insert before "return M" at the end
    if let Some(pos) = generated_code.rfind("return M") {
        let mut result = generated_code[..pos].to_string();
        result.push_str(&helper_block);
        result.push_str("return M\n");
        result
    } else {
        let mut result = generated_code.to_string();
        result.push_str(&helper_block);
        result
    }
}

/// Merge JS/TS helper functions into the generated abi.ts.
///
/// The helper file contains exported functions that are appended after
/// the generated type definitions and constants.
fn merge_js_helpers(generated_code: &str, helpers: &[(String, String)]) -> String {
    let mut result = generated_code.to_string();
    result.push_str("\n// ─── Helper Methods (embedded by the build script) ───\n\n");

    for (_filename, contents) in helpers {
        let cleaned = strip_auto_generated_header(contents);
        let trimmed = cleaned.trim();
        if !trimmed.is_empty() {
            // Strip import lines since types are in the same file now
            let body: String = trimmed
                .lines()
                .filter(|line| {
                    let lt = line.trim();
                    !lt.starts_with("import ")
                })
                .collect::<Vec<&str>>()
                .join("\n");
            result.push_str(&body);
            result.push_str("\n\n");
        }
    }

    result
}

/// Merge C++ helper functions into the generated abi.hpp.
///
/// The helper file contains inline functions in the polyplug::abi namespace.
/// They are appended at the end of the generated header, inside the namespace.
fn merge_cpp_helpers(generated_code: &str, helpers: &[(String, String)]) -> String {
    let mut result = generated_code.to_string();
    result.push_str("\n// ─── Helper Methods (embedded by the build script) ───\n");

    for (_filename, contents) in helpers {
        let cleaned = strip_auto_generated_header(contents);
        let trimmed = cleaned.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Strip include directives and pragma once (already in generated file)
        let body: String = trimmed
            .lines()
            .filter(|line| {
                let lt = line.trim();
                !lt.starts_with("#pragma once")
                    && !lt.starts_with("#include \"abi.hpp\"")
                    && !lt.starts_with("#include <cstring>")
                    && !lt.starts_with("#include <string>")
                    && !lt.starts_with("#include <string_view>")
                    && !lt.starts_with("#include <vector>")
            })
            .collect::<Vec<&str>>()
            .join("\n");

        result.push_str(&body);
        result.push('\n');
    }

    result
}

/// Generate all SDKs and write to sdks/{lang}/abi/.
///
/// # Arguments
/// * `abi_types` - Extracted ABI types (will be mutated to populate size hints).
/// * `workspace_root` - Path to the workspace root directory.
/// * `tracked_files` - Source files to emit `cargo:rerun-if-changed` for.
///
/// # Returns
/// Result indicating success or failure.
pub fn generate_all_sdks(
    abi_types: &mut AbiTypes,
    workspace_root: &Path,
    tracked_files: &[PathBuf],
) -> Result<(), Box<dyn std::error::Error>> {
    // Populate size hints from known size table.
    populate_size_hints(abi_types);

    // Validate that all types can be represented in target languages (D-09).
    validate_representable_types(abi_types)
        .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;

    // Emit cargo:rerun-if-changed for all tracked source files.
    for path in tracked_files {
        println!("cargo:rerun-if-changed={}", path.display());
    }

    let languages: [TargetLang; 5] = [
        TargetLang::Cpp,
        TargetLang::CSharp,
        TargetLang::Python,
        TargetLang::Lua,
        TargetLang::JavaScript,
    ];

    for lang in languages {
        let abi_dir: PathBuf = workspace_root
            .join("sdks")
            .join(lang.language_name())
            .join("abi");

        // ── Step 1: Get inline helper method content (D-12) ──
        let helpers = get_inline_helpers(lang);

        // ── Step 2: Delete old generated abi.* files (D-11) ──
        delete_old_generated_files(lang, &abi_dir);

        // ── Step 3: Generate fresh code ──
        let mut sdk: String = generate_language_sdk(lang, abi_types);

        // ── Step 4: Merge helper methods into generated output (D-12) ──
        sdk = merge_helpers_into_generated(lang, &sdk, &helpers);

        let output_path: PathBuf = if lang.subdir().is_empty() {
            abi_dir.join(lang.output_filename())
        } else {
            abi_dir.join(lang.subdir()).join(lang.output_filename())
        };

        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent)?;
        }

        fs::write(&output_path, sdk)?;
    }

    // Generate layout test source files per D-31.
    generate_layout_tests(abi_types, workspace_root)?;

    Ok(())
}

/// Generate layout test source files for all SDK languages per D-31.
///
/// Per D-32: Only generates test source files. Test scaffolding (project files,
/// conftest) must be created manually per SDK.
fn generate_layout_tests(
    abi_types: &AbiTypes,
    workspace_root: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    // Collect structs with known sizes.
    let sized_structs: Vec<(&str, usize)> = abi_types
        .structs
        .iter()
        .filter_map(|s| s.size_hint.map(|size| (s.name.as_str(), size)))
        .collect();

    if sized_structs.is_empty() {
        return Ok(());
    }

    // Python: test_layout.py with pytest assertions.
    let python_tests = generate_python_layout_tests(&sized_structs);
    let python_dir = workspace_root.join("sdks/python/abi");
    std::fs::create_dir_all(&python_dir)?;
    std::fs::write(python_dir.join("test_layout.py"), python_tests)?;

    // C#: LayoutTests.cs with xUnit. Written to the dedicated test project so
    // the shipped Polyplug.Abi library does not glob-compile an xunit-dependent file.
    let csharp_tests = generate_csharp_layout_tests(&sized_structs);
    let csharp_dir = workspace_root.join("sdks/csharp/abi.tests");
    std::fs::create_dir_all(&csharp_dir)?;
    std::fs::write(csharp_dir.join("LayoutTests.cs"), csharp_tests)?;

    // Lua: test_layout.lua with simple assertions.
    let lua_tests = generate_lua_layout_tests(&sized_structs);
    let lua_dir = workspace_root.join("sdks/lua/abi");
    std::fs::create_dir_all(&lua_dir)?;
    std::fs::write(lua_dir.join("test_layout.lua"), lua_tests)?;

    // JS: test_layout.ts with Deno.test.
    let js_tests = generate_js_layout_tests(&sized_structs);
    let js_dir = workspace_root.join("sdks/js/abi");
    std::fs::create_dir_all(&js_dir)?;
    std::fs::write(js_dir.join("test_layout.ts"), js_tests)?;

    // C++: test_layout.cpp with static_assert.
    let cpp_tests = generate_cpp_layout_tests(&sized_structs);
    let cpp_dir = workspace_root.join("sdks/cpp/abi");
    std::fs::create_dir_all(&cpp_dir)?;
    std::fs::write(cpp_dir.join("test_layout.cpp"), cpp_tests)?;

    Ok(())
}

/// Generate Python layout test file content.
fn generate_python_layout_tests(sized_structs: &[(&str, usize)]) -> String {
    let mut output = String::new();
    output.push_str("# Layout tests for polyplug ABI structs.\n");
    output.push_str("# AUTO-GENERATED by polyplug_abi build script — do not edit.\n\n");
    output.push_str("import ctypes\n\n");

    // Import all structs from the generated abi module.
    output.push_str("from abi import (\n");
    for (name, _) in sized_structs {
        output.push_str(&format!("    {},\n", name));
    }
    output.push_str(")\n\n\n");

    for (name, size) in sized_structs {
        let test_name = to_snake_case(name);
        output.push_str(&format!(
            "def test_{}_size():\n    assert ctypes.sizeof({}) == {}, \
             f\"{} expected {} bytes, got {{ctypes.sizeof({})}}\"\n\n\n",
            test_name, name, size, name, size, name
        ));
    }

    output
}

/// Generate C# layout test file content.
fn generate_csharp_layout_tests(sized_structs: &[(&str, usize)]) -> String {
    let mut output = String::new();
    output.push_str("// Layout tests for polyplug ABI structs.\n");
    output.push_str("// AUTO-GENERATED by polyplug_abi build script — do not edit.\n\n");
    output.push_str("using System.Runtime.InteropServices;\n");
    output.push_str("using Xunit;\n\n");
    output.push_str("namespace Polyplug.Abi.Tests\n{\n");
    output.push_str("    public class LayoutTests\n    {\n");

    for (name, size) in sized_structs {
        let test_name = format!("{}Is{}Bytes", name, size);
        output.push_str(&format!(
            "        [Fact]\n        public void {}() => \
             Assert.Equal({}, Marshal.SizeOf<{}>());\n\n",
            test_name, size, name
        ));
    }

    // Field OFFSET asserts for the frozen tail of HostApi and the logging
    // fields of RuntimeConfig. Size-only asserts cannot catch a transposed
    // or dropped field that another field's padding silently compensates
    // for; these offsets are frozen ABI (see CLAUDE.md: unload_bundle @136,
    // log @144, create_guest_instance @152, destroy_guest_instance @160,
    // reserved @176; RuntimeConfig log @24, log_user_data @32,
    // log_max_level @40).
    let offset_asserts: [(&str, &str, usize); 8] = [
        ("HostApi", "UnloadBundle", 136),
        ("HostApi", "Log", 144),
        ("HostApi", "CreateGuestInstance", 152),
        ("HostApi", "DestroyGuestInstance", 160),
        ("HostApi", "Reserved", 176),
        ("RuntimeConfig", "Log", 24),
        ("RuntimeConfig", "LogUserData", 32),
        ("RuntimeConfig", "LogMaxLevel", 40),
    ];
    for (struct_name, field, offset) in offset_asserts {
        output.push_str(&format!(
            "        [Fact]\n        public void {struct_name}{field}AtOffset{offset}() => \
             Assert.Equal((nint){offset}, Marshal.OffsetOf<{struct_name}>(nameof({struct_name}.{field})));\n\n",
        ));
    }

    output.push_str("    }\n}\n");
    output
}

/// Generate Lua layout test file content.
fn generate_lua_layout_tests(sized_structs: &[(&str, usize)]) -> String {
    let mut output = String::new();
    output.push_str("-- Layout tests for polyplug ABI structs.\n");
    output.push_str("-- AUTO-GENERATED by polyplug_abi build script — do not edit.\n\n");
    // Resolve sibling modules (abi.lua) when run standalone from any directory,
    // then load abi.lua so its `ffi.cdef` struct declarations are registered
    // before `ffi.sizeof` is called. Without this, `ffi.sizeof("NativeDispatch")`
    // fails with "declaration specifier expected" — the types are undeclared.
    output.push_str(
        "local script_dir = (arg and arg[0] or \"\"):match(\"^(.*[/\\\\])\") or \"./\"\n",
    );
    output.push_str("package.path = script_dir .. \"?.lua;\" .. package.path\n");
    output.push_str("local ffi = require(\"ffi\")\n");
    output.push_str("require(\"abi\")\n\n");

    for (name, size) in sized_structs {
        output.push_str(&format!(
            "assert(ffi.sizeof(\"{}\") == {}, \"{} size mismatch\")\n",
            name, size, name
        ));
    }

    output.push_str("\nprint(\"All layout tests passed!\")\n");
    output
}

/// Generate JS/TS layout test file content.
fn generate_js_layout_tests(sized_structs: &[(&str, usize)]) -> String {
    let mut output = String::new();
    output.push_str("// Layout tests for polyplug ABI structs.\n");
    output.push_str("// AUTO-GENERATED by polyplug_abi build script — do not edit.\n\n");
    output.push_str("import {\n");
    for (name, _) in sized_structs {
        output.push_str(&format!(
            "    {}_SIZE,\n",
            to_upper_snake_case_for_generate(name)
        ));
    }
    output.push_str("} from \"./abi.ts\";\n");
    output.push_str("import { assert } from \"jsr:@std/assert\";\n\n");

    for (name, size) in sized_structs {
        let const_name = format!("{}_SIZE", to_upper_snake_case_for_generate(name));
        output.push_str(&format!(
            "Deno.test(\"{} is {} bytes\", () => {{\n    assert({} === {});\n}});\n\n",
            name, size, const_name, size
        ));
    }

    output
}

/// Generate C++ layout test file content.
fn generate_cpp_layout_tests(sized_structs: &[(&str, usize)]) -> String {
    let mut output = String::new();
    output.push_str("// Layout tests for polyplug ABI structs.\n");
    output.push_str("// AUTO-GENERATED by polyplug_abi build script — do not edit.\n\n");
    output.push_str("#include \"polyplug/abi.hpp\"\n\n");

    for (name, size) in sized_structs {
        output.push_str(&format!(
            "static_assert(sizeof({}) == {}, \"{} size mismatch\");\n",
            name, size, name
        ));
    }

    output
}

/// Convert PascalCase to snake_case.
fn to_snake_case(s: &str) -> String {
    let mut result = String::new();
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_ascii_lowercase());
        } else {
            result.push(c);
        }
    }
    result
}

/// Convert PascalCase to UPPER_SNAKE_CASE for JS constants.
///
/// Handles consecutive uppercase letters correctly:
/// `AbiError` -> `ABI_ERROR`, not `A_B_I_E_R_R_O_R`.
fn to_upper_snake_case_for_generate(s: &str) -> String {
    let mut result = String::new();
    let chars: Vec<char> = s.chars().collect();
    for (i, c) in chars.iter().enumerate() {
        if c.is_uppercase() {
            // Insert underscore at boundaries:
            // - Before uppercase if previous was lowercase (e.g., `aB` -> `a_B`)
            // - Before uppercase if next is lowercase and we have a run of uppercase
            //   (e.g., `ABIError` -> `ABI_Error`)
            if i > 0 {
                let prev = chars[i - 1];
                if prev.is_ascii_lowercase()
                    || (prev.is_uppercase()
                        && i + 1 < chars.len()
                        && chars[i + 1].is_ascii_lowercase())
                {
                    result.push('_');
                }
            }
            result.push(*c);
        } else {
            result.push(c.to_ascii_uppercase());
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::build::types::{AbiConst, AbiStruct};

    #[test]
    fn test_target_lang_language_name() {
        assert_eq!(TargetLang::Cpp.language_name(), "cpp");
        assert_eq!(TargetLang::CSharp.language_name(), "csharp");
        assert_eq!(TargetLang::Python.language_name(), "python");
        assert_eq!(TargetLang::Lua.language_name(), "lua");
        assert_eq!(TargetLang::JavaScript.language_name(), "js");
    }

    #[test]
    fn test_generate_language_sdk_cpp() {
        let mut abi_types: AbiTypes = AbiTypes::new();
        abi_types.add_const(AbiConst {
            name: String::from("TEST_CONST"),
            rust_type: String::from("u32"),
            value: String::from("42"),
            doc: Some(String::from("Test constant.")),
        });

        let sdk: String = generate_language_sdk(TargetLang::Cpp, &abi_types);

        assert!(sdk.contains("#pragma once"));
        assert!(sdk.contains("#include <cstdint>"));
        assert!(sdk.contains("TEST_CONST"));
    }

    #[test]
    fn test_generate_language_sdk_python() {
        let mut abi_types: AbiTypes = AbiTypes::new();
        abi_types.add_const(AbiConst {
            name: String::from("TEST_CONST"),
            rust_type: String::from("u32"),
            value: String::from("42"),
            doc: Some(String::from("Test constant.")),
        });

        let sdk: String = generate_language_sdk(TargetLang::Python, &abi_types);

        assert!(sdk.contains("import ctypes"));
        assert!(sdk.contains("TEST_CONST"));
    }

    /// Test that populate_size_hints fills in known struct sizes.
    #[test]
    fn test_populate_size_hints() {
        use crate::build::types::AbiField;

        let mut abi_types: AbiTypes = AbiTypes::new();
        abi_types.add_struct(AbiStruct {
            name: String::from("RuntimeConfig"),
            fields: vec![],
            doc: None,
            repr_c: true,
            size_hint: None,
        });
        abi_types.add_struct(AbiStruct {
            name: String::from("GuestContractHandle"),
            fields: vec![],
            doc: None,
            repr_c: true,
            size_hint: None,
        });
        abi_types.add_struct(AbiStruct {
            name: String::from("UnknownStruct"),
            fields: vec![],
            doc: None,
            repr_c: true,
            size_hint: None,
        });

        populate_size_hints(&mut abi_types);

        assert_eq!(
            abi_types.structs[0].size_hint,
            Some(16),
            "RuntimeConfig should be 16 bytes"
        );
        assert_eq!(
            abi_types.structs[1].size_hint,
            Some(8),
            "GuestContractHandle should be 8 bytes"
        );
        assert_eq!(
            abi_types.structs[2].size_hint, None,
            "Unknown struct should have no size hint"
        );
    }

    /// Test that C++ output contains static_assert for structs with size hints.
    #[test]
    fn test_cpp_output_contains_static_assert() {
        use crate::build::types::AbiField;

        let mut abi_types: AbiTypes = AbiTypes::new();
        abi_types.add_struct(AbiStruct {
            name: String::from("RuntimeConfig"),
            fields: vec![AbiField {
                name: String::from("compatibility"),
                rust_type: String::from("u32"),
                doc: None,
            }],
            doc: None,
            repr_c: true,
            size_hint: Some(16),
        });

        let sdk: String = generate_language_sdk(TargetLang::Cpp, &abi_types);
        assert!(
            sdk.contains("static_assert(sizeof(RuntimeConfig) == 16"),
            "C++ should contain static_assert for RuntimeConfig: {}",
            sdk
        );
    }

    /// Test that Python output contains ctypes.sizeof assertions for structs with size hints.
    #[test]
    fn test_python_output_contains_sizeof_assertions() {
        use crate::build::types::AbiField;

        let mut abi_types: AbiTypes = AbiTypes::new();
        abi_types.add_struct(AbiStruct {
            name: String::from("RuntimeConfig"),
            fields: vec![AbiField {
                name: String::from("compatibility"),
                rust_type: String::from("u32"),
                doc: None,
            }],
            doc: None,
            repr_c: true,
            size_hint: Some(16),
        });

        let sdk: String = generate_language_sdk(TargetLang::Python, &abi_types);
        assert!(
            sdk.contains("assert ctypes.sizeof(RuntimeConfig) == 16"),
            "Python should contain ctypes.sizeof assertion for RuntimeConfig: {}",
            sdk
        );
    }
}