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
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
//! Minimal STEP / ISO-10303-21 serializer for `IfcModel` → valid IFC4.
//!
//! This is the serialization half of Layer 5. Given an `IfcModel` in
//! memory, produce a .ifc text file that a spec-compliant reader
//! (IfcOpenShell, BlenderBIM, buildingSMART validator) accepts.
//!
//! The output is intentionally minimal but **structurally valid**: a
//! well-formed IFC4 schema header, the required framework entities
//! (`IfcPerson` / `IfcOrganization` / `IfcApplication` /
//! `IfcOwnerHistory` / `IfcSIUnit` / `IfcUnitAssignment` /
//! `IfcGeometricRepresentationContext`), and an `IfcProject` populated
//! from the model's metadata. As the walker grows, `BuildingElement`
//! and family entities will land too; those extensions plug in here
//! without touching the header-level plumbing.
//!
//! Design principle: string-based emission, no external IFC library
//! dependency, fully `#![deny(unsafe_code)]`-clean.

use std::collections::HashMap;

use super::IfcModel;
use super::entities::{Extrusion, OpeningCut, SolidShape};

/// Options controlling STEP serialization.
#[derive(Debug, Clone, Default)]
pub struct StepOptions {
    /// If `Some`, use this Unix timestamp (in seconds) for both the
    /// `FILE_NAME` header and the `IfcOwnerHistory` creation time
    /// instead of `SystemTime::now()`. Setting this makes the
    /// output deterministic — identical `(IfcModel, StepOptions)`
    /// pairs produce byte-identical STEP strings, which makes
    /// STEP-text diffs tractable and regression tests reliable.
    pub timestamp: Option<i64>,
}

/// Serialize an `IfcModel` into an IFC4 STEP text stream. The output
/// includes the ISO-10303-21 envelope and a minimal but spec-valid
/// data section centred on `IfcProject`. Uses current wall-clock
/// timestamp. For deterministic output (e.g. tests), use
/// [`write_step_with_options`] with `StepOptions::timestamp = Some(_)`.
pub fn write_step(model: &IfcModel) -> String {
    write_step_with_options(model, &StepOptions::default())
}

/// Deterministic-option variant of [`write_step`].
///
/// When `options.timestamp = Some(t)`, the emitted STEP is a pure
/// function of `(model, t)` — no wall-clock access. Use this in
/// tests and regression fixtures.
pub fn write_step_with_options(model: &IfcModel, options: &StepOptions) -> String {
    let now = options.timestamp.unwrap_or_else(unix_seconds);
    let mut w = StepWriter::new(now);
    w.emit_header(model);
    w.emit_data(model);
    w.finish()
}

/// Attribute layout of the tail an IFC4 building-element instance
/// carries after `IfcProduct`'s seven common attributes
/// (`GlobalId`, `OwnerHistory`, `Name`, `Description`, `ObjectType`,
/// `ObjectPlacement`, `Representation`).
///
/// IFC4 requires an instance to list **every** attribute its entity
/// type declares; an unknown optional occupies its slot as `$`.
/// Omitting the trailing ones entirely — which is what the writer did
/// before #214 — yields a record that most readers tolerate but that
/// no spec-conformant consumer can index, so `IfcColumn.PredefinedType`
/// raised "index 8 is out of range for variant of size 8".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ElementTail {
    /// `Tag` only — the entity declares no `PredefinedType`
    /// (`IfcFurnishingElement`, `IfcFlowController`). Arity 8.
    Tag,
    /// `Tag, PredefinedType` — the shape almost every
    /// `IfcBuildingElement` subtype takes. Arity 9.
    TagPredefined,
    /// `Tag, OverallHeight, OverallWidth, PredefinedType,
    /// OperationType|PartitioningType, UserDefined…Type` —
    /// `IfcDoor` / `IfcWindow`. Arity 13.
    Opening,
    /// `LongName, CompositionType, PredefinedType,
    /// ElevationWithFlooring` — `IfcSpace`, which is an
    /// `IfcSpatialStructureElement` and so declares no `Tag` at all.
    /// Arity 11.
    Space,
    /// `Tag, SteelGrade, NominalDiameter, CrossSectionArea,
    /// BarLength, PredefinedType, BarSurface` —
    /// `IfcReinforcingBar`. Arity 14.
    ReinforcingBar,
    /// `Tag, NumberOfRisers, NumberOfTreads, RiserHeight,
    /// TreadLength, PredefinedType` — `IfcStairFlight`. Arity 13.
    StairFlight,
}

impl ElementTail {
    /// Total IFC4 attribute count for an entity with this tail.
    #[cfg(test)]
    const fn arity(self) -> usize {
        match self {
            ElementTail::Tag => 8,
            ElementTail::TagPredefined => 9,
            ElementTail::Opening => 13,
            ElementTail::Space => 11,
            ElementTail::ReinforcingBar => 14,
            ElementTail::StairFlight => 13,
        }
    }
}

/// Which tail an emitted STEP entity name takes.
///
/// Every value here is the IFC4 EXPRESS declaration, cross-checked
/// against `ifcopenshell.ifcopenshell_wrapper.schema_by_name("IFC4")
/// .declaration_by_name(<name>).attribute_count()`; the same table is
/// re-derived from the schema by `tools/ci/ifc_schema_arity.py` on
/// every emitted file, so a wrong row cannot survive CI.
///
/// Unlisted names fall through to [`ElementTail::TagPredefined`],
/// which is the shape of every remaining `IfcBuildingElement`
/// subtype in IFC4.
fn element_tail_for(ifc_upper: &str) -> ElementTail {
    match ifc_upper {
        "IFCFURNISHINGELEMENT" | "IFCFLOWCONTROLLER" => ElementTail::Tag,
        "IFCDOOR" | "IFCWINDOW" => ElementTail::Opening,
        "IFCSPACE" => ElementTail::Space,
        "IFCREINFORCINGBAR" => ElementTail::ReinforcingBar,
        "IFCSTAIRFLIGHT" => ElementTail::StairFlight,
        _ => ElementTail::TagPredefined,
    }
}

/// Total IFC4 attribute count the writer emits for `ifc_upper`.
///
/// Exists for the arity regression test, which compares it against the
/// schema-derived table *and* against the emitted text, so a layout
/// that renders the wrong number of slots fails twice.
#[cfg(test)]
pub(crate) fn element_attribute_arity(ifc_upper: &str) -> usize {
    element_tail_for(ifc_upper).arity()
}

/// Accept a `PredefinedType` token only when it is a well-formed STEP
/// enumeration name: uppercase ASCII letters, digits and underscores,
/// starting with a letter.
///
/// An enumeration reference is written bare between dots, so unlike a
/// string it has no escape form — a caller-supplied value with a
/// quote, dot or newline in it would corrupt the record. Rejecting
/// writes `$` instead, which is always legal for an optional
/// attribute. (`tests/fuzz_regressions.rs` drives hostile names
/// through this path.)
fn step_enum_token(raw: &str) -> Option<String> {
    let token = raw.trim().to_ascii_uppercase();
    let mut chars = token.chars();
    match chars.next() {
        Some(c) if c.is_ascii_uppercase() => {}
        _ => return None,
    }
    if chars.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') {
        Some(token)
    } else {
        None
    }
}

/// The IFC4 type entity an occurrence of `ifc_upper` is typed by, and the
/// attributes that entity declares after `ElementType`, with `predefined`
/// the occurrence's `PredefinedType` (RE-110). An occurrence and its type
/// share one enumeration. `None` for entities rvt-rs does not type.
fn type_entity_for(ifc_upper: &str, predefined: Option<&str>) -> Option<(String, String)> {
    let pt = format!(
        ".{}.",
        predefined
            .and_then(step_enum_token)
            .unwrap_or_else(|| "NOTDEFINED".into())
    );
    let tail = match ifc_upper {
        "IFCDOOR" | "IFCWINDOW" => format!("{pt},.NOTDEFINED.,$,$"),
        "IFCFURNITURE" => format!(".NOTDEFINED.,{pt}"),
        "IFCWALL"
        | "IFCSLAB"
        | "IFCBEAM"
        | "IFCCOLUMN"
        | "IFCMEMBER"
        | "IFCPLATE"
        | "IFCCOVERING"
        | "IFCCURTAINWALL"
        | "IFCFOOTING"
        | "IFCRAMP"
        | "IFCROOF"
        | "IFCSTAIR"
        | "IFCSTAIRFLIGHT"
        | "IFCSHADINGDEVICE"
        | "IFCBUILDINGELEMENTPROXY"
        | "IFCAIRTERMINAL"
        | "IFCALARM"
        | "IFCDUCTFITTING"
        | "IFCDUCTSEGMENT"
        | "IFCELECTRICAPPLIANCE"
        | "IFCLIGHTFIXTURE"
        | "IFCPIPEFITTING"
        | "IFCPIPESEGMENT"
        | "IFCSANITARYTERMINAL"
        | "IFCTRANSPORTELEMENT" => pt,
        _ => return None,
    };
    Some((format!("{ifc_upper}TYPE"), tail))
}

/// Render the attribute tail for one building element.
///
/// `tag_quoted` and `name_quoted` are already STEP-quoted (`'…'` or
/// `$`). `predefined` is the bare enum token (`"COLUMN"`), written as
/// `.COLUMN.`; `None` writes `$` — the writer never invents an enum
/// value it did not decode.
fn element_attribute_tail(
    ifc_upper: &str,
    tag_quoted: &str,
    predefined: Option<&str>,
    long_name_quoted: &str,
    overall_height_width_feet: Option<(f64, f64)>,
) -> String {
    let pt = match predefined.and_then(step_enum_token) {
        Some(token) => format!(".{token}."),
        None => "$".to_string(),
    };
    match element_tail_for(ifc_upper) {
        ElementTail::Tag => tag_quoted.to_string(),
        ElementTail::TagPredefined => format!("{tag_quoted},{pt}"),
        // OverallHeight / OverallWidth are the type's, where read (RE-93),
        // and otherwise `$`.
        ElementTail::Opening => match overall_height_width_feet {
            Some((height, width)) => format!(
                "{tag_quoted},{:.6},{:.6},{pt},$,$",
                height * 0.3048,
                width * 0.3048
            ),
            None => format!("{tag_quoted},$,$,{pt},$,$"),
        },
        // IfcSpace has no Tag attribute — slot 8 is LongName. Before
        // #214 the writer put the type GUID there, which typed as a
        // label but meant the wrong thing; the element's own Name
        // carries the identity instead. CompositionType `.ELEMENT.`
        // matches what Revit's exporter writes for a room.
        //
        // `long_name_quoted` is the room's name from its `RoomName`
        // property, the slot Revit's own exporter puts it in, or `$`
        // (RE-117). The element Name is its room number.
        ElementTail::Space => format!("{long_name_quoted},.ELEMENT.,{pt},$"),
        ElementTail::ReinforcingBar => format!("{tag_quoted},$,$,$,$,{pt},$"),
        ElementTail::StairFlight => format!("{tag_quoted},$,$,$,$,{pt}"),
    }
}

struct StepWriter {
    out: String,
    next_id: usize,
    /// Unix timestamp (seconds) used for FILE_NAME + IfcOwnerHistory.
    /// Injected at construction so the output is a pure function of
    /// `(model, timestamp)` when a fixed timestamp is supplied.
    timestamp: i64,
}

impl StepWriter {
    /// The `Position` and depth, metres, of an opening's extruded solid: the
    /// shared `solid_position` and the body's `depth_m`, or, for a cut with
    /// its own height (RE-93), a placement that far above the element's and
    /// that height.
    fn opening_solid_position(
        &mut self,
        solid_position: usize,
        cut: Option<&OpeningCut>,
        depth_m: f64,
    ) -> (usize, f64) {
        let Some([z, height]) = cut.and_then(|cut| cut.z_range_feet) else {
            return (solid_position, depth_m);
        };
        let point = self.id();
        self.emit_entity(
            point,
            format!("IFCCARTESIANPOINT((0.,0.,{:.6}))", z * 0.3048),
        );
        let position = self.id();
        self.emit_entity(position, format!("IFCAXIS2PLACEMENT3D(#{point},$,$)"));
        (position, height * 0.3048)
    }

    fn new(timestamp: i64) -> Self {
        Self {
            out: String::new(),
            next_id: 1,
            timestamp,
        }
    }

    fn id(&mut self) -> usize {
        let id = self.next_id;
        self.next_id += 1;
        id
    }

    fn emit_line<S: AsRef<str>>(&mut self, line: S) {
        self.out.push_str(line.as_ref());
        self.out.push('\n');
    }

    fn emit_entity<S: AsRef<str>>(&mut self, id: usize, body: S) {
        self.out.push_str(&format!("#{id}={};\n", body.as_ref()));
    }

    /// Emit one `IfcProfileDef` subclass from an [`Extrusion`],
    /// dispatching on [`Extrusion::profile_override`]. Returns the
    /// entity ID of the emitted profile so the caller can wire it
    /// into an `IFCEXTRUDEDAREASOLID`.
    ///
    /// - `ex.profile_override = None` emits the default
    ///   `IFCRECTANGLEPROFILEDEF` from `width_feet` × `depth_feet`.
    /// - `Circle { radius }` emits `IFCCIRCLEPROFILEDEF`.
    /// - `IShape { … }` emits `IFCIShapeProfileDef` with a full
    ///   OverallWidth / OverallDepth / WebThickness /
    ///   FlangeThickness attribute set (fillet radius = $).
    /// - `TShape { … }` emits `IFCTShapeProfileDef`.
    /// - `LShape { … }` emits `IFCLShapeProfileDef` (EdgeRadius,
    ///   LegSlope = $).
    /// - `UShape { … }` emits `IFCUShapeProfileDef`.
    /// - `RectangleHollow { … }` emits
    ///   `IFCRectangleHollowProfileDef`.
    /// - `CircleHollow { … }` emits `IFCCircleHollowProfileDef`.
    /// - `ArbitraryClosed { points }` emits `IFCPOLYLINE` +
    ///   `IFCArbitraryClosedProfileDef`; if the polyline isn't
    ///   already closed (last == first), the writer appends the
    ///   first point at the tail.
    /// - `ArbitraryWithVoids { points, voids }` emits one
    ///   `IFCPOLYLINE` for the outer ring and one per hole, then
    ///   `IFCArbitraryProfileDefWithVoids`.
    ///
    /// All length values are converted from feet to metres at emit
    /// time (factor 0.3048).
    fn emit_profile_def(&mut self, ex: &Extrusion, profile_placement: usize) -> usize {
        use super::entities::ProfileDef;

        let profile_id = self.id();
        match &ex.profile_override {
            None | Some(ProfileDef::Rectangle { .. }) => {
                let (w_ft, d_ft) = match ex.profile_override {
                    Some(ProfileDef::Rectangle {
                        width_feet,
                        depth_feet,
                    }) => (width_feet, depth_feet),
                    _ => (ex.width_feet, ex.depth_feet),
                };
                let x_dim = w_ft * 0.3048;
                let y_dim = d_ft * 0.3048;
                self.emit_entity(
                    profile_id,
                    format!(
                        "IFCRECTANGLEPROFILEDEF(.AREA.,$,#{profile_placement},{x_dim:.6},{y_dim:.6})"
                    ),
                );
            }
            Some(ProfileDef::Circle { radius_feet }) => {
                let r = radius_feet * 0.3048;
                self.emit_entity(
                    profile_id,
                    format!("IFCCIRCLEPROFILEDEF(.AREA.,$,#{profile_placement},{r:.6})"),
                );
            }
            Some(ProfileDef::IShape {
                overall_width_feet,
                overall_depth_feet,
                web_thickness_feet,
                flange_thickness_feet,
            }) => {
                let w = overall_width_feet * 0.3048;
                let d = overall_depth_feet * 0.3048;
                let tw = web_thickness_feet * 0.3048;
                let tf = flange_thickness_feet * 0.3048;
                // IFCIShapeProfileDef(ProfileType, ProfileName,
                // Position, OverallWidth, OverallDepth,
                // WebThickness, FlangeThickness, FilletRadius?,
                // FlangeEdgeRadius?, FlangeSlope?) — ten attributes
                // in IFC4; the last two are IFC4 additions over
                // IFC2X3 and must still occupy their slots (#214).
                self.emit_entity(
                    profile_id,
                    format!(
                        "IFCISHAPEPROFILEDEF(.AREA.,$,#{profile_placement},{w:.6},{d:.6},{tw:.6},{tf:.6},$,$,$)"
                    ),
                );
            }
            Some(ProfileDef::TShape {
                overall_depth_feet,
                flange_width_feet,
                web_thickness_feet,
                flange_thickness_feet,
            }) => {
                let d = overall_depth_feet * 0.3048;
                let fw = flange_width_feet * 0.3048;
                let tw = web_thickness_feet * 0.3048;
                let tf = flange_thickness_feet * 0.3048;
                // IFCTShapeProfileDef(ProfileType, ProfileName,
                // Position, Depth, FlangeWidth, WebThickness,
                // FlangeThickness, FilletRadius?, FlangeEdgeRadius?,
                // WebEdgeRadius?, WebSlope?, FlangeSlope?).
                self.emit_entity(
                    profile_id,
                    format!(
                        "IFCTSHAPEPROFILEDEF(.AREA.,$,#{profile_placement},{d:.6},{fw:.6},{tw:.6},{tf:.6},$,$,$,$,$)"
                    ),
                );
            }
            Some(ProfileDef::LShape {
                overall_depth_feet,
                overall_width_feet,
                thickness_feet,
            }) => {
                let d = overall_depth_feet * 0.3048;
                let w = overall_width_feet * 0.3048;
                let t = thickness_feet * 0.3048;
                // IFCLShapeProfileDef(ProfileType, ProfileName,
                // Position, Depth, Width, Thickness, FilletRadius?,
                // EdgeRadius?, LegSlope?).
                self.emit_entity(
                    profile_id,
                    format!(
                        "IFCLSHAPEPROFILEDEF(.AREA.,$,#{profile_placement},{d:.6},{w:.6},{t:.6},$,$,$)"
                    ),
                );
            }
            Some(ProfileDef::UShape {
                overall_depth_feet,
                flange_width_feet,
                web_thickness_feet,
                flange_thickness_feet,
            }) => {
                let d = overall_depth_feet * 0.3048;
                let fw = flange_width_feet * 0.3048;
                let tw = web_thickness_feet * 0.3048;
                let tf = flange_thickness_feet * 0.3048;
                // IFCUShapeProfileDef(ProfileType, ProfileName,
                // Position, Depth, FlangeWidth, WebThickness,
                // FlangeThickness, FilletRadius?,
                // EdgeRadius?, FlangeSlope?).
                self.emit_entity(
                    profile_id,
                    format!(
                        "IFCUSHAPEPROFILEDEF(.AREA.,$,#{profile_placement},{d:.6},{fw:.6},{tw:.6},{tf:.6},$,$,$)"
                    ),
                );
            }
            Some(ProfileDef::RectangleHollow {
                overall_width_feet,
                overall_depth_feet,
                wall_thickness_feet,
            }) => {
                let w = overall_width_feet * 0.3048;
                let d = overall_depth_feet * 0.3048;
                let t = wall_thickness_feet * 0.3048;
                // IFCRectangleHollowProfileDef(ProfileType, ProfileName,
                // Position, XDim, YDim, WallThickness,
                // InnerFilletRadius?, OuterFilletRadius?).
                self.emit_entity(
                    profile_id,
                    format!(
                        "IFCRECTANGLEHOLLOWPROFILEDEF(.AREA.,$,#{profile_placement},{w:.6},{d:.6},{t:.6},$,$)"
                    ),
                );
            }
            Some(ProfileDef::CircleHollow {
                radius_feet,
                wall_thickness_feet,
            }) => {
                let r = radius_feet * 0.3048;
                let t = wall_thickness_feet * 0.3048;
                // IFCCircleHollowProfileDef(ProfileType, ProfileName,
                // Position, Radius, WallThickness).
                self.emit_entity(
                    profile_id,
                    format!(
                        "IFCCIRCLEHOLLOWPROFILEDEF(.AREA.,$,#{profile_placement},{r:.6},{t:.6})"
                    ),
                );
            }
            Some(ProfileDef::ArbitraryClosed { points }) => {
                // Build the polyline by emitting one IFCCARTESIANPOINT
                // per vertex, then an IFCPOLYLINE that references them
                // as its Points list. Auto-close by appending the first
                // point if the last doesn't already equal it.
                let mut pts: Vec<(f64, f64)> = points
                    .iter()
                    .map(|(x, y)| (*x * 0.3048, *y * 0.3048))
                    .collect();
                if let (Some(first), Some(last)) = (pts.first().copied(), pts.last().copied()) {
                    if (first.0 - last.0).abs().max((first.1 - last.1).abs()) > 1e-9_f64 {
                        pts.push(first);
                    }
                }
                let mut point_ids: Vec<usize> = Vec::with_capacity(pts.len());
                for (x, y) in &pts {
                    let pt_id = self.id();
                    self.emit_entity(pt_id, format!("IFCCARTESIANPOINT(({x:.6},{y:.6}))"));
                    point_ids.push(pt_id);
                }
                let polyline_id = self.id();
                let refs = point_ids
                    .iter()
                    .map(|id| format!("#{id}"))
                    .collect::<Vec<_>>()
                    .join(",");
                self.emit_entity(polyline_id, format!("IFCPOLYLINE(({refs}))"));
                // IFCArbitraryClosedProfileDef(ProfileType, ProfileName,
                // OuterCurve).
                self.emit_entity(
                    profile_id,
                    format!("IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#{polyline_id})"),
                );
            }
            Some(ProfileDef::ArbitraryWithVoids { points, voids }) => {
                let outer_id = self.emit_closed_polyline(points);
                let inner_ids: Vec<usize> = voids
                    .iter()
                    .map(|hole| self.emit_closed_polyline(hole))
                    .collect();
                let inner_refs = inner_ids
                    .iter()
                    .map(|id| format!("#{id}"))
                    .collect::<Vec<_>>()
                    .join(",");
                // IFCArbitraryProfileDefWithVoids(ProfileType,
                // ProfileName, OuterCurve, InnerCurves) — four
                // attributes in IFC4, the fourth a set of curves.
                self.emit_entity(
                    profile_id,
                    format!("IFCARBITRARYPROFILEDEFWITHVOIDS(.AREA.,$,#{outer_id},({inner_refs}))"),
                );
            }
        }
        profile_id
    }

    /// Emit one `IFCCARTESIANPOINT` per vertex plus the
    /// `IFCPOLYLINE` that lists them, closing the ring by repeating
    /// the first point when the caller did not. Returns the polyline
    /// entity id. Coordinates are feet in, metres out.
    fn emit_closed_polyline(&mut self, points: &[(f64, f64)]) -> usize {
        let mut metres: Vec<(f64, f64)> = points
            .iter()
            .map(|(x, y)| (*x * 0.3048, *y * 0.3048))
            .collect();
        if let (Some(first), Some(last)) = (metres.first().copied(), metres.last().copied()) {
            if (first.0 - last.0).abs().max((first.1 - last.1).abs()) > 1e-9_f64 {
                metres.push(first);
            }
        }
        let mut point_ids: Vec<usize> = Vec::with_capacity(metres.len());
        for (x, y) in &metres {
            let pt_id = self.id();
            self.emit_entity(pt_id, format!("IFCCARTESIANPOINT(({x:.6},{y:.6}))"));
            point_ids.push(pt_id);
        }
        let polyline_id = self.id();
        let refs = point_ids
            .iter()
            .map(|id| format!("#{id}"))
            .collect::<Vec<_>>()
            .join(",");
        self.emit_entity(polyline_id, format!("IFCPOLYLINE(({refs}))"));
        polyline_id
    }

    /// Emit a richer solid body (IFC-18 / IFC-19 / IFC-20) and
    /// return `(solid_entity_id, representation_type_token)`. The
    /// second value is the `IfcShapeRepresentation.RepresentationType`
    /// token that the caller should use: `"SweptSolid"` for
    /// extruded / revolved, `"CSG"` for boolean results, `"Brep"`
    /// for faceted breps.
    ///
    /// The caller is responsible for wrapping the returned entity
    /// ID in an `IfcShapeRepresentation` + `IfcProductDefinitionShape`
    /// chain.
    ///
    /// `solid_position` is the `IFCAXIS2PLACEMENT3D` that goes into
    /// the swept solid's `Position` slot, and `z_axis` the
    /// `IFCDIRECTION` used as the extrusion direction.
    ///
    /// `Position` is the profile's frame **inside** the object's own
    /// coordinate system, not a second copy of the object placement:
    /// a conforming consumer composes `ObjectPlacement × Position`, so
    /// passing the element's own axis here applies the element
    /// translation twice (#232). Callers that author their profiles in
    /// the element-local frame — every rvt-rs path does — pass the
    /// project-level identity placement.
    fn emit_solid_shape(
        &mut self,
        shape: &SolidShape,
        solid_position: usize,
        z_axis: usize,
    ) -> (usize, &'static str) {
        match shape {
            SolidShape::ExtrudedArea(ex) => {
                // Same chain as the inline extrusion path — call
                // emit_profile_def then wrap in IFCEXTRUDEDAREASOLID.
                let profile_origin = self.id();
                self.emit_entity(profile_origin, "IFCCARTESIANPOINT((0.,0.))");
                let profile_x_axis = self.id();
                self.emit_entity(profile_x_axis, "IFCDIRECTION((1.,0.))");
                let profile_placement = self.id();
                self.emit_entity(
                    profile_placement,
                    format!("IFCAXIS2PLACEMENT2D(#{profile_origin},#{profile_x_axis})"),
                );
                let profile_id = self.emit_profile_def(ex, profile_placement);
                let depth = ex.height_feet * 0.3048;
                let solid_id = self.id();
                self.emit_entity(
                    solid_id,
                    format!(
                        "IFCEXTRUDEDAREASOLID(#{profile_id},#{solid_position},#{z_axis},{depth:.6})"
                    ),
                );
                (solid_id, "SweptSolid")
            }
            SolidShape::RevolvedArea {
                profile,
                axis_origin_feet,
                axis_direction,
                angle_radians,
            } => {
                // Axis-of-revolution: IfcAxis1Placement (Location,
                // Direction). Both location and direction are
                // element-local.
                let axis_origin_id = self.id();
                let [ox, oy, oz] = *axis_origin_feet;
                let (ox, oy, oz) = (ox * 0.3048, oy * 0.3048, oz * 0.3048);
                self.emit_entity(
                    axis_origin_id,
                    format!("IFCCARTESIANPOINT(({ox:.6},{oy:.6},{oz:.6}))"),
                );
                let axis_dir_id = self.id();
                let [dx, dy, dz] = *axis_direction;
                // Normalise to unit vector per IFC4.
                let mag = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-12);
                let (dx, dy, dz) = (dx / mag, dy / mag, dz / mag);
                self.emit_entity(
                    axis_dir_id,
                    format!("IFCDIRECTION(({dx:.6},{dy:.6},{dz:.6}))"),
                );
                let axis1_id = self.id();
                self.emit_entity(
                    axis1_id,
                    format!("IFCAXIS1PLACEMENT(#{axis_origin_id},#{axis_dir_id})"),
                );
                // Profile (same 2D placement boilerplate as
                // extruded-area). Reuse emit_profile_def by wrapping
                // our ProfileDef in a temporary Extrusion — the
                // emit_profile_def signature takes an Extrusion but
                // only reads profile_override / width_feet / depth_feet.
                let profile_origin = self.id();
                self.emit_entity(profile_origin, "IFCCARTESIANPOINT((0.,0.))");
                let profile_x_axis = self.id();
                self.emit_entity(profile_x_axis, "IFCDIRECTION((1.,0.))");
                let profile_placement = self.id();
                self.emit_entity(
                    profile_placement,
                    format!("IFCAXIS2PLACEMENT2D(#{profile_origin},#{profile_x_axis})"),
                );
                let wrap_ex = Extrusion {
                    width_feet: 0.0,
                    depth_feet: 0.0,
                    height_feet: 0.0,
                    profile_override: Some(profile.clone()),
                };
                let profile_id = self.emit_profile_def(&wrap_ex, profile_placement);
                let solid_id = self.id();
                // IFCREVOLVEDAREASOLID(SweptArea, Position, Axis, Angle).
                // SI units = radians, writer converts caller's angle
                // (already in radians) at identity.
                self.emit_entity(
                    solid_id,
                    format!(
                        "IFCREVOLVEDAREASOLID(#{profile_id},#{solid_position},#{axis1_id},{angle_radians:.6})"
                    ),
                );
                (solid_id, "SweptSolid")
            }
            SolidShape::BooleanResult {
                op,
                operand_a,
                operand_b,
            } => {
                // Recursively emit operands, then wrap in
                // IFCBOOLEANRESULT(op, first, second). Nested
                // booleans compose naturally.
                let (a_id, _rep_a) = self.emit_solid_shape(operand_a, solid_position, z_axis);
                let (b_id, _rep_b) = self.emit_solid_shape(operand_b, solid_position, z_axis);
                let solid_id = self.id();
                self.emit_entity(
                    solid_id,
                    format!("IFCBOOLEANRESULT({},#{a_id},#{b_id})", op.as_step_keyword()),
                );
                (solid_id, "CSG")
            }
            SolidShape::FacetedBrep {
                vertices_feet,
                triangles,
            } => {
                // One IfcCartesianPoint per vertex.
                let mut vert_ids: Vec<usize> = Vec::with_capacity(vertices_feet.len());
                for [x, y, z] in vertices_feet {
                    let (xm, ym, zm) = (x * 0.3048, y * 0.3048, z * 0.3048);
                    let pid = self.id();
                    self.emit_entity(pid, format!("IFCCARTESIANPOINT(({xm:.6},{ym:.6},{zm:.6}))"));
                    vert_ids.push(pid);
                }
                // One IfcPolyLoop + IfcFaceBound + IfcFace per triangle.
                // Triangles with out-of-range indices are skipped so
                // downstream parsers don't choke on a dangling ref;
                // debug builds panic instead so the caller learns
                // about bad mesh input during testing.
                let mut face_ids: Vec<usize> = Vec::new();
                for tri in triangles {
                    let idx_a = tri.0 as usize;
                    let idx_b = tri.1 as usize;
                    let idx_c = tri.2 as usize;
                    if idx_a >= vert_ids.len() || idx_b >= vert_ids.len() || idx_c >= vert_ids.len()
                    {
                        debug_assert!(
                            false,
                            "FacetedBrep triangle ({},{},{}) refers to vertex out of range (len={})",
                            tri.0,
                            tri.1,
                            tri.2,
                            vert_ids.len(),
                        );
                        continue;
                    }
                    let (va, vb, vc) = (vert_ids[idx_a], vert_ids[idx_b], vert_ids[idx_c]);
                    let loop_id = self.id();
                    self.emit_entity(loop_id, format!("IFCPOLYLOOP((#{va},#{vb},#{vc}))"));
                    let bound_id = self.id();
                    self.emit_entity(bound_id, format!("IFCFACEBOUND(#{loop_id},.T.)"));
                    let face_id = self.id();
                    self.emit_entity(face_id, format!("IFCFACE((#{bound_id}))"));
                    face_ids.push(face_id);
                }
                // IfcClosedShell wrapping all faces, then IfcFacetedBrep.
                let shell_id = self.id();
                let face_refs = face_ids
                    .iter()
                    .map(|id| format!("#{id}"))
                    .collect::<Vec<_>>()
                    .join(",");
                self.emit_entity(shell_id, format!("IFCCLOSEDSHELL(({face_refs}))"));
                let brep_id = self.id();
                self.emit_entity(
                    brep_id,
                    format!(
                        "IFCFACETEDBREP(#{brep_id_placeholder})",
                        brep_id_placeholder = shell_id
                    ),
                );
                (brep_id, "Brep")
            }
            SolidShape::SweptPath {
                profile,
                directrix_points_feet,
                fixed_reference,
            } => {
                // IFC-17: IfcFixedReferenceSweptAreaSolid. Profile
                // sweeps along the directrix polyline, orthogonal
                // at every sample, with `fixed_reference` providing
                // the "up" direction.

                // Directrix — one IfcCartesianPoint per vertex, then
                // an IfcPolyline referencing them.
                let mut dir_pt_ids: Vec<usize> = Vec::with_capacity(directrix_points_feet.len());
                for [x, y, z] in directrix_points_feet {
                    let (xm, ym, zm) = (x * 0.3048, y * 0.3048, z * 0.3048);
                    let pt = self.id();
                    self.emit_entity(pt, format!("IFCCARTESIANPOINT(({xm:.6},{ym:.6},{zm:.6}))"));
                    dir_pt_ids.push(pt);
                }
                let directrix = self.id();
                let pt_refs = dir_pt_ids
                    .iter()
                    .map(|id| format!("#{id}"))
                    .collect::<Vec<_>>()
                    .join(",");
                self.emit_entity(directrix, format!("IFCPOLYLINE(({pt_refs}))"));

                // Profile — same 2D placement pattern as
                // emit_profile_def. Wrap ProfileDef in a temporary
                // Extrusion to reuse the existing helper (its
                // dimensions aren't used since we override via
                // profile_override).
                let profile_origin = self.id();
                self.emit_entity(profile_origin, "IFCCARTESIANPOINT((0.,0.))");
                let profile_x_axis = self.id();
                self.emit_entity(profile_x_axis, "IFCDIRECTION((1.,0.))");
                let profile_placement = self.id();
                self.emit_entity(
                    profile_placement,
                    format!("IFCAXIS2PLACEMENT2D(#{profile_origin},#{profile_x_axis})"),
                );
                let wrap_ex = Extrusion {
                    width_feet: 0.0,
                    depth_feet: 0.0,
                    height_feet: 0.0,
                    profile_override: Some(profile.clone()),
                };
                let profile_id = self.emit_profile_def(&wrap_ex, profile_placement);

                // Fixed reference — normalise to unit length.
                let [fx, fy, fz] = *fixed_reference;
                let mag = (fx * fx + fy * fy + fz * fz).sqrt().max(1e-12);
                let (fx, fy, fz) = (fx / mag, fy / mag, fz / mag);
                let fixed_ref_id = self.id();
                self.emit_entity(
                    fixed_ref_id,
                    format!("IFCDIRECTION(({fx:.6},{fy:.6},{fz:.6}))"),
                );

                // IFCFIXEDREFERENCESWEPTAREASOLID(SweptArea, Position,
                //   Directrix, StartParam, EndParam, FixedReference).
                // StartParam / EndParam = $ means use the full
                // directrix from start to end — the IFC4 default.
                let solid_id = self.id();
                self.emit_entity(
                    solid_id,
                    format!(
                        "IFCFIXEDREFERENCESWEPTAREASOLID(#{profile_id},#{solid_position},#{directrix},$,$,#{fixed_ref_id})"
                    ),
                );
                (solid_id, "SweptSolid")
            }
            SolidShape::PlacedExtrusion {
                profile,
                origin_feet,
                axis,
                ref_direction,
                depth_feet,
            } => {
                // RE-52: IfcExtrudedAreaSolid with its own Position, so the
                // profile's plane is stated rather than implied.
                let profile_origin = self.id();
                self.emit_entity(profile_origin, "IFCCARTESIANPOINT((0.,0.))");
                let profile_x_axis = self.id();
                self.emit_entity(profile_x_axis, "IFCDIRECTION((1.,0.))");
                let profile_placement = self.id();
                self.emit_entity(
                    profile_placement,
                    format!("IFCAXIS2PLACEMENT2D(#{profile_origin},#{profile_x_axis})"),
                );
                let wrap_ex = Extrusion {
                    width_feet: 0.0,
                    depth_feet: 0.0,
                    height_feet: 0.0,
                    profile_override: Some(profile.clone()),
                };
                let profile_id = self.emit_profile_def(&wrap_ex, profile_placement);
                let unit = |v: [f64; 3]| {
                    let mag = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-12);
                    (v[0] / mag, v[1] / mag, v[2] / mag)
                };
                let [ox, oy, oz] = *origin_feet;
                let origin_id = self.id();
                self.emit_entity(
                    origin_id,
                    format!(
                        "IFCCARTESIANPOINT(({:.6},{:.6},{:.6}))",
                        ox * 0.3048,
                        oy * 0.3048,
                        oz * 0.3048
                    ),
                );
                let (ax, ay, az) = unit(*axis);
                let axis_id = self.id();
                self.emit_entity(axis_id, format!("IFCDIRECTION(({ax:.9},{ay:.9},{az:.9}))"));
                let (rx, ry, rz) = unit(*ref_direction);
                let ref_id = self.id();
                self.emit_entity(ref_id, format!("IFCDIRECTION(({rx:.9},{ry:.9},{rz:.9}))"));
                let position = self.id();
                self.emit_entity(
                    position,
                    format!("IFCAXIS2PLACEMENT3D(#{origin_id},#{axis_id},#{ref_id})"),
                );
                let depth = depth_feet * 0.3048;
                let solid_id = self.id();
                self.emit_entity(
                    solid_id,
                    format!("IFCEXTRUDEDAREASOLID(#{profile_id},#{position},#{z_axis},{depth:.6})"),
                );
                (solid_id, "SweptSolid")
            }
        }
    }

    /// The IfcUnitAssignment: the SI units every value is written in
    /// (#403). The writer converts Revit's feet, square and cubic feet and
    /// pounds on the way out and writes angles in radians, so these are
    /// the units a reader must apply. `model.units`, Revit's display units
    /// (IFC-40), describe the source model and stay out of it; the export
    /// diagnostics report them.
    fn emit_unit_assignment(&mut self) -> Vec<usize> {
        [
            ("LENGTHUNIT", "$", "METRE"),
            ("AREAUNIT", "$", "SQUARE_METRE"),
            ("VOLUMEUNIT", "$", "CUBIC_METRE"),
            ("PLANEANGLEUNIT", "$", "RADIAN"),
            ("MASSUNIT", ".KILO.", "GRAM"),
            ("TIMEUNIT", "$", "SECOND"),
        ]
        .into_iter()
        .map(|(unit_type, prefix, name)| {
            let id = self.id();
            self.emit_entity(id, format!("IFCSIUNIT(*,.{unit_type}.,{prefix},.{name}.)"));
            id
        })
        .collect()
    }

    fn emit_header(&mut self, model: &IfcModel) {
        let project = escape(model.project_name.as_deref().unwrap_or("Untitled"));
        let desc = escape(model.description.as_deref().unwrap_or(
            "Produced by rvt-rs (https://github.com/DrunkOnJava/rvt-rs) — \
                 clean-room Apache-2 Revit reader.",
        ));
        self.emit_line("ISO-10303-21;");
        self.emit_line("HEADER;");
        self.emit_line("FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');");
        self.emit_line(format!(
            "FILE_NAME('{project}.ifc','{}',('rvt-rs'),('DrunkOnJava/rvt-rs'),'rvt-rs {version}','rvt-rs STEP writer','');",
            iso_timestamp_from(self.timestamp),
            version = env!("CARGO_PKG_VERSION"),
        ));
        self.emit_line("FILE_SCHEMA(('IFC4'));");
        self.emit_line("ENDSEC;");
        self.emit_line(format!("/* {desc} */"));
    }

    fn emit_data(&mut self, model: &IfcModel) {
        self.emit_line("DATA;");
        let document = model.global_ids.document.as_deref().unwrap_or("");
        let gid = |key: &[&str]| stable_guid(document, key);

        // Required framework entities (buildingSMART minimum viable).
        let person = self.id();
        self.emit_entity(person, "IFCPERSON($,$,'rvt-rs',$,$,$,$,$)");
        let org = self.id();
        self.emit_entity(
            org,
            "IFCORGANIZATION($,'rvt-rs','Clean-room Apache-2 Revit reader',$,$)",
        );
        let person_and_org = self.id();
        self.emit_entity(
            person_and_org,
            format!("IFCPERSONANDORGANIZATION(#{person},#{org},$)"),
        );
        let application = self.id();
        self.emit_entity(
            application,
            format!(
                "IFCAPPLICATION(#{org},'{}','rvt-rs','rvt_rs')",
                env!("CARGO_PKG_VERSION")
            ),
        );
        let owner_hist = self.id();
        self.emit_entity(
            owner_hist,
            format!(
                "IFCOWNERHISTORY(#{person_and_org},#{application},$,.ADDED.,$,#{person_and_org},#{application},{})",
                self.timestamp
            ),
        );

        // Unit assignment (IFC-40, #403).
        let unit_entity_ids = self.emit_unit_assignment();
        let unit_assignment = self.id();
        let unit_refs = unit_entity_ids
            .iter()
            .map(|id| format!("#{id}"))
            .collect::<Vec<_>>()
            .join(",");
        self.emit_entity(unit_assignment, format!("IFCUNITASSIGNMENT(({unit_refs}))"));

        // Representation context — needs IfcAxis2Placement3D +
        // IfcDirection + IfcCartesianPoint (origin, X, Z axes).
        let origin = self.id();
        self.emit_entity(origin, "IFCCARTESIANPOINT((0.,0.,0.))");
        let z_axis = self.id();
        self.emit_entity(z_axis, "IFCDIRECTION((0.,0.,1.))");
        let x_axis = self.id();
        self.emit_entity(x_axis, "IFCDIRECTION((1.,0.,0.))");
        let axis_placement = self.id();
        self.emit_entity(
            axis_placement,
            format!("IFCAXIS2PLACEMENT3D(#{origin},#{z_axis},#{x_axis})"),
        );
        let geom_ctx = self.id();
        self.emit_entity(
            geom_ctx,
            format!("IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-5,#{axis_placement},$)"),
        );

        // Root project.
        let project_name = escape(model.project_name.as_deref().unwrap_or("Untitled"));
        let project_desc = escape(model.description.as_deref().unwrap_or("Exported by rvt-rs"));
        let project_id = self.id();
        self.emit_entity(
            project_id,
            format!(
                "IFCPROJECT('{}',#{owner_hist},'{}',{},$,$,$,(#{geom_ctx}),#{unit_assignment})",
                gid(&["project"]),
                project_name,
                quoted_or_dollar(&project_desc),
            ),
        );

        // Spatial containment hierarchy — required by IFC4 for any
        // project with building content. We emit a minimal but valid
        // IfcSite → IfcBuilding → IfcBuildingStorey chain with
        // identity placements so downstream viewers (BlenderBIM,
        // IfcOpenShell-based tools, buildingSMART validator) render
        // the file directly without needing to synthesise a host
        // structure. Names default to "Default {Site,Building,Level
        // 1}"; once the walker surfaces site/level instances they'll
        // flow in here.
        //
        // Every IfcSpatialStructureElement needs its own
        // IfcLocalPlacement — we share the `axis_placement` across
        // the three (they're all identity), then chain the
        // placements via `PlacementRelTo` so the coordinate frames
        // compose correctly.
        let site_placement = self.id();
        self.emit_entity(
            site_placement,
            format!("IFCLOCALPLACEMENT($,#{axis_placement})"),
        );
        let site_id = self.id();
        self.emit_entity(
            site_id,
            format!(
                "IFCSITE('{}',#{owner_hist},'Default Site',$,$,#{site_placement},$,'Default Site',.ELEMENT.,$,$,$,$,$)",
                gid(&["site"]),
            ),
        );

        let building_placement = self.id();
        self.emit_entity(
            building_placement,
            format!("IFCLOCALPLACEMENT(#{site_placement},#{axis_placement})"),
        );
        let building_id = self.id();
        self.emit_entity(
            building_id,
            format!(
                "IFCBUILDING('{}',#{owner_hist},'Default Building',$,$,#{building_placement},$,'Default Building',.ELEMENT.,$,$,$)",
                gid(&["building"]),
            ),
        );

        // Emit one IfcBuildingStorey per Revit Level (or one
        // placeholder when no Levels have been decoded yet). Every
        // storey gets its own IfcLocalPlacement; their IDs are later
        // bundled into a single IfcRelAggregates bound to the
        // building. The first storey doubles as the default container
        // for elements that don't carry a level_id hint — Phase 4b+
        // per-level containment is a follow-up.
        let mut storey_ids: Vec<usize> = Vec::new();
        let mut storey_placements: Vec<usize> = Vec::new();
        let storeys = if model.building_storeys.is_empty() {
            // Fallback: one placeholder so the IFC spatial hierarchy
            // remains valid even when the caller hasn't provided any
            // Levels yet.
            vec![super::Storey {
                name: "Level 1".to_string(),
                elevation_feet: 0.0,
            }]
        } else {
            model.building_storeys.clone()
        };
        let mut storey_gids: Vec<String> = Vec::with_capacity(storeys.len());
        let mut storey_name_counts: HashMap<&str, usize> = HashMap::new();
        for (storey_index, storey) in storeys.iter().enumerate() {
            let occurrence = storey_name_counts.entry(storey.name.as_str()).or_default();
            // RE-48: the Level's own GlobalId where the file yields it.
            let storey_gid = model
                .global_ids
                .storeys
                .get(&storey_index)
                .cloned()
                .unwrap_or_else(|| gid(&["storey", &storey.name, &occurrence.to_string()]));
            *occurrence += 1;
            let placement_id = self.id();
            self.emit_entity(
                placement_id,
                format!("IFCLOCALPLACEMENT(#{building_placement},#{axis_placement})"),
            );
            let id = self.id();
            // Convert feet → metres at emit boundary; IFC4 elevation
            // attribute is in the project's length unit (metres here).
            let elevation_m = storey.elevation_feet * 0.3048;
            let name_escaped = escape(&storey.name);
            self.emit_entity(
                id,
                format!(
                    // `Elevation` is an IfcLengthMeasure (REAL), so it
                    // needs a decimal point — `0` is an INTEGER literal
                    // and ISO-10303-21 does not admit it here (#214).
                    "IFCBUILDINGSTOREY('{storey_gid}',#{owner_hist},'{name_escaped}',$,$,#{placement_id},$,'{name_escaped}',.ELEMENT.,{elevation_m:.6})",
                ),
            );
            storey_gids.push(storey_gid);
            storey_ids.push(id);
            storey_placements.push(placement_id);
        }
        // First storey stands in as the default container for
        // BuildingElements that don't yet carry a level reference.
        let storey_id = storey_ids[0];
        let storey_placement = storey_placements[0];

        // Aggregation relationships — IfcRelAggregates is how the
        // spatial hierarchy binds in IFC4. Each level of the chain
        // gets one relationship pointing from parent to child.
        let rel_proj_site = self.id();
        self.emit_entity(
            rel_proj_site,
            format!(
                "IFCRELAGGREGATES('{}',#{owner_hist},$,$,#{project_id},(#{site_id}))",
                gid(&["aggregates", "project"]),
            ),
        );
        let rel_site_building = self.id();
        self.emit_entity(
            rel_site_building,
            format!(
                "IFCRELAGGREGATES('{}',#{owner_hist},$,$,#{site_id},(#{building_id}))",
                gid(&["aggregates", "site"]),
            ),
        );
        let rel_building_storey = self.id();
        let storey_refs = storey_ids
            .iter()
            .map(|id| format!("#{id}"))
            .collect::<Vec<_>>()
            .join(",");
        self.emit_entity(
            rel_building_storey,
            format!(
                "IFCRELAGGREGATES('{}',#{owner_hist},$,$,#{building_id},({storey_refs}))",
                gid(&["aggregates", "building"]),
            ),
        );

        // Classifications — one IfcClassification per source
        // (OmniClass, Uniformat, …), with one IfcClassificationReference
        // per coded item. Each classification gets its own
        // IfcRelAssociatesClassification tying its references back to
        // the project, which is how IFC4 consumers (BlenderBIM,
        // IfcOpenShell's classification viewer) discover code refs.
        //
        // RvtDocExporter populates `model.classifications` from
        // PartAtom's `<category term="...">` blocks. Previously those
        // codes were collected but never emitted; this wires them
        // through the STEP writer so downstream consumers can see
        // them directly.
        let mut classification_counts: HashMap<(&str, &str), usize> = HashMap::new();
        for classification in &model.classifications {
            let source_name = match &classification.source {
                super::entities::ClassificationSource::OmniClass => "OmniClass",
                super::entities::ClassificationSource::Uniformat => "Uniformat",
                super::entities::ClassificationSource::Other(s) => s.as_str(),
            };
            let source_name_escaped = escape(source_name);
            let edition = classification
                .edition
                .as_deref()
                .map(escape)
                .map(|e| format!("'{e}'"))
                .unwrap_or_else(|| "$".into());

            let classification_id = self.id();
            self.emit_entity(
                classification_id,
                format!("IFCCLASSIFICATION($,{edition},$,'{source_name_escaped}',$,$,$)"),
            );

            // One IfcClassificationReference per item; collect their
            // ids so we can bundle them into the IfcRelAssociatesClassification.
            let mut ref_ids: Vec<usize> = Vec::with_capacity(classification.items.len());
            let mut ref_gids: Vec<String> = Vec::with_capacity(classification.items.len());
            for item in &classification.items {
                let code_escaped = escape(&item.code);
                let name_str = item
                    .name
                    .as_deref()
                    .map(escape)
                    .map(|n| format!("'{n}'"))
                    .unwrap_or_else(|| "$".into());
                let ref_id = self.id();
                self.emit_entity(
                    ref_id,
                    format!(
                        // (Location, Identification, Name,
                        //  ReferencedSource, Description, Sort) — six
                        // attributes in IFC4 (#214).
                        "IFCCLASSIFICATIONREFERENCE($,'{code_escaped}',{name_str},#{classification_id},$,$)"
                    ),
                );
                ref_ids.push(ref_id);
                let occurrence = classification_counts
                    .entry((source_name, item.code.as_str()))
                    .or_default();
                ref_gids.push(gid(&[
                    "classification",
                    source_name,
                    &item.code,
                    &occurrence.to_string(),
                ]));
                *occurrence += 1;
            }

            if !ref_ids.is_empty() {
                let refs_list = ref_ids
                    .iter()
                    .map(|id| format!("#{id}"))
                    .collect::<Vec<_>>()
                    .join(",");
                // IfcRelAssociatesClassification binds a set of objects
                // to one classification reference. IFC4's schema
                // requires the RelatingClassification to be a single
                // IfcClassificationReferenceSelect; we pick the last
                // reference as the relating one and treat the rest as
                // project associations. If the project only has one
                // reference this is exact; when there are multiple,
                // each gets its own association relationship.
                for (ref_id, ref_gid) in ref_ids.iter().zip(&ref_gids) {
                    let rel_id = self.id();
                    self.emit_entity(
                        rel_id,
                        format!(
                            "IFCRELASSOCIATESCLASSIFICATION('{ref_gid}',#{owner_hist},$,$,(#{project_id}),#{ref_id})",
                        ),
                    );
                }
                // Silence the warning about an unused local when the
                // outer `for` loop only iterates once.
                let _ = refs_list;
            }
        }

        // BuildingElement emission — one `IFC<TYPE>` instance per decoded
        // Revit element (Wall, Floor, Roof, Ceiling, Door, Window, Column,
        // Beam…). Each element gets its own `IFCLOCALPLACEMENT` relative
        // to whichever storey contains it (index from
        // `BuildingElement.storey_index`; falls back to storey[0] when
        // unset). At the end, elements are grouped by storey and one
        // `IFCRELCONTAINEDINSPATIALSTRUCTURE` is emitted per non-empty
        // storey — which is how IFC4 tools (BlenderBIM, IfcOpenShell)
        // show "Floor 2 contains Wall-7, Wall-8" in the project
        // browser.
        //
        // Geometry (`IfcShapeRepresentation`) is intentionally omitted
        // here — tasks IFC-15 through IFC-22 produce proper
        // representations once Phase-5 geometry lands. For now every
        // element carries its placement + name + GUID, which validates
        // against the IFC4 schema as a "geometry-free" element.
        // Emit IfcMaterials upfront so BuildingElements can reference
        // them. Each material gets:
        //   - IFCMATERIAL with just a name (IFC4 minimum)
        //   - If the material has a color: IFCCOLOURRGB +
        //     IFCSURFACESTYLERENDERING + IFCSURFACESTYLE +
        //     IFCSTYLEDITEM to surface the color to IFC4 viewers
        // The color emission is gated because a color-less material
        // is valid IFC4 — we don't want to emit empty rendering
        // records when there's nothing to render.
        let mut material_ids: Vec<usize> = Vec::with_capacity(model.materials.len());
        for mat in &model.materials {
            let mat_id = self.id();
            let name_escaped = escape(&mat.name);
            self.emit_entity(mat_id, format!("IFCMATERIAL('{name_escaped}',$,$)"));
            if let Some(packed) = mat.color_packed {
                let r = (packed & 0xFF) as f64 / 255.0;
                let g = ((packed >> 8) & 0xFF) as f64 / 255.0;
                let b = ((packed >> 16) & 0xFF) as f64 / 255.0;
                let colour_id = self.id();
                self.emit_entity(colour_id, format!("IFCCOLOURRGB($,{r:.6},{g:.6},{b:.6})"));
                let rendering_id = self.id();
                let transparency = mat.transparency.unwrap_or(0.0);
                self.emit_entity(
                    rendering_id,
                    format!(
                        "IFCSURFACESTYLERENDERING(#{colour_id},{transparency:.6},$,$,$,$,$,$,.FLAT.)"
                    ),
                );
                let style_id = self.id();
                self.emit_entity(
                    style_id,
                    format!("IFCSURFACESTYLE('{name_escaped}',.BOTH.,(#{rendering_id}))"),
                );
                let presentation_id = self.id();
                self.emit_entity(
                    presentation_id,
                    format!("IFCPRESENTATIONSTYLEASSIGNMENT((#{style_id}))"),
                );
                let styled_item_id = self.id();
                self.emit_entity(
                    styled_item_id,
                    format!("IFCSTYLEDITEM($,(#{presentation_id}),'{name_escaped}')"),
                );
            }
            material_ids.push(mat_id);
        }

        // IFC-28: Emit IfcMaterialLayer + IfcMaterialLayerSet for
        // every compound assembly declared on the model. Layers
        // reference the `material_ids` vector above by index, so
        // layer_set emission MUST follow single-material emission.
        // Track layer-set ids for later IfcRelAssociatesMaterial
        // pairing.
        let mut layer_set_ids: Vec<usize> = Vec::with_capacity(model.material_layer_sets.len());
        for lset in &model.material_layer_sets {
            let mut layer_ids: Vec<usize> = Vec::with_capacity(lset.layers.len());
            for layer in &lset.layers {
                // A layer with no material writes `$` (IFC4 makes
                // IfcMaterialLayer.Material optional). An out-of-range
                // index gets the first material as a defensive fallback;
                // losing the layer would be worse.
                let material_slot = match layer.material_index {
                    None => "$".to_string(),
                    Some(index) => {
                        let mat_id = material_ids
                            .get(index)
                            .copied()
                            .or_else(|| material_ids.first().copied())
                            .unwrap_or(0);
                        if mat_id == 0 {
                            // No materials at all — skip this layer. IFC4
                            // allows IfcMaterialLayerSet with zero layers,
                            // so the set will still emit below, just empty.
                            continue;
                        }
                        format!("#{mat_id}")
                    }
                };
                let layer_id = self.id();
                // IfcMaterialLayer(Material, LayerThickness, IsVentilated=$,
                //                  Category=$, Priority=$, Name=$, Description=$)
                // Thickness in metres (feet × 0.3048).
                let thickness_m = layer.thickness_feet * 0.3048;
                let name_slot = match &layer.name {
                    Some(n) => format!("'{}'", escape(n)),
                    None => "$".into(),
                };
                self.emit_entity(
                    layer_id,
                    format!(
                        "IFCMATERIALLAYER({material_slot},{thickness_m:.6},$,$,$,{name_slot},$)"
                    ),
                );
                layer_ids.push(layer_id);
            }
            let set_id = self.id();
            let set_name = escape(&lset.name);
            let desc_slot = match &lset.description {
                Some(d) => format!("'{}'", escape(d)),
                None => "$".into(),
            };
            let layer_refs = if layer_ids.is_empty() {
                "()".to_string()
            } else {
                format!(
                    "({})",
                    layer_ids
                        .iter()
                        .map(|id| format!("#{id}"))
                        .collect::<Vec<_>>()
                        .join(",")
                )
            };
            // IfcMaterialLayerSet(MaterialLayers, LayerSetName, Description)
            self.emit_entity(
                set_id,
                format!("IFCMATERIALLAYERSET({layer_refs},'{set_name}',{desc_slot})"),
            );
            layer_set_ids.push(set_id);
        }

        // IFC-30: Emit IfcMaterialProfileSet for structural framing
        // (columns / beams) with named cross-sections. Each profile
        // carries a material index + profile name; at IfcMaterialProfile
        // emission time the profile name is also echoed as the
        // associated IfcProfileDef name — downstream tools that care
        // about precise cross-section geometry still need the profile
        // def itself (tracked separately in IFC-24).
        let mut profile_set_ids: Vec<usize> = Vec::with_capacity(model.material_profile_sets.len());
        for pset in &model.material_profile_sets {
            let mut profile_ids: Vec<usize> = Vec::with_capacity(pset.profiles.len());
            for profile in &pset.profiles {
                let mat_id = material_ids
                    .get(profile.material_index)
                    .copied()
                    .or_else(|| material_ids.first().copied())
                    .unwrap_or(0);
                if mat_id == 0 {
                    continue;
                }
                // The profile itself where the model carries it (RE-105);
                // otherwise a 1 x 1 m IfcRectangleProfileDef stand-in, as
                // IfcMaterialProfile requires a profile def reference.
                let profile_def_id = match &profile.profile {
                    Some(def) => {
                        let origin = self.id();
                        self.emit_entity(origin, "IFCCARTESIANPOINT((0.,0.))");
                        let x_axis = self.id();
                        self.emit_entity(x_axis, "IFCDIRECTION((1.,0.))");
                        let placement = self.id();
                        self.emit_entity(
                            placement,
                            format!("IFCAXIS2PLACEMENT2D(#{origin},#{x_axis})"),
                        );
                        let wrap = Extrusion {
                            width_feet: 0.0,
                            depth_feet: 0.0,
                            height_feet: 0.0,
                            profile_override: Some(def.clone()),
                        };
                        self.emit_profile_def(&wrap, placement)
                    }
                    None => {
                        let profile_def_id = self.id();
                        let profile_def_name = escape(&profile.profile_name);
                        self.emit_entity(
                            profile_def_id,
                            format!("IFCRECTANGLEPROFILEDEF(.AREA.,'{profile_def_name}',$,1.,1.)"),
                        );
                        profile_def_id
                    }
                };
                let profile_id = self.id();
                let profile_name = escape(&profile.profile_name);
                let desc_slot = match &profile.description {
                    Some(d) => format!("'{}'", escape(d)),
                    None => "$".into(),
                };
                // IfcMaterialProfile(Name, Description, Material, Profile,
                //                    Priority=$, Category=$)
                self.emit_entity(
                    profile_id,
                    format!(
                        "IFCMATERIALPROFILE('{profile_name}',{desc_slot},#{mat_id},#{profile_def_id},$,$)"
                    ),
                );
                profile_ids.push(profile_id);
            }
            let set_id = self.id();
            let set_name = escape(&pset.name);
            let desc_slot = match &pset.description {
                Some(d) => format!("'{}'", escape(d)),
                None => "$".into(),
            };
            let profile_refs = if profile_ids.is_empty() {
                "()".to_string()
            } else {
                format!(
                    "({})",
                    profile_ids
                        .iter()
                        .map(|id| format!("#{id}"))
                        .collect::<Vec<_>>()
                        .join(",")
                )
            };
            // IfcMaterialProfileSet(Name, Description, MaterialProfiles, CompositeProfile)
            self.emit_entity(
                set_id,
                format!("IFCMATERIALPROFILESET('{set_name}',{desc_slot},{profile_refs},$)"),
            );
            profile_set_ids.push(set_id);
        }

        // RE-82: family instances' material constituent sets, as Revit's
        // export writes them: unnamed, one constituent per material named
        // after it, in the category "Materials".
        let mut constituent_set_ids: Vec<Option<usize>> =
            Vec::with_capacity(model.material_constituent_sets.len());
        for cset in &model.material_constituent_sets {
            let mut constituent_ids = Vec::with_capacity(cset.material_indices.len());
            for (position, &material_index) in cset.material_indices.iter().enumerate() {
                let (Some(&mat_id), Some(material)) = (
                    material_ids.get(material_index),
                    model.materials.get(material_index),
                ) else {
                    continue;
                };
                let constituent_id = self.id();
                // IfcMaterialConstituent(Name, Description, Material,
                //   Fraction, Category)
                self.emit_entity(
                    constituent_id,
                    format!(
                        "IFCMATERIALCONSTITUENT('{}',$,#{mat_id},$,'Materials')",
                        escape(cset.names.get(position).unwrap_or(&material.name))
                    ),
                );
                constituent_ids.push(constituent_id);
            }
            if constituent_ids.is_empty() {
                constituent_set_ids.push(None);
                continue;
            }
            let set_id = self.id();
            // IfcMaterialConstituentSet(Name, Description, MaterialConstituents)
            self.emit_entity(
                set_id,
                format!(
                    "IFCMATERIALCONSTITUENTSET($,$,({}))",
                    constituent_ids
                        .iter()
                        .map(|id| format!("#{id}"))
                        .collect::<Vec<_>>()
                        .join(",")
                ),
            );
            constituent_set_ids.push(Some(set_id));
        }
        let constituent_set_of: HashMap<usize, usize> = model
            .material_constituent_sets
            .iter()
            .enumerate()
            .flat_map(|(set, cset)| cset.elements.iter().map(move |&entity| (entity, set)))
            .collect();
        let mut element_constituent_pairs: Vec<(usize, usize)> = Vec::new();

        // IFC-21: emit IfcRepresentationMap entities up-front. Each
        // map carries its shape representation (emitted once) and an
        // IFCAXIS2PLACEMENT3D mapping origin; instances reference
        // the map via IFCMAPPEDITEM in their own
        // IfcShapeRepresentation body. The emitted-map ID is stored
        // by index so the per-element loop can look it up from
        // `representation_map_index`.
        let mut representation_map_ids: Vec<usize> =
            Vec::with_capacity(model.representation_maps.len());
        for rmap in &model.representation_maps {
            // Mapping origin: per IFC4, usually identity (0,0,0)
            // with +X east / +Z up. Non-identity origins are rare —
            // they shift the shared shape relative to the mapped-item
            // transform.
            let [mx, my, mz] = rmap.origin_feet;
            let (mx, my, mz) = (mx * 0.3048, my * 0.3048, mz * 0.3048);
            let map_origin_pt = self.id();
            self.emit_entity(
                map_origin_pt,
                format!("IFCCARTESIANPOINT(({mx:.6},{my:.6},{mz:.6}))"),
            );
            // Reuse the project-level #z_axis / project-level #x_axis
            // directions — identity orientation is the common case.
            let map_placement = self.id();
            self.emit_entity(
                map_placement,
                format!("IFCAXIS2PLACEMENT3D(#{map_origin_pt},#{z_axis},#{x_axis})"),
            );
            // Emit the shared shape body. The emission helper returns
            // (solid_entity_id, rep_type_token). For the map's own
            // IfcShapeRepresentation we use the returned rep_type
            // (SweptSolid / CSG / Brep).
            //
            // Passing `map_placement` as the solid `Position` here is
            // not the #232 double-translation: a mapped item resolves
            // as `MappingTarget × MappingOrigin⁻¹ × geometry`, so a
            // Position equal to the MappingOrigin cancels against the
            // inverse rather than compounding. `origin_feet` is
            // `[0,0,0]` on every map rvt-rs builds today, which makes
            // the two placements the same identity frame anyway.
            let (solid_id, rep_type) = self.emit_solid_shape(&rmap.shape, map_placement, z_axis);
            let body_rep_id = self.id();
            self.emit_entity(
                body_rep_id,
                format!("IFCSHAPEREPRESENTATION(#{geom_ctx},'Body','{rep_type}',(#{solid_id}))"),
            );
            // IFCREPRESENTATIONMAP(MappingOrigin, MappedRepresentation).
            let rep_map_id = self.id();
            self.emit_entity(
                rep_map_id,
                format!("IFCREPRESENTATIONMAP(#{map_placement},#{body_rep_id})"),
            );
            representation_map_ids.push(rep_map_id);
        }

        let mut per_storey_elements: Vec<Vec<usize>> = vec![Vec::new(); storeys.len()];
        // #219: elements no storey join reached. They are contained in
        // the `IfcBuilding` rather than in whichever storey happens to
        // be first — "somewhere in this building" is the honest claim,
        // and putting them on a named storey would state a containment
        // nothing measured.
        let mut unplaced_elements: Vec<usize> = Vec::new();
        // Track (element_id, material_index) pairs so we can emit
        // IfcRelAssociatesMaterial per material after the element
        // loop completes.
        let mut element_material_pairs: Vec<(usize, usize)> = Vec::new();
        // Track (element_id, &PropertySet) so property-set emission
        // runs after all element IDs are assigned.
        let mut element_property_sets: Vec<(usize, &super::entities::PropertySet)> = Vec::new();
        // Map vec index in model.entities → emitted IFC element id.
        // None when that entity wasn't a BuildingElement. Consulted
        // when resolving `host_element_index` for openings + for
        // IfcRelVoidsElement / IfcRelFillsElement emission.
        let mut entity_index_to_el_id: Vec<Option<usize>> = vec![None; model.entities.len()];
        // Void/fill tracking: for each element with a host, note
        // (host_el_id, opening_el_id, element_el_id) so the rels can
        // be emitted after the element loop. Openings themselves are
        // also BuildingElements (IfcOpeningElement) but they're never
        // contained in a storey — IFC4 treats them as "virtual"
        // elements that only live through IfcRelVoidsElement.
        let mut void_fill_triples: Vec<(usize, usize, Option<usize>, String)> = Vec::new();
        // #323: parts of an aggregate whose whole is a building element
        // reach the spatial structure through that whole, so they are left
        // out of the storey containment below.
        let is_building_element = |index: usize| {
            matches!(
                model.entities.get(index),
                Some(super::entities::IfcEntity::BuildingElement { .. })
            )
        };
        let aggregate_parts: std::collections::BTreeSet<usize> = model
            .entities
            .iter()
            .filter_map(|entity| match entity {
                super::entities::IfcEntity::Aggregate { whole, parts }
                    if is_building_element(*whole) =>
                {
                    Some(
                        parts
                            .iter()
                            .copied()
                            .filter(|part| *part != *whole && is_building_element(*part)),
                    )
                }
                _ => None,
            })
            .flatten()
            .collect();
        // #400: each building element's GlobalId, fixed from what the
        // element is rather than where it lands in the file. Revit's own
        // where the file yields it (RE-48); otherwise the element's
        // ElementId (its `Tag`) and which of the entities sharing that Tag
        // it is — a slab's further pieces (#331) or a curtain wall's parts
        // share their element's. An element with no Tag falls back to its
        // entity type and name. Everything the element owns (its opening,
        // property sets, material association) derives from this one.
        let mut element_gids: Vec<Option<String>> = vec![None; model.entities.len()];
        let mut element_counts: HashMap<(&str, &str, &str), usize> = HashMap::new();
        for (entity_idx, entity) in model.entities.iter().enumerate() {
            let super::entities::IfcEntity::BuildingElement {
                ifc_type,
                name,
                type_guid,
                ..
            } = entity
            else {
                continue;
            };
            let key = match type_guid.as_deref() {
                Some(tag) => ("element", tag, ""),
                None => ("untagged-element", ifc_type.as_str(), name.as_str()),
            };
            let occurrence = element_counts.entry(key).or_default();
            let element_gid = model
                .global_ids
                .elements
                .get(&entity_idx)
                .cloned()
                .unwrap_or_else(|| gid(&[key.0, key.1, key.2, &occurrence.to_string()]));
            *occurrence += 1;
            element_gids[entity_idx] = Some(element_gid);
        }
        let mut el_id_to_gid: HashMap<usize, &str> = HashMap::new();
        for (entity_idx, entity) in model.entities.iter().enumerate() {
            if let super::entities::IfcEntity::BuildingElement {
                ifc_type,
                name,
                type_guid,
                predefined_type,
                storey_index,
                material_index,
                property_set,
                location_feet,
                rotation_radians,
                extrusion,
                host_element_index,
                material_layer_set_index,
                material_profile_set_index,
                solid_shape,
                representation_map_index,
            } = entity
            {
                // An out-of-range index is a caller bug; treat it as
                // unbound rather than silently dropping the element or
                // pinning it to an unrelated storey.
                let idx = storey_index.filter(|index| *index < storeys.len());
                let placement_parent = match idx {
                    Some(index) => storey_placements[index],
                    None => building_placement,
                };
                // Decide whether to emit a per-element axis placement
                // (with real origin + rotation) or share the project-
                // level identity placement. Sharing keeps byte counts
                // down for elements where no location has been decoded;
                // unique placements matter once geometry attaches to
                // the element and tools read element.position.
                let element_axis = if let Some([x_ft, y_ft, z_ft]) = location_feet {
                    let x_m = x_ft * 0.3048;
                    let y_m = y_ft * 0.3048;
                    let z_m = z_ft * 0.3048;
                    let point_id = self.id();
                    self.emit_entity(
                        point_id,
                        format!("IFCCARTESIANPOINT(({x_m:.6},{y_m:.6},{z_m:.6}))"),
                    );
                    // Rotation is applied about Z only — all Revit
                    // element placements we've seen so far are upright
                    // with yaw-only rotation. Full 3D rotation needs
                    // the BasePoint / ProjectPosition transform chain
                    // (already decoded, not yet threaded here).
                    let x_axis_id = if let Some(angle) = rotation_radians {
                        let cx = angle.cos();
                        let cy = angle.sin();
                        let dir = self.id();
                        self.emit_entity(dir, format!("IFCDIRECTION(({cx:.6},{cy:.6},0.))"));
                        Some(dir)
                    } else {
                        None
                    };
                    let axis_id = self.id();
                    // If we have a yaw rotation, reference our own X-
                    // axis IfcDirection; otherwise reuse the shared
                    // +X axis_placement points at (via `x_axis`).
                    let axis_body = match x_axis_id {
                        Some(d) => format!("IFCAXIS2PLACEMENT3D(#{point_id},#{z_axis},#{d})"),
                        None => format!("IFCAXIS2PLACEMENT3D(#{point_id},#{z_axis},#{x_axis})"),
                    };
                    self.emit_entity(axis_id, axis_body);
                    axis_id
                } else {
                    axis_placement
                };
                let placement_id = self.id();
                self.emit_entity(
                    placement_id,
                    format!("IFCLOCALPLACEMENT(#{placement_parent},#{element_axis})"),
                );
                // The element translation is carried exactly once, by
                // the `IfcLocalPlacement` above. Every swept solid this
                // element emits is authored in the element-local frame
                // (profiles are centred on their own origin), so its
                // `Position` is the project-level identity placement —
                // reusing `element_axis` there made a conforming
                // consumer composing `ObjectPlacement × Position` apply
                // the translation twice (#232). Revit's own exporter
                // splits it the same way: on
                // `2024_Core_Interior_slim.ifc` the `IfcWall`
                // `SweptSolid` bodies sit at `Position = (0,0,0)` with
                // the wall's `IfcLocalPlacement` carrying the location,
                // and the `IfcSlab` / `IfcSpace` bodies do the mirror
                // image — an identity placement with the frame in
                // `Position`. Never both.
                let solid_position = axis_placement;

                // Emit the extrusion chain when geometry is present.
                // Chain: IfcProfileDef subclass → IfcExtrudedAreaSolid
                // → IfcShapeRepresentation → IfcProductDefinitionShape.
                // Profile placement uses a single fresh 2D axis per
                // element (profile-local XY frame centred on origin).
                // 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 = $)
                let shape_ref = if let Some(rm_idx) = representation_map_index {
                    representation_map_ids.get(*rm_idx).map(|rep_map_id| {
                        // Mapped item: the instance's own
                        // transformation operator (identity for now —
                        // the element's own IfcLocalPlacement carries
                        // the instance position, and the mapped item
                        // rides on top of that).
                        let tx_op_origin = self.id();
                        self.emit_entity(
                            tx_op_origin,
                            "IFCCARTESIANPOINT((0.,0.,0.))",
                        );
                        // IFC4 uses IfcCartesianTransformationOperator3D
                        // for the mapped-target transform. Identity =
                        // ($,$,ORIGIN,$,$) per spec (Axis1/Axis2 left
                        // null, scale defaults to 1.0, Axis3 null).
                        let tx_op = self.id();
                        self.emit_entity(
                            tx_op,
                            format!(
                                "IFCCARTESIANTRANSFORMATIONOPERATOR3D($,$,#{tx_op_origin},$,$)"
                            ),
                        );
                        let mapped_item = self.id();
                        self.emit_entity(
                            mapped_item,
                            format!("IFCMAPPEDITEM(#{rep_map_id},#{tx_op})"),
                        );
                        // The instance's IfcShapeRepresentation wraps
                        // the mapped item with representation-type
                        // 'MappedRepresentation' (IFC4 convention for
                        // type-instance shared geometry).
                        let rep_id = self.id();
                        self.emit_entity(
                            rep_id,
                            format!(
                                "IFCSHAPEREPRESENTATION(#{geom_ctx},'Body','MappedRepresentation',(#{mapped_item}))"
                            ),
                        );
                        let prod_shape_id = self.id();
                        self.emit_entity(
                            prod_shape_id,
                            format!("IFCPRODUCTDEFINITIONSHAPE($,$,(#{rep_id}))"),
                        );
                        prod_shape_id
                    })
                } else if let Some(shape) = solid_shape {
                    let (solid_id, rep_type) = self.emit_solid_shape(shape, solid_position, z_axis);
                    let rep_id = self.id();
                    self.emit_entity(
                        rep_id,
                        format!(
                            "IFCSHAPEREPRESENTATION(#{geom_ctx},'Body','{rep_type}',(#{solid_id}))"
                        ),
                    );
                    let prod_shape_id = self.id();
                    self.emit_entity(
                        prod_shape_id,
                        format!("IFCPRODUCTDEFINITIONSHAPE($,$,(#{rep_id}))"),
                    );
                    Some(prod_shape_id)
                } else if let Some(ex) = extrusion {
                    let depth = ex.height_feet * 0.3048;
                    // IfcProfileDef has a 2D placement; we emit a
                    // fresh 2D origin + direction + 2D axis per
                    // extrusion. Sharing a single 2D placement across
                    // all extrusions would be possible but muddies
                    // byte-by-byte diff tooling, so pay the ~3-entity
                    // cost for clarity.
                    // RE-84: an opening standing for a door or window takes
                    // the same cut to its host's depth as a filled one (#227).
                    let own_cut = (ifc_type == "IFCOPENINGELEMENT")
                        .then(|| model.opening_cuts.get(&entity_idx))
                        .flatten();
                    let [cx, cy] = own_cut.map_or([0.0, 0.0], |c| c.centre_feet);
                    let profile_origin = self.id();
                    self.emit_entity(
                        profile_origin,
                        format!("IFCCARTESIANPOINT(({:.6},{:.6}))", cx * 0.3048, cy * 0.3048),
                    );
                    let profile_x_axis = self.id();
                    self.emit_entity(profile_x_axis, "IFCDIRECTION((1.,0.))");
                    let profile_placement = self.id();
                    self.emit_entity(
                        profile_placement,
                        format!("IFCAXIS2PLACEMENT2D(#{profile_origin},#{profile_x_axis})"),
                    );
                    let profile_id = match own_cut {
                        Some(cut) => {
                            let profile_id = self.id();
                            self.emit_entity(
                                profile_id,
                                format!(
                                    "IFCRECTANGLEPROFILEDEF(.AREA.,$,#{profile_placement},{:.6},{:.6})",
                                    cut.x_dim_feet * 0.3048,
                                    cut.y_dim_feet * 0.3048,
                                ),
                            );
                            profile_id
                        }
                        None => self.emit_profile_def(ex, profile_placement),
                    };
                    // Solid-local placement: the identity axis, so the
                    // extrusion sits at the element origin and the
                    // element's own IfcLocalPlacement moves it into
                    // the world exactly once (#232).
                    let (position, depth) =
                        self.opening_solid_position(solid_position, own_cut, depth);
                    let solid_id = self.id();
                    self.emit_entity(
                        solid_id,
                        format!(
                            "IFCEXTRUDEDAREASOLID(#{profile_id},#{position},#{z_axis},{depth:.6})"
                        ),
                    );
                    // The representation groups the solid inside the
                    // project's 3D geometric context (#geom_ctx) with
                    // the IFC4-standard identifier + type for a
                    // swept-solid body.
                    let rep_id = self.id();
                    self.emit_entity(
                        rep_id,
                        format!(
                            "IFCSHAPEREPRESENTATION(#{geom_ctx},'Body','SweptSolid',(#{solid_id}))"
                        ),
                    );
                    let prod_shape_id = self.id();
                    self.emit_entity(
                        prod_shape_id,
                        format!("IFCPRODUCTDEFINITIONSHAPE($,$,(#{rep_id}))"),
                    );
                    Some(prod_shape_id)
                } else {
                    None
                };

                let el_id = self.id();
                // A room's own text property, when recovered and not blank.
                let room_text = |key: &str| {
                    property_set.as_ref().and_then(|set| {
                        set.properties
                            .iter()
                            .find(|p| p.name == key)
                            .and_then(|p| match &p.value {
                                super::entities::PropertyValue::Text(text)
                                    if !text.trim().is_empty() =>
                                {
                                    Some(quoted_or_dollar(&escape(text)))
                                }
                                _ => None,
                            })
                    })
                };
                let is_space = ifc_type.eq_ignore_ascii_case("IFCSPACE");
                // An `IfcSpace` is named by its room number and described
                // by its room name, as Revit's own exporter writes it
                // (RE-117): `Name` the number, `LongName` the name. A room
                // with no number keeps the `Room-<ElementId>` Name, and one
                // with no name has no LongName.
                let name_quoted = is_space
                    .then(|| room_text(super::export_content::ROOM_NUMBER_PROPERTY))
                    .flatten()
                    .unwrap_or_else(|| quoted_or_dollar(&escape(name)));
                let long_name_quoted = room_text(super::export_content::ROOM_NAME_PROPERTY)
                    .unwrap_or_else(|| "$".into());
                // `ObjectType` is `Family:Type` when RE-38 named the
                // element's family and type, as in Revit's own export.
                let property_text = |key: &str| {
                    property_set.as_ref().and_then(|set| {
                        set.properties.iter().find_map(|p| match &p.value {
                            super::entities::PropertyValue::Text(text) if p.name == key => {
                                Some(text.clone())
                            }
                            _ => None,
                        })
                    })
                };
                let object_type_quoted = match (
                    property_text(super::export_content::FAMILY_NAME_PROPERTY),
                    property_text(super::export_content::TYPE_NAME_PROPERTY),
                ) {
                    (Some(family), Some(type_name)) => {
                        quoted_or_dollar(&escape(&format!("{family}:{type_name}")))
                    }
                    _ => "$".into(),
                };
                let tag_quoted = type_guid
                    .as_deref()
                    .map(escape)
                    .map(|t| format!("'{t}'"))
                    .unwrap_or_else(|| "$".into());
                let rep_slot = match shape_ref {
                    Some(id) => format!("#{id}"),
                    None => "$".into(),
                };
                // Every IFC4 instance carries every attribute its
                // entity type declares — an unknown optional is `$`,
                // never an omitted slot (#214). The shared head is
                // IfcProduct's:
                //   (GlobalId, OwnerHist, Name, Desc, ObjectType,
                //    ObjectPlacement, Representation)
                // and `element_attribute_tail` supplies the rest for
                // the type, so a reader can index PredefinedType
                // instead of hitting "index out of range".
                let ifc_upper = ifc_type.to_ascii_uppercase();
                // RE-93, RE-94: a window's or door's OverallHeight and
                // OverallWidth are its opening's, which Revit's export writes
                // there.
                let property_length = |key: &str| {
                    property_set.as_ref().and_then(|set| {
                        set.properties.iter().find_map(|p| match &p.value {
                            super::entities::PropertyValue::PositiveLengthFeet(value)
                                if p.name == key =>
                            {
                                Some(*value)
                            }
                            _ => None,
                        })
                    })
                };
                let [.., width_key, height_key] = super::export_content::FILLER_OPENING_PROPERTIES;
                let overall = property_length(height_key).zip(property_length(width_key));
                let tail = element_attribute_tail(
                    &ifc_upper,
                    &tag_quoted,
                    predefined_type.as_deref(),
                    &long_name_quoted,
                    overall,
                );
                let global_id: &str = element_gids[entity_idx]
                    .as_deref()
                    .expect("every building element has a GlobalId");
                el_id_to_gid.insert(el_id, global_id);
                let line = format!(
                    "{ifc_upper}('{global_id}',#{owner_hist},{name_quoted},$,{object_type_quoted},#{placement_id},{rep_slot},{tail})",
                );
                self.emit_entity(el_id, line);
                // RE-84: an opening standing for a door or window that draws
                // no geometry voids its host and fills nothing. Like every
                // opening it lives through that relation, not in a storey.
                let hosted_opening =
                    ifc_upper == "IFCOPENINGELEMENT" && host_element_index.is_some();
                if let (true, Some(h_idx)) = (hosted_opening, host_element_index) {
                    void_fill_triples.push((*h_idx, el_id, None, global_id.to_string()));
                } else if !aggregate_parts.contains(&entity_idx) {
                    match idx {
                        Some(index) => per_storey_elements[index].push(el_id),
                        None => unplaced_elements.push(el_id),
                    }
                }
                entity_index_to_el_id[entity_idx] = Some(el_id);
                // IFC-30 / IFC-28: precedence order for material
                // association is profile_set > layer_set > single
                // material. Try each in order; `profile_or_layer_applied`
                // carries the "already emitted" flag through so the
                // single-material path below doesn't double-associate.
                let profile_set_applied = if let Some(ps_idx) = material_profile_set_index {
                    if let Some(&ps_id) = profile_set_ids.get(*ps_idx) {
                        let usage_id = self.id();
                        // IfcMaterialProfileSetUsage(ForProfileSet,
                        //   CardinalPoint=5, ReferenceExtent=$). In IFC4's
                        // IfcCardinalPointReference, 5 is the mid-depth
                        // centre: the profile is centred on the member's
                        // axis, as every profile the exporter writes is.
                        self.emit_entity(
                            usage_id,
                            format!("IFCMATERIALPROFILESETUSAGE(#{ps_id},5,$)"),
                        );
                        let rel_id = self.id();
                        self.emit_entity(
                            rel_id,
                            format!(
                                "IFCRELASSOCIATESMATERIAL('{}',#{owner_hist},$,$,(#{el_id}),#{usage_id})",
                                gid(&["material-association", global_id]),
                            ),
                        );
                        true
                    } else {
                        false
                    }
                } else {
                    false
                };
                // IFC-28: material_layer_set_index falls through when
                // profile-set didn't apply. Emits IfcMaterialLayerSetUsage
                // + IfcRelAssociatesMaterial.
                let layer_set_applied = !profile_set_applied
                    && if let Some(ls_idx) = material_layer_set_index {
                        if let Some(&ls_id) = layer_set_ids.get(*ls_idx) {
                            let usage_id = self.id();
                            // IfcMaterialLayerSetUsage(ForLayerSet, LayerSetDirection,
                            //   DirectionSense, OffsetFromReferenceLine, ReferenceExtent).
                            // The element's own usage when the model states
                            // one (RE-58); otherwise .AXIS2. (the extrusion's
                            // Y axis, a wall's thickness), .POSITIVE. from 0,
                            // the IFC4 defaults most exporters emit.
                            // ReferenceExtent stays `$` — undecoded, but its
                            // slot is still written (#214).
                            let usage = model.material_layer_usages.get(&entity_idx);
                            let direction = match usage.map(|u| u.direction) {
                                Some(super::entities::LayerSetDirection::Axis1) => ".AXIS1.",
                                Some(super::entities::LayerSetDirection::Axis3) => ".AXIS3.",
                                _ => ".AXIS2.",
                            };
                            let sense = if usage.is_none_or(|u| u.positive) {
                                ".POSITIVE."
                            } else {
                                ".NEGATIVE."
                            };
                            let offset = usage.map_or_else(
                                || "0.".to_string(),
                                |u| format!("{:.6}", u.offset_feet * 0.3048),
                            );
                            self.emit_entity(
                                usage_id,
                                format!(
                                    "IFCMATERIALLAYERSETUSAGE(#{ls_id},{direction},{sense},{offset},$)"
                                ),
                            );
                            let rel_id = self.id();
                            self.emit_entity(
                            rel_id,
                            format!(
                                "IFCRELASSOCIATESMATERIAL('{}',#{owner_hist},$,$,(#{el_id}),#{usage_id})",
                                gid(&["material-association", global_id]),
                            ),
                        );
                            true
                        } else {
                            false
                        }
                    } else {
                        false
                    };
                if !profile_set_applied && !layer_set_applied {
                    if let Some(m_idx) = material_index {
                        if *m_idx < material_ids.len() {
                            element_material_pairs.push((el_id, *m_idx));
                        }
                    } else if let Some(&set) = constituent_set_of.get(&entity_idx) {
                        element_constituent_pairs.push((el_id, set));
                    }
                }
                if let Some(pset) = property_set {
                    if !pset.properties.is_empty() {
                        element_property_sets.push((el_id, pset));
                    }
                }
                // Void / fill chain: when the element has both an
                // extrusion (describes its volume) and a host_element_
                // index (points at its parent wall/floor), emit an
                // IfcOpeningElement matching the shape + the two
                // binding relationships.
                if let (false, Some(h_idx), Some(ex)) =
                    (hosted_opening, host_element_index, extrusion)
                {
                    {
                        // Emit a second extrusion chain — same shape
                        // as the element, placed on the element's
                        // placement so the void sits where the door
                        // sits. We reuse the element's placement for
                        // simplicity; IFC4 validators accept this. The
                        // solid's own `Position` stays identity for the
                        // same reason it does on the filling element
                        // (#232) — the opening's IfcLocalPlacement
                        // below already carries `element_axis`.
                        // #227: cut to the host wall's thickness where it is
                        // known, else the element's own body.
                        let cut = model.opening_cuts.get(&entity_idx);
                        let x_dim = cut.map_or(ex.width_feet, |c| c.x_dim_feet) * 0.3048;
                        let y_dim = cut.map_or(ex.depth_feet, |c| c.y_dim_feet) * 0.3048;
                        let [cx, cy] = cut.map_or([0.0, 0.0], |c| c.centre_feet);
                        let depth_m = ex.height_feet * 0.3048;
                        let o_profile_origin = self.id();
                        self.emit_entity(
                            o_profile_origin,
                            format!("IFCCARTESIANPOINT(({:.6},{:.6}))", cx * 0.3048, cy * 0.3048),
                        );
                        let o_profile_x = self.id();
                        self.emit_entity(o_profile_x, "IFCDIRECTION((1.,0.))");
                        let o_profile_place = self.id();
                        self.emit_entity(
                            o_profile_place,
                            format!("IFCAXIS2PLACEMENT2D(#{o_profile_origin},#{o_profile_x})"),
                        );
                        let o_profile = self.id();
                        self.emit_entity(
                            o_profile,
                            format!(
                                "IFCRECTANGLEPROFILEDEF(.AREA.,$,#{o_profile_place},{x_dim:.6},{y_dim:.6})"
                            ),
                        );
                        let (position, depth_m) =
                            self.opening_solid_position(solid_position, cut, depth_m);
                        let o_solid = self.id();
                        self.emit_entity(
                            o_solid,
                            format!(
                                "IFCEXTRUDEDAREASOLID(#{o_profile},#{position},#{z_axis},{depth_m:.6})"
                            ),
                        );
                        let o_rep = self.id();
                        self.emit_entity(
                            o_rep,
                            format!(
                                "IFCSHAPEREPRESENTATION(#{geom_ctx},'Body','SweptSolid',(#{o_solid}))"
                            ),
                        );
                        let o_prod_shape = self.id();
                        self.emit_entity(
                            o_prod_shape,
                            format!("IFCPRODUCTDEFINITIONSHAPE($,$,(#{o_rep}))"),
                        );
                        // IfcOpeningElement uses its own placement
                        // (relative to the host wall's) — we reuse the
                        // door/window placement.
                        let o_placement = self.id();
                        self.emit_entity(
                            o_placement,
                            format!("IFCLOCALPLACEMENT(#{placement_parent},#{element_axis})"),
                        );
                        let opening_id = self.id();
                        // #400: an opening exists only because the element
                        // filling it does, so its identity is that element's.
                        let opening_gid = gid(&["opening", global_id]);
                        // IfcOpeningElement: (GlobalId, OwnerHist, Name,
                        //   Desc, ObjectType, Placement, Rep, Tag,
                        //   PredefinedType). IFC4 adds PredefinedType.
                        //
                        // `Tag` repeats the filling element's own tag.
                        // That is what Revit's exporter does — on
                        // `2024_Core_Interior_slim.ifc` all 138
                        // door/window openings carry the Tag of the
                        // element that fills them — and it invents
                        // nothing: the opening exists only because
                        // that element does.
                        self.emit_entity(
                            opening_id,
                            format!(
                                "IFCOPENINGELEMENT('{opening_gid}',#{owner_hist},'Opening for {name_esc}',$,$,#{o_placement},#{o_prod_shape},{tag_quoted},.OPENING.)",
                                name_esc = escape(name),
                            ),
                        );
                        void_fill_triples.push((*h_idx, opening_id, Some(el_id), opening_gid));
                    }
                }
            }
        }

        // IfcRelVoidsElement + IfcRelFillsElement — for each
        // (host, opening, element) triple we collected during
        // element emission, emit:
        //   - IFCRELVOIDSELEMENT(host_wall, opening)
        //   - IFCRELFILLSELEMENT(opening, door/window)
        // Together these tell IFC4 viewers "subtract this opening's
        // volume from the host wall, and fill the hole with this
        // door/window."
        //
        // The host is resolved here, after the element loop, rather
        // than inside it: `entity_index_to_el_id` is only complete
        // once every BuildingElement has been emitted, so resolving
        // inline silently dropped the chain whenever a host happened
        // to sit after its opening in `model.entities`.
        for (host_entity_idx, opening_id, el_id, opening_gid) in &void_fill_triples {
            let Some(host_el_id) = entity_index_to_el_id
                .get(*host_entity_idx)
                .and_then(|slot| *slot)
            else {
                continue;
            };
            let voids_rel = self.id();
            self.emit_entity(
                voids_rel,
                format!(
                    "IFCRELVOIDSELEMENT('{}',#{owner_hist},$,$,#{host_el_id},#{opening_id})",
                    gid(&["voids", opening_gid]),
                ),
            );
            let Some(el_id) = el_id else {
                continue;
            };
            let fills_rel = self.id();
            self.emit_entity(
                fills_rel,
                format!(
                    "IFCRELFILLSELEMENT('{}',#{owner_hist},$,$,#{opening_id},#{el_id})",
                    gid(&["fills", opening_gid]),
                ),
            );
        }

        // #323: one IfcRelAggregates per aggregate, whole to parts. Resolved
        // after the element loop for the same reason as the void chain.
        for entity in &model.entities {
            let super::entities::IfcEntity::Aggregate { whole, parts } = entity else {
                continue;
            };
            if !is_building_element(*whole) {
                continue;
            }
            let Some(whole_el_id) = entity_index_to_el_id.get(*whole).and_then(|slot| *slot) else {
                continue;
            };
            let part_refs: Vec<String> = parts
                .iter()
                .filter(|part| aggregate_parts.contains(part))
                .filter_map(|part| entity_index_to_el_id.get(*part).and_then(|slot| *slot))
                .map(|id| format!("#{id}"))
                .collect();
            if part_refs.is_empty() {
                continue;
            }
            let rel_id = self.id();
            self.emit_entity(
                rel_id,
                format!(
                    "IFCRELAGGREGATES('{}',#{owner_hist},$,$,#{whole_el_id},({}))",
                    gid(&["aggregates", el_id_to_gid[&whole_el_id]]),
                    part_refs.join(","),
                ),
            );
        }

        // RE-47: further sets of an element, such as Pset_StairCommon.
        for entity in &model.entities {
            let super::entities::IfcEntity::ElementPropertySet { element, set } = entity else {
                continue;
            };
            if !is_building_element(*element) || set.properties.is_empty() {
                continue;
            }
            if let Some(el_id) = entity_index_to_el_id.get(*element).and_then(|slot| *slot) {
                element_property_sets.push((el_id, set));
            }
        }

        // IfcPropertySet emission — one set per element that ships
        // properties. Each property becomes an
        // IfcPropertySingleValue, the set wraps them, then an
        // IfcRelDefinesByProperties links the set to its element.
        let mut pset_counts: HashMap<(usize, &str), usize> = HashMap::new();
        for (el_id, pset) in &element_property_sets {
            let occurrence = pset_counts.entry((*el_id, pset.name.as_str())).or_default();
            let set_key = [
                el_id_to_gid[el_id],
                pset.name.as_str(),
                &occurrence.to_string(),
            ]
            .join("\u{1f}");
            *occurrence += 1;
            let mut prop_ids: Vec<usize> = Vec::with_capacity(pset.properties.len());
            for prop in &pset.properties {
                let p_id = self.id();
                let name_esc = escape(&prop.name);
                let value_step = prop.value.to_step();
                self.emit_entity(
                    p_id,
                    format!("IFCPROPERTYSINGLEVALUE('{name_esc}',$,{value_step},$)"),
                );
                prop_ids.push(p_id);
            }
            let refs = prop_ids
                .iter()
                .map(|id| format!("#{id}"))
                .collect::<Vec<_>>()
                .join(",");
            let set_id = self.id();
            let set_name = escape(&pset.name);
            self.emit_entity(
                set_id,
                format!(
                    "IFCPROPERTYSET('{}',#{owner_hist},'{set_name}',$,({refs}))",
                    gid(&["property-set", &set_key])
                ),
            );
            let rel_id = self.id();
            self.emit_entity(
                rel_id,
                format!(
                    "IFCRELDEFINESBYPROPERTIES('{}',#{owner_hist},$,$,(#{el_id}),#{set_id})",
                    gid(&["defines-by-properties", &set_key])
                ),
            );
        }

        // Bucket element_id lists by material_index so each material
        // gets one IfcRelAssociatesMaterial (rather than N, where N
        // is the number of elements using it).
        let mut by_material: Vec<Vec<usize>> = vec![Vec::new(); material_ids.len()];
        // RE-82: one association per constituent set, keyed by its
        // materials' names so its GlobalId does not depend on file order.
        let mut by_constituent_set: Vec<Vec<usize>> =
            vec![Vec::new(); model.material_constituent_sets.len()];
        for (el_id, set) in &element_constituent_pairs {
            by_constituent_set[*set].push(*el_id);
        }
        for (set, elements) in by_constituent_set.iter().enumerate() {
            let Some(Some(set_id)) = constituent_set_ids.get(set) else {
                continue;
            };
            if elements.is_empty() {
                continue;
            }
            let names: Vec<&str> = model.material_constituent_sets[set]
                .material_indices
                .iter()
                .filter_map(|&index| model.materials.get(index).map(|m| m.name.as_str()))
                .collect();
            let mut key = vec!["material-constituents"];
            key.extend(names);
            let rel_id = self.id();
            self.emit_entity(
                rel_id,
                format!(
                    "IFCRELASSOCIATESMATERIAL('{}',#{owner_hist},$,$,({}),#{set_id})",
                    gid(&key),
                    elements
                        .iter()
                        .map(|id| format!("#{id}"))
                        .collect::<Vec<_>>()
                        .join(","),
                ),
            );
        }

        for (el_id, m_idx) in &element_material_pairs {
            by_material[*m_idx].push(*el_id);
        }
        let mut material_name_counts: HashMap<&str, usize> = HashMap::new();
        for (m_idx, elements) in by_material.iter().enumerate() {
            let material_name = model.materials[m_idx].name.as_str();
            let occurrence = material_name_counts.entry(material_name).or_default();
            let material_key = occurrence.to_string();
            *occurrence += 1;
            if elements.is_empty() {
                continue;
            }
            let rel_id = self.id();
            let refs_list = elements
                .iter()
                .map(|id| format!("#{id}"))
                .collect::<Vec<_>>()
                .join(",");
            self.emit_entity(
                rel_id,
                format!(
                    "IFCRELASSOCIATESMATERIAL('{}',#{owner_hist},$,$,({refs_list}),#{})",
                    gid(&["material", material_name, &material_key]),
                    material_ids[m_idx],
                ),
            );
        }

        // RE-110: every element named `Family:Type` whose type is read is
        // typed by one IFC type object per type, as in Revit's own export:
        // named `Family:Type`, its `Tag` the type's ElementId and its
        // GlobalId Revit's.
        struct TypeGroup {
            type_id: u32,
            entity: String,
            name: String,
            tail: String,
            elements: Vec<usize>,
        }
        let mut type_groups: Vec<TypeGroup> = Vec::new();
        for (entity_idx, entity) in model.entities.iter().enumerate() {
            let super::entities::IfcEntity::BuildingElement {
                ifc_type,
                type_guid,
                predefined_type,
                property_set,
                ..
            } = entity
            else {
                continue;
            };
            let (Some(el_id), Some(type_id)) = (
                entity_index_to_el_id[entity_idx],
                type_guid
                    .as_deref()
                    .and_then(|tag| tag.parse::<u32>().ok())
                    .and_then(|id| model.element_type_ids.get(&id)),
            ) else {
                continue;
            };
            let property_text = |key: &str| {
                property_set.as_ref().and_then(|set| {
                    set.properties.iter().find_map(|p| match &p.value {
                        super::entities::PropertyValue::Text(text) if p.name == key => {
                            Some(text.clone())
                        }
                        _ => None,
                    })
                })
            };
            let (Some(family), Some(type_name)) = (
                property_text(super::export_content::FAMILY_NAME_PROPERTY),
                property_text(super::export_content::TYPE_NAME_PROPERTY),
            ) else {
                continue;
            };
            let Some((entity_name, tail)) =
                type_entity_for(&ifc_type.to_ascii_uppercase(), predefined_type.as_deref())
            else {
                continue;
            };
            match type_groups
                .iter_mut()
                .find(|group| group.type_id == *type_id && group.entity == entity_name)
            {
                Some(group) => group.elements.push(el_id),
                None => type_groups.push(TypeGroup {
                    type_id: *type_id,
                    entity: entity_name,
                    name: format!("{family}:{type_name}"),
                    tail,
                    elements: vec![el_id],
                }),
            }
        }
        let mut typed_ids: std::collections::BTreeSet<u32> = Default::default();
        for TypeGroup {
            type_id,
            entity: entity_name,
            name,
            tail,
            elements,
        } in &type_groups
        {
            let tag = type_id.to_string();
            // A type split across two entities keeps Revit's GlobalId once.
            let type_gid = match model.global_ids.types.get(type_id) {
                Some(global_id) if typed_ids.insert(*type_id) => global_id.clone(),
                _ => gid(&["type", entity_name, &tag]),
            };
            let type_el_id = self.id();
            self.emit_entity(
                type_el_id,
                format!(
                    "{entity_name}('{type_gid}',#{owner_hist},{},$,$,$,$,'{tag}',$,{tail})",
                    quoted_or_dollar(&escape(name)),
                ),
            );
            let rel_id = self.id();
            self.emit_entity(
                rel_id,
                format!(
                    "IFCRELDEFINESBYTYPE('{}',#{owner_hist},$,$,({}),#{type_el_id})",
                    gid(&["defines-by-type", &type_gid]),
                    elements
                        .iter()
                        .map(|id| format!("#{id}"))
                        .collect::<Vec<_>>()
                        .join(","),
                ),
            );
        }

        // Suppress unused-variable warning from the legacy single-
        // storey fallback — the loop above now consults
        // storey_placements[idx] instead of this scalar binding.
        let _ = storey_placement;

        for (idx, element_ids) in per_storey_elements
            .iter()
            .enumerate()
            .map(|(idx, ids)| (Some(idx), ids))
            .chain(std::iter::once((None, &unplaced_elements)))
        {
            if element_ids.is_empty() {
                continue;
            }
            let (target_storey, container_gid) = match idx {
                Some(index) => (storey_ids[index], gid(&["contains", &storey_gids[index]])),
                None => (building_id, gid(&["contains", "building"])),
            };
            let rel_id = self.id();
            let refs_list = element_ids
                .iter()
                .map(|id| format!("#{id}"))
                .collect::<Vec<_>>()
                .join(",");
            self.emit_entity(
                rel_id,
                format!(
                    "IFCRELCONTAINEDINSPATIALSTRUCTURE('{container_gid}',#{owner_hist},$,$,({refs_list}),#{target_storey})",
                ),
            );
        }
        // storey_id from the pre-refactor era is still valid as the
        // default storey; kept live above so existing tests that
        // count placements / storeys on the empty-model path keep
        // passing.
        let _ = storey_id;

        self.emit_line("ENDSEC;");
    }

    fn finish(self) -> String {
        let mut out = self.out;
        out.push_str("END-ISO-10303-21;\n");
        out
    }
}

/// STEP-style string escape per ISO-10303-21:
///
/// - Literal apostrophe → `''` (doubled).
/// - Literal backslash → `\\`.
/// - ASCII printable (0x20–0x7E) → pass through.
/// - ASCII control (0x00–0x1F, 0x7F) → `\X\<HH>` (2-hex-digit byte).
/// - Non-ASCII code points:
///   - BMP (≤ U+FFFF): `\X2\<HHHH>\X0\`
///   - Supplementary plane (> U+FFFF): `\X4\<HHHHHHHH>\X0\`
///
/// Previous implementation replaced non-ASCII with underscore, which
/// silently mangled accented project names, CJK text, and any Unicode
/// symbols in Revit metadata. Real RVT files routinely have
/// non-ASCII in title, path, and taxonomy strings; this escape
/// preserves them round-trip per the STEP spec.
///
/// Two consecutive non-ASCII chars produce separate `\X2\<HHHH>\X0\`
/// sequences rather than a concatenated run. The spec allows either
/// form; separate sequences keep the encoder stateless and the
/// output diff-friendly.
pub(crate) fn escape(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for c in input.chars() {
        match c {
            '\'' => out.push_str("''"),
            '\\' => out.push_str("\\\\"),
            c if c.is_ascii() && !c.is_control() => out.push(c),
            c if c.is_ascii() => {
                // ASCII control byte.
                out.push_str(&format!("\\X\\{:02X}", c as u32));
            }
            c if (c as u32) <= 0xFFFF => {
                // BMP non-ASCII.
                out.push_str(&format!("\\X2\\{:04X}\\X0\\", c as u32));
            }
            c => {
                // Supplementary plane (emoji, rare scripts).
                out.push_str(&format!("\\X4\\{:08X}\\X0\\", c as u32));
            }
        }
    }
    out
}

fn quoted_or_dollar(s: &str) -> String {
    if s.is_empty() {
        "$".into()
    } else {
        format!("'{s}'")
    }
}

fn iso_timestamp_from(secs: i64) -> String {
    // Format a Unix epoch as ISO 8601. Avoids chrono to stay
    // dep-lean. Pure function — deterministic given its input.
    let (y, m, d, hh, mm, ss) = epoch_to_ymdhms(secs);
    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}")
}

/// Wall-clock Unix seconds for the header stamps. `std::time::SystemTime`
/// panics on `wasm32-unknown-unknown` ("time not implemented on this
/// platform"), which made the browser viewer's Export IFC fail on every
/// click; the wasm build reads the JavaScript host clock instead.
fn unix_seconds() -> i64 {
    #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
    {
        (crate::wasm::host_now_millis() / 1000.0) as i64
    }
    #[cfg(not(all(target_arch = "wasm32", feature = "wasm")))]
    {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0)
    }
}

/// Gregorian breakdown without chrono. Good from 1970 through 2400.
fn epoch_to_ymdhms(secs: i64) -> (i32, u32, u32, u32, u32, u32) {
    let days = secs.div_euclid(86_400);
    let remainder = secs.rem_euclid(86_400) as u32;
    let hh = remainder / 3600;
    let mm = (remainder % 3600) / 60;
    let ss = remainder % 60;

    // Days since 1970-01-01 → Gregorian date. Algorithm from Howard
    // Hinnant's date.h (public domain).
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = (yoe as i64) + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
    let y = (y + if m <= 2 { 1 } else { 0 }) as i32;
    (y, m, d, hh, mm, ss)
}

/// The GlobalId of an entity Revit gives none (#400): SHA-256 over a fixed
/// namespace, the document's identity and `key` (the entity's role and the
/// identities it derives from), as an RFC 9562 version-8 UUID in IFC's
/// 22-character form. It depends on nothing about the entity's position in
/// the file, so it survives changes elsewhere in the model, and the
/// namespace keeps it apart from GlobalIds other tools derive.
fn stable_guid(document: &str, key: &[&str]) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(b"rvt-rs ifc GlobalId v1\0");
    hasher.update(document.as_bytes());
    for part in key {
        hasher.update([0x1f]);
        hasher.update(part.as_bytes());
    }
    let digest = hasher.finalize();
    let mut value = [0u8; 16];
    value.copy_from_slice(&digest[..16]);
    value[6] = (value[6] & 0x0f) | 0x80;
    value[8] = (value[8] & 0x3f) | 0x80;
    crate::revit_global_ids::compress_ifc_guid(value)
}

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

    #[test]
    fn step_emits_iso_envelope() {
        let model = IfcModel {
            project_name: Some("Demo".into()),
            description: None,
            entities: Vec::new(),
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        assert!(s.starts_with("ISO-10303-21;\n"));
        assert!(s.contains("FILE_SCHEMA(('IFC4'));"));
        assert!(s.contains("DATA;"));
        assert!(s.contains("IFCPROJECT"));
        assert!(s.ends_with("END-ISO-10303-21;\n"));
    }

    #[test]
    fn step_output_deterministic_with_fixed_timestamp() {
        // Byte-identical output across calls when timestamp is pinned.
        let model = IfcModel {
            project_name: Some("Stable".into()),
            description: Some("Deterministic test".into()),
            entities: Vec::new(),
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let opts = StepOptions {
            timestamp: Some(1_700_000_000), // 2023-11-14T22:13:20
        };
        let a = write_step_with_options(&model, &opts);
        let b = write_step_with_options(&model, &opts);
        assert_eq!(
            a, b,
            "identical (model, opts) must produce identical STEP output"
        );
        // And the timestamp actually shows up.
        assert!(a.contains("2023-11-14T22:13:20"), "ISO timestamp missing");
        assert!(
            a.contains(",1700000000)"),
            "IfcOwnerHistory seconds missing"
        );
    }

    #[test]
    fn escape_handles_unicode_bmp_codepoints() {
        // BMP non-ASCII (é, ü, 中, 文, ç) should be \X2\HHHH\X0\.
        let s = escape("Café 中文");
        assert!(s.starts_with("Caf"), "ASCII prefix preserved: {s:?}");
        assert!(s.contains("\\X2\\00E9\\X0\\"), "é as \\X2\\00E9: {s:?}");
        assert!(s.contains("\\X2\\4E2D\\X0\\"), "中 as \\X2\\4E2D: {s:?}");
        assert!(s.contains("\\X2\\6587\\X0\\"), "文 as \\X2\\6587: {s:?}");
    }

    #[test]
    fn escape_handles_supplementary_plane() {
        // 🏢 (U+1F3E2, office building emoji — apt for BIM data)
        // must use \X4\0001F3E2\X0\ form.
        let s = escape("🏢");
        assert!(
            s.contains("\\X4\\0001F3E2\\X0\\"),
            "emoji as \\X4\\0001F3E2: {s:?}"
        );
    }

    #[test]
    fn escape_preserves_ascii_printable() {
        let s = escape("Hello, World! 0123 @#$%^&*()");
        assert_eq!(s, "Hello, World! 0123 @#$%^&*()");
    }

    #[test]
    fn escape_backslash_doubled() {
        // Windows paths in original_path fields have backslashes.
        let s = escape("C:\\Users\\x");
        assert_eq!(s, "C:\\\\Users\\\\x");
    }

    #[test]
    fn step_escapes_apostrophes_in_project_name() {
        let model = IfcModel {
            project_name: Some("Griffin's Building".into()),
            description: None,
            entities: Vec::new(),
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        assert!(s.contains("Griffin''s Building"));
    }

    #[test]
    fn step_includes_required_framework_entities() {
        let model = IfcModel::default();
        let s = write_step(&model);
        for required in [
            "IFCPERSON",
            "IFCORGANIZATION",
            "IFCAPPLICATION",
            "IFCOWNERHISTORY",
            "IFCSIUNIT",
            "IFCUNITASSIGNMENT",
            "IFCGEOMETRICREPRESENTATIONCONTEXT",
            "IFCPROJECT",
        ] {
            assert!(s.contains(required), "missing required entity: {required}");
        }
    }

    #[test]
    fn epoch_to_ymdhms_known_dates() {
        // 1970-01-01 00:00:00 UTC
        assert_eq!(epoch_to_ymdhms(0), (1970, 1, 1, 0, 0, 0));
        // 2024-04-01 00:00:00 UTC = 1711929600
        assert_eq!(epoch_to_ymdhms(1_711_929_600), (2024, 4, 1, 0, 0, 0));
    }

    #[test]
    fn step_emits_spatial_hierarchy() {
        // IFC4 viewers expect a Project → Site → Building → Storey
        // spine before any building elements. Every IfcSpatialStructureElement
        // in the chain needs its own IfcLocalPlacement and must be
        // bound to its parent via IfcRelAggregates.
        let model = IfcModel::default();
        let s = write_step(&model);
        for required in [
            "IFCSITE(",
            "IFCBUILDING(",
            "IFCBUILDINGSTOREY(",
            "IFCLOCALPLACEMENT(",
            "IFCRELAGGREGATES(",
        ] {
            assert!(
                s.contains(required),
                "spatial hierarchy missing required entity: {required}\n\nOutput:\n{s}"
            );
        }
    }

    #[test]
    fn step_hierarchy_count_is_stable() {
        // The hierarchy adds exactly:
        //   3 IfcLocalPlacement (one per spatial container)
        //   1 IfcSite
        //   1 IfcBuilding
        //   1 IfcBuildingStorey
        //   3 IfcRelAggregates (project-site, site-building, building-storey)
        // Pinning the counts prevents silent regressions if the writer
        // grows extra placeholder entities.
        let model = IfcModel::default();
        let s = write_step(&model);
        assert_eq!(s.matches("IFCSITE(").count(), 1);
        assert_eq!(s.matches("IFCBUILDING(").count(), 1);
        assert_eq!(s.matches("IFCBUILDINGSTOREY(").count(), 1);
        assert_eq!(s.matches("IFCLOCALPLACEMENT(").count(), 3);
        assert_eq!(s.matches("IFCRELAGGREGATES(").count(), 3);
    }

    #[test]
    fn step_emits_omniclass_classification_when_present() {
        use super::super::entities::{Classification, ClassificationItem, ClassificationSource};
        let model = IfcModel {
            project_name: Some("ClassifiedDemo".into()),
            description: None,
            entities: Vec::new(),
            classifications: vec![Classification {
                source: ClassificationSource::OmniClass,
                edition: Some("2012".into()),
                items: vec![
                    ClassificationItem {
                        code: "23.45.12.34".into(),
                        name: Some("Example Product".into()),
                    },
                    ClassificationItem {
                        code: "23.45.12.35".into(),
                        name: None,
                    },
                ],
            }],
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        assert!(
            s.contains("IFCCLASSIFICATION("),
            "classification entity missing"
        );
        assert!(s.contains("'OmniClass'"), "OmniClass source missing");
        assert!(s.contains("'2012'"), "edition 2012 missing");
        assert!(
            s.matches("IFCCLASSIFICATIONREFERENCE(").count() == 2,
            "expected two classification references (one per item)"
        );
        assert!(s.contains("'23.45.12.34'"), "first code missing");
        assert!(s.contains("'23.45.12.35'"), "second code missing");
        assert!(s.contains("'Example Product'"), "item name missing");
        assert!(
            s.matches("IFCRELASSOCIATESCLASSIFICATION(").count() == 2,
            "expected one association rel per reference"
        );
    }

    #[test]
    fn step_omits_classification_entities_when_empty() {
        // Model with no classifications must NOT emit classification
        // entities. Guards against a regression where the writer
        // emits empty IfcClassification / IfcRelAssociates entities.
        let model = IfcModel::default();
        let s = write_step(&model);
        assert!(
            !s.contains("IFCCLASSIFICATION("),
            "should not emit IfcClassification when model.classifications is empty"
        );
        assert!(
            !s.contains("IFCCLASSIFICATIONREFERENCE("),
            "should not emit IfcClassificationReference when model has no classifications"
        );
        assert!(
            !s.contains("IFCRELASSOCIATESCLASSIFICATION("),
            "should not emit IfcRelAssociatesClassification when model has no classifications"
        );
    }

    #[test]
    fn step_guids_are_unique_across_entities() {
        // Every rooted entity's GlobalId is the first attribute and is
        // followed by its OwnerHistory reference; none may repeat.
        let model = IfcModel::default();
        let s = write_step(&model);
        let guids: Vec<&str> = s
            .lines()
            .filter_map(|line| line.split_once("('")?.1.split_once("',#"))
            .map(|(guid, _)| guid)
            .filter(|guid| guid.len() == 22)
            .collect();
        let mut seen = std::collections::HashSet::new();
        for g in &guids {
            assert!(seen.insert(*g), "duplicate IFC GUID in output: {g}");
        }
        assert!(
            guids.len() >= 7,
            "expected ≥7 GUIDs (project+site+building+storey+3 rel-aggregates), got {}",
            guids.len()
        );
    }

    /// #323: a stair aggregates its parts; the parts leave the storey
    /// containment and reach it through the stair.
    #[test]
    fn an_aggregate_relates_its_parts_to_the_whole() {
        use super::super::entities::IfcEntity;
        let element = |ifc_type: &str, tag: &str| IfcEntity::BuildingElement {
            ifc_type: ifc_type.into(),
            name: format!("{ifc_type}-{tag}"),
            type_guid: Some(tag.into()),
            predefined_type: None,
            storey_index: None,
            material_index: None,
            property_set: None,
            location_feet: None,
            rotation_radians: None,
            extrusion: None,
            host_element_index: None,
            material_layer_set_index: None,
            material_profile_set_index: None,
            solid_shape: None,
            representation_map_index: None,
        };
        let entity_id = |step: &str, tag: &str| -> String {
            step.lines()
                .find(|line| line.contains(&format!(",'{tag}',")))
                .and_then(|line| line.split('=').next())
                .expect("element line")
                .to_string()
        };
        let model = IfcModel {
            entities: vec![
                element("IfcStair", "620883"),
                element("IfcStairFlight", "621141"),
                element("IfcMember", "621150"),
                element("IfcWall", "700000"),
                IfcEntity::Aggregate {
                    whole: 0,
                    parts: vec![1, 2],
                },
                // A whole that is not a building element aggregates nothing.
                IfcEntity::Aggregate {
                    whole: 99,
                    parts: vec![3],
                },
            ],
            ..Default::default()
        };
        let step = write_step(&model);
        let stair = entity_id(&step, "620883");
        let flight = entity_id(&step, "621141");
        let member = entity_id(&step, "621150");
        let wall = entity_id(&step, "700000");
        let aggregates: Vec<&str> = step
            .lines()
            .filter(|line| {
                line.contains("IFCRELAGGREGATES(") && line.contains(&format!(",{stair},"))
            })
            .collect();
        assert_eq!(aggregates.len(), 1);
        assert!(aggregates[0].ends_with(&format!(",{stair},({flight},{member}));")));
        let contained: String = step
            .lines()
            .filter(|line| line.contains("IFCRELCONTAINEDINSPATIALSTRUCTURE("))
            .collect();
        for part in [&flight, &member] {
            assert!(
                !contained.contains(&format!("{part},"))
                    && !contained.contains(&format!("{part})"))
            );
        }
        for standalone in [&stair, &wall] {
            assert!(
                contained.contains(&format!("{standalone},"))
                    || contained.contains(&format!("{standalone})")),
                "{standalone} contained"
            );
        }
    }

    #[test]
    fn step_emits_building_elements() {
        use super::super::entities::IfcEntity;
        let model = IfcModel {
            project_name: Some("ElementsDemo".into()),
            description: None,
            entities: vec![
                IfcEntity::BuildingElement {
                    ifc_type: "IfcWall".into(),
                    name: "North Wall".into(),
                    type_guid: None,
                    predefined_type: None,
                    storey_index: None,
                    material_index: None,
                    property_set: None,
                    location_feet: None,
                    rotation_radians: None,
                    extrusion: None,
                    host_element_index: None,
                    material_layer_set_index: None,
                    material_profile_set_index: None,
                    solid_shape: None,
                    representation_map_index: None,
                },
                IfcEntity::BuildingElement {
                    ifc_type: "IfcSlab".into(),
                    name: "Level 1 Floor".into(),
                    type_guid: Some("101".into()),
                    predefined_type: None,
                    storey_index: None,
                    material_index: None,
                    property_set: None,
                    location_feet: None,
                    rotation_radians: None,
                    extrusion: None,
                    host_element_index: None,
                    material_layer_set_index: None,
                    material_profile_set_index: None,
                    solid_shape: None,
                    representation_map_index: None,
                },
                IfcEntity::BuildingElement {
                    ifc_type: "IfcDoor".into(),
                    name: "Front Door".into(),
                    type_guid: None,
                    predefined_type: None,
                    storey_index: None,
                    material_index: None,
                    property_set: None,
                    location_feet: None,
                    rotation_radians: None,
                    extrusion: None,
                    host_element_index: None,
                    material_layer_set_index: None,
                    material_profile_set_index: None,
                    solid_shape: None,
                    representation_map_index: None,
                },
            ],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        // Each element's IFC4 entity constructor appears in the output.
        assert!(s.contains("IFCWALL("), "missing IFCWALL constructor:\n{s}");
        assert!(s.contains("IFCSLAB("), "missing IFCSLAB constructor:\n{s}");
        assert!(s.contains("IFCDOOR("), "missing IFCDOOR constructor:\n{s}");
        assert!(
            s.contains("North Wall"),
            "escaped element name not emitted:\n{s}"
        );
        // IfcRelContainedInSpatialStructure ties them to the storey.
        assert_eq!(
            s.matches("IFCRELCONTAINEDINSPATIALSTRUCTURE(").count(),
            1,
            "expected exactly one spatial-containment rel:\n{s}"
        );
        // Each element gets its own placement on top of the 3 spatial
        // placements (site, building, storey) → 6 total.
        assert_eq!(s.matches("IFCLOCALPLACEMENT(").count(), 6);
    }

    #[test]
    fn step_empty_entities_emits_no_containment_rel() {
        // When no BuildingElements are provided, the writer must NOT
        // emit an IFCRELCONTAINEDINSPATIALSTRUCTURE — an empty
        // references list would fail IFC4 schema validation.
        let model = IfcModel::default();
        let s = write_step(&model);
        assert_eq!(s.matches("IFCRELCONTAINEDINSPATIALSTRUCTURE(").count(), 0);
    }

    /// IFC4 attribute counts for every STEP entity name this writer
    /// can emit as an `IfcEntity::BuildingElement`.
    ///
    /// Each row is the entity's `attribute_count()` in the IFC4
    /// EXPRESS schema, read with
    /// `ifcopenshell.ifcopenshell_wrapper.schema_by_name("IFC4")
    ///  .declaration_by_name(<name>).attribute_count()` (IfcOpenShell
    /// 0.8.5). `tools/ci/ifc_schema_arity.py` re-derives the same
    /// numbers from the schema on every emitted `.ifc` in CI, so this
    /// table cannot silently drift away from the spec — it exists so
    /// the Rust suite fails without a Python toolchain too (#214).
    const IFC4_ELEMENT_ARITY: &[(&str, usize)] = &[
        ("IFCAIRTERMINAL", 9),
        ("IFCALARM", 9),
        ("IFCBEAM", 9),
        ("IFCBUILDINGELEMENTPROXY", 9),
        ("IFCCOLUMN", 9),
        ("IFCCOVERING", 9),
        ("IFCCURTAINWALL", 9),
        ("IFCDOOR", 13),
        ("IFCDUCTFITTING", 9),
        ("IFCDUCTSEGMENT", 9),
        ("IFCELECTRICAPPLIANCE", 9),
        ("IFCFLOWCONTROLLER", 8),
        ("IFCFOOTING", 9),
        ("IFCFURNISHINGELEMENT", 8),
        ("IFCFURNITURE", 9),
        ("IFCLIGHTFIXTURE", 9),
        ("IFCMEMBER", 9),
        ("IFCOPENINGELEMENT", 9),
        ("IFCPIPEFITTING", 9),
        ("IFCPIPESEGMENT", 9),
        ("IFCPLATE", 9),
        ("IFCRAILING", 9),
        ("IFCRAMP", 9),
        ("IFCRAMPFLIGHT", 9),
        ("IFCREINFORCINGBAR", 14),
        ("IFCROOF", 9),
        ("IFCSANITARYTERMINAL", 9),
        ("IFCSHADINGDEVICE", 9),
        ("IFCSLAB", 9),
        ("IFCSPACE", 11),
        ("IFCSTAIR", 9),
        ("IFCSTAIRFLIGHT", 13),
        ("IFCTRANSPORTELEMENT", 9),
        ("IFCWALL", 9),
        ("IFCWALLSTANDARDCASE", 9),
        ("IFCWINDOW", 13),
    ];

    /// Count top-level attributes in a STEP argument list, honouring
    /// quoted strings and nested aggregates.
    fn step_argument_count(args: &str) -> usize {
        if args.trim().is_empty() {
            return 0;
        }
        let mut count = 1;
        let mut depth = 0usize;
        let mut in_string = false;
        let mut chars = args.chars().peekable();
        while let Some(c) = chars.next() {
            if in_string {
                if c == '\'' {
                    if chars.peek() == Some(&'\'') {
                        chars.next();
                    } else {
                        in_string = false;
                    }
                }
                continue;
            }
            match c {
                '\'' => in_string = true,
                '(' => depth += 1,
                ')' => depth = depth.saturating_sub(1),
                ',' if depth == 0 => count += 1,
                _ => {}
            }
        }
        count
    }

    fn single_element_step(ifc_type: &str, predefined_type: Option<&str>) -> String {
        use super::super::entities::IfcEntity;
        let model = IfcModel {
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: ifc_type.into(),
                name: "Element".into(),
                type_guid: Some("tag-1".into()),
                predefined_type: predefined_type.map(str::to_string),
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: None,
                rotation_radians: None,
                extrusion: None,
                host_element_index: None,
                material_layer_set_index: None,
                material_profile_set_index: None,
                solid_shape: None,
                representation_map_index: None,
            }],
            ..IfcModel::default()
        };
        write_step(&model)
    }

    /// RE-47: a further property set is its own `IfcPropertySet`, related
    /// to its element, with the measure types its properties declare.
    #[test]
    fn a_further_property_set_is_related_to_its_element() {
        use super::super::entities::{IfcEntity, Property, PropertySet, PropertyValue};
        let stair = IfcEntity::BuildingElement {
            ifc_type: "IFCSTAIR".into(),
            name: "Stair".into(),
            type_guid: Some("620883".into()),
            predefined_type: None,
            storey_index: None,
            material_index: None,
            property_set: None,
            location_feet: None,
            rotation_radians: None,
            extrusion: None,
            host_element_index: None,
            material_layer_set_index: None,
            material_profile_set_index: None,
            solid_shape: None,
            representation_map_index: None,
        };
        let model = IfcModel {
            entities: vec![
                stair,
                IfcEntity::ElementPropertySet {
                    element: 0,
                    set: PropertySet {
                        name: "Pset_StairCommon".into(),
                        properties: vec![
                            Property {
                                name: "NumberOfRiser".into(),
                                value: PropertyValue::CountValue(19),
                            },
                            Property {
                                name: "TreadLength".into(),
                                value: PropertyValue::PositiveLengthFeet(11.0 / 12.0),
                            },
                        ],
                    },
                },
                // An index that is not a building element is ignored.
                IfcEntity::ElementPropertySet {
                    element: 9,
                    set: PropertySet {
                        name: "Pset_Nowhere".into(),
                        properties: vec![Property {
                            name: "X".into(),
                            value: PropertyValue::CountValue(1),
                        }],
                    },
                },
            ],
            ..IfcModel::default()
        };
        let step = write_step(&model);
        assert!(step.contains("IFCPROPERTYSINGLEVALUE('NumberOfRiser',$,IFCCOUNTMEASURE(19),$)"));
        assert!(step.contains(
            "IFCPROPERTYSINGLEVALUE('TreadLength',$,IFCPOSITIVELENGTHMEASURE(0.279400),$)"
        ));
        assert!(!step.contains("Pset_Nowhere"));
        let stair_id = step
            .lines()
            .find(|l| l.contains("=IFCSTAIR("))
            .and_then(|l| l.split('=').next())
            .expect("stair")
            .to_string();
        let set_id = step
            .lines()
            .find(|l| l.contains("'Pset_StairCommon'"))
            .and_then(|l| l.split('=').next())
            .expect("set")
            .to_string();
        assert!(step.lines().any(|l| l.contains("IFCRELDEFINESBYPROPERTIES")
            && l.contains(&format!("({stair_id}),{set_id})"))));
    }

    fn element_args<'a>(step: &'a str, ifc_type: &str) -> &'a str {
        let needle = format!("{ifc_type}(");
        let line = step
            .lines()
            .find(|l| l.contains(&needle))
            .unwrap_or_else(|| panic!("{ifc_type} was not emitted:\n{step}"));
        let open = line.find(&needle).unwrap() + needle.len();
        let close = line.rfind(");").unwrap();
        &line[open..close]
    }

    /// #214: every emitted building element must carry the full IFC4
    /// attribute list for its type — optional slots written as `$`,
    /// never dropped. Before the fix `IFCCOLUMN` / `IFCSLAB` shipped
    /// eight attributes against a declared nine, so a consumer asking
    /// for `PredefinedType` got "index 8 is out of range".
    #[test]
    fn every_emitted_element_type_has_full_ifc4_attribute_arity() {
        for (ifc_type, expected) in IFC4_ELEMENT_ARITY {
            assert_eq!(
                element_attribute_arity(ifc_type),
                *expected,
                "{ifc_type}: writer layout table disagrees with the IFC4 schema"
            );
            let step = single_element_step(ifc_type, None);
            let args = element_args(&step, ifc_type);
            assert_eq!(
                step_argument_count(args),
                *expected,
                "{ifc_type} emitted {args}"
            );
        }
    }

    /// Every `category_map` row that can become a building element
    /// must resolve to an arity the table above pins, so adding a
    /// Revit class cannot introduce an unvalidated entity type.
    #[test]
    fn category_map_entity_types_are_covered_by_the_arity_table() {
        use super::super::category_map::MAPPINGS;
        // Spatial containers are emitted by their own writer paths,
        // not through the BuildingElement branch.
        const SPATIAL: &[&str] = &["IFCBUILDINGSTOREY", "IFCGRID"];
        for mapping in MAPPINGS {
            if SPATIAL.contains(&mapping.ifc_type) {
                continue;
            }
            assert!(
                IFC4_ELEMENT_ARITY
                    .iter()
                    .any(|(name, _)| *name == mapping.ifc_type),
                "{} ({}) is missing from IFC4_ELEMENT_ARITY",
                mapping.ifc_type,
                mapping.revit_class
            );
        }
    }

    /// The mapped `PredefinedType` reaches the STEP record as a dotted
    /// enumeration in the schema's declared slot, and an absent one
    /// still occupies its slot as `$`.
    #[test]
    fn predefined_type_lands_in_its_declared_slot() {
        for (ifc_type, predefined, tail) in [
            ("IFCCOLUMN", Some("COLUMN"), ",'tag-1',.COLUMN."),
            ("IFCSLAB", Some("FLOOR"), ",'tag-1',.FLOOR."),
            ("IFCWALL", Some("STANDARD"), ",'tag-1',.STANDARD."),
            ("IFCMEMBER", Some("BRACE"), ",'tag-1',.BRACE."),
            (
                "IFCSPACE",
                Some("INTERNAL"),
                ",'Element',.ELEMENT.,.INTERNAL.,$",
            ),
            ("IFCDOOR", Some("DOOR"), ",'tag-1',$,$,.DOOR.,$,$"),
            ("IFCCOLUMN", None, ",'tag-1',$"),
            ("IFCDOOR", None, ",'tag-1',$,$,$,$,$"),
        ] {
            let step = single_element_step(ifc_type, predefined);
            let args = element_args(&step, ifc_type);
            assert!(
                args.ends_with(tail),
                "{ifc_type} with {predefined:?} should end in {tail}, got {args}"
            );
        }
    }

    /// RE-117: an `IfcSpace` is named by its room number and described by
    /// its room name, as Revit's own exporter writes it. Without a number
    /// the Name stays `Room-<ElementId>`; without a name LongName is unset.
    #[test]
    fn space_name_is_the_room_number_and_long_name_the_room_name() {
        use super::super::entities::{IfcEntity, Property, PropertySet, PropertyValue};

        let space = |properties: Vec<Property>| {
            let model = IfcModel {
                entities: vec![IfcEntity::BuildingElement {
                    ifc_type: "IFCSPACE".into(),
                    name: "Room-20822".into(),
                    type_guid: Some("20822".into()),
                    predefined_type: Some("SPACE".into()),
                    storey_index: None,
                    material_index: None,
                    property_set: (!properties.is_empty()).then(|| PropertySet {
                        name: "RvtElementRecordGeometry".into(),
                        properties,
                    }),
                    location_feet: None,
                    rotation_radians: None,
                    extrusion: None,
                    host_element_index: None,
                    material_layer_set_index: None,
                    material_profile_set_index: None,
                    solid_shape: None,
                    representation_map_index: None,
                }],
                ..IfcModel::default()
            };
            let step = write_step(&model);
            element_args(&step, "IFCSPACE").to_string()
        };
        let text = |key: &str, value: &str| Property {
            name: key.into(),
            value: PropertyValue::Text(value.into()),
        };
        let number = super::super::export_content::ROOM_NUMBER_PROPERTY;
        let name = super::super::export_content::ROOM_NAME_PROPERTY;

        let both = space(vec![text(number, "66"), text(name, "Stair 2")]);
        assert!(
            both.contains(",'66',") && both.ends_with(",'Stair 2',.ELEMENT.,.SPACE.,$"),
            "Name must be the number and LongName the name, got {both}"
        );

        let bare = space(Vec::new());
        assert!(
            bare.contains(",'Room-20822',") && bare.ends_with(",$,.ELEMENT.,.SPACE.,$"),
            "a space with neither keeps its Name and has no LongName, got {bare}"
        );

        let blank = space(vec![text(number, "  "), text(name, "   ")]);
        assert!(
            blank.contains(",'Room-20822',") && blank.ends_with(",$,.ELEMENT.,.SPACE.,$"),
            "blank values are not a number or a name, got {blank}"
        );
    }

    /// A `PredefinedType` that is not a legal STEP enumeration name
    /// degrades to `$` instead of corrupting the record — STEP
    /// enumeration references have no escape form.
    #[test]
    fn hostile_predefined_type_degrades_to_dollar() {
        for hostile in ["has space", "quote'inside", "0LEADING", "", "dot.ted"] {
            let step = single_element_step("IFCCOLUMN", Some(hostile));
            let args = element_args(&step, "IFCCOLUMN");
            assert!(
                args.ends_with(",'tag-1',$"),
                "hostile predefined type {hostile:?} leaked into {args}"
            );
            assert_eq!(step_argument_count(args), 9);
        }
    }

    /// IFC-28: A BuildingElement that references a MaterialLayerSet
    /// emits IFCMATERIALLAYER + IFCMATERIALLAYERSET +
    /// IFCMATERIALLAYERSETUSAGE + IFCRELASSOCIATESMATERIAL. Regression
    /// test for the writer's compound-material emission path.
    #[test]
    fn layer_set_emits_layer_chain_plus_usage() {
        use super::super::MaterialInfo;
        use super::super::entities::{IfcEntity, MaterialLayer, MaterialLayerSet};
        let model = IfcModel {
            project_name: Some("LayerSet demo".into()),
            description: None,
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: "IFCWALL".into(),
                name: "Exterior Wall".into(),
                type_guid: None,
                predefined_type: None,
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: None,
                rotation_radians: None,
                extrusion: None,
                host_element_index: None,
                material_layer_set_index: Some(0),
                material_profile_set_index: None,
                solid_shape: None,
                representation_map_index: None,
            }],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: vec![
                MaterialInfo {
                    name: "Gypsum".into(),
                    color_packed: None,
                    transparency: None,
                },
                MaterialInfo {
                    name: "Insulation".into(),
                    color_packed: None,
                    transparency: None,
                },
            ],
            material_layer_sets: vec![MaterialLayerSet {
                name: "Ext-6in".into(),
                description: None,
                layers: vec![
                    MaterialLayer {
                        material_index: Some(0),
                        thickness_feet: 5.0 / 8.0 / 12.0, // 5/8" gypsum
                        name: Some("Finish".into()),
                    },
                    MaterialLayer {
                        material_index: Some(1),
                        thickness_feet: 6.0 / 12.0, // 6" insulation
                        name: Some("Core".into()),
                    },
                ],
            }],
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        assert!(s.contains("IFCMATERIALLAYER("), "IFCMATERIALLAYER missing");
        assert_eq!(
            s.matches("IFCMATERIALLAYER(").count(),
            2,
            "expected two IFCMATERIALLAYER entities"
        );
        assert!(
            s.contains("IFCMATERIALLAYERSET("),
            "IFCMATERIALLAYERSET missing"
        );
        assert!(s.contains("'Ext-6in'"), "layer-set name missing");
        assert!(s.contains("IFCMATERIALLAYERSETUSAGE("), "usage missing");
        // Relationship must be present — tied to the wall element.
        assert!(
            s.contains("IFCRELASSOCIATESMATERIAL("),
            "IFCRELASSOCIATESMATERIAL missing"
        );
    }

    /// IFC-30: A BuildingElement that references a MaterialProfileSet
    /// emits IFCRECTANGLEPROFILEDEF + IFCMATERIALPROFILE +
    /// IFCMATERIALPROFILESET + IFCMATERIALPROFILESETUSAGE.
    #[test]
    fn profile_set_emits_profile_chain_plus_usage() {
        use super::super::MaterialInfo;
        use super::super::entities::{IfcEntity, MaterialProfile, MaterialProfileSet};
        let model = IfcModel {
            project_name: Some("ProfileSet demo".into()),
            description: None,
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: "IFCCOLUMN".into(),
                name: "W12x26 Col".into(),
                type_guid: None,
                predefined_type: None,
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: None,
                rotation_radians: None,
                extrusion: None,
                host_element_index: None,
                material_layer_set_index: None,
                material_profile_set_index: Some(0),
                solid_shape: None,
                representation_map_index: None,
            }],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: vec![MaterialInfo {
                name: "A992 Steel".into(),
                color_packed: None,
                transparency: None,
            }],
            material_layer_sets: Vec::new(),
            material_profile_sets: vec![MaterialProfileSet {
                name: "W12x26".into(),
                description: Some("AISC wide-flange".into()),
                profiles: vec![MaterialProfile {
                    material_index: 0,
                    profile_name: "W12x26".into(),
                    description: None,
                    profile: None,
                }],
            }],
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        assert!(
            s.contains("IFCRECTANGLEPROFILEDEF("),
            "placeholder profile def missing"
        );
        assert!(s.contains("IFCMATERIALPROFILE("), "profile entity missing");
        assert!(s.contains("IFCMATERIALPROFILESET("), "profile set missing");
        assert!(
            s.contains("IFCMATERIALPROFILESETUSAGE("),
            "profile set usage missing"
        );
        assert!(
            s.contains("IFCRELASSOCIATESMATERIAL("),
            "IFCRELASSOCIATESMATERIAL missing"
        );
    }

    /// Precedence: when both material_profile_set_index and
    /// material_layer_set_index are set on the same element, the
    /// profile-set path wins (matches Rust-side impl precedence).
    #[test]
    fn profile_set_takes_precedence_over_layer_set() {
        use super::super::MaterialInfo;
        use super::super::entities::{
            IfcEntity, MaterialLayer, MaterialLayerSet, MaterialProfile, MaterialProfileSet,
        };
        let model = IfcModel {
            project_name: Some("Precedence test".into()),
            description: None,
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: "IFCBEAM".into(),
                name: "Beam".into(),
                type_guid: None,
                predefined_type: None,
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: None,
                rotation_radians: None,
                extrusion: None,
                host_element_index: None,
                material_layer_set_index: Some(0),
                material_profile_set_index: Some(0),
                solid_shape: None,
                representation_map_index: None,
            }],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: vec![MaterialInfo {
                name: "Steel".into(),
                color_packed: None,
                transparency: None,
            }],
            material_layer_sets: vec![MaterialLayerSet {
                name: "Coincidental".into(),
                description: None,
                layers: vec![MaterialLayer {
                    material_index: Some(0),
                    thickness_feet: 0.5,
                    name: None,
                }],
            }],
            material_profile_sets: vec![MaterialProfileSet {
                name: "W12x26".into(),
                description: None,
                profiles: vec![MaterialProfile {
                    material_index: 0,
                    profile_name: "W12x26".into(),
                    description: None,
                    profile: None,
                }],
            }],
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        // Both layer set AND profile set entities exist because
        // every layer-set and profile-set in the model is emitted
        // up-front. What the precedence check governs is which
        // USAGE the element gets associated with.
        assert!(s.contains("IFCMATERIALLAYERSET("));
        assert!(s.contains("IFCMATERIALPROFILESET("));
        // Profile-set usage is emitted (because profile_set wins).
        assert!(s.contains("IFCMATERIALPROFILESETUSAGE("));
        // Layer-set usage is NOT emitted (layer_set lost to profile_set).
        assert!(
            !s.contains("IFCMATERIALLAYERSETUSAGE("),
            "layer-set usage should NOT be emitted when profile-set wins precedence"
        );
    }

    // -----------------------------------------------------------
    // IFC-24: IfcProfileDef subclasses.
    // Each test below builds a single-element IfcModel whose
    // extrusion carries a ProfileDef::X variant, then asserts the
    // STEP output contains the IFCxShAPEPROFILEDEF token AND that
    // the default IFCRECTANGLEPROFILEDEF is NOT emitted — the
    // whole point of the override is that the rectangle path is
    // bypassed.
    // -----------------------------------------------------------

    fn model_with_column_extrusion(ex: Extrusion) -> IfcModel {
        use super::super::entities::IfcEntity;
        IfcModel {
            project_name: Some("ProfileTest".into()),
            description: None,
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: "IFCCOLUMN".into(),
                name: "C1".into(),
                type_guid: None,
                predefined_type: None,
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: Some([0.0, 0.0, 0.0]),
                rotation_radians: Some(0.0),
                extrusion: Some(ex),
                host_element_index: None,
                material_layer_set_index: None,
                material_profile_set_index: None,
                solid_shape: None,
                representation_map_index: None,
            }],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        }
    }

    #[test]
    fn circle_profile_emits_ifccircleprofiledef() {
        let ex = Extrusion::circle(0.5, 10.0); // 1-ft-diameter, 10 ft tall
        let s = write_step(&model_with_column_extrusion(ex));
        assert!(s.contains("IFCCIRCLEPROFILEDEF(.AREA.,$,"));
        // 0.5 ft * 0.3048 = 0.152400 m
        assert!(s.contains(",0.152400)"));
        // The rectangle path must NOT fire.
        assert!(!s.contains("IFCRECTANGLEPROFILEDEF("));
    }

    #[test]
    fn i_shape_profile_emits_wide_flange() {
        // Approximate AISC W12x26: d=12.2 in, bf=6.49 in, tw=0.23 in, tf=0.38 in.
        let ex = Extrusion::i_shape(6.49 / 12.0, 12.2 / 12.0, 0.23 / 12.0, 0.38 / 12.0, 10.0);
        let s = write_step(&model_with_column_extrusion(ex));
        assert!(s.contains("IFCISHAPEPROFILEDEF(.AREA.,$,"));
        assert!(!s.contains("IFCRECTANGLEPROFILEDEF("));
    }

    #[test]
    fn t_shape_profile_emits_tee() {
        // Example WT6x20: d=5.97 in, bf=8.08 in, tw=0.415 in, tf=0.515 in.
        let ex = Extrusion::t_shape(5.97 / 12.0, 8.08 / 12.0, 0.415 / 12.0, 0.515 / 12.0, 10.0);
        let s = write_step(&model_with_column_extrusion(ex));
        assert!(s.contains("IFCTSHAPEPROFILEDEF(.AREA.,$,"));
        assert!(!s.contains("IFCRECTANGLEPROFILEDEF("));
    }

    #[test]
    fn l_shape_profile_emits_angle() {
        // L4x3x1/4: d=4 in, w=3 in, t=0.25 in.
        let ex = Extrusion::l_shape(4.0 / 12.0, 3.0 / 12.0, 0.25 / 12.0, 8.0);
        let s = write_step(&model_with_column_extrusion(ex));
        assert!(s.contains("IFCLSHAPEPROFILEDEF(.AREA.,$,"));
        assert!(!s.contains("IFCRECTANGLEPROFILEDEF("));
    }

    #[test]
    fn u_shape_profile_emits_channel() {
        // C8x11.5: d=8 in, bf=2.26 in, tw=0.22 in, tf=0.39 in.
        let ex = Extrusion::u_shape(8.0 / 12.0, 2.26 / 12.0, 0.22 / 12.0, 0.39 / 12.0, 12.0);
        let s = write_step(&model_with_column_extrusion(ex));
        assert!(s.contains("IFCUSHAPEPROFILEDEF(.AREA.,$,"));
        assert!(!s.contains("IFCRECTANGLEPROFILEDEF("));
    }

    #[test]
    fn rectangle_hollow_profile_emits_tube() {
        // HSS6x4x1/4: 6x4x0.25 in wall.
        let ex = Extrusion::rectangle_hollow(6.0 / 12.0, 4.0 / 12.0, 0.25 / 12.0, 10.0);
        let s = write_step(&model_with_column_extrusion(ex));
        assert!(s.contains("IFCRECTANGLEHOLLOWPROFILEDEF(.AREA.,$,"));
        // Plain rectangle MUST NOT fire — but 'IFCRECTANGLEHOLLOWPROFILEDEF'
        // contains the substring 'IFCRECTANGLE', so check for the
        // PROPER closing paren of the plain variant (never emitted).
        assert!(
            !s.contains("IFCRECTANGLEPROFILEDEF("),
            "plain IFCRECTANGLEPROFILEDEF must not be emitted when an HSS profile is present"
        );
    }

    #[test]
    fn circle_hollow_profile_emits_pipe() {
        // 6-inch-OD HSS round pipe with 0.25-in wall.
        let ex = Extrusion::circle_hollow(0.25, 0.25 / 12.0, 10.0);
        let s = write_step(&model_with_column_extrusion(ex));
        assert!(s.contains("IFCCIRCLEHOLLOWPROFILEDEF(.AREA.,$,"));
        // Neither the plain circle nor the plain rectangle should
        // fire.
        assert!(!s.contains("IFCCIRCLEPROFILEDEF("));
        assert!(!s.contains("IFCRECTANGLEPROFILEDEF("));
    }

    #[test]
    fn arbitrary_closed_profile_emits_polyline_and_profile() {
        // Simple triangle, NOT pre-closed — the writer must auto-close.
        let pts = vec![(0.0, 0.0), (1.0, 0.0), (0.5, 1.0)];
        let ex = Extrusion::arbitrary_closed(pts, 5.0);
        let s = write_step(&model_with_column_extrusion(ex));
        assert!(s.contains("IFCPOLYLINE(("));
        assert!(s.contains("IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,"));
        // Point count: 3 supplied vertices + 1 auto-closing
        // repeat = 4 IFCCARTESIANPOINT lines referenced by the
        // IFCPOLYLINE. Count the literal occurrences of '#N,' in
        // the polyline tuple by looking for 3+ commas.
        let comma_count = s
            .lines()
            .find(|l| l.contains("IFCPOLYLINE(("))
            .expect("polyline present")
            .matches(',')
            .count();
        assert!(
            comma_count >= 3,
            "expected polyline with ≥4 points (3 commas), got comma_count={}",
            comma_count
        );
    }

    // -----------------------------------------------------------
    // IFC-18 / IFC-19 / IFC-20: SolidShape emission paths.
    // -----------------------------------------------------------

    fn model_with_solid_shape(shape: SolidShape) -> IfcModel {
        use super::super::entities::IfcEntity;
        IfcModel {
            project_name: Some("SolidShapeTest".into()),
            description: None,
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: "IFCBUILDINGELEMENTPROXY".into(),
                name: "E1".into(),
                type_guid: None,
                predefined_type: None,
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: Some([0.0, 0.0, 0.0]),
                rotation_radians: Some(0.0),
                extrusion: None,
                host_element_index: None,
                material_layer_set_index: None,
                material_profile_set_index: None,
                solid_shape: Some(shape),
                representation_map_index: None,
            }],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        }
    }

    #[test]
    fn revolved_area_solid_emits_ifcrevolvedareasolid() {
        use super::super::entities::ProfileDef;
        let shape = SolidShape::RevolvedArea {
            profile: ProfileDef::Rectangle {
                width_feet: 1.0,
                depth_feet: 0.5,
            },
            axis_origin_feet: [0.0, 0.0, 0.0],
            axis_direction: [0.0, 0.0, 1.0],
            angle_radians: std::f64::consts::TAU,
        };
        let s = write_step(&model_with_solid_shape(shape));
        assert!(
            s.contains("IFCREVOLVEDAREASOLID("),
            "STEP output missing IFCREVOLVEDAREASOLID"
        );
        assert!(
            s.contains("IFCAXIS1PLACEMENT("),
            "revolved-area solid must include an IFCAXIS1PLACEMENT for axis"
        );
        assert!(
            s.contains("'Body','SweptSolid'"),
            "IfcRevolvedAreaSolid representation type must be SweptSolid"
        );
    }

    #[test]
    fn boolean_result_emits_ifcbooleanresult() {
        use super::super::entities::ProfileDef;
        let operand_a = SolidShape::ExtrudedArea(Extrusion::rectangle(2.0, 2.0, 10.0));
        let operand_b = SolidShape::ExtrudedArea(Extrusion::circle(0.5, 10.0));
        let shape = SolidShape::BooleanResult {
            op: super::super::entities::IfcBooleanOp::Difference,
            operand_a: Box::new(operand_a),
            operand_b: Box::new(operand_b),
        };
        let s = write_step(&model_with_solid_shape(shape));
        assert!(
            s.contains("IFCBOOLEANRESULT(.DIFFERENCE.,"),
            "STEP output missing IFCBOOLEANRESULT(.DIFFERENCE.,…)"
        );
        // Both operand shapes must be emitted:
        assert!(s.contains("IFCEXTRUDEDAREASOLID("));
        // operand_b is a circle-profile extrusion — IFCCIRCLEPROFILEDEF.
        assert!(s.contains("IFCCIRCLEPROFILEDEF("));
        // Representation-type token changes to CSG for boolean results.
        assert!(
            s.contains("'Body','CSG'"),
            "boolean-result representation must be 'CSG'"
        );
        let _ = ProfileDef::Rectangle {
            width_feet: 0.0,
            depth_feet: 0.0,
        };
    }

    #[test]
    fn faceted_brep_emits_full_chain() {
        // Simple tetrahedron: 4 vertices, 4 triangles.
        use super::super::entities::BrepTriangle;
        let vertices = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, 1.0],
        ];
        let triangles = vec![
            BrepTriangle(0, 1, 2), // bottom
            BrepTriangle(0, 1, 3), // front face
            BrepTriangle(1, 2, 3), // right face
            BrepTriangle(0, 2, 3), // left face
        ];
        let shape = SolidShape::FacetedBrep {
            vertices_feet: vertices,
            triangles,
        };
        let s = write_step(&model_with_solid_shape(shape));
        // 4 polyloops + 4 face bounds + 4 faces + 1 shell + 1 brep.
        assert_eq!(
            s.matches("IFCPOLYLOOP(").count(),
            4,
            "expected 4 IFCPOLYLOOP entities"
        );
        assert_eq!(
            s.matches("IFCFACEBOUND(").count(),
            4,
            "expected 4 IFCFACEBOUND entities"
        );
        assert_eq!(
            s.matches("IFCFACE((").count(),
            4,
            "expected 4 IFCFACE entities"
        );
        assert!(
            s.contains("IFCCLOSEDSHELL("),
            "faceted brep must include an IFCCLOSEDSHELL"
        );
        assert!(
            s.contains("IFCFACETEDBREP("),
            "faceted brep must include an IFCFACETEDBREP"
        );
        assert!(
            s.contains("'Body','Brep'"),
            "faceted-brep representation type must be 'Brep'"
        );
    }

    #[test]
    fn solid_shape_takes_precedence_over_extrusion() {
        // When both extrusion and solid_shape are set, solid_shape
        // wins (documented precedence). Pin the contract.
        use super::super::entities::{IfcEntity, ProfileDef};
        let model = IfcModel {
            project_name: Some("Precedence".into()),
            description: None,
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: "IFCCOLUMN".into(),
                name: "C1".into(),
                type_guid: None,
                predefined_type: None,
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: Some([0.0, 0.0, 0.0]),
                rotation_radians: Some(0.0),
                extrusion: Some(Extrusion::rectangle(2.0, 2.0, 10.0)),
                host_element_index: None,
                material_layer_set_index: None,
                material_profile_set_index: None,
                solid_shape: Some(SolidShape::RevolvedArea {
                    profile: ProfileDef::Rectangle {
                        width_feet: 0.5,
                        depth_feet: 2.0,
                    },
                    axis_origin_feet: [0.0, 0.0, 0.0],
                    axis_direction: [0.0, 0.0, 1.0],
                    angle_radians: std::f64::consts::TAU,
                }),
                representation_map_index: None,
            }],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        // solid_shape path fires:
        assert!(s.contains("IFCREVOLVEDAREASOLID("));
        // extrusion path does NOT fire — no IfcExtrudedAreaSolid in
        // output.
        assert!(
            !s.contains("IFCEXTRUDEDAREASOLID("),
            "extrusion path must not fire when solid_shape is set"
        );
    }

    /// RE-52: a placed extrusion is an IfcExtrudedAreaSolid whose Position
    /// carries its own origin, axis and reference direction.
    #[test]
    fn placed_extrusion_states_its_position() {
        use super::super::entities::ProfileDef;
        let shape = SolidShape::PlacedExtrusion {
            profile: ProfileDef::ArbitraryClosed {
                points: vec![(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (0.0, 1.0)],
            },
            origin_feet: [10.0, 0.0, 0.0],
            axis: [-1.0, 0.0, 0.0],
            ref_direction: [0.0, 0.0, 1.0],
            depth_feet: 4.0,
        };
        let s = write_step(&model_with_solid_shape(shape));
        let solid = s
            .lines()
            .find(|line| line.contains("IFCEXTRUDEDAREASOLID("))
            .expect("an extruded solid");
        assert!(solid.ends_with(",1.219200);"), "{solid}");
        let position = solid
            .split(',')
            .nth(1)
            .and_then(|p| p.strip_prefix('#'))
            .expect("position ref");
        let placement = s
            .lines()
            .find(|line| line.starts_with(&format!("#{position}=IFCAXIS2PLACEMENT3D(")))
            .expect("the solid's own placement");
        let refs: Vec<&str> = placement
            .trim_end_matches(");")
            .split('(')
            .nth(1)
            .expect("arguments")
            .split(',')
            .map(|r| r.trim_start_matches('#'))
            .collect();
        let line_of = |id: &str| {
            s.lines()
                .find(|line| line.starts_with(&format!("#{id}=")))
                .expect("referenced entity")
                .to_string()
        };
        assert!(line_of(refs[0]).contains("((3.048000,0.000000,0.000000))"));
        assert!(line_of(refs[1]).contains("((-1.000000000,0.000000000,0.000000000))"));
        assert!(line_of(refs[2]).contains("((0.000000000,0.000000000,1.000000000))"));
        assert!(s.contains("IFCARBITRARYCLOSEDPROFILEDEF("));
    }

    #[test]
    fn swept_path_emits_fixed_reference_swept_area_solid() {
        use super::super::entities::ProfileDef;
        // Pipe run: a 2-inch-diameter circular profile swept along a
        // 3-segment L-shape directrix with +Z as the fixed reference.
        let shape = SolidShape::SweptPath {
            profile: ProfileDef::Circle {
                radius_feet: 1.0 / 12.0,
            },
            directrix_points_feet: vec![
                [0.0, 0.0, 0.0],
                [10.0, 0.0, 0.0],
                [10.0, 0.0, 8.0],
                [10.0, 5.0, 8.0],
            ],
            fixed_reference: [0.0, 0.0, 1.0],
        };
        let s = write_step(&model_with_solid_shape(shape));
        assert!(
            s.contains("IFCFIXEDREFERENCESWEPTAREASOLID("),
            "swept-path shape missing IFCFIXEDREFERENCESWEPTAREASOLID"
        );
        assert!(s.contains("IFCCIRCLEPROFILEDEF("), "profile not emitted");
        assert!(
            s.contains("IFCPOLYLINE(("),
            "directrix polyline not emitted"
        );
        // 4 directrix vertices + 1 profile-placement origin =
        // minimum cartesian-point count. Profile origin + directrix
        // pts = 5. Actual count may be higher (project-level origins
        // also emit IFCCARTESIANPOINT) so we only lower-bound.
        assert!(
            s.matches("IFCCARTESIANPOINT((").count() >= 5,
            "expected at least 5 IFCCARTESIANPOINT entries"
        );
        assert!(
            s.contains("'Body','SweptSolid'"),
            "swept-path rep type must be 'SweptSolid'"
        );
    }

    #[test]
    fn nested_boolean_composes_recursively() {
        // ((A ∪ B) − C) — two levels of boolean nesting.
        use super::super::entities::IfcBooleanOp;
        let a = SolidShape::ExtrudedArea(Extrusion::rectangle(1.0, 1.0, 10.0));
        let b = SolidShape::ExtrudedArea(Extrusion::rectangle(0.5, 0.5, 10.0));
        let c = SolidShape::ExtrudedArea(Extrusion::rectangle(0.25, 0.25, 10.0));
        let union_ab = SolidShape::BooleanResult {
            op: IfcBooleanOp::Union,
            operand_a: Box::new(a),
            operand_b: Box::new(b),
        };
        let diff = SolidShape::BooleanResult {
            op: IfcBooleanOp::Difference,
            operand_a: Box::new(union_ab),
            operand_b: Box::new(c),
        };
        let s = write_step(&model_with_solid_shape(diff));
        assert_eq!(
            s.matches("IFCBOOLEANRESULT(").count(),
            2,
            "expected 2 nested IFCBOOLEANRESULT entities"
        );
        assert!(s.contains("IFCBOOLEANRESULT(.UNION.,"));
        assert!(s.contains("IFCBOOLEANRESULT(.DIFFERENCE.,"));
    }

    // -----------------------------------------------------------
    // IFC-21: IfcRepresentationMap + IfcMappedItem for shared
    // type-instance geometry.
    // -----------------------------------------------------------

    #[test]
    fn representation_map_emits_entity_once() {
        use super::super::entities::{IfcEntity, RepresentationMap};
        let shared_shape = SolidShape::ExtrudedArea(Extrusion::rectangle(3.0, 0.2, 7.0));
        let model = IfcModel {
            project_name: Some("shared door type".into()),
            description: None,
            entities: vec![
                // Three door instances, all referencing map 0.
                IfcEntity::BuildingElement {
                    ifc_type: "IFCDOOR".into(),
                    name: "D1".into(),
                    type_guid: Some("D-TYPE".into()),
                    predefined_type: None,
                    storey_index: None,
                    material_index: None,
                    property_set: None,
                    location_feet: Some([0.0, 0.0, 0.0]),
                    rotation_radians: Some(0.0),
                    extrusion: None,
                    host_element_index: None,
                    material_layer_set_index: None,
                    material_profile_set_index: None,
                    solid_shape: None,
                    representation_map_index: Some(0),
                },
                IfcEntity::BuildingElement {
                    ifc_type: "IFCDOOR".into(),
                    name: "D2".into(),
                    type_guid: Some("D-TYPE".into()),
                    predefined_type: None,
                    storey_index: None,
                    material_index: None,
                    property_set: None,
                    location_feet: Some([5.0, 0.0, 0.0]),
                    rotation_radians: Some(0.0),
                    extrusion: None,
                    host_element_index: None,
                    material_layer_set_index: None,
                    material_profile_set_index: None,
                    solid_shape: None,
                    representation_map_index: Some(0),
                },
                IfcEntity::BuildingElement {
                    ifc_type: "IFCDOOR".into(),
                    name: "D3".into(),
                    type_guid: Some("D-TYPE".into()),
                    predefined_type: None,
                    storey_index: None,
                    material_index: None,
                    property_set: None,
                    location_feet: Some([10.0, 0.0, 0.0]),
                    rotation_radians: Some(0.0),
                    extrusion: None,
                    host_element_index: None,
                    material_layer_set_index: None,
                    material_profile_set_index: None,
                    solid_shape: None,
                    representation_map_index: Some(0),
                },
            ],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: vec![RepresentationMap {
                name: Some("Simple Door".into()),
                shape: shared_shape,
                origin_feet: [0.0, 0.0, 0.0],
            }],
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        // Exactly ONE IfcRepresentationMap — that's the whole point
        // of the instancing.
        assert_eq!(
            s.matches("IFCREPRESENTATIONMAP(").count(),
            1,
            "expected exactly 1 IFCREPRESENTATIONMAP entity, shared by 3 instances"
        );
        // Exactly ONE underlying IFCEXTRUDEDAREASOLID (the shared
        // body) — NOT three.
        assert_eq!(
            s.matches("IFCEXTRUDEDAREASOLID(").count(),
            1,
            "expected exactly 1 shared IFCEXTRUDEDAREASOLID body"
        );
        // Three IfcMappedItem entities, one per instance.
        assert_eq!(
            s.matches("IFCMAPPEDITEM(").count(),
            3,
            "expected 3 IFCMAPPEDITEM entities (one per instance)"
        );
        // Each instance's IfcShapeRepresentation is of type
        // 'MappedRepresentation'.
        assert_eq!(
            s.matches("'Body','MappedRepresentation'").count(),
            3,
            "expected 3 IFCSHAPEREPRESENTATION('MappedRepresentation', …) entities"
        );
        // The shared body's own IfcShapeRepresentation uses the
        // representation type from the solid (SweptSolid for an
        // extrusion).
        assert!(
            s.contains("'Body','SweptSolid'"),
            "shared body's own IfcShapeRepresentation must use SweptSolid"
        );
        // And one IfcCartesianTransformationOperator3D per instance.
        assert_eq!(
            s.matches("IFCCARTESIANTRANSFORMATIONOPERATOR3D(").count(),
            3,
            "expected 3 CartesianTransformationOperator3D per instance"
        );
    }

    #[test]
    fn representation_map_takes_precedence_over_solid_shape_and_extrusion() {
        // When all three (representation_map_index, solid_shape,
        // extrusion) are set, the map wins.
        use super::super::entities::{IfcEntity, RepresentationMap};
        let model = IfcModel {
            project_name: Some("precedence".into()),
            description: None,
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: "IFCDOOR".into(),
                name: "D".into(),
                type_guid: None,
                predefined_type: None,
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: None,
                rotation_radians: None,
                extrusion: Some(Extrusion::rectangle(999.0, 999.0, 999.0)),
                host_element_index: None,
                material_layer_set_index: None,
                material_profile_set_index: None,
                solid_shape: Some(SolidShape::ExtrudedArea(Extrusion::rectangle(
                    888.0, 888.0, 888.0,
                ))),
                representation_map_index: Some(0),
            }],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: vec![RepresentationMap {
                name: Some("winner".into()),
                shape: SolidShape::ExtrudedArea(Extrusion::rectangle(1.0, 1.0, 1.0)),
                origin_feet: [0.0, 0.0, 0.0],
            }],
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        // IFCMAPPEDITEM must be emitted; no inline body extrusion
        // for this element. The map's own shared extrusion fires
        // once (3 ft × 0.5 ft etc from the map's body, converted
        // to metres), so we verify the NUMBER of extrusions equals
        // the NUMBER of map shapes (which is 1), not 2 + 1.
        assert_eq!(
            s.matches("IFCEXTRUDEDAREASOLID(").count(),
            1,
            "only the representation-map body should emit an IfcExtrudedAreaSolid"
        );
        assert_eq!(
            s.matches("IFCMAPPEDITEM(").count(),
            1,
            "instance should emit exactly one IfcMappedItem"
        );
        // 888 comes from solid_shape, 999 from extrusion — neither
        // should appear in the output if the map wins.
        let to_m = |ft: f64| format!("{:.6}", ft * 0.3048);
        assert!(
            !s.contains(&to_m(999.0)),
            "extrusion path fired unexpectedly — 999 ft converted to metres appears"
        );
        assert!(
            !s.contains(&to_m(888.0)),
            "solid_shape path fired unexpectedly — 888 ft converted to metres appears"
        );
    }

    #[test]
    fn representation_map_index_out_of_range_leaves_element_geometry_free() {
        // Out-of-range index → shape_ref = None → Representation =
        // `$` slot. Matches the safe-fallback philosophy elsewhere
        // (storey_index out-of-range clamps to storey[0]).
        use super::super::entities::IfcEntity;
        let model = IfcModel {
            project_name: Some("OOB".into()),
            description: None,
            entities: vec![IfcEntity::BuildingElement {
                ifc_type: "IFCWALL".into(),
                name: "W".into(),
                type_guid: None,
                predefined_type: None,
                storey_index: None,
                material_index: None,
                property_set: None,
                location_feet: None,
                rotation_radians: None,
                extrusion: None,
                host_element_index: None,
                material_layer_set_index: None,
                material_profile_set_index: None,
                solid_shape: None,
                representation_map_index: Some(42),
            }],
            classifications: Vec::new(),
            units: Vec::new(),
            building_storeys: Vec::new(),
            materials: Vec::new(),
            material_layer_sets: Vec::new(),
            material_profile_sets: Vec::new(),
            representation_maps: Vec::new(),
            global_ids: Default::default(),
            element_layers: Default::default(),
            material_layer_usages: Default::default(),
            element_type_materials: Default::default(),
            element_type_ids: Default::default(),
            material_constituent_sets: Vec::new(),
            opening_cuts: Default::default(),
        };
        let s = write_step(&model);
        // No mapped item, no extrusion, no brep — just an element
        // with $ in its representation slot.
        assert!(!s.contains("IFCMAPPEDITEM("));
        assert!(!s.contains("IFCREPRESENTATIONMAP("));
    }

    // #403: the unit assignment is the SI set the values are written in,
    // whatever display units the model carries.
    // -----------------------------------------------------------

    #[test]
    fn unit_assignment_is_si_whatever_the_model_declares() {
        use super::super::entities::UnitAssignment;
        let declared = |ids: &[&str]| IfcModel {
            units: ids
                .iter()
                .map(|id| UnitAssignment {
                    forge_identifier: (*id).into(),
                    ifc_mapping: None,
                })
                .collect(),
            ..IfcModel::default()
        };
        for model in [
            declared(&[]),
            declared(&[
                "autodesk.unit.unit:feet-1.0.1",
                "autodesk.unit.unit:squareInches-1.0.1",
                "autodesk.unit.unit:millimeters-1.0.1",
            ]),
        ] {
            let s = write_step(&model);
            for unit in [
                "IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.)",
                "IFCSIUNIT(*,.AREAUNIT.,$,.SQUARE_METRE.)",
                "IFCSIUNIT(*,.VOLUMEUNIT.,$,.CUBIC_METRE.)",
                "IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.)",
                "IFCSIUNIT(*,.MASSUNIT.,.KILO.,.GRAM.)",
                "IFCSIUNIT(*,.TIMEUNIT.,$,.SECOND.)",
            ] {
                assert!(s.contains(unit), "{unit}");
            }
            assert!(!s.contains("IFCCONVERSIONBASEDUNIT("));
            assert!(!s.contains(".MILLI."));
        }
    }

    #[test]
    fn ifc_boolean_op_step_keywords_are_spec_legal() {
        use super::super::entities::IfcBooleanOp;
        assert_eq!(IfcBooleanOp::Union.as_step_keyword(), ".UNION.");
        assert_eq!(IfcBooleanOp::Difference.as_step_keyword(), ".DIFFERENCE.");
        assert_eq!(
            IfcBooleanOp::Intersection.as_step_keyword(),
            ".INTERSECTION."
        );
    }

    #[test]
    fn explicit_rectangle_variant_matches_legacy_output() {
        // ProfileDef::Rectangle { .. } and profile_override=None
        // both produce IFCRECTANGLEPROFILEDEF — this pins the
        // round-trip contract.
        use super::super::entities::ProfileDef;
        let ex_none = Extrusion::rectangle(2.0, 0.5, 10.0);
        let mut ex_explicit = Extrusion::rectangle(2.0, 0.5, 10.0);
        ex_explicit.profile_override = Some(ProfileDef::Rectangle {
            width_feet: 2.0,
            depth_feet: 0.5,
        });
        let s_none = write_step(&model_with_column_extrusion(ex_none));
        let s_explicit = write_step(&model_with_column_extrusion(ex_explicit));
        // Both must contain the rectangle profile entity with the
        // same dimensions — the explicit-variant path must not
        // diverge from the implicit-default path.
        let rect_line = |s: &str| {
            s.lines()
                .find(|l| l.contains("IFCRECTANGLEPROFILEDEF"))
                .unwrap()
                .to_string()
        };
        assert_eq!(rect_line(&s_none), rect_line(&s_explicit));
    }
}