rvt 0.4.0

Apache-2.0 clean-room reader for Autodesk Revit files (.rvt, .rfa, .rte, .rft) without Revit: metadata, previews and the embedded schema of 2016-2026 files, and typed elements with measured geometry from Revit 2024 and 2025 projects, exported as IFC4, glTF and plan SVG.
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
//! IFC entity types targeted by the exporter.
//!
//! Intentionally minimal — only the entity categories the mapping table in
//! `mod.rs` references. Expand as Layer 4c progresses and more Revit
//! classes become decodable.

use serde::{Deserialize, Serialize};

// `IfcEntity::BuildingElement` is intentionally large (~608 B): it
// carries every per-element property slot (material indices, layer /
// profile set indices, extrusion, solid shape, representation map,
// property set, host element, location, rotation). Boxing it would
// spill one heap allocation per element — usually tens to hundreds
// of thousands in a real Revit project — for zero semantic win,
// since IfcModel owns these for the STEP writer's lifetime.
// Project / TypeObject are rare; BuildingElement dominates the cache
// footprint regardless of whether the variants are same-sized.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum IfcEntity {
    Project {
        name: Option<String>,
        description: Option<String>,
        long_name: Option<String>,
    },
    BuildingElementType {
        ifc_type: String,
        name: String,
        description: Option<String>,
    },
    BuildingElement {
        ifc_type: String,
        name: String,
        type_guid: Option<String>,
        /// IFC4 `PredefinedType` enum token for this element, without
        /// the STEP dots (`"COLUMN"`, `"FLOOR"`, `"STANDARD"`). Comes
        /// from [`super::category_map::Mapping::predefined_type`] —
        /// the Revit class decides it, so two elements that share an
        /// entity type can still differ (`IfcMember` is `BRACE` for
        /// `Brace` and `PURLIN` for `Purlin`).
        ///
        /// `None` writes `$` into the slot. The slot itself is always
        /// written when the entity declares the attribute: an IFC4
        /// instance must carry every attribute its type declares, so
        /// omitting an unknown optional makes the record
        /// non-conformant rather than merely incomplete (#214).
        #[serde(default)]
        predefined_type: Option<String>,
        /// Index into `IfcModel.building_storeys` — which storey
        /// contains this element. `None` means the writer should
        /// default it to the first storey (common when the element's
        /// `level_id` wasn't resolved yet).
        #[serde(default)]
        storey_index: Option<usize>,
        /// Index into `IfcModel.materials` — which material this
        /// element associates with. `None` means the element has no
        /// material, so no IfcRelAssociatesMaterial gets emitted for
        /// it (IFC4 treats material as optional for every concrete
        /// type).
        #[serde(default)]
        material_index: Option<usize>,
        /// Property-set name + list of (name, value) pairs to emit
        /// as IfcPropertySet → IfcPropertySingleValue → element via
        /// IfcRelDefinesByProperties. Empty = no property set. The
        /// property-set name should follow Revit / IFC convention:
        /// usually "Pset_RevitType_{ClassName}" to match what the
        /// Autodesk exporter produces.
        #[serde(default)]
        property_set: Option<PropertySet>,
        /// Element origin in feet, expressed in the project's
        /// coordinate system. When `Some`, the writer emits a
        /// unique IFCCARTESIANPOINT + IFCAXIS2PLACEMENT3D for this
        /// element (ft → m conversion at emit time). When `None`,
        /// the element uses the shared identity placement — fine
        /// until geometry lands and positions start mattering.
        #[serde(default)]
        location_feet: Option<[f64; 3]>,
        /// Element rotation about the Z (up) axis, in radians. Only
        /// consulted when `location_feet` is `Some` — the placement
        /// with a non-default X-axis direction needs a unique
        /// IFCDIRECTION.
        #[serde(default)]
        rotation_radians: Option<f64>,
        /// Optional rectangular extrusion geometry. When `Some`, the
        /// writer emits the IfcExtrudedAreaSolid chain and wires the
        /// element's Representation slot to it. When `None`, the
        /// element stays geometry-free (Representation = $).
        #[serde(default)]
        extrusion: Option<Extrusion>,
        /// Index into `IfcModel.entities` naming a host BuildingElement
        /// (typically the wall that contains this door/window). When
        /// set, the writer emits an IfcOpeningElement (same shape as
        /// this element's extrusion) + IfcRelVoidsElement (host →
        /// opening) + IfcRelFillsElement (opening → this element).
        /// The host must already be in `entities` before this element
        /// and must itself be a BuildingElement with an extrusion
        /// (otherwise the void subtracts from nothing).
        #[serde(default)]
        host_element_index: Option<usize>,
        /// Index into `IfcModel.material_layer_sets` — the layered
        /// assembly (gypsum / insulation / sheathing / …) that
        /// makes up this element (IFC-28). Used for walls, slabs,
        /// roofs, and ceilings that have a real multi-layer
        /// composition. When set, the writer emits
        /// `IfcMaterialLayerSet` + `IfcMaterialLayerSetUsage` + an
        /// `IfcRelAssociatesMaterial` pointing at the layer-set
        /// usage — *instead of* the single-material path driven by
        /// `material_index`. When both are set, the layer set
        /// wins (single-material falls back to the first layer).
        #[serde(default)]
        material_layer_set_index: Option<usize>,
        /// Index into `IfcModel.material_profile_sets` — the
        /// profile-based material assignment for structural framing
        /// (columns / beams) with named cross-sections (IFC-30).
        /// When set, the writer emits `IfcMaterialProfileSet` +
        /// `IfcMaterialProfileSetUsage` instead of the single-material
        /// or layer-set paths. Precedence order for material
        /// association: profile_set > layer_set > single material.
        #[serde(default)]
        material_profile_set_index: Option<usize>,
        /// Optional richer solid geometry (IFC-18 / IFC-19 / IFC-20).
        /// When `Some`, the writer emits the corresponding
        /// `IfcRevolvedAreaSolid`, `IfcBooleanResult`, or
        /// `IfcFacetedBrep` chain into the element's Representation
        /// slot **instead of** the `IfcExtrudedAreaSolid` chain
        /// driven by `extrusion`. When both `solid_shape` and
        /// `extrusion` are set, `solid_shape` wins; when both are
        /// `None`, the element stays geometry-free
        /// (Representation = $).
        #[serde(default)]
        solid_shape: Option<SolidShape>,
        /// Index into `IfcModel.representation_maps` — when set,
        /// the element shares a common shape representation with
        /// other instances pointing at the same map (IFC-21). The
        /// writer emits an `IfcMappedItem` + `IfcShapeRepresentation`
        /// with representation-type `'MappedRepresentation'` in
        /// place of the per-instance extrusion / solid chain.
        ///
        /// Precedence (highest wins):
        /// 1. `representation_map_index`   (IFC-21 mapped item)
        /// 2. `solid_shape`                (IFC-18/19/20 solid)
        /// 3. `extrusion`                  (IFC-16 extruded area)
        /// 4. none                         (Representation = $)
        ///
        /// Typical Revit → IFC use: every Door or Window sharing
        /// the same Symbol (type family) references a single
        /// representation map. The writer emits the shape chain
        /// once, instances emit a ~4-entity IfcMappedItem wrap.
        #[serde(default)]
        representation_map_index: Option<usize>,
    },
    TypeObject {
        name: String,
        shape_representations: Vec<String>,
    },
    /// An `IfcRelAggregates` between building elements: `whole` (a stair)
    /// decomposes into `parts` (its runs, landings and stringers), as
    /// in Revit's own export (#323). Both are indices into
    /// `IfcModel::entities`. A part is reached through its whole instead of
    /// being contained in a storey itself.
    Aggregate { whole: usize, parts: Vec<usize> },
    /// A further property set of the building element at `element` (an
    /// index into `IfcModel::entities`), beside its own `property_set`:
    /// a standard set such as `Pset_StairCommon` (RE-47).
    ElementPropertySet { element: usize, set: PropertySet },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Classification {
    pub source: ClassificationSource,
    pub edition: Option<String>,
    pub items: Vec<ClassificationItem>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ClassificationSource {
    OmniClass,
    Uniformat,
    Other(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClassificationItem {
    pub code: String,
    pub name: Option<String>,
}

/// Swept-area-solid geometry descriptor for a BuildingElement. The
/// writer turns this into an `IfcProfileDef` subclass +
/// `IfcExtrudedAreaSolid` + `IfcShapeRepresentation` +
/// `IfcProductDefinitionShape` chain and points the element's
/// Representation slot at the chain.
///
/// All values in feet; the writer converts to metres at emit
/// boundary (ft × 0.3048). The profile is centred on the element
/// origin and the extrusion runs +Z.
///
/// Backward-compat: the primary shape is still a rectangle defined
/// by [`width_feet`] × [`depth_feet`]. Callers that need a richer
/// cross-section (circle, I-beam, T, L, U, hollow rectangle, hollow
/// circle, arbitrary closed polyline) set [`profile_override`] to a
/// [`ProfileDef`] — when `Some`, the writer emits the matching
/// `IfcProfileDef` subclass (IFC-24) and ignores `width_feet` /
/// `depth_feet`. `height_feet` is always honoured as the extrusion
/// depth.
///
/// [`width_feet`]: Extrusion::width_feet
/// [`depth_feet`]: Extrusion::depth_feet
/// [`profile_override`]: Extrusion::profile_override
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Extrusion {
    /// Profile width (local X, in feet) when `profile_override` is
    /// `None`. For a wall = length along its location line. For a
    /// slab = plan dimension in X. Ignored when `profile_override`
    /// is `Some`.
    pub width_feet: f64,
    /// Profile depth (local Y, in feet) when `profile_override` is
    /// `None`. For a wall = thickness. For a slab = plan dimension
    /// in Y. Ignored when `profile_override` is `Some`.
    pub depth_feet: f64,
    /// Extrusion depth (local Z, in feet). For a wall = height;
    /// for a slab = slab thickness; for a column = height; for a
    /// beam = length along its structural axis.
    pub height_feet: f64,
    /// Optional non-rectangular profile (IFC-24). When `Some`, the
    /// writer emits the corresponding `IfcProfileDef` subclass
    /// (`IFCCIRCLEPROFILEDEF`, `IFCIShapeProfileDef`,
    /// `IFCTShapeProfileDef`, `IFCLShapeProfileDef`,
    /// `IFCUShapeProfileDef`, `IFCRectangleHollowProfileDef`,
    /// `IFCCircleHollowProfileDef`, or `IFCArbitraryClosedProfileDef`)
    /// instead of the default `IFCRectangleProfileDef`. Use
    /// `Extrusion::circle`, `Extrusion::i_shape`, etc. constructors
    /// for ergonomics.
    #[serde(default)]
    pub profile_override: Option<ProfileDef>,
}

impl Extrusion {
    /// Rectangular profile — the default / backward-compatible
    /// shape. Equivalent to leaving `profile_override` at `None`.
    pub fn rectangle(width_feet: f64, depth_feet: f64, height_feet: f64) -> Self {
        Self {
            width_feet,
            depth_feet,
            height_feet,
            profile_override: None,
        }
    }

    /// Solid circular profile (e.g. round column, round pier).
    /// Emits `IFCCIRCLEPROFILEDEF`.
    pub fn circle(radius_feet: f64, height_feet: f64) -> Self {
        let diameter = radius_feet * 2.0;
        Self {
            width_feet: diameter,
            depth_feet: diameter,
            height_feet,
            profile_override: Some(ProfileDef::Circle { radius_feet }),
        }
    }

    /// I-shape profile (wide-flange, W/S/HP shapes in AISC). Emits
    /// `IFCIShapeProfileDef`. `overall_width_feet` is the flange
    /// width; `overall_depth_feet` is the beam depth between outer
    /// flange faces.
    pub fn i_shape(
        overall_width_feet: f64,
        overall_depth_feet: f64,
        web_thickness_feet: f64,
        flange_thickness_feet: f64,
        height_feet: f64,
    ) -> Self {
        Self {
            width_feet: overall_width_feet,
            depth_feet: overall_depth_feet,
            height_feet,
            profile_override: Some(ProfileDef::IShape {
                overall_width_feet,
                overall_depth_feet,
                web_thickness_feet,
                flange_thickness_feet,
            }),
        }
    }

    /// T-shape profile (structural tee, WT/ST/MT cut from I-beams).
    /// Emits `IFCTShapeProfileDef`.
    pub fn t_shape(
        overall_depth_feet: f64,
        flange_width_feet: f64,
        web_thickness_feet: f64,
        flange_thickness_feet: f64,
        height_feet: f64,
    ) -> Self {
        Self {
            width_feet: flange_width_feet,
            depth_feet: overall_depth_feet,
            height_feet,
            profile_override: Some(ProfileDef::TShape {
                overall_depth_feet,
                flange_width_feet,
                web_thickness_feet,
                flange_thickness_feet,
            }),
        }
    }

    /// L-shape (angle) profile — equal-leg when `width == depth`.
    /// Emits `IFCLShapeProfileDef`.
    pub fn l_shape(
        overall_depth_feet: f64,
        overall_width_feet: f64,
        thickness_feet: f64,
        height_feet: f64,
    ) -> Self {
        Self {
            width_feet: overall_width_feet,
            depth_feet: overall_depth_feet,
            height_feet,
            profile_override: Some(ProfileDef::LShape {
                overall_depth_feet,
                overall_width_feet,
                thickness_feet,
            }),
        }
    }

    /// U-shape (channel) profile. Emits `IFCUShapeProfileDef`.
    pub fn u_shape(
        overall_depth_feet: f64,
        flange_width_feet: f64,
        web_thickness_feet: f64,
        flange_thickness_feet: f64,
        height_feet: f64,
    ) -> Self {
        Self {
            width_feet: flange_width_feet,
            depth_feet: overall_depth_feet,
            height_feet,
            profile_override: Some(ProfileDef::UShape {
                overall_depth_feet,
                flange_width_feet,
                web_thickness_feet,
                flange_thickness_feet,
            }),
        }
    }

    /// Rectangular hollow section (HSS tube). Emits
    /// `IFCRectangleHollowProfileDef`.
    pub fn rectangle_hollow(
        overall_width_feet: f64,
        overall_depth_feet: f64,
        wall_thickness_feet: f64,
        height_feet: f64,
    ) -> Self {
        Self {
            width_feet: overall_width_feet,
            depth_feet: overall_depth_feet,
            height_feet,
            profile_override: Some(ProfileDef::RectangleHollow {
                overall_width_feet,
                overall_depth_feet,
                wall_thickness_feet,
            }),
        }
    }

    /// Circular hollow section (round HSS pipe). Emits
    /// `IFCCIRCLEHOLLOWPROFILEDEF`.
    pub fn circle_hollow(radius_feet: f64, wall_thickness_feet: f64, height_feet: f64) -> Self {
        let diameter = radius_feet * 2.0;
        Self {
            width_feet: diameter,
            depth_feet: diameter,
            height_feet,
            profile_override: Some(ProfileDef::CircleHollow {
                radius_feet,
                wall_thickness_feet,
            }),
        }
    }

    /// Arbitrary closed polyline profile (e.g. curtain-mullion
    /// cross-section, custom sketched shape). Emits
    /// `IFCArbitraryClosedProfileDef` + an `IFCPOLYLINE` as the
    /// outer curve. The writer auto-closes the polyline if the
    /// last point doesn't equal the first.
    pub fn arbitrary_closed(points: Vec<(f64, f64)>, height_feet: f64) -> Self {
        let (min_x, max_x, min_y, max_y) = points.iter().fold(
            (
                f64::INFINITY,
                f64::NEG_INFINITY,
                f64::INFINITY,
                f64::NEG_INFINITY,
            ),
            |(mn_x, mx_x, mn_y, mx_y), (x, y)| {
                (mn_x.min(*x), mx_x.max(*x), mn_y.min(*y), mx_y.max(*y))
            },
        );
        let width = (max_x - min_x).max(0.0);
        let depth = (max_y - min_y).max(0.0);
        Self {
            width_feet: width,
            depth_feet: depth,
            height_feet,
            profile_override: Some(ProfileDef::ArbitraryClosed { points }),
        }
    }

    /// Extrusion of an arbitrary closed polygon with holes
    /// (`IFCArbitraryProfileDefWithVoids`). `width_feet` /
    /// `depth_feet` are set from the **outer** polygon's plan
    /// bounding box, so a consumer that ignores the override still
    /// reads a sane envelope.
    pub fn arbitrary_with_voids(
        points: Vec<(f64, f64)>,
        voids: Vec<Vec<(f64, f64)>>,
        height_feet: f64,
    ) -> Self {
        let mut base = Self::arbitrary_closed(points, height_feet);
        if let Some(ProfileDef::ArbitraryClosed { points }) = base.profile_override.take() {
            base.profile_override = Some(ProfileDef::ArbitraryWithVoids { points, voids });
        }
        base
    }
}

/// Boolean operation between two solids (IFC-19).
/// Maps to the IFC4 `IfcBooleanOperator` enum values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IfcBooleanOp {
    /// `.UNION.` — operand_a ∪ operand_b.
    Union,
    /// `.DIFFERENCE.` — operand_a − operand_b (the more common
    /// Revit case: wall minus opening void).
    Difference,
    /// `.INTERSECTION.` — operand_a ∩ operand_b.
    Intersection,
}

impl IfcBooleanOp {
    /// STEP-encoded keyword for the enum value (includes the
    /// surrounding dots, e.g. `".DIFFERENCE."`).
    pub fn as_step_keyword(self) -> &'static str {
        match self {
            IfcBooleanOp::Union => ".UNION.",
            IfcBooleanOp::Difference => ".DIFFERENCE.",
            IfcBooleanOp::Intersection => ".INTERSECTION.",
        }
    }
}

/// One triangular face of an `IfcFacetedBrep`. The three
/// `u32` values are indices into the `vertices` array on the
/// enclosing shell (range-checked at emit time; out-of-range
/// indices cause a panic in debug, are silently clamped to 0 in
/// release — invalid mesh topology is a caller bug).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrepTriangle(pub u32, pub u32, pub u32);

/// A rich solid geometry for a `BuildingElement` (IFC-18 /
/// IFC-19 / IFC-20). Covers three IFC4 solid-body paths that the
/// rectangular [`Extrusion`] can't express:
///
/// | Variant | IFC4 entity chain emitted |
/// |---|---|
/// | `RevolvedArea` | `IfcProfileDef subclass` + `IfcRevolvedAreaSolid` (IFC-18) |
/// | `BooleanResult` | `IfcBooleanResult(op, a, b)` with recursive operand emission (IFC-19) |
/// | `FacetedBrep` | `IfcCartesianPoint` × N + `IfcPolyLoop` × F + `IfcFaceBound` × F + `IfcFace` × F + `IfcClosedShell` + `IfcFacetedBrep` (IFC-20) |
///
/// The `RevolvedArea` variant is the right fit for axi-symmetric
/// elements — lathe-turned columns, bell curves, domes. The
/// `BooleanResult` variant is for elements whose body is a
/// *constructive-solid-geometry* result of simpler shapes
/// (typical Revit: wall minus opening void, when modelled as a
/// body solid rather than via `IfcRelVoidsElement`). The
/// `FacetedBrep` variant is the catch-all fallback for any
/// arbitrary mesh Revit produces (free-form roofs, imported
/// terrain, scanned point clouds meshed into polygons).
///
/// See the writer in `step_writer.rs::emit_solid_shape` for the
/// exact entity layout and the `emit_solid_shape_*` helper
/// methods.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SolidShape {
    /// Profile rotated about an axis through a specified angle.
    /// Emits `IfcRevolvedAreaSolid` (IFC-18). The profile is the
    /// same `ProfileDef` vocabulary used by
    /// [`Extrusion::profile_override`], so a pear-shaped turned
    /// pier column is `RevolvedArea { profile: ArbitraryClosed
    /// { points: <half-silhouette> }, axis_..., angle_radians:
    /// 2π }`.
    RevolvedArea {
        /// 2D cross-section to rotate.
        profile: ProfileDef,
        /// Axis origin in element-local coordinates (feet).
        axis_origin_feet: [f64; 3],
        /// Axis direction unit vector. Writer normalises at emit.
        axis_direction: [f64; 3],
        /// Sweep angle in radians. 2π = full rotation (dome /
        /// turned column / sphere-of-revolution).
        angle_radians: f64,
    },
    /// CSG combination of two nested solids (IFC-19). Emits
    /// `IfcBooleanResult(op, a, b)` with operand_a / operand_b
    /// recursively emitted by the same dispatcher. Use `Difference`
    /// for Revit "subtract void from body" patterns when the void
    /// can't be expressed as an `IfcOpeningElement` link (e.g. a
    /// coffered ceiling, a pier with a carved niche).
    BooleanResult {
        op: IfcBooleanOp,
        operand_a: Box<SolidShape>,
        operand_b: Box<SolidShape>,
    },
    /// Closed polyhedral surface as a faceted brep (IFC-20).
    /// Emits `IFCFACETEDBREP` with one `IfcClosedShell` wrapping
    /// `IfcFace` / `IfcFaceBound` / `IfcPolyLoop` entities and
    /// one `IfcCartesianPoint` per unique vertex. Used for any
    /// Revit element whose body is a mesh rather than a swept
    /// profile — imported terrain, free-form roofs, conceptual
    /// massing brep output, DirectShape IfcOpenShell triangulation.
    FacetedBrep {
        /// Vertex coordinates in element-local space (feet). The
        /// writer converts to metres at emit time.
        vertices_feet: Vec<[f64; 3]>,
        /// Triangular faces. Each triple indexes into
        /// `vertices_feet`. Non-triangular faces should be
        /// pre-tessellated by the caller — the writer emits a
        /// 3-vertex `IfcPolyLoop` per triangle.
        triangles: Vec<BrepTriangle>,
    },
    /// Simple extruded-area solid via the [`Extrusion`] struct.
    /// Emitted when a caller wants to keep `extrusion` set to
    /// `None` but route through `SolidShape` for uniform geometry
    /// handling. Most callers should leave this variant unused
    /// and just set `extrusion` directly — it exists for symmetry
    /// with the other CSG operands.
    ExtrudedArea(Extrusion),
    /// Profile swept along an arbitrary polyline directrix with a
    /// fixed up-reference direction (IFC-17). Emits IFC4
    /// `IfcFixedReferenceSweptAreaSolid`. Use for cable trays,
    /// pipes, duct runs, curtain-wall mullions along a curve,
    /// sloped handrails — anything where the profile stays
    /// orthogonal to the directrix at every sample.
    ///
    /// The directrix is a polyline through the supplied
    /// `directrix_points` (in feet, element-local coordinates).
    /// `fixed_reference` is a unit vector that together with the
    /// directrix tangent defines the profile orientation — it's
    /// the "up" direction the swept profile preserves as the
    /// directrix changes heading.
    ///
    /// IFC4 reserves start / end parameters for trimming the
    /// directrix; we always sweep the full polyline (0 → 1
    /// normalised) which is the correct default for Revit data.
    SweptPath {
        /// 2D cross-section (see [`ProfileDef`]).
        profile: ProfileDef,
        /// Polyline vertices of the directrix path, in feet,
        /// element-local coordinates.
        directrix_points_feet: Vec<[f64; 3]>,
        /// Fixed-reference direction (usually world +Z). Writer
        /// normalises to a unit vector at emit.
        fixed_reference: [f64; 3],
    },
    /// Profile extruded along the Z axis of its own placement. Emits
    /// `IfcExtrudedAreaSolid` whose `Position` is an
    /// `IfcAxis2Placement3D` with this origin, axis and reference
    /// direction, so the profile can stand in any plane: a stair run's
    /// side view extruded across the run (RE-52). The profile's X axis is
    /// `ref_direction` projected onto the plane normal to `axis`, and its
    /// Y axis is `axis` crossed with X, as IFC builds the placement.
    PlacedExtrusion {
        /// 2D cross-section (see [`ProfileDef`]), in the placement's XY
        /// plane.
        profile: ProfileDef,
        /// Placement origin, feet, element-local.
        origin_feet: [f64; 3],
        /// Placement Z axis: the extrusion direction.
        axis: [f64; 3],
        /// Placement reference direction: the profile's X axis.
        ref_direction: [f64; 3],
        /// Extrusion depth along `axis`, feet.
        depth_feet: f64,
    },
}

/// Named cross-sections for an extrusion (IFC-24). Feeds one of
/// eight IFC4 `IfcProfileDef` subclasses. All values in feet
/// (writer converts to metres at emit time). Profiles are centred
/// on the element origin in the local XY frame; positive X is the
/// profile width direction, positive Y is the profile depth
/// direction.
///
/// Profile selection cheat-sheet:
///
/// | Revit class | Typical profile |
/// |---|---|
/// | Structural column (round) | `Circle` |
/// | Structural column (wide-flange) | `IShape` |
/// | Structural column (HSS square) | `RectangleHollow` |
/// | Structural column (round HSS) | `CircleHollow` |
/// | Beam (wide-flange W-shape) | `IShape` |
/// | Beam (channel) | `UShape` |
/// | Beam (angle) | `LShape` |
/// | Beam (tee) | `TShape` |
/// | Curtain mullion | `ArbitraryClosed` |
/// | Wall / slab / roof / ceiling | `Rectangle` (default, no override) |
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ProfileDef {
    /// `IFCRectangleProfileDef` — the default if `profile_override`
    /// is `None`. Kept as an explicit variant so callers can round-
    /// trip through `profile_override` without losing shape info.
    Rectangle { width_feet: f64, depth_feet: f64 },
    /// `IFCCIRCLEPROFILEDEF` — solid circular cross-section.
    Circle { radius_feet: f64 },
    /// `IFCIShapeProfileDef` — wide-flange steel shape.
    ///
    /// - `overall_width_feet` is the flange width (local X span).
    /// - `overall_depth_feet` is the distance between outer flange
    ///   faces (local Y span).
    /// - `web_thickness_feet` is the web's thickness.
    /// - `flange_thickness_feet` is the (constant) flange thickness.
    ///
    /// All four values map directly onto the IFC4 attribute names
    /// `OverallWidth`, `OverallDepth`, `WebThickness`,
    /// `FlangeThickness`.
    IShape {
        overall_width_feet: f64,
        overall_depth_feet: f64,
        web_thickness_feet: f64,
        flange_thickness_feet: f64,
    },
    /// `IFCTShapeProfileDef` — structural tee.
    TShape {
        overall_depth_feet: f64,
        flange_width_feet: f64,
        web_thickness_feet: f64,
        flange_thickness_feet: f64,
    },
    /// `IFCLShapeProfileDef` — structural angle. `overall_depth` is
    /// the longer leg; `overall_width` the shorter leg (they can be
    /// equal for equal-leg angles).
    LShape {
        overall_depth_feet: f64,
        overall_width_feet: f64,
        thickness_feet: f64,
    },
    /// `IFCUShapeProfileDef` — structural channel (C-shape).
    UShape {
        overall_depth_feet: f64,
        flange_width_feet: f64,
        web_thickness_feet: f64,
        flange_thickness_feet: f64,
    },
    /// `IFCRectangleHollowProfileDef` — rectangular HSS tube.
    /// `wall_thickness` is the uniform wall thickness.
    RectangleHollow {
        overall_width_feet: f64,
        overall_depth_feet: f64,
        wall_thickness_feet: f64,
    },
    /// `IFCCircleHollowProfileDef` — round HSS pipe.
    CircleHollow {
        radius_feet: f64,
        wall_thickness_feet: f64,
    },
    /// `IFCArbitraryClosedProfileDef` with an `IFCPOLYLINE` outer
    /// curve. Points are in local 2D coordinates (feet); writer
    /// auto-closes the polyline if the last point isn't equal to
    /// the first. No self-intersection check is performed — callers
    /// supplying degenerate polygons will emit degenerate IFC.
    ArbitraryClosed { points: Vec<(f64, f64)> },
    /// `IFCArbitraryProfileDefWithVoids` — an `ArbitraryClosed`
    /// outer curve with one `IFCPOLYLINE` per hole. Points are in
    /// local 2D coordinates (feet); the writer auto-closes every
    /// polyline. Use it when the recovered boundary genuinely has
    /// voids: emitting only the outer loop would fill them, which
    /// states more solid than the source carries. IFC4 expects the
    /// outer curve counter-clockwise and each inner curve
    /// clockwise; the writer emits the point order it is given.
    ArbitraryWithVoids {
        points: Vec<(f64, f64)>,
        voids: Vec<Vec<(f64, f64)>>,
    },
}

/// One layer of a compound building-element material assembly
/// (IFC-28). `thickness_feet` is the physical thickness (writer
/// converts to metres at emit time). `material_index` points into
/// `IfcModel.materials` — the material filling this layer, or `None` for a
/// layer whose material is not known (IFC4 makes it optional).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialLayer {
    pub material_index: Option<usize>,
    pub thickness_feet: f64,
    /// Optional per-layer name. When `Some`, emitted as the
    /// `IfcMaterialLayer.Name` attribute. Revit's convention is
    /// layer names like "Finish - Face Layer", "Structure", "Air
    /// Gap", "Insulation" — useful for downstream BIM tools that
    /// surface them in schedules.
    #[serde(default)]
    pub name: Option<String>,
}

/// An ordered set of [`MaterialLayer`]s representing the compound
/// composition of a wall / floor / roof / ceiling (IFC-28). Maps
/// to IFC4 `IfcMaterialLayerSet` + (via
/// `IfcEntity::BuildingElement::material_layer_set_index`)
/// `IfcMaterialLayerSetUsage`.
///
/// `name` is the set-level label ("Generic - 6\" Wall", "Ext - CMU").
/// Revit's exterior wall types often carry 3-5 layers; interior
/// partitions are usually 2-3. The ordering matters: IFC4
/// interprets index `0` as the outermost layer (exterior or top side)
/// with subsequent layers stacked inward.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialLayerSet {
    pub name: String,
    pub layers: Vec<MaterialLayer>,
    /// Optional description; emitted as `IfcMaterialLayerSet.Description`.
    #[serde(default)]
    pub description: Option<String>,
}

/// Which axis of an element's placement a material layer set runs along
/// (IFC4 `IfcLayerSetDirectionEnum`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LayerSetDirection {
    Axis1,
    Axis2,
    Axis3,
}

/// The opening a door or window cuts in its host wall (#227), in the
/// filling element's own frame: its body's rectangle with the axis across
/// the wall set to the wall's thickness band. The writer emits it in place
/// of a copy of the filling element's body, which reaches past the wall by
/// the door's swing.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct OpeningCut {
    /// Rectangle size along the element's local X and Y, feet.
    pub x_dim_feet: f64,
    pub y_dim_feet: f64,
    /// Rectangle centre in the element's local frame, feet.
    pub centre_feet: [f64; 2],
    /// Where the opening starts above the element's placement and how high
    /// it is, feet (RE-93). `None` takes the element body's height.
    #[serde(default)]
    pub z_range_feet: Option<[f64; 2]>,
}

/// A family instance's materials (RE-82): IFC4 `IfcMaterialConstituentSet`,
/// unnamed, with one `IfcMaterialConstituent` per material, named after it
/// and in the category "Materials", as Revit's export writes them. A wall
/// whose body is not a layer set has one per layer instead (RE-88).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaterialConstituentSet {
    /// Indices into `IfcModel.materials`, one per constituent, in the order
    /// written: a family instance's in name order, a wall's layers exterior
    /// first.
    pub material_indices: Vec<usize>,
    /// Each constituent's name, where it is not its material's (RE-88);
    /// empty names every constituent after its material.
    #[serde(default)]
    pub names: Vec<String>,
    /// Indices into `IfcModel.entities` of the elements it is associated with.
    pub elements: Vec<usize>,
}

/// How a [`MaterialLayerSet`] lies on one element (IFC4
/// `IfcMaterialLayerSetUsage`): the axis its layers stack along, whether
/// they stack towards its positive or negative end, and where the first
/// layer starts on it, feet from the placement.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct MaterialLayerSetUsage {
    pub direction: LayerSetDirection,
    pub positive: bool,
    pub offset_feet: f64,
}

impl MaterialLayerSet {
    /// Total thickness in feet (sum of layer thicknesses). Useful
    /// for sanity-checking that the declared wall thickness matches
    /// the layer-set composition.
    pub fn total_thickness_feet(&self) -> f64 {
        self.layers.iter().map(|l| l.thickness_feet).sum()
    }
}

/// One material assigned to a structural profile in a
/// [`MaterialProfileSet`] (IFC-30). `material_index` references
/// `IfcModel.materials`; `profile_name` identifies the profile
/// (I-beam, HSS tube, circular column) defined elsewhere in the
/// model via `IfcProfileDef`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialProfile {
    pub material_index: usize,
    /// Profile identifier — emitted as `IfcMaterialProfile.Name`
    /// and matched against the corresponding `IfcProfileDef`.
    /// Revit convention: profile family name like
    /// "W12x26" / "HSS4x4x1/4" / "ROUND-6in".
    pub profile_name: String,
    /// Optional per-profile descriptive text.
    #[serde(default)]
    pub description: Option<String>,
    /// The cross-section itself, written as the material profile's
    /// `IfcProfileDef` (RE-105). `None` writes a 1 × 1 m rectangle stand-in.
    #[serde(default)]
    pub profile: Option<ProfileDef>,
}

/// An ordered set of [`MaterialProfile`]s for a structural
/// framing element (IFC-30). Analog of [`MaterialLayerSet`] but
/// for columns and beams rather than compound walls. Most
/// structural elements have exactly one profile; composite
/// sections (steel + concrete encasement) use multiple.
///
/// Maps to IFC4 `IfcMaterialProfileSet` + (via
/// `IfcEntity::BuildingElement::material_profile_set_index`)
/// `IfcMaterialProfileSetUsage`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialProfileSet {
    pub name: String,
    pub profiles: Vec<MaterialProfile>,
    #[serde(default)]
    pub description: Option<String>,
}

/// Shared geometry for a family / type / symbol (IFC-21).
/// Any number of `BuildingElement` instances can reference the
/// same `RepresentationMap` via `representation_map_index` —
/// the writer emits the underlying shape chain once and each
/// instance gets a ~4-entity `IfcMappedItem` wrap instead of a
/// full re-emission. Mirrors Revit's Symbol → FamilyInstance
/// relationship (a single door `Symbol` used by 20 `Door`
/// instances = 1 shape emission + 20 mapped items, not 20
/// shape chains).
///
/// Maps to IFC4 `IfcRepresentationMap` + (through the writer's
/// dispatch) `IfcMappedItem` per referencing instance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepresentationMap {
    /// Human-readable name for the family / type. Emitted as
    /// a comment-only field today (the IFC4
    /// `IfcRepresentationMap` entity itself doesn't carry a
    /// name slot — names live on the referencing type object
    /// when one exists). Kept here so downstream tooling (e.g.
    /// glTF export, schedule generation) can surface it.
    #[serde(default)]
    pub name: Option<String>,
    /// The shared geometry. Any `SolidShape` variant is valid:
    /// an extruded rectangle for simple doors, a revolved
    /// profile for lathe-turned piers, an arbitrary faceted-brep
    /// for imported free-form content. See [`SolidShape`] docs
    /// for the variant vocabulary.
    pub shape: SolidShape,
    /// Mapping origin in local coordinates (feet). Usually
    /// `[0.0, 0.0, 0.0]` — the identity origin. Non-zero origins
    /// are emitted as the mapping-origin's `IfcAxis2Placement3D`.
    #[serde(default)]
    pub origin_feet: [f64; 3],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnitAssignment {
    /// e.g. "autodesk.unit.unit:millimeters-1.0.1"
    pub forge_identifier: String,
    /// IFC base unit name, e.g. "MILLI" + "METRE"
    pub ifc_mapping: Option<String>,
}

/// A parsed Forge (Autodesk) unit identifier (IFC-39).
///
/// Revit carries its project / family unit preferences as
/// "Forge-style" identifier strings in the `PartAtom` XML and in
/// serialized `UnitType` fields, e.g.
/// `autodesk.unit.unit:millimeters-1.0.1`,
/// `autodesk.unit.unit:squareFeet-1.0.1`,
/// `autodesk.unit.unit:degrees-1.0.1`.
///
/// This enum captures every common one that maps cleanly to an
/// IFC4 `IfcSIUnit` (metric SI) or `IfcConversionBasedUnit` (non-
/// SI Imperial / mixed). Identifiers that don't match a known
/// unit fall through to [`ForgeUnit::Other`] carrying the raw
/// identifier so downstream code can still introspect it.
///
/// Invariant: every non-`Other` variant has a defined
/// [`ForgeUnit::ifc_emission`] mapping — callers can always emit
/// a valid IFC unit for a matched identifier.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ForgeUnit {
    // ---- Length ----
    Millimeters,
    Centimeters,
    Decimeters,
    Meters,
    Kilometers,
    Inches,
    Feet,
    Yards,
    Miles,

    // ---- Area ----
    SquareMillimeters,
    SquareCentimeters,
    SquareMeters,
    SquareFeet,
    SquareInches,
    SquareYards,
    Acres,
    Hectares,

    // ---- Volume ----
    CubicMillimeters,
    CubicCentimeters,
    CubicMeters,
    CubicFeet,
    CubicInches,
    CubicYards,
    Liters,
    UsGallons,

    // ---- Angle ----
    Radians,
    Degrees,
    Grads,

    // ---- Mass ----
    Kilograms,
    Grams,
    Pounds,

    // ---- Time ----
    Seconds,
    Minutes,
    Hours,

    /// Unrecognised Forge identifier — carries the raw string
    /// so callers can still round-trip it through serialization
    /// without losing data.
    Other(String),
}

/// IFC4 dimensional category (`LENGTHUNIT`, `AREAUNIT`, …).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IfcUnitType {
    Length,
    Area,
    Volume,
    PlaneAngle,
    Mass,
    Time,
}

impl IfcUnitType {
    /// STEP keyword (no surrounding dots — caller wraps).
    pub fn as_step_token(self) -> &'static str {
        match self {
            IfcUnitType::Length => "LENGTHUNIT",
            IfcUnitType::Area => "AREAUNIT",
            IfcUnitType::Volume => "VOLUMEUNIT",
            IfcUnitType::PlaneAngle => "PLANEANGLEUNIT",
            IfcUnitType::Mass => "MASSUNIT",
            IfcUnitType::Time => "TIMEUNIT",
        }
    }
}

/// How an IFC unit should be emitted (IFC-40).
///
/// - `SI { prefix, name }`: emits a single `IFCSIUNIT(*, <type>,
///   <prefix>, <name>)`. Prefix is `None` for ambient (e.g. metres,
///   square metres) or `Some("MILLI")` / `"CENTI")` / `"DECI")` /
///   `"KILO")` for multiples.
/// - `ConversionBased { base_name, conversion_factor_to_si_base }`
///   emits a pair `IFCMEASUREWITHUNIT(<measure>(<factor>), <si_base>)`
///   + `IFCCONVERSIONBASEDUNIT(<dim>, <type>, <name>, <measure_ref>)`.
///
/// Example conversion factors: one foot equals `0.3048 m`; one inch
/// equals `0.0254 m`; one degree equals `π / 180 rad`; one pound
/// equals `0.453592 kg`; one US gallon equals `0.00378541 m^3`.
#[derive(Debug, Clone, PartialEq)]
pub enum IfcUnitEmission {
    /// Pure SI unit.
    Si {
        unit_type: IfcUnitType,
        /// `None` for base unit, or `"MILLI"` / `"CENTI"` / `"DECI"`
        /// / `"KILO"` / `"HECTO"` for the standard IFC SI prefix
        /// vocabulary.
        prefix: Option<&'static str>,
        /// `"METRE"` / `"SQUARE_METRE"` / `"CUBIC_METRE"` /
        /// `"RADIAN"` / `"GRAM"` / `"SECOND"` — the unprefixed
        /// SI base name.
        name: &'static str,
    },
    /// Conversion-based unit derived from an SI base.
    ConversionBased {
        unit_type: IfcUnitType,
        /// Human / IFC name for the derived unit (`"FOOT"`,
        /// `"INCH"`, `"DEGREE"`, `"POUND"`, `"GALLON"`).
        derived_name: &'static str,
        /// Multiplier: `<derived_unit> = <this> × <si_base_unit>`.
        /// Example: foot = 0.3048 × metre; inch = 0.0254 × metre;
        /// degree = π/180 × radian.
        factor_to_si: f64,
        /// The SI base emission to attach the factor to (always
        /// `IfcUnitEmission::Si` conceptually, but inlined here
        /// as the bare IFC unit name to keep the data flat).
        si_base_name: &'static str,
    },
}

impl ForgeUnit {
    /// Parse an Autodesk Forge unit identifier. Returns
    /// `ForgeUnit::Other(raw)` for any string that doesn't match
    /// a known pattern.
    ///
    /// Accepted shapes:
    /// - `autodesk.unit.unit:millimeters-1.0.1` (canonical)
    /// - `autodesk.unit.unit:millimeters` (without version)
    /// - `millimeters` (bare — lenient)
    ///
    /// Case-insensitive on the unit token; versions are
    /// ignored (there's no meaningful difference between
    /// `-1.0.0` and `-1.0.1` for the unit vocabulary as of
    /// Revit 2026).
    pub fn from_forge_identifier(id: &str) -> Self {
        // Strip "autodesk.unit.unit:" prefix if present, then any
        // "-X.Y.Z" version suffix.
        let trimmed = id.trim().to_ascii_lowercase();
        let stripped = trimmed
            .strip_prefix("autodesk.unit.unit:")
            .unwrap_or(&trimmed);
        let bare = stripped.split('-').next().unwrap_or(stripped);
        match bare {
            "millimeters" | "mm" => ForgeUnit::Millimeters,
            "centimeters" | "cm" => ForgeUnit::Centimeters,
            "decimeters" | "dm" => ForgeUnit::Decimeters,
            "meters" | "m" => ForgeUnit::Meters,
            "kilometers" | "km" => ForgeUnit::Kilometers,
            "inches" | "in" => ForgeUnit::Inches,
            "feet" | "ft" | "fractionalinches" | "feetandfractionalinches" => ForgeUnit::Feet,
            "yards" | "yd" => ForgeUnit::Yards,
            "miles" | "mi" => ForgeUnit::Miles,
            "squaremillimeters" => ForgeUnit::SquareMillimeters,
            "squarecentimeters" => ForgeUnit::SquareCentimeters,
            "squaremeters" => ForgeUnit::SquareMeters,
            "squarefeet" => ForgeUnit::SquareFeet,
            "squareinches" => ForgeUnit::SquareInches,
            "squareyards" => ForgeUnit::SquareYards,
            "acres" => ForgeUnit::Acres,
            "hectares" => ForgeUnit::Hectares,
            "cubicmillimeters" => ForgeUnit::CubicMillimeters,
            "cubiccentimeters" => ForgeUnit::CubicCentimeters,
            "cubicmeters" => ForgeUnit::CubicMeters,
            "cubicfeet" => ForgeUnit::CubicFeet,
            "cubicinches" => ForgeUnit::CubicInches,
            "cubicyards" => ForgeUnit::CubicYards,
            "liters" | "litres" => ForgeUnit::Liters,
            "usgallons" | "gallons" => ForgeUnit::UsGallons,
            "radians" | "rad" => ForgeUnit::Radians,
            "degrees" | "deg" => ForgeUnit::Degrees,
            "grads" | "gradians" => ForgeUnit::Grads,
            "kilograms" | "kg" => ForgeUnit::Kilograms,
            "grams" | "g" => ForgeUnit::Grams,
            "pounds" | "lb" | "lbs" | "poundsmass" => ForgeUnit::Pounds,
            "seconds" | "s" => ForgeUnit::Seconds,
            "minutes" | "min" => ForgeUnit::Minutes,
            "hours" | "hr" | "h" => ForgeUnit::Hours,
            _ => ForgeUnit::Other(id.to_string()),
        }
    }

    /// Map a `ForgeUnit` to its IFC4 emission plan. Returns
    /// `None` for `Other(_)` — the caller should either fall back
    /// to a sensible default (usually metres) or surface a
    /// diagnostic.
    pub fn ifc_emission(&self) -> Option<IfcUnitEmission> {
        use IfcUnitType::*;
        match self {
            // Length — SI prefixes
            ForgeUnit::Millimeters => Some(IfcUnitEmission::Si {
                unit_type: Length,
                prefix: Some("MILLI"),
                name: "METRE",
            }),
            ForgeUnit::Centimeters => Some(IfcUnitEmission::Si {
                unit_type: Length,
                prefix: Some("CENTI"),
                name: "METRE",
            }),
            ForgeUnit::Decimeters => Some(IfcUnitEmission::Si {
                unit_type: Length,
                prefix: Some("DECI"),
                name: "METRE",
            }),
            ForgeUnit::Meters => Some(IfcUnitEmission::Si {
                unit_type: Length,
                prefix: None,
                name: "METRE",
            }),
            ForgeUnit::Kilometers => Some(IfcUnitEmission::Si {
                unit_type: Length,
                prefix: Some("KILO"),
                name: "METRE",
            }),
            // Length — conversion-based (Imperial)
            ForgeUnit::Inches => Some(IfcUnitEmission::ConversionBased {
                unit_type: Length,
                derived_name: "INCH",
                factor_to_si: 0.0254,
                si_base_name: "METRE",
            }),
            ForgeUnit::Feet => Some(IfcUnitEmission::ConversionBased {
                unit_type: Length,
                derived_name: "FOOT",
                factor_to_si: 0.3048,
                si_base_name: "METRE",
            }),
            ForgeUnit::Yards => Some(IfcUnitEmission::ConversionBased {
                unit_type: Length,
                derived_name: "YARD",
                factor_to_si: 0.9144,
                si_base_name: "METRE",
            }),
            ForgeUnit::Miles => Some(IfcUnitEmission::ConversionBased {
                unit_type: Length,
                derived_name: "MILE",
                factor_to_si: 1609.344,
                si_base_name: "METRE",
            }),
            // Area
            ForgeUnit::SquareMillimeters => Some(IfcUnitEmission::Si {
                unit_type: Area,
                prefix: Some("MILLI"),
                name: "SQUARE_METRE",
            }),
            ForgeUnit::SquareCentimeters => Some(IfcUnitEmission::Si {
                unit_type: Area,
                prefix: Some("CENTI"),
                name: "SQUARE_METRE",
            }),
            ForgeUnit::SquareMeters => Some(IfcUnitEmission::Si {
                unit_type: Area,
                prefix: None,
                name: "SQUARE_METRE",
            }),
            ForgeUnit::SquareFeet => Some(IfcUnitEmission::ConversionBased {
                unit_type: Area,
                derived_name: "SQUARE_FOOT",
                factor_to_si: 0.092_903_04,
                si_base_name: "SQUARE_METRE",
            }),
            ForgeUnit::SquareInches => Some(IfcUnitEmission::ConversionBased {
                unit_type: Area,
                derived_name: "SQUARE_INCH",
                factor_to_si: 0.000_645_16,
                si_base_name: "SQUARE_METRE",
            }),
            ForgeUnit::SquareYards => Some(IfcUnitEmission::ConversionBased {
                unit_type: Area,
                derived_name: "SQUARE_YARD",
                factor_to_si: 0.836_127_36,
                si_base_name: "SQUARE_METRE",
            }),
            ForgeUnit::Acres => Some(IfcUnitEmission::ConversionBased {
                unit_type: Area,
                derived_name: "ACRE",
                factor_to_si: 4_046.856_422_4,
                si_base_name: "SQUARE_METRE",
            }),
            ForgeUnit::Hectares => Some(IfcUnitEmission::ConversionBased {
                unit_type: Area,
                derived_name: "HECTARE",
                factor_to_si: 10_000.0,
                si_base_name: "SQUARE_METRE",
            }),
            // Volume
            ForgeUnit::CubicMillimeters => Some(IfcUnitEmission::Si {
                unit_type: Volume,
                prefix: Some("MILLI"),
                name: "CUBIC_METRE",
            }),
            ForgeUnit::CubicCentimeters => Some(IfcUnitEmission::Si {
                unit_type: Volume,
                prefix: Some("CENTI"),
                name: "CUBIC_METRE",
            }),
            ForgeUnit::CubicMeters => Some(IfcUnitEmission::Si {
                unit_type: Volume,
                prefix: None,
                name: "CUBIC_METRE",
            }),
            ForgeUnit::CubicFeet => Some(IfcUnitEmission::ConversionBased {
                unit_type: Volume,
                derived_name: "CUBIC_FOOT",
                factor_to_si: 0.028_316_846_592,
                si_base_name: "CUBIC_METRE",
            }),
            ForgeUnit::CubicInches => Some(IfcUnitEmission::ConversionBased {
                unit_type: Volume,
                derived_name: "CUBIC_INCH",
                factor_to_si: 0.000_016_387_064,
                si_base_name: "CUBIC_METRE",
            }),
            ForgeUnit::CubicYards => Some(IfcUnitEmission::ConversionBased {
                unit_type: Volume,
                derived_name: "CUBIC_YARD",
                factor_to_si: 0.764_554_857_984,
                si_base_name: "CUBIC_METRE",
            }),
            ForgeUnit::Liters => Some(IfcUnitEmission::ConversionBased {
                unit_type: Volume,
                derived_name: "LITRE",
                factor_to_si: 0.001,
                si_base_name: "CUBIC_METRE",
            }),
            ForgeUnit::UsGallons => Some(IfcUnitEmission::ConversionBased {
                unit_type: Volume,
                derived_name: "US_GALLON",
                factor_to_si: 0.003_785_411_784,
                si_base_name: "CUBIC_METRE",
            }),
            // Plane angle
            ForgeUnit::Radians => Some(IfcUnitEmission::Si {
                unit_type: PlaneAngle,
                prefix: None,
                name: "RADIAN",
            }),
            ForgeUnit::Degrees => Some(IfcUnitEmission::ConversionBased {
                unit_type: PlaneAngle,
                derived_name: "DEGREE",
                factor_to_si: std::f64::consts::PI / 180.0,
                si_base_name: "RADIAN",
            }),
            ForgeUnit::Grads => Some(IfcUnitEmission::ConversionBased {
                unit_type: PlaneAngle,
                derived_name: "GRAD",
                factor_to_si: std::f64::consts::PI / 200.0,
                si_base_name: "RADIAN",
            }),
            // Mass
            ForgeUnit::Kilograms => Some(IfcUnitEmission::Si {
                unit_type: Mass,
                prefix: None,
                name: "GRAM",
            }),
            ForgeUnit::Grams => Some(IfcUnitEmission::Si {
                unit_type: Mass,
                prefix: Some("MILLI"),
                name: "GRAM",
            }),
            ForgeUnit::Pounds => Some(IfcUnitEmission::ConversionBased {
                unit_type: Mass,
                derived_name: "POUND",
                factor_to_si: 0.453_592_37,
                si_base_name: "GRAM",
            }),
            // Time
            ForgeUnit::Seconds => Some(IfcUnitEmission::Si {
                unit_type: Time,
                prefix: None,
                name: "SECOND",
            }),
            ForgeUnit::Minutes => Some(IfcUnitEmission::ConversionBased {
                unit_type: Time,
                derived_name: "MINUTE",
                factor_to_si: 60.0,
                si_base_name: "SECOND",
            }),
            ForgeUnit::Hours => Some(IfcUnitEmission::ConversionBased {
                unit_type: Time,
                derived_name: "HOUR",
                factor_to_si: 3600.0,
                si_base_name: "SECOND",
            }),
            ForgeUnit::Other(_) => None,
        }
    }
}

/// A named collection of typed property values attached to a
/// BuildingElement. Emits as IfcPropertySet → IfcPropertySingleValue
/// → IfcRelDefinesByProperties in the STEP writer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropertySet {
    /// Property-set name. Convention: "Pset_WallCommon",
    /// "Pset_DoorCommon", or "Pset_RevitType_{ClassName}".
    pub name: String,
    pub properties: Vec<Property>,
}

/// A single property inside a [`PropertySet`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Property {
    pub name: String,
    pub value: PropertyValue,
}

/// IFC4 IfcValue subtypes we surface from Revit decoded fields.
/// Maps directly to the `NominalValue` slot of IfcPropertySingleValue.
///
/// Quantity variants (`AreaSquareFeet`, `VolumeCubicFeet`, `CountValue`,
/// `TimeSeconds`, `MassPounds`) are the measurement-flavoured siblings
/// of the primitive variants. They emit as the matching
/// `IfcAreaMeasure` / `IfcVolumeMeasure` / `IfcCountMeasure` / etc.
/// constructors — semantically they correspond to the IFC4 `IfcQuantity*`
/// family, but we route them through the existing
/// `IfcPropertySingleValue` carrier so the writer doesn't need a
/// parallel `IfcElementQuantity` path yet (tracked separately).
/// Feet / cubic-feet / pounds inputs are converted to metres /
/// cubic-metres / kilograms at emit time so the STEP output is
/// unit-consistent with the project-level `IfcUnitAssignment`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value")]
pub enum PropertyValue {
    /// Free-form text — `IfcText`.
    Text(String),
    /// Integer count — `IfcInteger`.
    Integer(i64),
    /// Floating-point real — `IfcReal`.
    Real(f64),
    /// Boolean — `IfcBoolean`.
    Boolean(bool),
    /// Length measurement in feet (writer converts to metres).
    /// Maps to `IfcLengthMeasure` with project length unit.
    LengthFeet(f64),
    /// A length that must be greater than zero, in feet (writer converts
    /// to metres). Maps to `IfcPositiveLengthMeasure`, the type standard
    /// property sets such as `Pset_StairCommon` declare (RE-47).
    PositiveLengthFeet(f64),
    /// Angle in radians. Maps to `IfcPlaneAngleMeasure`.
    AngleRadians(f64),
    /// Area in square feet (writer converts to square metres).
    /// Maps to `IfcAreaMeasure`. (IFC-32)
    AreaSquareFeet(f64),
    /// Volume in cubic feet (writer converts to cubic metres).
    /// Maps to `IfcVolumeMeasure`. (IFC-32)
    VolumeCubicFeet(f64),
    /// Unitless discrete count — occupancy, rebar count, fixture count.
    /// Maps to `IfcCountMeasure`. (IFC-32)
    CountValue(i64),
    /// Time measurement in seconds. Maps to `IfcTimeMeasure`. (IFC-32)
    TimeSeconds(f64),
    /// Mass in pounds (writer converts to kilograms).
    /// Maps to `IfcMassMeasure`. (IFC-32)
    MassPounds(f64),
}

impl PropertyValue {
    /// Emit the STEP-level IfcValue constructor for this value.
    /// Used by the writer; exposed for testing.
    pub fn to_step(&self) -> String {
        match self {
            PropertyValue::Text(s) => format!("IFCTEXT('{}')", escape_step_string(s)),
            PropertyValue::Integer(n) => format!("IFCINTEGER({n})"),
            PropertyValue::Real(v) => format!("IFCREAL({v:.6})"),
            PropertyValue::Boolean(b) => {
                format!("IFCBOOLEAN(.{}.)", if *b { "T" } else { "F" })
            }
            PropertyValue::LengthFeet(ft) => {
                // Convert to metres at emit time (project length unit).
                let metres = ft * 0.3048;
                format!("IFCLENGTHMEASURE({metres:.6})")
            }
            PropertyValue::PositiveLengthFeet(ft) => {
                let metres = ft * 0.3048;
                format!("IFCPOSITIVELENGTHMEASURE({metres:.6})")
            }
            PropertyValue::AngleRadians(r) => format!("IFCPLANEANGLEMEASURE({r:.6})"),
            PropertyValue::AreaSquareFeet(sqft) => {
                // 1 ft² = 0.09290304 m² (exact, from international foot).
                let sqm = sqft * 0.09290304;
                format!("IFCAREAMEASURE({sqm:.6})")
            }
            PropertyValue::VolumeCubicFeet(cuft) => {
                // 1 ft³ = 0.028316846592 m³ (exact).
                let cum = cuft * 0.028316846592;
                format!("IFCVOLUMEMEASURE({cum:.6})")
            }
            PropertyValue::CountValue(n) => format!("IFCCOUNTMEASURE({n})"),
            PropertyValue::TimeSeconds(s) => format!("IFCTIMEMEASURE({s:.6})"),
            PropertyValue::MassPounds(lb) => {
                // 1 lb = 0.45359237 kg (exact, international avoirdupois pound).
                let kg = lb * 0.45359237;
                format!("IFCMASSMEASURE({kg:.6})")
            }
        }
    }
}

/// Minimal STEP string escape — apostrophes doubled, backslashes
/// doubled. Non-ASCII escape isn't needed here because the writer's
/// full `escape()` is used for BuildingElement names; property
/// values are typically numeric or short ASCII. Keeping the escape
/// local to entities.rs avoids a cross-module dependency.
/// A property's text written as an ISO 10303-21 string: the same
/// encoding every other string in the file gets
/// ([`super::step_writer::escape`]), so a non-ASCII character is a
/// `\X2\…\X0\` escape rather than a raw UTF-8 byte.
fn escape_step_string(s: &str) -> String {
    super::step_writer::escape(s)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn property_value_to_step_primitives() {
        assert_eq!(PropertyValue::Integer(42).to_step(), "IFCINTEGER(42)");
        assert_eq!(PropertyValue::Real(1.25).to_step(), "IFCREAL(1.250000)");
        // A STEP enumeration is written between two dots (ISO 10303-21);
        // `.T)` without the closing dot is not a valid IfcBoolean.
        assert_eq!(PropertyValue::Boolean(true).to_step(), "IFCBOOLEAN(.T.)");
        assert_eq!(PropertyValue::Boolean(false).to_step(), "IFCBOOLEAN(.F.)");
        assert_eq!(
            PropertyValue::Text("hello".into()).to_step(),
            "IFCTEXT('hello')"
        );
        assert_eq!(
            PropertyValue::Text("it's".into()).to_step(),
            "IFCTEXT('it''s')"
        );
        // A Revit type name from a Portuguese model (`teste_export_2025`).
        assert_eq!(
            PropertyValue::Text("Genérico - 200 mm".into()).to_step(),
            "IFCTEXT('Gen\\X2\\00E9\\X0\\rico - 200 mm')"
        );
    }

    #[test]
    fn property_value_to_step_length_and_angle() {
        // 10 ft = 3.048 m.
        assert_eq!(
            PropertyValue::LengthFeet(10.0).to_step(),
            "IFCLENGTHMEASURE(3.048000)"
        );
        // π/2 rad comes out to ~1.570796.
        let step = PropertyValue::AngleRadians(std::f64::consts::FRAC_PI_2).to_step();
        assert!(step.starts_with("IFCPLANEANGLEMEASURE(1.570796"));
    }

    /// IFC-32: quantity variants emit IfcAreaMeasure / IfcVolumeMeasure
    /// / IfcCountMeasure / IfcTimeMeasure / IfcMassMeasure, with the
    /// Imperial → SI conversion applied at emit time so downstream
    /// tools see unit-consistent output against the project's SI
    /// `IfcUnitAssignment`.
    /// IFC-28: MaterialLayerSet totals its layer thicknesses.
    #[test]
    fn material_layer_set_total_thickness() {
        let lset = MaterialLayerSet {
            name: "Ext - Generic 8\" Wall".into(),
            description: None,
            layers: vec![
                MaterialLayer {
                    material_index: Some(0),
                    thickness_feet: 5.0 / 12.0, // 5"
                    name: Some("Finish".into()),
                },
                MaterialLayer {
                    material_index: Some(1),
                    thickness_feet: 2.0 / 12.0, // 2"
                    name: Some("Structure".into()),
                },
                MaterialLayer {
                    material_index: Some(2),
                    thickness_feet: 1.0 / 12.0, // 1"
                    name: Some("Air Gap".into()),
                },
            ],
        };
        let total = lset.total_thickness_feet();
        assert!((total - (8.0 / 12.0)).abs() < 1e-9);
    }

    #[test]
    fn property_value_to_step_quantities() {
        // 1 ft² = 0.09290304 m² exact.
        assert_eq!(
            PropertyValue::AreaSquareFeet(1.0).to_step(),
            "IFCAREAMEASURE(0.092903)"
        );
        // 100 ft² = 9.290304 m².
        assert_eq!(
            PropertyValue::AreaSquareFeet(100.0).to_step(),
            "IFCAREAMEASURE(9.290304)"
        );

        // 1 ft³ = 0.028316846592 m³ exact.
        assert_eq!(
            PropertyValue::VolumeCubicFeet(1.0).to_step(),
            "IFCVOLUMEMEASURE(0.028317)"
        );

        // Counts are unitless integers.
        assert_eq!(
            PropertyValue::CountValue(12).to_step(),
            "IFCCOUNTMEASURE(12)"
        );

        // Time in seconds is already SI.
        assert_eq!(
            PropertyValue::TimeSeconds(3.0).to_step(),
            "IFCTIMEMEASURE(3.000000)"
        );

        // 1 lb = 0.45359237 kg exact.
        assert_eq!(
            PropertyValue::MassPounds(1.0).to_step(),
            "IFCMASSMEASURE(0.453592)"
        );
    }

    // ---------------- IFC-39 / IFC-40: ForgeUnit parsing + IFC map ----------------

    #[test]
    fn forge_unit_parses_canonical_ids() {
        // Canonical: `autodesk.unit.unit:<name>-<version>`.
        assert_eq!(
            ForgeUnit::from_forge_identifier("autodesk.unit.unit:millimeters-1.0.1"),
            ForgeUnit::Millimeters
        );
        assert_eq!(
            ForgeUnit::from_forge_identifier("autodesk.unit.unit:feet-1.0.1"),
            ForgeUnit::Feet
        );
        assert_eq!(
            ForgeUnit::from_forge_identifier("autodesk.unit.unit:degrees-1.0.1"),
            ForgeUnit::Degrees
        );
    }

    #[test]
    fn forge_unit_parses_without_version() {
        assert_eq!(
            ForgeUnit::from_forge_identifier("autodesk.unit.unit:meters"),
            ForgeUnit::Meters
        );
    }

    #[test]
    fn forge_unit_parses_bare_names() {
        // Bare-name lenient path — sometimes PartAtom carries just
        // the tail (`millimeters`) rather than the full identifier.
        assert_eq!(
            ForgeUnit::from_forge_identifier("millimeters"),
            ForgeUnit::Millimeters
        );
        assert_eq!(ForgeUnit::from_forge_identifier("Feet"), ForgeUnit::Feet);
    }

    #[test]
    fn forge_unit_unknown_falls_through_to_other() {
        let fu = ForgeUnit::from_forge_identifier("autodesk.unit.unit:furlongsPerFortnight-1.0.1");
        match fu {
            ForgeUnit::Other(id) => assert!(id.contains("furlongsPerFortnight")),
            _ => panic!("unknown units must map to ForgeUnit::Other(_)"),
        }
    }

    #[test]
    fn forge_unit_length_metric_emits_si() {
        match ForgeUnit::Millimeters.ifc_emission().unwrap() {
            IfcUnitEmission::Si {
                unit_type,
                prefix,
                name,
            } => {
                assert_eq!(unit_type, IfcUnitType::Length);
                assert_eq!(prefix, Some("MILLI"));
                assert_eq!(name, "METRE");
            }
            _ => panic!("millimeters should emit as IfcSIUnit"),
        }
    }

    #[test]
    fn forge_unit_feet_emits_conversion_based() {
        match ForgeUnit::Feet.ifc_emission().unwrap() {
            IfcUnitEmission::ConversionBased {
                unit_type,
                derived_name,
                factor_to_si,
                si_base_name,
            } => {
                assert_eq!(unit_type, IfcUnitType::Length);
                assert_eq!(derived_name, "FOOT");
                // 1 foot = 0.3048 metre exactly.
                assert!((factor_to_si - 0.3048).abs() < 1e-12);
                assert_eq!(si_base_name, "METRE");
            }
            _ => panic!("feet should emit as IfcConversionBasedUnit"),
        }
    }

    #[test]
    fn forge_unit_all_known_variants_have_emission() {
        // Every non-Other variant MUST have a defined ifc_emission.
        // (Pinned as an invariant — if a new unit lands without its
        // mapping, this test fails instead of the bug shipping.)
        for fu in [
            ForgeUnit::Millimeters,
            ForgeUnit::Centimeters,
            ForgeUnit::Decimeters,
            ForgeUnit::Meters,
            ForgeUnit::Kilometers,
            ForgeUnit::Inches,
            ForgeUnit::Feet,
            ForgeUnit::Yards,
            ForgeUnit::Miles,
            ForgeUnit::SquareMillimeters,
            ForgeUnit::SquareCentimeters,
            ForgeUnit::SquareMeters,
            ForgeUnit::SquareFeet,
            ForgeUnit::SquareInches,
            ForgeUnit::SquareYards,
            ForgeUnit::Acres,
            ForgeUnit::Hectares,
            ForgeUnit::CubicMillimeters,
            ForgeUnit::CubicCentimeters,
            ForgeUnit::CubicMeters,
            ForgeUnit::CubicFeet,
            ForgeUnit::CubicInches,
            ForgeUnit::CubicYards,
            ForgeUnit::Liters,
            ForgeUnit::UsGallons,
            ForgeUnit::Radians,
            ForgeUnit::Degrees,
            ForgeUnit::Grads,
            ForgeUnit::Kilograms,
            ForgeUnit::Grams,
            ForgeUnit::Pounds,
            ForgeUnit::Seconds,
            ForgeUnit::Minutes,
            ForgeUnit::Hours,
        ] {
            assert!(
                fu.ifc_emission().is_some(),
                "ForgeUnit {fu:?} has no ifc_emission mapping"
            );
        }
        // ...while Other must return None.
        assert!(ForgeUnit::Other("x".into()).ifc_emission().is_none());
    }

    #[test]
    fn ifc_unit_type_step_tokens() {
        assert_eq!(IfcUnitType::Length.as_step_token(), "LENGTHUNIT");
        assert_eq!(IfcUnitType::Area.as_step_token(), "AREAUNIT");
        assert_eq!(IfcUnitType::Volume.as_step_token(), "VOLUMEUNIT");
        assert_eq!(IfcUnitType::PlaneAngle.as_step_token(), "PLANEANGLEUNIT");
        assert_eq!(IfcUnitType::Mass.as_step_token(), "MASSUNIT");
        assert_eq!(IfcUnitType::Time.as_step_token(), "TIMEUNIT");
    }
}