facet_generate 0.16.0

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

pub mod format;
#[cfg(test)]
pub mod regression_tests;

use std::{
    collections::{BTreeMap, HashMap, HashSet},
    string::ToString,
    sync::LazyLock,
};

use facet::{
    ArrayDef, Def, EnumType, Facet, Field, FieldFlags, ListDef, MapDef, NumericType, OptionDef,
    PointerDef, PointerType, PrimitiveType, SequenceType, SetDef, Shape, SliceDef, StructKind,
    StructType, TextualType, Type, UserType, Variant,
};
use regex::Regex;

use crate as fg;
use crate::{Registry, error::Error};

use format::{
    ContainerFormat, Format, FormatHolder, Named, Namespace, QualifiedTypeName, VariantFormat,
};

const SUPPORTED_GENERIC_TYPES: [&str; 10] = [
    "Arc", "Rc", "Box", "Option", "Vec", "HashMap", "HashSet", "BTreeMap", "BTreeSet", "DateTime",
];

/// A namespace context with its source information
#[derive(Debug, Clone, PartialEq)]
struct NamespaceContext {
    namespace: Namespace,
    explicit: bool, // true = explicitly set, false = inherited
}

impl NamespaceContext {
    /// Creates a cleared namespace context (explicit root)
    fn cleared() -> Self {
        Self {
            namespace: Namespace::Root,
            explicit: true,
        }
    }

    /// Creates an explicitly set namespace context
    fn explicit(namespace: Namespace) -> Self {
        Self {
            namespace,
            explicit: true,
        }
    }

    /// Checks if this context is explicit
    fn is_explicit(&self) -> bool {
        self.explicit
    }

    /// Checks if this context was cleared (explicit root)
    fn is_cleared(&self) -> bool {
        self.explicit && matches!(self.namespace, Namespace::Root)
    }
}

/// Action to take with namespace context
#[derive(Debug, Clone, PartialEq)]
enum NamespaceAction {
    /// Set a specific namespace context
    SetContext(NamespaceContext),
    /// Inherit the current context unchanged (push current context again)
    Inherit,
}

impl NamespaceAction {
    /// Returns true if this action represents an explicit namespace setting
    fn is_explicit(&self) -> bool {
        match self {
            NamespaceAction::SetContext(ctx) => ctx.is_explicit(),
            NamespaceAction::Inherit => false, // Inheriting is not explicit
        }
    }

    /// Returns true if this action should move a type to a specific namespace
    fn should_move_to_namespace(&self, target_namespace: &str) -> bool {
        match self {
            NamespaceAction::SetContext(ctx) if ctx.is_explicit() => {
                match &ctx.namespace {
                    Namespace::Named(type_ns) => {
                        // Type has explicit namespace - only move if it matches the target namespace
                        type_ns == target_namespace
                    }
                    Namespace::Root => {
                        // Type explicitly wants to be in root - don't move to named namespace
                        target_namespace.is_empty() // This would be unusual but handle it
                    }
                }
            }
            NamespaceAction::SetContext(_) | NamespaceAction::Inherit => {
                // No type-level explicit annotation - field-level can override
                true
            }
        }
    }
}

/// The bridge between `facet` compile-time type metadata and the [`Registry`] consumed by
/// code generators.
///
/// Types are added with [`add_type`](Self::add_type), which recursively reflects the type and
/// all types reachable from its fields and variants. The builder tracks which types have already
/// been processed to avoid duplicates and detects conflicts (e.g. a generic type instantiated
/// with different type parameters).
#[derive(Debug, Default)]
pub struct RegistryBuilder {
    pub registry: Registry,
    current: Vec<QualifiedTypeName>,
    processed: HashSet<QualifiedTypeName>,
    name_mappings: BTreeMap<QualifiedTypeName, QualifiedTypeName>,
    generic_type_params: HashMap<String, String>,
    processing_nested: bool,
    namespace_context_stack: Vec<NamespaceContext>,
    type_namespace_sources: HashMap<QualifiedTypeName, bool>, // true = explicit, false = inherited
}

impl RegistryBuilder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Builds the registry from the current state.
    /// # Errors
    /// Will return an error with a suitable error message if the registry is invalid,
    /// usually due to incomplete reflection.
    pub fn build(self) -> Result<Registry, Error> {
        for (type_name, format) in &self.registry {
            if let Err(err) = format.visit(&mut |_| Ok(())) {
                return Err(Error::ReflectionError {
                    type_name: type_name.clone().to_string(),
                    message: err.to_string(),
                });
            }
        }

        Ok(self.registry)
    }

    /// Reflect a type into the registry.
    ///
    /// # Errors
    /// Will return an error if:
    /// * there is a problem building the registry,
    /// * non-special generic types are used with different type parameters,
    /// * there is an unsupported layout,
    /// * namespaces are conflicting,
    /// * namespaces have invalid names, or
    /// * attributes are malformed.
    pub fn add_type<'a, T: Facet<'a>>(mut self) -> Result<Self, Error> {
        self.format(T::SHAPE)?;
        Ok(self)
    }
}

impl RegistryBuilder {
    fn push(&mut self, name: QualifiedTypeName, container: ContainerFormat) {
        self.registry.insert(name.clone(), container);
        self.current.push(name);
    }

    fn push_with_type_check(
        &mut self,
        name: QualifiedTypeName,
        container: ContainerFormat,
        shape: &Shape,
    ) -> Result<(), Error> {
        let is_explicit = extract_namespace_from_shape(shape)?.is_explicit();

        // Check for conflicts: type name in multiple namespaces with mixed explicit/inherited sources
        self.check_namespace_ambiguity(&name, is_explicit)?;

        self.registry.insert(name.clone(), container);
        self.current.push(name);
        Ok(())
    }

    fn push_temporary(
        &mut self,
        name: String,
        container: ContainerFormat,
        parent_context: Option<&Shape>,
    ) -> QualifiedTypeName {
        let temp_name = if let Some(parent) = parent_context {
            let parent_name = parent.type_identifier.replace(['<', '>', ' ', ','], "_");
            format!("{name}__in__{parent_name}")
        } else {
            name
        };
        let qualified_name = QualifiedTypeName {
            namespace: Namespace::Named("__temp__".to_string()),
            name: temp_name,
        };

        self.push(qualified_name.clone(), container);
        qualified_name
    }

    fn register_type_mapping(&mut self, original: QualifiedTypeName, renamed: QualifiedTypeName) {
        self.name_mappings.insert(original, renamed);
    }

    fn is_processed(&self, name: &QualifiedTypeName) -> bool {
        self.processed.contains(name)
    }

    fn mark_processed(&mut self, name: QualifiedTypeName) {
        self.processed.insert(name);
    }

    fn pop(&mut self) {
        self.current.pop();
    }

    fn get_mut(&mut self) -> Option<&mut ContainerFormat> {
        if let Some(name) = self.current.last() {
            self.registry.get_mut(name)
        } else {
            None
        }
    }

    fn format_with_namespace_override(
        &mut self,
        shape: &Shape,
        namespace: &str,
    ) -> Result<(), Error> {
        let base_name = shape.type_identifier.to_string();
        let namespaced_key =
            QualifiedTypeName::namespaced(namespace.to_string(), base_name.clone());

        if !self.registry.contains_key(&namespaced_key) {
            // Store the previous namespace context
            let context = NamespaceContext::explicit(Namespace::Named(namespace.to_string()));
            self.push_namespace(NamespaceAction::SetContext(context));

            // Process the type with the namespace context so nested types inherit the namespace
            self.format(shape)?;

            // Restore the previous namespace context
            self.pop_namespace();

            // Check if the type has a conflicting type-level explicit namespace
            // If type-level explicit matches what we want, or if no type-level explicit, then move is OK
            let original_key = self.get_name_with_mappings(shape)?;

            if original_key != namespaced_key {
                let type_level_namespace = extract_namespace_from_shape(shape)?;

                let should_move = type_level_namespace.should_move_to_namespace(namespace);

                if should_move && let Some(format) = self.registry.remove(&original_key) {
                    self.registry.insert(namespaced_key.clone(), format);
                }
            }
        }

        Ok(())
    }

    fn format(&mut self, mut shape: &Shape) -> Result<(), Error> {
        if is_transparent_shape(shape)
            && let Some(inner) = shape.inner
        {
            shape = inner;
        }

        if !self.is_supported_generic_type(shape) {
            return Err(Error::UnsupportedGenericType(shape.to_string()));
        }

        // First check for special cases in the def system (like Option)
        if let Def::Option(option_def) = shape.def {
            self.format_option(option_def)?;
            return Ok(());
        }

        // Try type system first
        if self.try_format_from_type_system(shape)? {
            return Ok(());
        }

        // Fall back to def system
        self.format_from_def_system(shape)?;
        Ok(())
    }

    fn is_supported_generic_type(&mut self, shape: &Shape) -> bool {
        // Return true immediately for non-generic or special cases
        if shape.type_params.is_empty() {
            return true;
        }

        // Skip lifetimes and arrays
        if shape.type_identifier.starts_with('&') || shape.type_identifier.starts_with('[') {
            return true;
        }

        // Accept known generic types unconditionally
        if SUPPORTED_GENERIC_TYPES.contains(&shape.type_identifier) {
            return true;
        }

        // For other generics, verify all type parameters are consistent with previous uses
        let current_params = format!("{:?}", shape.type_params);
        let previous_params = self
            .generic_type_params
            .entry(shape.type_identifier.to_string())
            .or_insert_with(|| current_params.clone());

        *previous_params == current_params
    }

    fn try_format_from_type_system(&mut self, shape: &Shape) -> Result<bool, Error> {
        match &shape.ty {
            Type::User(UserType::Struct(struct_def)) => {
                self.handle_user_struct(shape, struct_def)?;
                Ok(true)
            }
            Type::User(UserType::Enum(enum_def)) => {
                self.format_enum(enum_def, shape)?;
                Ok(true)
            }
            Type::Sequence(sequence_type) => {
                self.handle_sequence_type(shape, sequence_type)?;
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    fn handle_user_struct(&mut self, shape: &Shape, struct_def: &StructType) -> Result<(), Error> {
        let type_name = self.get_name_with_mappings(shape)?;

        // Update container with the struct format only if not processing nested types
        if !self.processing_nested {
            let format = if shape.type_identifier == "()" {
                Format::Unit
            } else {
                Format::TypeName(type_name.clone())
            };

            self.update_container_format(format, UpdateMode::IfUnknown);
        }

        self.format_struct(struct_def, shape)?;
        Ok(())
    }

    fn handle_sequence_type(
        &mut self,
        shape: &Shape,
        sequence_type: &SequenceType,
    ) -> Result<(), Error> {
        match sequence_type {
            SequenceType::Slice(slice_type) => {
                // For slices, use the Def::Slice if available
                if let Def::Slice(slice_def) = shape.def {
                    self.format_slice(slice_def)?;
                } else {
                    // Fallback: create a slice format from the sequence type info
                    let target_shape = slice_type.t;
                    let inner_format = get_inner_format(target_shape)?;
                    let slice_format = Format::Seq(Box::new(inner_format));
                    self.update_container_format(slice_format, UpdateMode::Force);
                    self.process_nested_types(target_shape)?;
                }
            }
            SequenceType::Array(array_type) => {
                // For arrays, use the Def::Array if available
                if let Def::Array(array_def) = shape.def {
                    self.format_array(array_def)?;
                } else {
                    // Fallback: create an array format from the sequence type info
                    let target_shape = array_type.t;
                    let inner_format = get_inner_format(target_shape)?;
                    let array_format = Format::Seq(Box::new(inner_format)); // Arrays are also sequences
                    self.update_container_format(array_format, UpdateMode::Force);
                    self.process_nested_types(target_shape)?;
                }
            }
        }
        Ok(())
    }

    fn format_from_def_system(&mut self, shape: &Shape) -> Result<(), Error> {
        match shape.def {
            Def::Scalar => self.format_scalar(shape)?,
            Def::Map(map_def) => self.format_map(map_def)?,
            Def::List(list_def) => self.format_list(list_def)?,
            Def::Slice(slice_def) => self.format_slice(slice_def)?,
            Def::Array(array_def) => self.format_array(array_def)?,
            Def::Set(set_def) => self.format_set(set_def)?,
            Def::Option(option_def) => self.format_option(option_def)?,
            Def::Pointer(PointerDef {
                pointee: Some(inner_shape),
                ..
            }) => {
                self.handle_pointer(inner_shape)?;
            }
            Def::Pointer(PointerDef { pointee: None, .. }) => {
                self.handle_opaque_pointee();
            }
            Def::Undefined => {
                self.handle_undefined_def(shape)?;
            }
            _ => (),
        }
        Ok(())
    }

    fn handle_pointer(&mut self, inner_shape: &Shape) -> Result<(), Error> {
        // For Pointer, we need to update the current container with the inner type's format
        let inner_format = get_format_for_shape(inner_shape)?;

        // Update the current container with the Pointer's inner format
        self.update_container_format(inner_format, UpdateMode::IfUnknown);

        // Also process the inner type if it's a user-defined type
        self.process_nested_types(inner_shape)?;

        Ok(())
    }

    fn handle_undefined_def(&mut self, shape: &Shape) -> Result<(), Error> {
        // Handle the case when not yet migrated to the Type enum
        // For primitives, we can try to infer the type
        match &shape.ty {
            Type::Primitive(primitive) => match primitive {
                PrimitiveType::Boolean => {
                    let format = Format::Bool;
                    self.update_container_format(format, UpdateMode::Force);
                }
                PrimitiveType::Numeric(NumericType::Float) => {
                    let format = Format::F32; // or F64, but F32 is more common
                    self.update_container_format(format, UpdateMode::Force);
                }
                PrimitiveType::Textual(TextualType::Str) => {
                    let format = Format::Str;
                    self.update_container_format(format, UpdateMode::Force);
                }
                p => {
                    unimplemented!("Unknown primitive type: {p:?}");
                }
            },
            Type::Pointer(PointerType::Reference(pt) | PointerType::Raw(pt)) => {
                self.format(pt.target)?;
            }
            _ => {}
        }

        Ok(())
    }

    fn format_scalar(&mut self, shape: &Shape) -> Result<(), Error> {
        if let Some(format) = type_to_format(shape)? {
            self.update_container_format(format, UpdateMode::Force);
        }
        // If type_to_format returns None, we skip this field
        Ok(())
    }

    fn format_struct(&mut self, struct_type: &StructType, shape: &Shape) -> Result<(), Error> {
        let struct_name = self.get_name_with_mappings(shape)?;

        // Check if already processed using the full namespaced name
        if self.is_processed(&struct_name) {
            // This is a mutual recursion case - only update if there's an unknown format that needs updating
            let format = Format::TypeName(struct_name.clone());
            self.update_container_format(format, UpdateMode::MutualRecursion);
            return Ok(());
        }

        // Register name mapping if it's different from original
        if struct_name.name != shape.type_identifier {
            let name = QualifiedTypeName {
                namespace: struct_name.namespace.clone(),
                name: shape.type_identifier.to_string(),
            };
            self.register_type_mapping(name, struct_name.clone());
        }

        self.mark_processed(struct_name.clone());

        // Extract namespace from this enum if it has one
        let type_level_namespace = extract_namespace_from_shape(shape)?;

        // Handle namespace context for the enum processing
        self.push_namespace(type_level_namespace);

        match struct_type.kind {
            StructKind::Unit => {
                self.push_with_type_check(
                    struct_name.clone(),
                    ContainerFormat::UnitStruct(shape.into()),
                    shape,
                )?;
                self.pop();
            }
            StructKind::TupleStruct => {
                if struct_type.fields.len() == 1 {
                    let field = struct_type.fields[0];
                    let field_shape = field.shape();

                    // Check if this is a transparent struct
                    let is_transparent = is_transparent_shape(shape);

                    if is_transparent {
                        // For transparent structs, don't create a container - just process the inner type
                        // This will register the transparent struct with its inner type's format
                        if !self.try_handle_bytes_attribute(&field) {
                            self.format(field_shape)?;
                        }
                        self.pop_namespace();
                        return Ok(());
                    }

                    // Handle regular newtype struct
                    let container = ContainerFormat::NewTypeStruct(Box::default(), shape.into());
                    self.push_with_type_check(struct_name.clone(), container, shape)?;

                    // Process the inner field
                    if !self.try_handle_bytes_attribute(&field) {
                        self.format(field_shape)?;
                    }

                    self.pop();
                } else {
                    // Handle tuple struct with multiple fields
                    let container = ContainerFormat::TupleStruct(vec![], shape.into());
                    self.push_with_type_check(struct_name.clone(), container, shape)?;
                    for field in struct_type.fields {
                        let skip = field.flags.contains(FieldFlags::SKIP);
                        if skip {
                            continue;
                        }
                        if !self.try_handle_bytes_attribute(field) {
                            self.format(field.shape())?;
                        }
                    }
                    self.pop();
                }
            }
            StructKind::Struct => {
                let container = ContainerFormat::Struct(vec![], shape.into());
                self.push_with_type_check(struct_name.clone(), container, shape)?;
                for field in struct_type.fields {
                    let skip = field.flags.contains(FieldFlags::SKIP);
                    if skip {
                        continue;
                    }
                    self.handle_struct_field(field)?;
                }

                // If all fields were skipped, convert to UnitStruct to avoid empty data class issues
                if let Some(ContainerFormat::Struct(fields, doc)) = self.get_mut()
                    && fields.is_empty()
                {
                    let unit_container = ContainerFormat::UnitStruct(doc.clone());
                    if let Some(current_name) = self.current.last() {
                        self.registry.insert(current_name.clone(), unit_container);
                    }
                }

                self.pop();
            }
            StructKind::Tuple => {
                // Standalone tuple types never appear as StructKind::Tuple in facet's
                // struct dispatch; they come through as Def::Scalar or Type::Primitive.
            }
        }

        self.pop_namespace();
        Ok(())
    }

    fn handle_struct_field(&mut self, field: &Field) -> Result<(), Error> {
        let field_shape = field.shape();

        // Check for field-level attributes first
        if self.try_handle_bytes_attribute(field) {
            return Ok(());
        }

        if self.try_handle_option_field(field)? {
            return Ok(());
        }

        if self.try_handle_tuple_struct_field(field)? {
            return Ok(());
        }

        // Check for field-level namespace annotation
        let field_namespace = extract_namespace_from_field_attributes(field)?;

        self.push_namespace(field_namespace.clone());

        // Now determine the proper format with the field-level context in place
        let Some(field_format) = self.get_user_type_format(field_shape)? else {
            // Skip this field if format is None (e.g. unknown opaque types)
            self.pop_namespace();
            return Ok(());
        };

        // Process the type under the field-level namespace context
        if let NamespaceAction::SetContext(ctx) = &field_namespace {
            if ctx.is_explicit() {
                if let Namespace::Named(name) = &ctx.namespace {
                    self.format_with_namespace_override(field_shape, name)?;
                } else {
                    self.format(field_shape)?;
                }
            } else {
                self.format(field_shape)?;
            }
        } else {
            self.format(field_shape)?;
        }

        self.pop_namespace();

        if let Some(ContainerFormat::Struct(named_formats, _doc)) = self.get_mut() {
            let format = Named {
                name: field_display_name(field),
                doc: field.into(),
                value: field_format,
            };
            named_formats.push(format);
        }
        Ok(())
    }

    fn try_handle_bytes_attribute(&mut self, field: &Field) -> bool {
        let Some(value) = bytes_attribute_format(field) else {
            return false;
        };
        let Some(container) = self.get_mut() else {
            return false;
        };
        match container {
            ContainerFormat::NewTypeStruct(format, _doc) => **format = value,
            ContainerFormat::TupleStruct(formats, _doc) => formats.push(value),
            ContainerFormat::Struct(nameds, _doc) => nameds.push(Named {
                name: field_display_name(field),
                doc: field.shape().into(),
                value,
            }),
            _ => return false,
        }
        true
    }

    fn try_handle_option_field(&mut self, field: &Field) -> Result<bool, Error> {
        let field_shape = field.shape();
        // Check if the field is an Option
        if field_shape.type_identifier == "Option"
            && let Def::Option(option_def) = field_shape.def
        {
            // Handle Option types directly
            let inner_shape = option_def.t();
            // Handle pointer types specially
            let inner_format = get_format_for_shape(inner_shape)?;
            let option_format = Format::Option(Box::new(inner_format));

            if let Some(ContainerFormat::Struct(named_formats, _doc)) = self.get_mut() {
                named_formats.push(Named {
                    name: field_display_name(field),
                    doc: field.into(),
                    value: option_format,
                });
            }

            // If the inner type is a user-defined type, we need to process it too
            if !matches!(inner_shape.def, Def::Scalar) {
                self.format(inner_shape)?;
            }
            return Ok(true);
        }
        Ok(false)
    }

    fn try_handle_tuple_struct_field(&mut self, field: &Field) -> Result<bool, Error> {
        let field_shape = field.shape();
        // Check if the field is a tuple struct
        if let Type::User(UserType::Struct(inner_struct)) = &field_shape.ty {
            if inner_struct.kind == StructKind::Tuple {
                // Handle tuple field specially
                let mut tuple_formats = vec![];
                for tuple_field in inner_struct.fields {
                    let tuple_field_shape = tuple_field.shape();
                    let field_format = get_inner_format(tuple_field_shape)?;
                    tuple_formats.push(field_format);
                }

                if let Some(ContainerFormat::Struct(named_formats, _doc)) = self.get_mut() {
                    let tuple_format = if tuple_formats.is_empty() {
                        Format::Unit
                    } else {
                        Format::Tuple(tuple_formats)
                    };
                    named_formats.push(Named {
                        name: field_display_name(field),
                        doc: field.into(),
                        value: tuple_format,
                    });
                }
                return Ok(true);
            }

            // Check if the referenced struct is transparent
            let is_referenced_transparent = inner_struct.kind == StructKind::TupleStruct
                && inner_struct.fields.len() == 1
                && is_transparent_shape(field_shape);

            if is_referenced_transparent {
                // For transparent struct references, use the inner type directly with namespace context
                // Extract namespace from the transparent struct itself, not the parent
                let transparent_namespace = extract_namespace_from_shape(field_shape)?;

                let inner_field = inner_struct.fields[0];
                let inner_field_shape = inner_field.shape();

                // Check if the inner type is a user-defined type that needs namespace-aware naming
                let inner_format = if let Type::User(UserType::Struct(_) | UserType::Enum(_)) =
                    &inner_field_shape.ty
                {
                    let namespaced_name = self.get_name_with_mappings(inner_field_shape)?;
                    Format::TypeName(namespaced_name)
                } else {
                    get_inner_format(inner_field_shape)?
                };

                if let Some(ContainerFormat::Struct(named_formats, _doc)) = self.get_mut() {
                    named_formats.push(Named {
                        name: field_display_name(field),
                        doc: field.into(),
                        value: inner_format,
                    });
                }

                // Process the inner type with the namespace context of the transparent struct
                self.push_namespace(transparent_namespace);
                self.format(inner_field_shape)?;
                self.pop_namespace();

                return Ok(true);
            }
        }

        Ok(false)
    }

    fn format_enum(&mut self, enum_type: &EnumType, shape: &Shape) -> Result<(), Error> {
        let enum_name = self.get_name_with_mappings(shape)?;

        // Check if already processed using the full namespaced name
        if self.is_processed(&enum_name) {
            return Ok(());
        }

        // Register name mapping if it's different from original
        if enum_name.name != shape.type_identifier {
            let name = QualifiedTypeName {
                namespace: enum_name.namespace.clone(),
                name: shape.type_identifier.to_string(),
            };
            self.register_type_mapping(name, enum_name.clone());
        }

        self.mark_processed(enum_name.clone());

        // Extract namespace from this enum if it has one
        let type_level_namespace = extract_namespace_from_shape(shape)?;

        // Handle namespace context for the enum processing
        self.push_namespace(type_level_namespace);

        let variants = self.process_enum_variants(enum_type, shape)?;
        let container = ContainerFormat::Enum(variants, shape.into());
        self.push_with_type_check(enum_name.clone(), container, shape)?;
        self.pop();

        self.pop_namespace();
        Ok(())
    }

    fn process_enum_variants(
        &mut self,
        enum_type: &EnumType,
        shape: &Shape,
    ) -> Result<BTreeMap<u32, Named<VariantFormat>>, Error> {
        let mut variants = BTreeMap::new();
        let mut variant_index = 0u32;

        for variant in enum_type.variants {
            let skip = variant
                .attributes
                .iter()
                .any(|attr| attr.key == "skip" && attr.is_builtin());
            if skip {
                continue;
            }

            let variant_format = self.process_single_variant(variant, shape)?;

            variants.insert(
                variant_index,
                Named {
                    name: variant_display_name(variant),
                    doc: variant.into(),
                    value: variant_format,
                },
            );
            variant_index += 1;
        }

        Ok(variants)
    }

    fn process_single_variant(
        &mut self,
        variant: &Variant,
        shape: &Shape,
    ) -> Result<VariantFormat, Error> {
        if variant.data.fields.is_empty() {
            // Unit variant
            Ok(VariantFormat::Unit)
        } else if variant.data.fields.len() == 1 {
            let is_struct_variant = !variant.data.fields[0]
                .name
                .chars()
                .all(|c| c.is_ascii_digit());

            if is_struct_variant {
                self.process_struct_variant(variant, shape)
            } else {
                self.process_newtype_variant(variant, shape)
            }
        } else {
            self.process_multi_field_variant(variant, shape)
        }
    }

    fn process_newtype_variant(
        &mut self,
        variant: &Variant,
        shape: &Shape,
    ) -> Result<VariantFormat, Error> {
        let field = variant.data.fields[0];
        if let Some(value) = bytes_attribute_format(&field) {
            return Ok(VariantFormat::NewType(Box::new(value)));
        }
        let field_shape = field.shape();
        if is_transparent_shape(field_shape)
            && let Some(inner) = field_shape.inner
            && let Some(format) = self.get_user_type_format(inner)?
        {
            return Ok(VariantFormat::NewType(Box::new(format)));
        }
        if let Def::Option(v) = field_shape.def
            && let Some(format) = self.get_user_type_format(v.t)?
        {
            return Ok(VariantFormat::NewType(Box::new(Format::Option(Box::new(
                format,
            )))));
        }

        if field_shape.type_identifier == "()" {
            Ok(VariantFormat::NewType(Box::new(Format::Unit)))
        } else if let Type::User(UserType::Struct(_) | UserType::Enum(_)) = &field_shape.ty {
            // Check for field-level namespace annotation
            let field_namespace = extract_namespace_from_field_attributes(&field)?;

            match field_namespace {
                NamespaceAction::SetContext(ctx) if ctx.is_explicit() => {
                    // Process the type under the field-specified namespace and create qualified name
                    let base_name = field_shape.type_identifier.to_string();
                    let qualified_name = match &ctx.namespace {
                        Namespace::Root => {
                            let context = NamespaceContext::explicit(Namespace::Root);
                            self.push_namespace(NamespaceAction::SetContext(context));
                            self.format(field_shape)?;
                            self.pop_namespace();
                            QualifiedTypeName::root(base_name)
                        }
                        Namespace::Named(name) => {
                            let context =
                                NamespaceContext::explicit(Namespace::Named(name.clone()));
                            self.push_namespace(NamespaceAction::SetContext(context));
                            self.format(field_shape)?;
                            self.pop_namespace();
                            QualifiedTypeName::namespaced(name.clone(), base_name)
                        }
                    };
                    Ok(VariantFormat::NewType(Box::new(Format::TypeName(
                        qualified_name,
                    ))))
                }
                NamespaceAction::SetContext(_) | NamespaceAction::Inherit => {
                    // For user-defined struct/enum types, create a TypeName reference and process the type
                    self.format(field_shape)?;
                    let namespaced_name = self.get_name_with_mappings(field_shape)?;
                    Ok(VariantFormat::NewType(Box::new(Format::TypeName(
                        namespaced_name,
                    ))))
                }
            }
        } else {
            // For other types, use the temporary container approach
            self.process_newtype_variant_with_temp_container(variant, field_shape, shape)
        }
    }

    fn process_newtype_variant_with_temp_container(
        &mut self,
        variant: &Variant,
        field_shape: &Shape,
        _shape: &Shape,
    ) -> Result<VariantFormat, Error> {
        let field = variant.data.fields[0];

        // Check for field-level namespace annotation
        let field_namespace = extract_namespace_from_field_attributes(&field)?;

        self.push_namespace(field_namespace);

        // Check if this field should be skipped (opaque types)
        let Some(format) = self.get_user_type_format(field_shape)? else {
            // If the field should be skipped, make this a unit variant
            self.pop_namespace();
            return Ok(VariantFormat::Unit);
        };

        // If the field is Unit (opaque), also make this a unit variant
        if matches!(format, Format::Unit) {
            self.pop_namespace();
            return Ok(VariantFormat::Unit);
        }

        // Also ensure the type itself gets processed with the namespace context
        self.format(field_shape)?;

        self.pop_namespace();

        Ok(VariantFormat::NewType(Box::new(format)))
    }

    fn process_multi_field_variant(
        &mut self,
        variant: &Variant,
        shape: &Shape,
    ) -> Result<VariantFormat, Error> {
        // Check if it's a struct variant (named fields) or tuple variant
        let first_field = variant.data.fields[0];
        let is_struct_variant = !first_field.name.chars().all(|c| c.is_ascii_digit());

        if is_struct_variant {
            self.process_struct_variant(variant, shape)
        } else {
            self.process_tuple_variant(variant, shape)
        }
    }

    fn process_struct_variant(
        &mut self,
        variant: &Variant,
        shape: &Shape,
    ) -> Result<VariantFormat, Error> {
        let temp = self.push_temporary(
            variant_display_name(variant),
            ContainerFormat::Struct(vec![], variant.into()),
            Some(shape),
        );

        // Process all fields with their names
        for field in variant.data.fields {
            // Check for #[facet(skip)] attribute on the field
            let skip = field.flags.contains(FieldFlags::SKIP);
            if skip {
                continue;
            }

            let field_shape = field.shape();

            // Check for field-level attributes first
            if let Some(value) = bytes_attribute_format(field) {
                if let Some(ContainerFormat::Struct(named_formats, _doc)) = self.get_mut() {
                    named_formats.push(Named {
                        name: field_display_name(field),
                        doc: field.into(),
                        value,
                    });
                }
                continue;
            }

            // Check for field-level namespace annotation
            let field_namespace = extract_namespace_from_field_attributes(field)?;

            self.push_namespace(field_namespace.clone());

            // Handle Option types specially (like handle_struct_field does)
            if field_shape.type_identifier == "Option"
                && let Def::Option(option_def) = field_shape.def
            {
                let inner_shape = option_def.t();
                let inner_format =
                    get_inner_format_with_context(inner_shape, self.current_namespace())?;
                let option_format = Format::Option(Box::new(inner_format));

                // Process any user-defined types in the nested structure
                if !matches!(inner_shape.def, Def::Scalar) {
                    self.format(inner_shape)?;
                }

                self.pop_namespace();

                if let Some(ContainerFormat::Struct(named_formats, _doc)) = self.get_mut() {
                    named_formats.push(Named {
                        name: field_display_name(field),
                        doc: field.into(),
                        value: option_format,
                    });
                }
                continue;
            }

            // Determine the proper format with the field-level context in place
            let Some(value) = self.get_user_type_format(field_shape)? else {
                // Skip this field if format couldn't be determined
                self.pop_namespace();
                continue;
            };

            // Process the type under the field-level namespace context
            if let NamespaceAction::SetContext(ctx) = &field_namespace {
                if ctx.is_explicit() {
                    if let Namespace::Named(name) = &ctx.namespace {
                        self.format_with_namespace_override(field_shape, name)?;
                    } else {
                        self.format(field_shape)?;
                    }
                } else {
                    self.format(field_shape)?;
                }
            } else {
                self.format(field_shape)?;
            }

            self.pop_namespace();

            if let Some(ContainerFormat::Struct(named_formats, _doc)) = self.get_mut() {
                named_formats.push(Named {
                    name: field_display_name(field),
                    doc: field.into(),
                    value,
                });
            }
        }

        // Extract the formats from the temporary container
        let variant_format = match self.registry.get(&temp) {
            Some(ContainerFormat::Struct(named_formats, _doc)) => {
                if named_formats.is_empty() {
                    // If all fields were skipped, this should be a unit variant
                    VariantFormat::Unit
                } else {
                    VariantFormat::Struct(named_formats.clone())
                }
            }
            _ => VariantFormat::Unit, // Handles missing entries
        };

        // Clean up the temporary container
        let _removed = self.registry.remove(&temp);

        self.pop();

        Ok(variant_format)
    }

    fn process_tuple_variant(
        &mut self,
        variant: &Variant,
        shape: &Shape,
    ) -> Result<VariantFormat, Error> {
        let temp = self.push_temporary(
            variant_display_name(variant),
            ContainerFormat::TupleStruct(vec![], variant.into()),
            Some(shape),
        );

        // Process all fields
        for field in variant.data.fields {
            // Check for #[facet(skip)] attribute on the field
            let skip = field.flags.contains(FieldFlags::SKIP);
            if skip {
                continue;
            }

            if let Some(value) = bytes_attribute_format(field) {
                if let Some(ContainerFormat::TupleStruct(formats, _doc)) = self.get_mut() {
                    formats.push(value);
                }
                continue;
            }
            // Use the namespace context of the current enum for its variant fields
            let transparent_namespace = extract_namespace_from_shape(shape)?;

            self.push_namespace(transparent_namespace);
            self.format(field.shape())?;
            self.pop_namespace();
        }

        // Extract the formats from the temporary container
        let variant_format =
            if let Some(ContainerFormat::TupleStruct(formats, _doc)) = self.registry.get(&temp) {
                VariantFormat::Tuple(formats.clone())
            } else {
                VariantFormat::Unit
            };

        // Clean up the temporary container
        let _removed = self.registry.remove(&temp);

        self.pop();

        Ok(variant_format)
    }

    fn format_list(&mut self, list_def: ListDef) -> Result<(), Error> {
        // Get the inner type of the list
        let inner_shape = list_def.t();

        // Get the format for the inner type recursively
        let inner_format = get_inner_format(inner_shape)?;
        let seq_format = Format::Seq(Box::new(inner_format));

        // Update the current container with the sequence format
        self.update_container_format(seq_format, UpdateMode::Force);

        // Process any user-defined types in the nested structure
        self.process_nested_types(inner_shape)?;

        Ok(())
    }

    fn format_map(&mut self, map_def: MapDef) -> Result<(), Error> {
        // Get the key and value types of the map
        let key_shape = map_def.k();
        let value_shape = map_def.v();

        // Get the formats for key and value types
        let key_format = get_inner_format(key_shape)?;
        let value_format = get_inner_format(value_shape)?;

        let map_format = Format::Map {
            key: Box::new(key_format),
            value: Box::new(value_format),
        };

        // Update the current container with the map format
        self.update_container_format(map_format, UpdateMode::Force);

        // Process any user-defined types in the nested structure
        self.process_nested_types(key_shape)?;
        self.process_nested_types(value_shape)?;

        Ok(())
    }

    fn format_slice(&mut self, slice_def: SliceDef) -> Result<(), Error> {
        // Get the inner type of the slice
        let inner_shape = slice_def.t();

        // Get the format for the inner type
        let inner_format = get_format_for_shape(inner_shape)?;

        let slice_format = Format::Seq(Box::new(inner_format));

        // Update the current container with the slice format
        self.update_container_format(slice_format, UpdateMode::Force);

        // Process any user-defined types in the nested structure
        self.process_nested_types(inner_shape)?;

        Ok(())
    }

    fn format_array(&mut self, array_def: ArrayDef) -> Result<(), Error> {
        // Get the inner type and size of the array
        let inner_shape = array_def.t();
        let array_size = array_def.n;

        // Determine the format for the inner type
        let inner_format = get_inner_format(inner_shape)?;

        let array_format = Format::TupleArray {
            content: Box::new(inner_format),
            size: array_size,
        };

        // Update the current container with the array format
        self.update_container_format(array_format, UpdateMode::Force);

        // If the inner type is a user-defined type, we need to process it too
        if !matches!(inner_shape.def, Def::Scalar) {
            self.format(inner_shape)?;
        }

        Ok(())
    }

    fn format_option(&mut self, option_def: OptionDef) -> Result<(), Error> {
        // Get the inner type of the Option
        let inner_shape = option_def.t();

        // We need to determine what format to use for the Option based on the inner type
        let inner_format = get_format_for_shape(inner_shape)?;
        let option_format = Format::Option(Box::new(inner_format));

        // Update the current container with the option format
        self.update_container_format(option_format, UpdateMode::Force);

        // Process any user-defined types in the nested structure
        self.process_nested_types(inner_shape)?;

        Ok(())
    }

    fn format_set(&mut self, set_def: SetDef) -> Result<(), Error> {
        // Get the element type of the Set
        let element_shape = set_def.t();

        // Get the format for the element type recursively
        let element_format = get_inner_format(element_shape)?;

        // Sets are represented as sets in the format system
        let set_format = Format::Set(Box::new(element_format));

        // Update the current container with the set format
        self.update_container_format(set_format, UpdateMode::Force);

        // Process any user-defined types in the nested structure
        self.process_nested_types(element_shape)?;

        Ok(())
    }

    fn handle_opaque_pointee(&mut self) {
        // For pointers that point to opaque types, treat as unit type for now
        let format = Format::Unit;
        self.update_container_format(format, UpdateMode::Force);
    }

    /// Push a namespace action onto the stack (always pushes something)
    fn push_namespace(&mut self, action: NamespaceAction) {
        let context = match action {
            NamespaceAction::SetContext(ctx) => ctx,
            NamespaceAction::Inherit => {
                // Push the current context again (or cleared context if none exists)
                self.namespace_context_stack
                    .last()
                    .cloned()
                    .unwrap_or_else(NamespaceContext::cleared)
            }
        };
        self.namespace_context_stack.push(context);
    }

    /// Pop the current namespace context from the stack
    fn pop_namespace(&mut self) {
        self.namespace_context_stack.pop();
    }

    /// Get the current namespace context (top of stack)
    fn current_namespace_context(&self) -> Option<&NamespaceContext> {
        match self.namespace_context_stack.last() {
            Some(ctx) if ctx.is_cleared() => {
                // This is a "cleared context" marker, so return None
                None
            }
            Some(ctx) => Some(ctx),
            None => None,
        }
    }

    /// Get the current namespace (if any) for use with format functions
    fn current_namespace(&self) -> Option<&Namespace> {
        self.current_namespace_context().map(|ctx| &ctx.namespace)
    }

    /// Helper method to determine format for user-defined types with namespace context
    fn get_user_type_format(&mut self, mut field_shape: &Shape) -> Result<Option<Format>, Error> {
        if is_transparent_shape(field_shape)
            && let Some(inner) = field_shape.inner
        {
            field_shape = inner;
        }
        match &field_shape.ty {
            Type::User(UserType::Struct(_) | UserType::Enum(_)) => {
                if field_shape.type_identifier == "()" {
                    Ok(Some(Format::Unit))
                } else if let Def::Option(v) = field_shape.def {
                    let renamed_name = self.get_name_with_mappings(v.t)?;
                    Ok(Some(Format::Option(Box::new(Format::TypeName(
                        renamed_name,
                    )))))
                } else {
                    let renamed_name = self.get_name_with_mappings(field_shape)?;
                    Ok(Some(Format::TypeName(renamed_name)))
                }
            }
            Type::Pointer(PointerType::Reference(pt) | PointerType::Raw(pt)) => {
                let target_shape = pt.target;
                match get_inner_format_with_context(target_shape, self.current_namespace()) {
                    Ok(format) => Ok(Some(format)),
                    Err(_) => Ok(None), // Skip if inner format fails
                }
            }
            _ => {
                // Check if this is an opaque type that should be skipped.
                // #[facet(opaque)] fields use Def::Undefined.
                if matches!(field_shape.def, Def::Undefined) {
                    Ok(None)
                } else {
                    match get_inner_format_with_context(field_shape, self.current_namespace()) {
                        Ok(format) => Ok(Some(format)),
                        Err(_) => Ok(None), // Skip if inner format fails
                    }
                }
            }
        }
    }

    fn update_container_format(&mut self, format: Format, mode: UpdateMode) {
        if let Some(container_format) = self.get_mut() {
            match container_format {
                ContainerFormat::UnitStruct(_doc) => {}
                ContainerFormat::NewTypeStruct(inner_format, _doc) => match mode {
                    UpdateMode::Force => {
                        **inner_format = format;
                    }
                    UpdateMode::IfUnknown | UpdateMode::MutualRecursion => {
                        if inner_format.is_unknown() {
                            **inner_format = format;
                        }
                    }
                },
                ContainerFormat::TupleStruct(formats, _doc) => {
                    match mode {
                        UpdateMode::Force | UpdateMode::IfUnknown => {
                            formats.push(format);
                        }
                        UpdateMode::MutualRecursion => {
                            // For mutual recursion, don't add duplicate entries to TupleStruct
                            // They should already have the proper format from initial processing
                        }
                    }
                }
                ContainerFormat::Struct(fields, _doc) => {
                    if let Some(last_named) = fields.last_mut() {
                        match mode {
                            UpdateMode::Force => {
                                // Even in Force mode, struct fields are only updated if unknown
                                // This preserves the original behavior where struct fields are set
                                // when first processed and shouldn't be overwritten later
                                if last_named.value.is_unknown() {
                                    last_named.value = format;
                                }
                            }
                            UpdateMode::IfUnknown | UpdateMode::MutualRecursion => {
                                if last_named.value.is_unknown() {
                                    last_named.value = format;
                                }
                            }
                        }
                    }
                }
                ContainerFormat::Enum(_, _doc) => {
                    if matches!(mode, UpdateMode::Force) {
                        todo!("Enum container format update not implemented");
                    }
                }
            }
        }
    }

    fn process_nested_types(&mut self, shape: &Shape) -> Result<(), Error> {
        self.processing_nested = true;
        match shape.def {
            Def::Scalar => {
                // Scalar types don't need further processing
            }
            Def::List(inner_list_def) => {
                // Recursively process nested lists
                let inner_shape = inner_list_def.t();
                self.process_nested_types(inner_shape)?;
            }
            Def::Option(option_def) => {
                // Recursively process options
                let inner_shape = option_def.t();
                if should_process_nested_type(inner_shape) {
                    self.process_nested_types(inner_shape)?;
                }
            }
            Def::Map(map_def) => {
                // Recursively process maps
                let key_shape = map_def.k();
                let value_shape = map_def.v();
                if should_process_nested_type(key_shape) {
                    self.process_nested_types(key_shape)?;
                }
                if should_process_nested_type(value_shape) {
                    self.process_nested_types(value_shape)?;
                }
            }
            Def::Slice(slice_def) => {
                // Recursively process slice inner types
                let inner_shape = slice_def.t();
                self.process_nested_types(inner_shape)?;
            }
            _ => {
                // For other user-defined types, process them
                if should_process_nested_type(shape) {
                    self.format(shape)?;
                }
            }
        }
        self.processing_nested = false;
        Ok(())
    }

    fn get_name_with_mappings(&mut self, shape: &Shape) -> Result<QualifiedTypeName, Error> {
        // First check if there's a mapping for this type
        let base_key = QualifiedTypeName::root(shape.type_identifier.to_string());
        if let Some(mapped_name) = self.name_mappings.get(&base_key) {
            return Ok(mapped_name.clone());
        }

        // Get the original name (which includes explicit namespace annotations)
        let original_name = get_name(shape)?;

        // Check if the type has an explicit namespace annotation (type-level explicit)
        let has_explicit_namespace = extract_namespace_from_shape(shape)?.is_explicit();

        if has_explicit_namespace {
            // Type-level explicit namespace annotation overrides everything (including field-level explicit)
            self.check_namespace_ambiguity(&original_name, true)?;
            return Ok(original_name);
        }

        // If no type-level explicit namespace annotation, apply current context if available
        if let Some(namespace_context) = self.current_namespace_context() {
            match &namespace_context.namespace {
                Namespace::Root => {
                    // Context is explicitly root, use root namespace
                    let root_name = QualifiedTypeName::root(original_name.name.clone());
                    self.check_namespace_ambiguity(&root_name, namespace_context.is_explicit())?;
                    return Ok(root_name);
                }
                Namespace::Named(context_ns) => {
                    // Apply the context namespace
                    let namespaced_name = QualifiedTypeName::namespaced(
                        context_ns.clone(),
                        original_name.name.clone(),
                    );

                    self.check_namespace_ambiguity(
                        &namespaced_name,
                        namespace_context.is_explicit(),
                    )?;

                    return Ok(namespaced_name);
                }
            }
        }

        // Fall back to the original name (which will be root if no annotation)
        Ok(original_name)
    }

    fn check_namespace_ambiguity(
        &mut self,
        new_name: &QualifiedTypeName,
        new_has_explicit_namespace: bool,
    ) -> Result<(), Error> {
        for (existing_name, existing_has_explicit_namespace) in &self.type_namespace_sources {
            if existing_name.name == new_name.name
                && existing_name.namespace != new_name.namespace
                && (!matches!(existing_name.namespace, Namespace::Root)
                    && !matches!(new_name.namespace, Namespace::Root))
            {
                let at_least_one_namespace_inherited =
                    !new_has_explicit_namespace || !*existing_has_explicit_namespace;
                if at_least_one_namespace_inherited {
                    return Err(Error::AmbiguousNamespaceInheritance {
                        type_name: new_name.name.clone(),
                        existing_namespace: existing_name.namespace.to_string(),
                        new_namespace: new_name.namespace.to_string(),
                    });
                }
            }
        }

        self.type_namespace_sources
            .insert(new_name.clone(), new_has_explicit_namespace);

        Ok(())
    }
}

fn get_name(shape: &Shape) -> Result<QualifiedTypeName, Error> {
    // Check type_tag first (is this where facet rename is stored?)
    if let Some(type_tag) = shape.type_tag {
        return Ok(QualifiedTypeName::root(type_tag.to_string()));
    }

    let shape_namespace = extract_namespace_from_shape(shape)?;

    // Check for transparent via repr
    if is_transparent_shape(shape)
        && let Some(inner) = shape.inner
    {
        return get_name(inner);
    }

    // Determine the base name — use the built-in `rename` field if present,
    // then check attributes for a rename (facet derive stores it there),
    // otherwise fall back to the type identifier.
    let base_name = if let Some(rename) = shape.rename {
        rename.to_string()
    } else if let Some(rename) = extract_rename_from_shape_attributes(shape) {
        rename.to_string()
    } else {
        shape.type_identifier.to_string()
    };

    // Apply namespace - only use explicit namespace annotations, no inheritance
    Ok(match shape_namespace {
        NamespaceAction::SetContext(ctx) => match &ctx.namespace {
            Namespace::Root => QualifiedTypeName::root(base_name),
            Namespace::Named(name) => QualifiedTypeName::namespaced(name.clone(), base_name),
        },
        NamespaceAction::Inherit => QualifiedTypeName::root(base_name),
    })
}

fn get_format_for_shape(shape: &Shape) -> Result<Format, Error> {
    let mut shape = match &shape.ty {
        Type::Pointer(PointerType::Reference(pt) | PointerType::Raw(pt)) => pt.target,
        _ => shape,
    };
    if is_transparent_shape(shape)
        && let Some(inner) = shape.inner
    {
        shape = inner;
    }
    get_inner_format(shape)
}

fn type_to_format(shape: &Shape) -> Result<Option<Format>, Error> {
    let format = match &shape.ty {
        Type::Primitive(primitive) => Some(match primitive {
            PrimitiveType::Boolean => Format::Bool,
            PrimitiveType::Numeric(numeric_type) => match numeric_type {
                NumericType::Float => {
                    // Determine float type based on size or type identifier
                    match shape.type_identifier {
                        "f32" => Format::F32,
                        "f64" => Format::F64,
                        _ => unimplemented!("Unsupported float type: {}", shape.type_identifier),
                    }
                }
                NumericType::Integer { signed } => {
                    // Get the size from the layout
                    let size_bytes = shape
                        .layout
                        .sized_layout()
                        .map_err(|_| Error::LayoutUnsized(shape.to_string()))?
                        .size();
                    let size_bits = size_bytes * 8;

                    match (*signed, size_bits) {
                        (false, 8) => Format::U8,
                        (false, 16) => Format::U16,
                        (false, 32) => Format::U32,
                        (false, 64) => Format::U64,
                        (false, 128) => Format::U128,
                        (true, 8) => Format::I8,
                        (true, 16) => Format::I16,
                        (true, 32) => Format::I32,
                        (true, 64) => Format::I64,
                        (true, 128) => Format::I128,
                        _ => unimplemented!(
                            "Unsupported integer type: {size_bits} bits, signed: {signed}"
                        ),
                    }
                }
            },
            PrimitiveType::Textual(textual_type) => match textual_type {
                TextualType::Str => Format::Str,
                TextualType::Char => Format::Char,
            },
            PrimitiveType::Never => {
                unimplemented!("Never type not supported: {}", shape.type_identifier)
            }
        }),
        Type::User(UserType::Opaque) => match shape.type_identifier {
            "String" | "DateTime<Utc>" => Some(Format::Str),
            _ => None,
        },
        // Handle () unit type which in facet 0.44.1 appears as User(Struct(Tuple, []))
        Type::User(UserType::Struct(st))
            if st.kind == StructKind::Tuple && st.fields.is_empty() =>
        {
            Some(Format::Unit)
        }
        _ => unimplemented!(
            "Unsupported type for scalar format: {}: {:?}",
            shape.type_identifier,
            shape.ty
        ),
    };

    Ok(format)
}

/// Extract a rename value from shape attributes.
///
/// In the latest facet, `#[facet(rename = "...")]` on a container is stored
/// in `shape.attributes` rather than `shape.rename`. This helper checks the
/// attributes for a builtin `rename` key and returns the value if found.
fn extract_rename_from_shape_attributes(shape: &Shape) -> Option<&'static str> {
    for attr in shape.attributes {
        if attr.ns.is_none()
            && attr.key == "rename"
            && let Some(s) = attr.get_as::<&str>()
        {
            return Some(s);
        }
    }
    None
}

fn extract_namespace_from_shape(shape: &Shape) -> Result<NamespaceAction, Error> {
    for attr in shape.attributes {
        if let Some(action) = extract_namespace_from_attr(attr)? {
            return Ok(action);
        }
    }
    Ok(NamespaceAction::Inherit)
}

fn extract_namespace_from_field_attributes(field: &Field) -> Result<NamespaceAction, Error> {
    for attr in field.attributes {
        if let Some(action) = extract_namespace_from_attr(attr)? {
            return Ok(action);
        }
    }
    Ok(NamespaceAction::Inherit)
}

/// Returns the display name for a field, respecting `#[facet(rename = "...")]`.
///
/// If the field has a `rename` value, that is used; otherwise falls back to `field.name`.
fn field_display_name(field: &Field) -> String {
    field.rename.unwrap_or(field.name).to_string()
}

/// Returns the display name for a variant, respecting `#[facet(rename = "...")]`.
///
/// If the variant has a `rename` value, that is used; otherwise falls back to `variant.name`.
fn variant_display_name(variant: &facet::Variant) -> String {
    variant.rename.unwrap_or(variant.name).to_string()
}

/// Extract a namespace action from a single `fg::namespace` extension attribute.
///
/// - `#[facet(fg::namespace = "MyNs")]` → `SetContext(explicit(Named("MyNs")))`
/// - `#[facet(fg::namespace)]` (no value) → `SetContext(cleared())`
/// - Any other attribute → `None` (not a namespace attr)
fn extract_namespace_from_attr(attr: &facet::Attr) -> Result<Option<NamespaceAction>, Error> {
    if attr.ns != Some("fg") || attr.key != "namespace" {
        return Ok(None);
    }

    // The data is stored as fg::Attr::Namespace(Option<&'static str>)
    let Some(gen_attr) = attr.get_as::<fg::Attr>() else {
        return Err(Error::InvalidNamespaceFormat);
    };

    match gen_attr {
        fg::Attr::Namespace(Some(ns_str)) => {
            static VALID_IDENT: LazyLock<Regex> =
                LazyLock::new(|| Regex::new(r"^[a-zA-Z_]\w*$").expect("Invalid regex"));
            if !VALID_IDENT.is_match(ns_str) {
                return Err(Error::InvalidNamespaceIdentifier);
            }
            Ok(Some(NamespaceAction::SetContext(
                NamespaceContext::explicit(Namespace::Named(ns_str.to_string())),
            )))
        }
        fg::Attr::Namespace(None) => Ok(Some(NamespaceAction::SetContext(
            NamespaceContext::cleared(),
        ))),
        _ => Ok(None),
    }
}

fn is_transparent_shape(shape: &Shape) -> bool {
    shape
        .attributes
        .iter()
        .any(|attr| attr.ns.is_none() && attr.key == "transparent")
}

#[derive(Debug, Clone, Copy)]
enum UpdateMode {
    /// Unconditionally update the container format
    Force,
    /// Only update if the current format is unknown
    IfUnknown,
    /// Only update unknown formats, but don't add to `TupleStruct` (for mutual recursion)
    MutualRecursion,
}

fn should_process_nested_type(shape: &Shape) -> bool {
    !matches!(shape.def, Def::Scalar) && shape.type_identifier != "()"
}

fn bytes_attribute_format(field: &Field) -> Option<Format> {
    let mut shape = field.shape();
    let is_bytes_attr = |field: &Field| {
        field
            .attributes
            .iter()
            .any(|attr| attr.key == "bytes" && attr.ns == Some("fg"))
    };
    let mut is_transparent_bytes = || {
        if is_transparent_shape(shape) {
            match shape.ty {
                Type::User(ty) => match ty {
                    UserType::Struct(ty) => match ty.kind {
                        StructKind::TupleStruct => {
                            if ty.fields.len() == 1 {
                                let field = ty.fields[0];
                                shape = field.shape();
                                is_bytes_attr(&field)
                            } else {
                                false
                            }
                        }
                        _ => false,
                    },
                    UserType::Enum(_) => todo!(),
                    UserType::Union(_) => todo!(),
                    UserType::Opaque => false,
                },
                _ => false,
            }
        } else {
            false
        }
    };
    if !is_bytes_attr(field) && !is_transparent_bytes() {
        return None;
    }

    let (is_option, field_shape) = {
        let base_shape = shape;
        if let Def::Option(opt) = base_shape.def {
            (true, opt.t)
        } else {
            (false, base_shape)
        }
    };

    let format = || {
        if is_option {
            Format::Option(Box::new(Format::Bytes))
        } else {
            Format::Bytes
        }
    };

    // Handle bytes attribute for Vec<u8>
    if field_shape.type_identifier == "Vec" {
        // Check if it's actually Vec<u8> by examining the definition
        if let Def::List(list_def) = field_shape.def {
            let inner_shape = list_def.t();
            if inner_shape.type_identifier == "u8" {
                return Some(format());
            }
        }
    }

    if field_shape.type_identifier == "Bytes" {
        return Some(format());
    }

    // Handle fixed byte arrays
    if let Def::Array(ArrayDef { t, .. }) = field_shape.def
        && t.type_identifier == "u8"
    {
        return Some(format());
    }

    // Handle bytes attribute for &[u8] slices
    if let Type::Pointer(PointerType::Reference(pd) | PointerType::Raw(pd)) = &field_shape.ty {
        let target_shape = pd.target;
        if let Def::Slice(slice_def) = target_shape.def {
            let element_shape = slice_def.t();
            if element_shape.type_identifier == "u8" {
                return Some(format());
            }
        }
    }
    eprintln!(
        "{} is not a valid bytes attribute",
        field_shape.type_identifier
    );
    None
}

fn get_inner_format(shape: &Shape) -> Result<Format, Error> {
    get_inner_format_with_context(shape, None)
}

#[allow(clippy::too_many_lines)]
fn get_inner_format_with_context(
    mut shape: &Shape,
    namespace_context: Option<&Namespace>,
) -> Result<Format, Error> {
    if is_transparent_shape(shape)
        && let Some(inner) = shape.inner
    {
        shape = inner;
    }
    let format = match shape.def {
        Def::Scalar => match type_to_format(shape)? {
            Some(format) => format,
            None => {
                return Err(Error::ReflectionError {
                    type_name: shape.type_identifier.to_string(),
                    message: "Scalar type is not supported and should be skipped".to_string(),
                });
            }
        },
        Def::List(inner_list_def) => {
            // Recursively handle nested lists
            let inner_shape = inner_list_def.t();
            Format::Seq(Box::new(get_inner_format_with_context(
                inner_shape,
                namespace_context,
            )?))
        }
        Def::Option(option_def) => {
            // Handle Option<T> -> OPTION: T
            let inner_shape = option_def.t();
            let inner_format = get_inner_format_with_context(inner_shape, namespace_context)?;
            Format::Option(Box::new(inner_format))
        }
        Def::Map(map_def) => {
            // Handle Map<K, V> -> MAP: { KEY: K, VALUE: V }
            let key_shape = map_def.k();
            let value_shape = map_def.v();
            let key_format = get_inner_format_with_context(key_shape, namespace_context)?;
            let value_format = get_inner_format_with_context(value_shape, namespace_context)?;
            Format::Map {
                key: Box::new(key_format),
                value: Box::new(value_format),
            }
        }
        Def::Set(set_def) => {
            // Handle Set<T> -> SET: T
            let inner_shape = set_def.t();
            Format::Set(Box::new(get_inner_format_with_context(
                inner_shape,
                namespace_context,
            )?))
        }
        Def::Array(array_def) => {
            // Handle Array<T, N> -> TUPLEARRAY: { CONTENT: T, SIZE: N }
            let inner_shape = array_def.t();
            let inner_format = get_inner_format_with_context(inner_shape, namespace_context)?;
            Format::TupleArray {
                content: Box::new(inner_format),
                size: array_def.n,
            }
        }
        Def::Undefined => {
            // Check if this is a tuple type by examining the type structure
            if let Type::User(UserType::Struct(struct_type)) = &shape.ty
                && struct_type.kind == StructKind::Tuple
                && !struct_type.fields.is_empty()
            {
                // Handle tuple types -> TUPLE: [field1, field2, ...]
                let mut tuple_formats = vec![];
                for field in struct_type.fields {
                    let field_shape = field.shape();
                    let field_format =
                        get_inner_format_with_context(field_shape, namespace_context)?;
                    tuple_formats.push(field_format);
                }
                return Ok(Format::Tuple(tuple_formats));
            }

            // Special case for unit type
            if shape.type_identifier == "()" {
                Format::Unit
            } else if let Type::Pointer(PointerType::Reference(pt) | PointerType::Raw(pt)) =
                &shape.ty
            {
                // For pointer types like &'static str, get the format of the target type
                let target_shape = pt.target;
                get_inner_format_with_context(target_shape, namespace_context)?
            } else {
                // For user-defined types, use TypeName with namespace context if available
                let original_name = get_name(shape)?;
                let name = if let Some(namespace) = namespace_context {
                    // If the type doesn't have its own namespace annotation and we're in a namespace context,
                    // apply the context namespace
                    if matches!(original_name.namespace, Namespace::Root) {
                        match namespace {
                            Namespace::Root => QualifiedTypeName::root(original_name.name.clone()),
                            Namespace::Named(name) => QualifiedTypeName::namespaced(
                                name.clone(),
                                original_name.name.clone(),
                            ),
                        }
                    } else {
                        original_name
                    }
                } else {
                    original_name
                };

                Format::TypeName(name)
            }
        }
        Def::Slice(slice_def) => {
            // Handle Slice<T> -> SEQ: T
            let inner_shape = slice_def.t();
            Format::Seq(Box::new(get_inner_format_with_context(
                inner_shape,
                namespace_context,
            )?))
        }
        Def::Pointer(pointer_def) => {
            // Handle Pointer (Box, Arc, etc.) by recursively processing the inner type
            if let Some(inner_shape) = pointer_def.pointee {
                get_inner_format_with_context(inner_shape, namespace_context)?
            } else {
                // Fallback for pointers without a known pointee
                Format::Unit
            }
        }
        _ => todo!(),
    };

    Ok(format)
}

#[cfg(test)]
mod tests;

#[cfg(test)]
#[path = "namespace_tests.rs"]
mod namespace_tests;