alef-codegen 0.15.12

Shared codegen utilities for the alef polyglot binding generator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
//! Shared trait bridge code generation.
//!
//! Generates wrapper structs that allow foreign language objects (Python, JS, etc.)
//! to implement Rust traits via FFI. Each backend implements [`TraitBridgeGenerator`]
//! to provide language-specific dispatch logic; the shared functions in this module
//! handle the structural boilerplate.

use alef_core::config::{BridgeBinding, TraitBridgeConfig};
use alef_core::ir::{FieldDef, FunctionDef, MethodDef, ParamDef, PrimitiveType, TypeDef, TypeRef};
use heck::ToSnakeCase;
use std::collections::HashMap;

/// Everything needed to generate a trait bridge for one trait.
pub struct TraitBridgeSpec<'a> {
    /// The trait definition from the IR.
    pub trait_def: &'a TypeDef,
    /// Bridge configuration from `alef.toml`.
    pub bridge_config: &'a TraitBridgeConfig,
    /// Core crate import path (e.g., `"kreuzberg"`).
    pub core_import: &'a str,
    /// Language-specific prefix for the wrapper type (e.g., `"Python"`, `"Js"`, `"Wasm"`).
    pub wrapper_prefix: &'a str,
    /// Map of type name → fully-qualified Rust path for qualifying `Named` types.
    pub type_paths: HashMap<String, String>,
    /// The crate's error type name (e.g., `"KreuzbergError"`). Defaults to `"Error"`.
    pub error_type: String,
    /// Error constructor pattern. `{msg}` is replaced with the message expression.
    pub error_constructor: String,
}

impl<'a> TraitBridgeSpec<'a> {
    /// Fully qualified error type path (e.g., `"kreuzberg::KreuzbergError"`).
    ///
    /// If `error_type` already looks fully-qualified (contains `::`) or is a generic
    /// type expression (contains `<`), it is returned as-is without prefixing
    /// `core_import`. This lets backends specify rich error types like
    /// `"Box<dyn std::error::Error + Send + Sync>"` directly.
    pub fn error_path(&self) -> String {
        if self.error_type.contains("::") || self.error_type.contains('<') {
            self.error_type.clone()
        } else {
            format!("{}::{}", self.core_import, self.error_type)
        }
    }

    /// Generate an error construction expression from a message expression.
    pub fn make_error(&self, msg_expr: &str) -> String {
        self.error_constructor.replace("{msg}", msg_expr)
    }

    /// Wrapper struct name: `{prefix}{TraitName}Bridge` (e.g., `PythonOcrBackendBridge`).
    pub fn wrapper_name(&self) -> String {
        format!("{}{}Bridge", self.wrapper_prefix, self.trait_def.name)
    }

    /// Snake-case version of the trait name (e.g., `"ocr_backend"`).
    pub fn trait_snake(&self) -> String {
        self.trait_def.name.to_snake_case()
    }

    /// Full Rust path to the trait (e.g., `kreuzberg::OcrBackend`).
    pub fn trait_path(&self) -> String {
        self.trait_def.rust_path.replace('-', "_")
    }

    /// Methods that are required (no default impl) — must be provided by the foreign object.
    pub fn required_methods(&self) -> Vec<&'a MethodDef> {
        self.trait_def.methods.iter().filter(|m| !m.has_default_impl).collect()
    }

    /// Methods that have a default impl — optional on the foreign object.
    pub fn optional_methods(&self) -> Vec<&'a MethodDef> {
        self.trait_def.methods.iter().filter(|m| m.has_default_impl).collect()
    }
}

/// Backend-specific trait bridge generation.
///
/// Each binding backend (PyO3, NAPI-RS, wasm-bindgen, etc.) implements this trait
/// to provide the language-specific parts of bridge codegen. The shared functions
/// in this module call these methods to fill in the backend-dependent pieces.
pub trait TraitBridgeGenerator {
    /// The type of the wrapped foreign object (e.g., `"Py<PyAny>"`, `"ThreadsafeFunction"`).
    fn foreign_object_type(&self) -> &str;

    /// Additional `use` imports needed for the bridge code.
    fn bridge_imports(&self) -> Vec<String>;

    /// Generate the body of a synchronous method bridge.
    ///
    /// The returned string is inserted inside the trait impl method. It should
    /// call through to the foreign object and convert the result.
    fn gen_sync_method_body(&self, method: &MethodDef, spec: &TraitBridgeSpec) -> String;

    /// Generate the body of an async method bridge.
    ///
    /// The returned string is the body of a `Box::pin(async move { ... })` block.
    fn gen_async_method_body(&self, method: &MethodDef, spec: &TraitBridgeSpec) -> String;

    /// Generate the constructor body that validates and wraps the foreign object.
    ///
    /// Should check that the foreign object provides all required methods and
    /// return `Self { ... }` on success.
    fn gen_constructor(&self, spec: &TraitBridgeSpec) -> String;

    /// Generate the complete registration function including attributes, signature, and body.
    ///
    /// Each backend needs different function signatures (PyO3 takes `py: Python`,
    /// NAPI takes `#[napi]` with JS params, FFI takes `extern "C"` with raw pointers),
    /// so the generator owns the full function.
    fn gen_registration_fn(&self, spec: &TraitBridgeSpec) -> String;

    /// Generate an unregistration function for the bridge.
    ///
    /// Default implementation returns an empty string — backends opt in by
    /// emitting a function whose name is `spec.bridge_config.unregister_fn`
    /// (when set) and whose body calls into the host crate's
    /// `unregister_*(name)` plugin entry point.
    fn gen_unregistration_fn(&self, _spec: &TraitBridgeSpec) -> String {
        String::new()
    }

    /// Generate a clear-all-plugins function for the bridge.
    ///
    /// Default implementation returns an empty string — backends opt in by
    /// emitting a function whose name is `spec.bridge_config.clear_fn`
    /// (when set) and whose body calls into the host crate's `clear_*()`
    /// plugin entry point. Typically used in test teardown.
    fn gen_clear_fn(&self, _spec: &TraitBridgeSpec) -> String {
        String::new()
    }

    /// Whether the `#[async_trait]` macro should require `Send` on its futures.
    ///
    /// Returns `true` (default) for most targets. WASM is single-threaded so its
    /// trait bounds don't include `Send`; implementors should return `false` there.
    fn async_trait_is_send(&self) -> bool {
        true
    }
}

// ---------------------------------------------------------------------------
// Shared generation functions
// ---------------------------------------------------------------------------

/// Generate the wrapper struct holding the foreign object and cached fields.
///
/// Produces a struct like:
/// ```ignore
/// pub struct PythonOcrBackendBridge {
///     inner: Py<PyAny>,
///     cached_name: String,
/// }
/// ```
pub fn gen_bridge_wrapper_struct(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> String {
    let wrapper = spec.wrapper_name();
    let foreign_type = generator.foreign_object_type();

    crate::template_env::render(
        "generators/trait_bridge/wrapper_struct.jinja",
        minijinja::context! {
            wrapper_prefix => spec.wrapper_prefix,
            trait_name => &spec.trait_def.name,
            wrapper_name => wrapper,
            foreign_type => foreign_type,
        },
    )
}

/// Generate `impl std::fmt::Debug for Wrapper`.
///
/// Required by trait bounds on `Plugin` super-trait (and many others) that
/// extend `Debug`. Without this, generic plugin-pattern bridges fail to
/// compile when the user's trait has a `Debug` super-trait bound.
fn gen_bridge_debug_impl(spec: &TraitBridgeSpec) -> String {
    let wrapper = spec.wrapper_name();
    format!(
        "impl std::fmt::Debug for {wrapper} {{\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{\n        write!(f, \"{wrapper}\")\n    }}\n}}"
    )
}

/// Generate `impl SuperTrait for Wrapper` when the bridge config specifies a super-trait.
///
/// Forwards `name()`, `version()`, `initialize()`, and `shutdown()` to the
/// foreign object, using `cached_name` for `name()`.
///
/// The super-trait path is derived from the config's `super_trait` field. If it
/// contains `::`, it's used as-is; otherwise it's qualified as `{core_import}::{super_trait}`.
pub fn gen_bridge_plugin_impl(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> Option<String> {
    let super_trait_name = spec.bridge_config.super_trait.as_deref()?;

    let wrapper = spec.wrapper_name();
    let core_import = spec.core_import;

    // Derive the fully-qualified super-trait path
    let super_trait_path = if super_trait_name.contains("::") {
        super_trait_name.to_string()
    } else {
        format!("{core_import}::{super_trait_name}")
    };

    // Build synthetic MethodDefs for the Plugin methods and delegate to the generator
    // for the actual call bodies. The Plugin trait interface is well-known: name(),
    // version(), initialize(), shutdown().
    let error_path = spec.error_path();

    // version() -> String — delegate to foreign object
    let version_method = MethodDef {
        name: "version".to_string(),
        params: vec![],
        return_type: alef_core::ir::TypeRef::String,
        is_async: false,
        is_static: false,
        error_type: None,
        doc: String::new(),
        receiver: Some(alef_core::ir::ReceiverKind::Ref),
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: false,
    };
    let version_body = generator.gen_sync_method_body(&version_method, spec);

    // initialize() -> Result<(), ErrorType>
    let init_method = MethodDef {
        name: "initialize".to_string(),
        params: vec![],
        return_type: alef_core::ir::TypeRef::Unit,
        is_async: false,
        is_static: false,
        error_type: Some(error_path.clone()),
        doc: String::new(),
        receiver: Some(alef_core::ir::ReceiverKind::Ref),
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: true,
    };
    let init_body = generator.gen_sync_method_body(&init_method, spec);

    // shutdown() -> Result<(), ErrorType>
    let shutdown_method = MethodDef {
        name: "shutdown".to_string(),
        params: vec![],
        return_type: alef_core::ir::TypeRef::Unit,
        is_async: false,
        is_static: false,
        error_type: Some(error_path.clone()),
        doc: String::new(),
        receiver: Some(alef_core::ir::ReceiverKind::Ref),
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: true,
    };
    let shutdown_body = generator.gen_sync_method_body(&shutdown_method, spec);

    // Split method bodies into lines for template iteration
    let version_lines: Vec<&str> = version_body.lines().collect();
    let init_lines: Vec<&str> = init_body.lines().collect();
    let shutdown_lines: Vec<&str> = shutdown_body.lines().collect();

    Some(crate::template_env::render(
        "generators/trait_bridge/plugin_impl.jinja",
        minijinja::context! {
            super_trait_path => super_trait_path,
            wrapper_name => wrapper,
            error_path => error_path,
            version_lines => version_lines,
            init_lines => init_lines,
            shutdown_lines => shutdown_lines,
        },
    ))
}

/// Generate `impl Trait for Wrapper` dispatching each method through the generator.
///
/// Every method on the trait (including those with `has_default_impl`) gets a
/// generated body that forwards to the foreign object.
pub fn gen_bridge_trait_impl(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> String {
    let wrapper = spec.wrapper_name();
    let trait_path = spec.trait_path();

    // Check if the trait has async methods (needed for async_trait macro compatibility).
    let has_async_methods = spec
        .trait_def
        .methods
        .iter()
        .any(|m| m.is_async && m.trait_source.is_none());
    let async_trait_is_send = generator.async_trait_is_send();

    // Filter out methods inherited from super-traits (they're handled by gen_bridge_plugin_impl)
    let own_methods: Vec<_> = spec
        .trait_def
        .methods
        .iter()
        .filter(|m| m.trait_source.is_none())
        .collect();

    // Build method code with proper indentation
    let mut methods_code = String::with_capacity(1024);
    for (i, method) in own_methods.iter().enumerate() {
        if i > 0 {
            methods_code.push_str("\n\n");
        }

        // Build the method signature
        let async_kw = if method.is_async { "async " } else { "" };
        let receiver = match &method.receiver {
            Some(alef_core::ir::ReceiverKind::Ref) => "&self",
            Some(alef_core::ir::ReceiverKind::RefMut) => "&mut self",
            Some(alef_core::ir::ReceiverKind::Owned) => "self",
            None => "",
        };

        // Build params (excluding self), using format_param_type to respect is_ref/is_mut
        let params: Vec<String> = method
            .params
            .iter()
            .map(|p| format!("{}: {}", p.name, format_param_type(p, &spec.type_paths)))
            .collect();

        let all_params = if receiver.is_empty() {
            params.join(", ")
        } else if params.is_empty() {
            receiver.to_string()
        } else {
            format!("{}, {}", receiver, params.join(", "))
        };

        // Return type — override the IR's error type with the configured crate error type
        // so the impl matches the actual trait definition (the IR may extract a different
        // error type like anyhow::Error from re-exports or type alias resolution).
        let error_override = method.error_type.as_ref().map(|_| spec.error_path());
        let ret = format_return_type(&method.return_type, error_override.as_deref(), &spec.type_paths);

        // Generate body: async methods use Box::pin, sync methods call directly
        let body = if method.is_async {
            generator.gen_async_method_body(method, spec)
        } else {
            generator.gen_sync_method_body(method, spec)
        };

        // Indent body lines
        let indented_body = body
            .lines()
            .map(|line| format!("        {line}"))
            .collect::<Vec<_>>()
            .join("\n");

        methods_code.push_str(&crate::template_env::render(
            "generators/trait_bridge/trait_method.jinja",
            minijinja::context! {
                async_kw => async_kw,
                method_name => &method.name,
                all_params => all_params,
                ret => ret,
                indented_body => &indented_body,
            },
        ));
    }

    crate::template_env::render(
        "generators/trait_bridge/trait_impl.jinja",
        minijinja::context! {
            has_async_methods => has_async_methods,
            async_trait_is_send => async_trait_is_send,
            trait_path => trait_path,
            wrapper_name => wrapper,
            methods_code => methods_code,
        },
    )
}

/// Generate the `register_xxx()` function that wraps a foreign object and
/// inserts it into the plugin registry.
///
/// Returns `None` when `bridge_config.register_fn` is absent (per-call bridge pattern).
/// The generator owns the full function (attributes, signature, body) because each
/// backend needs different signatures.
pub fn gen_bridge_registration_fn(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> Option<String> {
    spec.bridge_config.register_fn.as_deref()?;
    Some(generator.gen_registration_fn(spec))
}

/// Generate the `unregister_xxx(name)` function that removes a previously
/// registered plugin from the registry.
///
/// Returns `None` when `bridge_config.unregister_fn` is absent or when the
/// backend hasn't opted in (returns the empty string from
/// [`TraitBridgeGenerator::gen_unregistration_fn`]).
pub fn gen_bridge_unregistration_fn(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> Option<String> {
    spec.bridge_config.unregister_fn.as_deref()?;
    let body = generator.gen_unregistration_fn(spec);
    if body.is_empty() { None } else { Some(body) }
}

/// Generate the `clear_xxx()` function that removes all registered plugins
/// of this type.
///
/// Returns `None` when `bridge_config.clear_fn` is absent or when the
/// backend hasn't opted in (returns the empty string from
/// [`TraitBridgeGenerator::gen_clear_fn`]).
pub fn gen_bridge_clear_fn(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> Option<String> {
    spec.bridge_config.clear_fn.as_deref()?;
    let body = generator.gen_clear_fn(spec);
    if body.is_empty() { None } else { Some(body) }
}

/// Resolve the FQN of a host-crate plugin function (e.g.
/// `kreuzberg::plugins::ocr::unregister_ocr_backend`) given the bridge's
/// `registry_getter` path. The convention used by host crates is:
///
/// - `registry_getter = "kreuzberg::plugins::registry::get_ocr_backend_registry"`
/// - top-level fn      = `kreuzberg::plugins::ocr::unregister_ocr_backend`
///
/// We rewrite `::registry::get_*_registry` to `::<sub>::<fn_name>` where
/// `<sub>` is the trait submodule name (extracted from `_*_registry`).
/// When the heuristic fails (no `registry_getter`, unexpected shape), we
/// fall back to `{core_import}::plugins::{fn_name}` so the user can rely on
/// a re-export.
///
/// Shared by every backend that opts in to `unregister_*`/`clear_*` codegen
/// (pyo3, napi, magnus, php, rustler, gleam, extendr, dart, swift, kotlin,
/// wasm). Replaces the duplicated `<lang>_host_function_path` helpers that
/// each backend used to define.
pub fn host_function_path(spec: &TraitBridgeSpec, fn_name: &str) -> String {
    if let Some(getter) = spec.bridge_config.registry_getter.as_deref() {
        let last = getter.rsplit("::").next().unwrap_or("");
        if let Some(sub) = last.strip_prefix("get_").and_then(|s| s.strip_suffix("_registry")) {
            let prefix_end = getter.len() - last.len();
            let prefix = &getter[..prefix_end];
            let prefix = prefix.trim_end_matches("registry::");
            return format!("{prefix}{sub}::{fn_name}");
        }
    }
    format!("{}::plugins::{}", spec.core_import, fn_name)
}

/// Result of trait bridge generation: imports (to be added via `builder.add_import`)
/// and the code body (to be added via `builder.add_item`).
pub struct BridgeOutput {
    /// Import paths (e.g., `"std::sync::Arc"`) — callers should add via `builder.add_import()`.
    pub imports: Vec<String>,
    /// The generated code (struct, impls, registration fn).
    pub code: String,
}

/// Generate the complete trait bridge code block: struct, impls, and
/// optionally a registration function.
///
/// Returns [`BridgeOutput`] with imports separated from code so callers can
/// route imports through `builder.add_import()` (which deduplicates).
pub fn gen_bridge_all(spec: &TraitBridgeSpec, generator: &dyn TraitBridgeGenerator) -> BridgeOutput {
    let imports = generator.bridge_imports();
    let mut out = String::with_capacity(4096);

    // Wrapper struct
    out.push_str(&gen_bridge_wrapper_struct(spec, generator));
    out.push_str("\n\n");

    // Debug impl (required by Plugin super-trait Debug bound)
    out.push_str(&gen_bridge_debug_impl(spec));
    out.push_str("\n\n");

    // Constructor (impl block with new())
    out.push_str(&generator.gen_constructor(spec));
    out.push_str("\n\n");

    // Plugin super-trait impl (if applicable)
    if let Some(plugin_impl) = gen_bridge_plugin_impl(spec, generator) {
        out.push_str(&plugin_impl);
        out.push_str("\n\n");
    }

    // Trait impl
    out.push_str(&gen_bridge_trait_impl(spec, generator));

    // Registration function — only when register_fn is configured
    if let Some(reg_fn_code) = gen_bridge_registration_fn(spec, generator) {
        out.push_str("\n\n");
        out.push_str(&reg_fn_code);
    }

    // Unregistration function — only when unregister_fn is configured AND
    // the backend has opted in (non-empty body).
    if let Some(unreg_fn_code) = gen_bridge_unregistration_fn(spec, generator) {
        out.push_str("\n\n");
        out.push_str(&unreg_fn_code);
    }

    // Clear-all function — only when clear_fn is configured AND the backend
    // has opted in (non-empty body).
    if let Some(clear_fn_code) = gen_bridge_clear_fn(spec, generator) {
        out.push_str("\n\n");
        out.push_str(&clear_fn_code);
    }

    BridgeOutput { imports, code: out }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Format a `TypeRef` as a Rust type string for use in trait method signatures.
///
/// `type_paths` qualifies `Named` types with their full Rust path (e.g., `"Config"` →
/// `"kreuzberg::Config"`). If a name isn't in `type_paths`, it's used as-is.
pub fn format_type_ref(ty: &alef_core::ir::TypeRef, type_paths: &HashMap<String, String>) -> String {
    use alef_core::ir::{PrimitiveType, TypeRef};
    match ty {
        TypeRef::Primitive(p) => match p {
            PrimitiveType::Bool => "bool",
            PrimitiveType::U8 => "u8",
            PrimitiveType::U16 => "u16",
            PrimitiveType::U32 => "u32",
            PrimitiveType::U64 => "u64",
            PrimitiveType::I8 => "i8",
            PrimitiveType::I16 => "i16",
            PrimitiveType::I32 => "i32",
            PrimitiveType::I64 => "i64",
            PrimitiveType::F32 => "f32",
            PrimitiveType::F64 => "f64",
            PrimitiveType::Usize => "usize",
            PrimitiveType::Isize => "isize",
        }
        .to_string(),
        TypeRef::String => "String".to_string(),
        TypeRef::Char => "char".to_string(),
        TypeRef::Bytes => "Vec<u8>".to_string(),
        TypeRef::Optional(inner) => format!("Option<{}>", format_type_ref(inner, type_paths)),
        TypeRef::Vec(inner) => format!("Vec<{}>", format_type_ref(inner, type_paths)),
        TypeRef::Map(k, v) => format!(
            "std::collections::HashMap<{}, {}>",
            format_type_ref(k, type_paths),
            format_type_ref(v, type_paths)
        ),
        TypeRef::Named(name) => type_paths.get(name.as_str()).cloned().unwrap_or_else(|| name.clone()),
        TypeRef::Path => "std::path::PathBuf".to_string(),
        TypeRef::Unit => "()".to_string(),
        TypeRef::Json => "serde_json::Value".to_string(),
        TypeRef::Duration => "std::time::Duration".to_string(),
    }
}

/// Format a return type, wrapping in `Result` when an error type is present.
pub fn format_return_type(
    ty: &alef_core::ir::TypeRef,
    error_type: Option<&str>,
    type_paths: &HashMap<String, String>,
) -> String {
    let inner = format_type_ref(ty, type_paths);
    match error_type {
        Some(err) => format!("std::result::Result<{inner}, {err}>"),
        None => inner,
    }
}

/// Format a parameter type, respecting `is_ref`, `is_mut`, and `optional` from the IR.
///
/// Unlike [`format_type_ref`], this function produces reference types when the
/// original Rust parameter was a `&T` or `&mut T`, and wraps in `Option<>` when
/// `param.optional` is true:
/// - `String + is_ref` → `&str`
/// - `String + is_ref + optional` → `Option<&str>`
/// - `Bytes + is_ref` → `&[u8]`
/// - `Path + is_ref` → `&std::path::Path`
/// - `Vec<T> + is_ref` → `&[T]`
/// - `Named(n) + is_ref` → `&{qualified_name}`
pub fn format_param_type(param: &ParamDef, type_paths: &HashMap<String, String>) -> String {
    use alef_core::ir::TypeRef;
    let base = if param.is_ref {
        let mutability = if param.is_mut { "mut " } else { "" };
        match &param.ty {
            TypeRef::String => format!("&{mutability}str"),
            TypeRef::Bytes => format!("&{mutability}[u8]"),
            TypeRef::Path => format!("&{mutability}std::path::Path"),
            TypeRef::Vec(inner) => format!("&{mutability}[{}]", format_type_ref(inner, type_paths)),
            TypeRef::Named(name) => {
                let qualified = type_paths.get(name.as_str()).cloned().unwrap_or_else(|| name.clone());
                format!("&{mutability}{qualified}")
            }
            TypeRef::Optional(inner) => {
                // Preserve the Option wrapper but apply the ref transformation to the inner type.
                // e.g. Option<String> + is_ref → Option<&str>
                //      Option<Vec<T>> + is_ref → Option<&[T]>
                let inner_type_str = match inner.as_ref() {
                    TypeRef::String => format!("&{mutability}str"),
                    TypeRef::Bytes => format!("&{mutability}[u8]"),
                    TypeRef::Path => format!("&{mutability}std::path::Path"),
                    TypeRef::Vec(v) => format!("&{mutability}[{}]", format_type_ref(v, type_paths)),
                    TypeRef::Named(name) => {
                        let qualified = type_paths.get(name.as_str()).cloned().unwrap_or_else(|| name.clone());
                        format!("&{mutability}{qualified}")
                    }
                    // Primitives and other Copy types: pass by value inside Option
                    other => format_type_ref(other, type_paths),
                };
                // Already wrapped in Option — return directly to avoid double-wrapping below.
                return format!("Option<{inner_type_str}>");
            }
            // All other types are Copy/small — pass by value even when is_ref is set
            other => format_type_ref(other, type_paths),
        }
    } else {
        format_type_ref(&param.ty, type_paths)
    };

    // Wrap in Option<> when the parameter is optional (e.g. `title: Option<&str>`).
    // The TypeRef::Optional arm above returns early, so this only fires for the
    // `optional: true` IR flag pattern where ty is the unwrapped inner type.
    if param.optional {
        format!("Option<{base}>")
    } else {
        base
    }
}

// ---------------------------------------------------------------------------
// Shared helpers — used by all backend trait_bridge modules.
// ---------------------------------------------------------------------------

/// Map a Rust primitive to its type string.
pub fn prim(p: &PrimitiveType) -> &'static str {
    use PrimitiveType::*;
    match p {
        Bool => "bool",
        U8 => "u8",
        U16 => "u16",
        U32 => "u32",
        U64 => "u64",
        I8 => "i8",
        I16 => "i16",
        I32 => "i32",
        I64 => "i64",
        F32 => "f32",
        F64 => "f64",
        Usize => "usize",
        Isize => "isize",
    }
}

/// Map a `TypeRef` to its Rust source type string for use in trait bridge method
/// signatures. `ci` is the core import path (e.g. `"kreuzberg"`), `tp` maps
/// type names to fully-qualified paths.
pub fn bridge_param_type(ty: &TypeRef, ci: &str, is_ref: bool, tp: &HashMap<String, String>) -> String {
    match ty {
        TypeRef::Bytes if is_ref => "&[u8]".into(),
        TypeRef::Bytes => "Vec<u8>".into(),
        TypeRef::String if is_ref => "&str".into(),
        TypeRef::String => "String".into(),
        TypeRef::Path if is_ref => "&std::path::Path".into(),
        TypeRef::Path => "std::path::PathBuf".into(),
        TypeRef::Named(n) => {
            let qualified = tp.get(n).cloned().unwrap_or_else(|| format!("{ci}::{n}"));
            if is_ref { format!("&{qualified}") } else { qualified }
        }
        TypeRef::Vec(inner) => format!("Vec<{}>", bridge_param_type(inner, ci, false, tp)),
        TypeRef::Optional(inner) => format!("Option<{}>", bridge_param_type(inner, ci, false, tp)),
        TypeRef::Primitive(p) => prim(p).into(),
        TypeRef::Unit => "()".into(),
        TypeRef::Char => "char".into(),
        TypeRef::Map(k, v) => format!(
            "std::collections::HashMap<{}, {}>",
            bridge_param_type(k, ci, false, tp),
            bridge_param_type(v, ci, false, tp)
        ),
        TypeRef::Json => "serde_json::Value".into(),
        TypeRef::Duration => "std::time::Duration".into(),
    }
}

/// Map a visitor method parameter type to the correct Rust type string, handling
/// IR quirks:
/// - `ty=String, optional=true, is_ref=true` → `Option<&str>` (IR collapses `Option<&str>`)
/// - `ty=Vec<T>, is_ref=true` → `&[T]` (IR collapses `&[T]`)
/// - Everything else delegates to [`bridge_param_type`].
pub fn visitor_param_type(ty: &TypeRef, is_ref: bool, optional: bool, tp: &HashMap<String, String>) -> String {
    if optional && matches!(ty, TypeRef::String) && is_ref {
        return "Option<&str>".to_string();
    }
    if is_ref {
        if let TypeRef::Vec(inner) = ty {
            let inner_str = bridge_param_type(inner, "", false, tp);
            return format!("&[{inner_str}]");
        }
    }
    bridge_param_type(ty, "", is_ref, tp)
}

/// Find the first function parameter that matches a trait bridge configuration
/// (by type alias or parameter name).
///
/// Bridges configured with `bind_via = "options_field"` are skipped — they live on a
/// struct field rather than directly as a parameter, and are returned by
/// [`find_bridge_field`] instead.
pub fn find_bridge_param<'a>(
    func: &FunctionDef,
    bridges: &'a [TraitBridgeConfig],
) -> Option<(usize, &'a TraitBridgeConfig)> {
    for (idx, param) in func.params.iter().enumerate() {
        let named = match &param.ty {
            TypeRef::Named(n) => Some(n.as_str()),
            TypeRef::Optional(inner) => {
                if let TypeRef::Named(n) = inner.as_ref() {
                    Some(n.as_str())
                } else {
                    None
                }
            }
            _ => None,
        };
        for bridge in bridges {
            if bridge.bind_via != BridgeBinding::FunctionParam {
                continue;
            }
            if let Some(type_name) = named {
                if bridge.type_alias.as_deref() == Some(type_name) {
                    return Some((idx, bridge));
                }
            }
            if bridge.param_name.as_deref() == Some(param.name.as_str()) {
                return Some((idx, bridge));
            }
        }
    }
    None
}

/// Match info for a trait bridge whose handle lives as a struct field
/// (`bind_via = "options_field"`).
#[derive(Debug, Clone)]
pub struct BridgeFieldMatch<'a> {
    /// Index of the function parameter that carries the owning struct.
    pub param_index: usize,
    /// Name of the parameter (e.g., `"options"`).
    pub param_name: String,
    /// IR type name of the parameter, with any `Option<>` wrapper unwrapped.
    pub options_type: String,
    /// True if the param is `Option<TypeName>` rather than `TypeName`.
    pub param_is_optional: bool,
    /// Name of the field on `options_type` that holds the bridge handle.
    pub field_name: String,
    /// The matching field definition (carries the field's `TypeRef`).
    pub field: &'a FieldDef,
    /// The bridge configuration that produced the match.
    pub bridge: &'a TraitBridgeConfig,
}

/// Find the first function parameter whose IR type carries a bridge field
/// (`bind_via = "options_field"`).
///
/// For each function parameter whose IR type is `Named(N)` or `Optional<Named(N)>`,
/// look up `N` in `types`. If `N` matches any bridge's `options_type`, search its
/// fields for one whose name matches the bridge's resolved options field (or whose
/// type's `Named` alias matches the bridge's `type_alias`). Returns the first match.
///
/// Bridges configured with `bind_via = "function_param"` are skipped — those go
/// through [`find_bridge_param`] instead.
pub fn find_bridge_field<'a>(
    func: &FunctionDef,
    types: &'a [TypeDef],
    bridges: &'a [TraitBridgeConfig],
) -> Option<BridgeFieldMatch<'a>> {
    fn unwrap_named(ty: &TypeRef) -> Option<(&str, bool)> {
        match ty {
            TypeRef::Named(n) => Some((n.as_str(), false)),
            TypeRef::Optional(inner) => {
                if let TypeRef::Named(n) = inner.as_ref() {
                    Some((n.as_str(), true))
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    for (idx, param) in func.params.iter().enumerate() {
        let Some((type_name, is_optional)) = unwrap_named(&param.ty) else {
            continue;
        };
        let Some(type_def) = types.iter().find(|t| t.name == type_name) else {
            continue;
        };
        for bridge in bridges {
            if bridge.bind_via != BridgeBinding::OptionsField {
                continue;
            }
            if bridge.options_type.as_deref() != Some(type_name) {
                continue;
            }
            let field_name = bridge.resolved_options_field();
            for field in &type_def.fields {
                let matches_name = field_name.is_some_and(|n| field.name == n);
                let matches_alias = bridge
                    .type_alias
                    .as_deref()
                    .is_some_and(|alias| field_type_matches_alias(&field.ty, alias));
                if matches_name || matches_alias {
                    return Some(BridgeFieldMatch {
                        param_index: idx,
                        param_name: param.name.clone(),
                        options_type: type_name.to_string(),
                        param_is_optional: is_optional,
                        field_name: field.name.clone(),
                        field,
                        bridge,
                    });
                }
            }
        }
    }
    None
}

/// True if `field_ty` references a `Named` type whose name equals `alias`,
/// allowing for `Option<>` and `Vec<>` wrappers.
fn field_type_matches_alias(field_ty: &TypeRef, alias: &str) -> bool {
    match field_ty {
        TypeRef::Named(n) => n == alias,
        TypeRef::Optional(inner) | TypeRef::Vec(inner) => field_type_matches_alias(inner, alias),
        _ => false,
    }
}

/// Convert a snake_case string to camelCase.
pub fn to_camel_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = false;
    for ch in s.chars() {
        if ch == '_' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(ch.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(ch);
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use alef_core::config::TraitBridgeConfig;
    use alef_core::ir::{MethodDef, ParamDef, PrimitiveType, ReceiverKind, TypeDef, TypeRef};

    // ---------------------------------------------------------------------------
    // Test helpers
    // ---------------------------------------------------------------------------

    fn make_trait_bridge_config(super_trait: Option<&str>, register_fn: Option<&str>) -> TraitBridgeConfig {
        TraitBridgeConfig {
            trait_name: "OcrBackend".to_string(),
            super_trait: super_trait.map(str::to_string),
            registry_getter: None,
            register_fn: register_fn.map(str::to_string),
            unregister_fn: None,
            clear_fn: None,
            type_alias: None,
            param_name: None,
            register_extra_args: None,
            exclude_languages: Vec::new(),
            bind_via: BridgeBinding::FunctionParam,
            options_type: None,
            options_field: None,
        }
    }

    fn make_type_def(name: &str, rust_path: &str, methods: Vec<MethodDef>) -> TypeDef {
        TypeDef {
            name: name.to_string(),
            rust_path: rust_path.to_string(),
            original_rust_path: rust_path.to_string(),
            fields: vec![],
            methods,
            is_opaque: true,
            is_clone: false,
            is_copy: false,
            doc: String::new(),
            cfg: None,
            is_trait: true,
            has_default: false,
            has_stripped_cfg_fields: false,
            is_return_type: false,
            serde_rename_all: None,
            has_serde: false,
            super_traits: vec![],
        }
    }

    fn make_method(
        name: &str,
        params: Vec<ParamDef>,
        return_type: TypeRef,
        is_async: bool,
        has_default_impl: bool,
        trait_source: Option<&str>,
        error_type: Option<&str>,
    ) -> MethodDef {
        MethodDef {
            name: name.to_string(),
            params,
            return_type,
            is_async,
            is_static: false,
            error_type: error_type.map(str::to_string),
            doc: String::new(),
            receiver: Some(ReceiverKind::Ref),
            sanitized: false,
            trait_source: trait_source.map(str::to_string),
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl,
        }
    }

    fn make_func(name: &str, params: Vec<ParamDef>) -> FunctionDef {
        FunctionDef {
            name: name.to_string(),
            rust_path: format!("mylib::{name}"),
            original_rust_path: String::new(),
            params,
            return_type: TypeRef::Unit,
            is_async: false,
            error_type: None,
            doc: String::new(),
            cfg: None,
            sanitized: false,
            return_sanitized: false,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
        }
    }

    fn make_field(name: &str, ty: TypeRef) -> FieldDef {
        FieldDef {
            name: name.to_string(),
            ty,
            optional: false,
            default: None,
            doc: String::new(),
            sanitized: false,
            is_boxed: false,
            type_rust_path: None,
            cfg: None,
            typed_default: None,
            core_wrapper: Default::default(),
            vec_inner_core_wrapper: Default::default(),
            newtype_wrapper: None,
            serde_rename: None,
        }
    }

    fn make_param(name: &str, ty: TypeRef, is_ref: bool) -> ParamDef {
        ParamDef {
            name: name.to_string(),
            ty,
            optional: false,
            default: None,
            sanitized: false,
            typed_default: None,
            is_ref,
            is_mut: false,
            newtype_wrapper: None,
            original_type: None,
        }
    }

    fn make_spec<'a>(
        trait_def: &'a TypeDef,
        bridge_config: &'a TraitBridgeConfig,
        wrapper_prefix: &'a str,
        type_paths: HashMap<String, String>,
    ) -> TraitBridgeSpec<'a> {
        TraitBridgeSpec {
            trait_def,
            bridge_config,
            core_import: "mylib",
            wrapper_prefix,
            type_paths,
            error_type: "MyError".to_string(),
            error_constructor: "MyError::from({msg})".to_string(),
        }
    }

    // ---------------------------------------------------------------------------
    // Mock backend
    // ---------------------------------------------------------------------------

    struct MockBridgeGenerator;

    impl TraitBridgeGenerator for MockBridgeGenerator {
        fn foreign_object_type(&self) -> &str {
            "Py<PyAny>"
        }

        fn bridge_imports(&self) -> Vec<String> {
            vec!["pyo3::prelude::*".to_string(), "pyo3::types::PyString".to_string()]
        }

        fn gen_sync_method_body(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
            format!("// sync body for {}", method.name)
        }

        fn gen_async_method_body(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
            format!("// async body for {}", method.name)
        }

        fn gen_constructor(&self, spec: &TraitBridgeSpec) -> String {
            format!(
                "impl {} {{\n    pub fn new(obj: Py<PyAny>) -> Self {{ Self {{ inner: obj, cached_name: String::new() }} }}\n}}",
                spec.wrapper_name()
            )
        }

        fn gen_registration_fn(&self, spec: &TraitBridgeSpec) -> String {
            let fn_name = spec.bridge_config.register_fn.as_deref().unwrap_or("register");
            format!("pub fn {fn_name}(obj: Py<PyAny>) {{ /* register */ }}")
        }
    }

    // ---------------------------------------------------------------------------
    // TraitBridgeSpec helpers
    // ---------------------------------------------------------------------------

    #[test]
    fn test_wrapper_name() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        assert_eq!(spec.wrapper_name(), "PyOcrBackendBridge");
    }

    #[test]
    fn test_trait_snake() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        assert_eq!(spec.trait_snake(), "ocr_backend");
    }

    #[test]
    fn test_trait_path_replaces_hyphens() {
        let trait_def = make_type_def("OcrBackend", "my-lib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        assert_eq!(spec.trait_path(), "my_lib::OcrBackend");
    }

    #[test]
    fn test_required_methods_filters_no_default_impl() {
        let methods = vec![
            make_method("process", vec![], TypeRef::String, false, false, None, None),
            make_method("initialize", vec![], TypeRef::Unit, false, true, None, None),
            make_method("detect", vec![], TypeRef::String, false, false, None, None),
        ];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let required = spec.required_methods();
        assert_eq!(required.len(), 2);
        assert!(required.iter().any(|m| m.name == "process"));
        assert!(required.iter().any(|m| m.name == "detect"));
    }

    #[test]
    fn test_optional_methods_filters_has_default_impl() {
        let methods = vec![
            make_method("process", vec![], TypeRef::String, false, false, None, None),
            make_method("initialize", vec![], TypeRef::Unit, false, true, None, None),
            make_method("shutdown", vec![], TypeRef::Unit, false, true, None, None),
        ];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let optional = spec.optional_methods();
        assert_eq!(optional.len(), 2);
        assert!(optional.iter().any(|m| m.name == "initialize"));
        assert!(optional.iter().any(|m| m.name == "shutdown"));
    }

    #[test]
    fn test_error_path() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        assert_eq!(spec.error_path(), "mylib::MyError");
    }

    // ---------------------------------------------------------------------------
    // format_type_ref
    // ---------------------------------------------------------------------------

    #[test]
    fn test_format_type_ref_primitives() {
        let paths = HashMap::new();
        let cases: Vec<(TypeRef, &str)> = vec![
            (TypeRef::Primitive(PrimitiveType::Bool), "bool"),
            (TypeRef::Primitive(PrimitiveType::U8), "u8"),
            (TypeRef::Primitive(PrimitiveType::U16), "u16"),
            (TypeRef::Primitive(PrimitiveType::U32), "u32"),
            (TypeRef::Primitive(PrimitiveType::U64), "u64"),
            (TypeRef::Primitive(PrimitiveType::I8), "i8"),
            (TypeRef::Primitive(PrimitiveType::I16), "i16"),
            (TypeRef::Primitive(PrimitiveType::I32), "i32"),
            (TypeRef::Primitive(PrimitiveType::I64), "i64"),
            (TypeRef::Primitive(PrimitiveType::F32), "f32"),
            (TypeRef::Primitive(PrimitiveType::F64), "f64"),
            (TypeRef::Primitive(PrimitiveType::Usize), "usize"),
            (TypeRef::Primitive(PrimitiveType::Isize), "isize"),
        ];
        for (ty, expected) in cases {
            assert_eq!(format_type_ref(&ty, &paths), expected, "mismatch for {expected}");
        }
    }

    #[test]
    fn test_format_type_ref_string() {
        assert_eq!(format_type_ref(&TypeRef::String, &HashMap::new()), "String");
    }

    #[test]
    fn test_format_type_ref_char() {
        assert_eq!(format_type_ref(&TypeRef::Char, &HashMap::new()), "char");
    }

    #[test]
    fn test_format_type_ref_bytes() {
        assert_eq!(format_type_ref(&TypeRef::Bytes, &HashMap::new()), "Vec<u8>");
    }

    #[test]
    fn test_format_type_ref_path() {
        assert_eq!(format_type_ref(&TypeRef::Path, &HashMap::new()), "std::path::PathBuf");
    }

    #[test]
    fn test_format_type_ref_unit() {
        assert_eq!(format_type_ref(&TypeRef::Unit, &HashMap::new()), "()");
    }

    #[test]
    fn test_format_type_ref_json() {
        assert_eq!(format_type_ref(&TypeRef::Json, &HashMap::new()), "serde_json::Value");
    }

    #[test]
    fn test_format_type_ref_duration() {
        assert_eq!(
            format_type_ref(&TypeRef::Duration, &HashMap::new()),
            "std::time::Duration"
        );
    }

    #[test]
    fn test_format_type_ref_optional() {
        let ty = TypeRef::Optional(Box::new(TypeRef::String));
        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Option<String>");
    }

    #[test]
    fn test_format_type_ref_optional_nested() {
        let ty = TypeRef::Optional(Box::new(TypeRef::Optional(Box::new(TypeRef::Primitive(
            PrimitiveType::U32,
        )))));
        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Option<Option<u32>>");
    }

    #[test]
    fn test_format_type_ref_vec() {
        let ty = TypeRef::Vec(Box::new(TypeRef::Primitive(PrimitiveType::U8)));
        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Vec<u8>");
    }

    #[test]
    fn test_format_type_ref_vec_nested() {
        let ty = TypeRef::Vec(Box::new(TypeRef::Vec(Box::new(TypeRef::String))));
        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Vec<Vec<String>>");
    }

    #[test]
    fn test_format_type_ref_map() {
        let ty = TypeRef::Map(
            Box::new(TypeRef::String),
            Box::new(TypeRef::Primitive(PrimitiveType::I64)),
        );
        assert_eq!(
            format_type_ref(&ty, &HashMap::new()),
            "std::collections::HashMap<String, i64>"
        );
    }

    #[test]
    fn test_format_type_ref_map_nested_value() {
        let ty = TypeRef::Map(
            Box::new(TypeRef::String),
            Box::new(TypeRef::Vec(Box::new(TypeRef::String))),
        );
        assert_eq!(
            format_type_ref(&ty, &HashMap::new()),
            "std::collections::HashMap<String, Vec<String>>"
        );
    }

    #[test]
    fn test_format_type_ref_named_without_type_paths() {
        let ty = TypeRef::Named("Config".to_string());
        assert_eq!(format_type_ref(&ty, &HashMap::new()), "Config");
    }

    #[test]
    fn test_format_type_ref_named_with_type_paths() {
        let ty = TypeRef::Named("Config".to_string());
        let mut paths = HashMap::new();
        paths.insert("Config".to_string(), "mylib::Config".to_string());
        assert_eq!(format_type_ref(&ty, &paths), "mylib::Config");
    }

    #[test]
    fn test_format_type_ref_named_not_in_type_paths_falls_back_to_name() {
        let ty = TypeRef::Named("Unknown".to_string());
        let mut paths = HashMap::new();
        paths.insert("Other".to_string(), "mylib::Other".to_string());
        assert_eq!(format_type_ref(&ty, &paths), "Unknown");
    }

    // ---------------------------------------------------------------------------
    // format_param_type
    // ---------------------------------------------------------------------------

    #[test]
    fn test_format_param_type_string_ref() {
        let param = make_param("input", TypeRef::String, true);
        assert_eq!(format_param_type(&param, &HashMap::new()), "&str");
    }

    #[test]
    fn test_format_param_type_string_owned() {
        let param = make_param("input", TypeRef::String, false);
        assert_eq!(format_param_type(&param, &HashMap::new()), "String");
    }

    #[test]
    fn test_format_param_type_bytes_ref() {
        let param = make_param("data", TypeRef::Bytes, true);
        assert_eq!(format_param_type(&param, &HashMap::new()), "&[u8]");
    }

    #[test]
    fn test_format_param_type_bytes_owned() {
        let param = make_param("data", TypeRef::Bytes, false);
        assert_eq!(format_param_type(&param, &HashMap::new()), "Vec<u8>");
    }

    #[test]
    fn test_format_param_type_path_ref() {
        let param = make_param("path", TypeRef::Path, true);
        assert_eq!(format_param_type(&param, &HashMap::new()), "&std::path::Path");
    }

    #[test]
    fn test_format_param_type_path_owned() {
        let param = make_param("path", TypeRef::Path, false);
        assert_eq!(format_param_type(&param, &HashMap::new()), "std::path::PathBuf");
    }

    #[test]
    fn test_format_param_type_vec_ref() {
        let param = make_param("items", TypeRef::Vec(Box::new(TypeRef::String)), true);
        assert_eq!(format_param_type(&param, &HashMap::new()), "&[String]");
    }

    #[test]
    fn test_format_param_type_vec_owned() {
        let param = make_param("items", TypeRef::Vec(Box::new(TypeRef::String)), false);
        assert_eq!(format_param_type(&param, &HashMap::new()), "Vec<String>");
    }

    #[test]
    fn test_format_param_type_named_ref_with_type_paths() {
        let mut paths = HashMap::new();
        paths.insert("Config".to_string(), "mylib::Config".to_string());
        let param = make_param("cfg", TypeRef::Named("Config".to_string()), true);
        assert_eq!(format_param_type(&param, &paths), "&mylib::Config");
    }

    #[test]
    fn test_format_param_type_named_ref_without_type_paths() {
        let param = make_param("cfg", TypeRef::Named("Config".to_string()), true);
        assert_eq!(format_param_type(&param, &HashMap::new()), "&Config");
    }

    #[test]
    fn test_format_param_type_primitive_ref_passes_by_value() {
        // Copy types like u32 are passed by value even when is_ref is set
        let param = make_param("count", TypeRef::Primitive(PrimitiveType::U32), true);
        assert_eq!(format_param_type(&param, &HashMap::new()), "u32");
    }

    #[test]
    fn test_format_param_type_unit_ref_passes_by_value() {
        let param = make_param("nothing", TypeRef::Unit, true);
        assert_eq!(format_param_type(&param, &HashMap::new()), "()");
    }

    // ---------------------------------------------------------------------------
    // format_return_type
    // ---------------------------------------------------------------------------

    #[test]
    fn test_format_return_type_without_error() {
        let result = format_return_type(&TypeRef::String, None, &HashMap::new());
        assert_eq!(result, "String");
    }

    #[test]
    fn test_format_return_type_with_error() {
        let result = format_return_type(&TypeRef::String, Some("MyError"), &HashMap::new());
        assert_eq!(result, "std::result::Result<String, MyError>");
    }

    #[test]
    fn test_format_return_type_unit_with_error() {
        let result = format_return_type(&TypeRef::Unit, Some("Box<dyn std::error::Error>"), &HashMap::new());
        assert_eq!(result, "std::result::Result<(), Box<dyn std::error::Error>>");
    }

    #[test]
    fn test_format_return_type_named_with_type_paths_and_error() {
        let mut paths = HashMap::new();
        paths.insert("Output".to_string(), "mylib::Output".to_string());
        let result = format_return_type(&TypeRef::Named("Output".to_string()), Some("mylib::MyError"), &paths);
        assert_eq!(result, "std::result::Result<mylib::Output, mylib::MyError>");
    }

    // ---------------------------------------------------------------------------
    // gen_bridge_wrapper_struct
    // ---------------------------------------------------------------------------

    #[test]
    fn test_gen_bridge_wrapper_struct_contains_struct_name() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_wrapper_struct(&spec, &generator);
        assert!(
            result.contains("pub struct PyOcrBackendBridge"),
            "missing struct declaration in:\n{result}"
        );
    }

    #[test]
    fn test_gen_bridge_wrapper_struct_contains_inner_field() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_wrapper_struct(&spec, &generator);
        assert!(result.contains("inner: Py<PyAny>"), "missing inner field in:\n{result}");
    }

    #[test]
    fn test_gen_bridge_wrapper_struct_contains_cached_name() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_wrapper_struct(&spec, &generator);
        assert!(
            result.contains("cached_name: String"),
            "missing cached_name field in:\n{result}"
        );
    }

    // ---------------------------------------------------------------------------
    // gen_bridge_plugin_impl
    // ---------------------------------------------------------------------------

    #[test]
    fn test_gen_bridge_plugin_impl_returns_none_when_no_super_trait() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        assert!(gen_bridge_plugin_impl(&spec, &generator).is_none());
    }

    #[test]
    fn test_gen_bridge_plugin_impl_returns_some_when_super_trait_configured() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(Some("Plugin"), None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        assert!(gen_bridge_plugin_impl(&spec, &generator).is_some());
    }

    #[test]
    fn test_gen_bridge_plugin_impl_uses_qualified_super_trait_path() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(Some("Plugin"), None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
        assert!(
            result.contains("impl mylib::Plugin for PyOcrBackendBridge"),
            "missing qualified super-trait path in:\n{result}"
        );
    }

    #[test]
    fn test_gen_bridge_plugin_impl_uses_already_qualified_super_trait_path() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(Some("other_crate::Plugin"), None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
        assert!(
            result.contains("impl other_crate::Plugin for PyOcrBackendBridge"),
            "wrong super-trait path in:\n{result}"
        );
    }

    #[test]
    fn test_gen_bridge_plugin_impl_contains_name_fn() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(Some("Plugin"), None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
        assert!(
            result.contains("fn name(") && result.contains("cached_name"),
            "missing name() using cached_name in:\n{result}"
        );
    }

    #[test]
    fn test_gen_bridge_plugin_impl_contains_version_fn() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(Some("Plugin"), None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
        assert!(result.contains("fn version("), "missing version() in:\n{result}");
    }

    #[test]
    fn test_gen_bridge_plugin_impl_contains_initialize_fn() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(Some("Plugin"), None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
        assert!(result.contains("fn initialize("), "missing initialize() in:\n{result}");
    }

    #[test]
    fn test_gen_bridge_plugin_impl_contains_shutdown_fn() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(Some("Plugin"), None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_plugin_impl(&spec, &generator).unwrap();
        assert!(result.contains("fn shutdown("), "missing shutdown() in:\n{result}");
    }

    // ---------------------------------------------------------------------------
    // gen_bridge_trait_impl
    // ---------------------------------------------------------------------------

    #[test]
    fn test_gen_bridge_trait_impl_includes_impl_header() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_trait_impl(&spec, &generator);
        assert!(
            result.contains("impl mylib::OcrBackend for PyOcrBackendBridge"),
            "missing impl header in:\n{result}"
        );
    }

    #[test]
    fn test_gen_bridge_trait_impl_includes_method_signatures() {
        let methods = vec![make_method(
            "process",
            vec![],
            TypeRef::String,
            false,
            false,
            None,
            None,
        )];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_trait_impl(&spec, &generator);
        assert!(result.contains("fn process("), "missing method signature in:\n{result}");
    }

    #[test]
    fn test_gen_bridge_trait_impl_includes_method_body_from_generator() {
        let methods = vec![make_method(
            "process",
            vec![],
            TypeRef::String,
            false,
            false,
            None,
            None,
        )];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_trait_impl(&spec, &generator);
        assert!(
            result.contains("// sync body for process"),
            "missing sync method body in:\n{result}"
        );
    }

    #[test]
    fn test_gen_bridge_trait_impl_async_method_uses_async_body() {
        let methods = vec![make_method(
            "process_async",
            vec![],
            TypeRef::String,
            true,
            false,
            None,
            None,
        )];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_trait_impl(&spec, &generator);
        assert!(
            result.contains("// async body for process_async"),
            "missing async method body in:\n{result}"
        );
        assert!(
            result.contains("async fn process_async("),
            "missing async keyword in method signature in:\n{result}"
        );
    }

    #[test]
    fn test_gen_bridge_trait_impl_filters_trait_source_methods() {
        // Methods with trait_source set come from super-traits and should be excluded
        let methods = vec![
            make_method("own_method", vec![], TypeRef::String, false, false, None, None),
            make_method(
                "inherited_method",
                vec![],
                TypeRef::String,
                false,
                false,
                Some("other_crate::OtherTrait"),
                None,
            ),
        ];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_trait_impl(&spec, &generator);
        assert!(
            result.contains("fn own_method("),
            "own method should be present in:\n{result}"
        );
        assert!(
            !result.contains("fn inherited_method("),
            "inherited method should be filtered out in:\n{result}"
        );
    }

    #[test]
    fn test_gen_bridge_trait_impl_method_with_params() {
        let params = vec![
            make_param("input", TypeRef::String, true),
            make_param("count", TypeRef::Primitive(PrimitiveType::U32), false),
        ];
        let methods = vec![make_method(
            "process",
            params,
            TypeRef::String,
            false,
            false,
            None,
            None,
        )];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_trait_impl(&spec, &generator);
        assert!(result.contains("input: &str"), "missing &str param in:\n{result}");
        assert!(result.contains("count: u32"), "missing u32 param in:\n{result}");
    }

    #[test]
    fn test_gen_bridge_trait_impl_return_type_with_error() {
        let methods = vec![make_method(
            "process",
            vec![],
            TypeRef::String,
            false,
            false,
            None,
            Some("MyError"),
        )];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_trait_impl(&spec, &generator);
        assert!(
            result.contains("-> std::result::Result<String, mylib::MyError>"),
            "missing std::result::Result return type in:\n{result}"
        );
    }

    // ---------------------------------------------------------------------------
    // gen_bridge_registration_fn
    // ---------------------------------------------------------------------------

    #[test]
    fn test_gen_bridge_registration_fn_returns_none_without_register_fn() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        assert!(gen_bridge_registration_fn(&spec, &generator).is_none());
    }

    #[test]
    fn test_gen_bridge_registration_fn_returns_some_with_register_fn() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, Some("register_ocr_backend"));
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let result = gen_bridge_registration_fn(&spec, &generator);
        assert!(result.is_some());
        let code = result.unwrap();
        assert!(
            code.contains("register_ocr_backend"),
            "missing register fn name in:\n{code}"
        );
    }

    // ---------------------------------------------------------------------------
    // gen_bridge_all
    // ---------------------------------------------------------------------------

    #[test]
    fn test_gen_bridge_all_includes_imports() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        assert!(output.imports.contains(&"pyo3::prelude::*".to_string()));
        assert!(output.imports.contains(&"pyo3::types::PyString".to_string()));
    }

    #[test]
    fn test_gen_bridge_all_includes_wrapper_struct() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        assert!(
            output.code.contains("pub struct PyOcrBackendBridge"),
            "missing struct in:\n{}",
            output.code
        );
    }

    #[test]
    fn test_gen_bridge_all_includes_constructor() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        assert!(
            output.code.contains("pub fn new("),
            "missing constructor in:\n{}",
            output.code
        );
    }

    #[test]
    fn test_gen_bridge_all_includes_trait_impl() {
        let methods = vec![make_method(
            "process",
            vec![],
            TypeRef::String,
            false,
            false,
            None,
            None,
        )];
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", methods);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        assert!(
            output.code.contains("impl mylib::OcrBackend for PyOcrBackendBridge"),
            "missing trait impl in:\n{}",
            output.code
        );
    }

    #[test]
    fn test_gen_bridge_all_includes_plugin_impl_when_super_trait_set() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(Some("Plugin"), None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        assert!(
            output.code.contains("impl mylib::Plugin for PyOcrBackendBridge"),
            "missing plugin impl in:\n{}",
            output.code
        );
    }

    #[test]
    fn test_gen_bridge_all_no_plugin_impl_when_no_super_trait() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        assert!(
            !output.code.contains("fn name(") || !output.code.contains("cached_name"),
            "unexpected plugin impl present without super_trait"
        );
    }

    #[test]
    fn test_gen_bridge_all_includes_registration_fn_when_configured() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, Some("register_ocr_backend"));
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        assert!(
            output.code.contains("register_ocr_backend"),
            "missing registration fn in:\n{}",
            output.code
        );
    }

    #[test]
    fn test_gen_bridge_all_no_registration_fn_when_absent() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        assert!(
            !output.code.contains("register_ocr_backend"),
            "unexpected registration fn present:\n{}",
            output.code
        );
    }

    #[test]
    fn test_gen_bridge_all_ordering_struct_before_trait_impl() {
        let trait_def = make_type_def("OcrBackend", "mylib::OcrBackend", vec![]);
        let config = make_trait_bridge_config(None, None);
        let spec = make_spec(&trait_def, &config, "Py", HashMap::new());
        let generator = MockBridgeGenerator;
        let output = gen_bridge_all(&spec, &generator);
        let struct_pos = output.code.find("pub struct PyOcrBackendBridge").unwrap();
        let impl_pos = output
            .code
            .find("impl mylib::OcrBackend for PyOcrBackendBridge")
            .unwrap();
        assert!(struct_pos < impl_pos, "struct should appear before trait impl");
    }

    // ---------------------------------------------------------------------------
    // find_bridge_param / find_bridge_field
    // ---------------------------------------------------------------------------

    fn make_bridge(
        type_alias: Option<&str>,
        param_name: Option<&str>,
        bind_via: BridgeBinding,
        options_type: Option<&str>,
        options_field: Option<&str>,
    ) -> TraitBridgeConfig {
        TraitBridgeConfig {
            trait_name: "HtmlVisitor".to_string(),
            super_trait: None,
            registry_getter: None,
            register_fn: None,
            unregister_fn: None,
            clear_fn: None,
            type_alias: type_alias.map(str::to_string),
            param_name: param_name.map(str::to_string),
            register_extra_args: None,
            exclude_languages: vec![],
            bind_via,
            options_type: options_type.map(str::to_string),
            options_field: options_field.map(str::to_string),
        }
    }

    #[test]
    fn find_bridge_param_returns_first_param_match_in_function_param_mode() {
        let func = make_func(
            "convert",
            vec![
                make_param("html", TypeRef::String, true),
                make_param("visitor", TypeRef::Named("VisitorHandle".to_string()), false),
            ],
        );
        let bridges = vec![make_bridge(
            Some("VisitorHandle"),
            Some("visitor"),
            BridgeBinding::FunctionParam,
            None,
            None,
        )];
        let result = find_bridge_param(&func, &bridges).expect("bridge match");
        assert_eq!(result.0, 1);
    }

    #[test]
    fn find_bridge_param_skips_options_field_bridges() {
        let func = make_func(
            "convert",
            vec![
                make_param("html", TypeRef::String, true),
                make_param("visitor", TypeRef::Named("VisitorHandle".to_string()), false),
            ],
        );
        let bridges = vec![make_bridge(
            Some("VisitorHandle"),
            Some("visitor"),
            BridgeBinding::OptionsField,
            Some("ConversionOptions"),
            Some("visitor"),
        )];
        assert!(
            find_bridge_param(&func, &bridges).is_none(),
            "bridges configured with bind_via=options_field must not be returned by find_bridge_param"
        );
    }

    #[test]
    fn find_bridge_field_detects_field_via_alias() {
        let opts_type = TypeDef {
            name: "ConversionOptions".to_string(),
            rust_path: "mylib::ConversionOptions".to_string(),
            original_rust_path: String::new(),
            fields: vec![
                make_field("debug", TypeRef::Primitive(PrimitiveType::Bool)),
                make_field(
                    "visitor",
                    TypeRef::Optional(Box::new(TypeRef::Named("VisitorHandle".to_string()))),
                ),
            ],
            methods: vec![],
            is_opaque: false,
            is_clone: true,
            is_copy: false,
            doc: String::new(),
            cfg: None,
            is_trait: false,
            has_default: true,
            has_stripped_cfg_fields: false,
            is_return_type: false,
            serde_rename_all: None,
            has_serde: false,
            super_traits: vec![],
        };
        let func = make_func(
            "convert",
            vec![
                make_param("html", TypeRef::String, true),
                make_param(
                    "options",
                    TypeRef::Optional(Box::new(TypeRef::Named("ConversionOptions".to_string()))),
                    false,
                ),
            ],
        );
        let bridges = vec![make_bridge(
            Some("VisitorHandle"),
            Some("visitor"),
            BridgeBinding::OptionsField,
            Some("ConversionOptions"),
            None,
        )];
        let m = find_bridge_field(&func, std::slice::from_ref(&opts_type), &bridges).expect("bridge field match");
        assert_eq!(m.param_index, 1);
        assert_eq!(m.param_name, "options");
        assert_eq!(m.options_type, "ConversionOptions");
        assert!(m.param_is_optional);
        assert_eq!(m.field_name, "visitor");
    }

    #[test]
    fn find_bridge_field_returns_none_for_function_param_bridge() {
        let opts_type = TypeDef {
            name: "ConversionOptions".to_string(),
            rust_path: "mylib::ConversionOptions".to_string(),
            original_rust_path: String::new(),
            fields: vec![make_field(
                "visitor",
                TypeRef::Optional(Box::new(TypeRef::Named("VisitorHandle".to_string()))),
            )],
            methods: vec![],
            is_opaque: false,
            is_clone: true,
            is_copy: false,
            doc: String::new(),
            cfg: None,
            is_trait: false,
            has_default: true,
            has_stripped_cfg_fields: false,
            is_return_type: false,
            serde_rename_all: None,
            has_serde: false,
            super_traits: vec![],
        };
        let func = make_func(
            "convert",
            vec![make_param(
                "options",
                TypeRef::Named("ConversionOptions".to_string()),
                false,
            )],
        );
        let bridges = vec![make_bridge(
            Some("VisitorHandle"),
            Some("visitor"),
            BridgeBinding::FunctionParam,
            None,
            None,
        )];
        assert!(find_bridge_field(&func, std::slice::from_ref(&opts_type), &bridges).is_none());
    }
}