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
//! Layer 5 — IFC export (document-level scaffold).
//!
//! # What this module currently produces
//!
//! A spec-valid but structurally minimal IFC4 STEP file containing:
//!
//! - `IfcProject` with name + description from PartAtom / BasicFileInfo
//! - `IfcSite` → `IfcBuilding` → `IfcBuildingStorey` spatial hierarchy
//!   (placeholder names today; real names from `Level` elements when
//!   Lane Six elevation recovery succeeds)
//! - `IfcClassification` + `IfcClassificationReference` for any
//!   OmniClass codes found in PartAtom
//! - Required framework entities (`IfcPerson`, `IfcOrganization`,
//!   `IfcApplication`, `IfcOwnerHistory`, `IfcSIUnit`×4,
//!   `IfcUnitAssignment`, `IfcGeometricRepresentationContext`)
//!
//! **Per-element entities now land as geometry-free IFC4 elements by
//! default**, with Lane Six curves / loops / hosts / elevations
//! attached when [`ExportQualityMode::Geometry`] or
//! [`ExportQualityMode::Strict`] content policy requests them and
//! recovery succeeds. `typed-no-geometry` strips geometry claims.
//! Misleading `HostObjAttr` proxies are never emitted on the
//! production path — use [`DiagnosticRvtDocExporter`] for research.
//!
//! # Eventual implementation plan
//!
//! 1. Layer 5b (per-element walker) produces typed `Category`, `Level`,
//!    `Wall`, `Floor`, `Door`, `Window`, `Column`, `Beam`, etc.
//! 2. Phase 5 (geometry) extracts curves, faces, solids for each
//!    element.
//! 3. Entity mapper translates:
//!
//!    | Revit concept | IFC mapping |
//!    |---|---|
//!    | Project metadata (PartAtom) | `IfcProject` (done) |
//!    | Unit set (autodesk.unit.*) | `IfcUnitAssignment` / `IfcSIUnit` (best-effort modal read) |
//!    | Level | `IfcBuildingStorey` (pending Layer 5b) |
//!    | Wall | `IfcWall` + geometry (pending Phase 5) |
//!    | Floor/Roof/Ceiling | `IfcSlab` / `IfcRoof` / `IfcCovering` (pending) |
//!    | Door/Window | `IfcDoor` / `IfcWindow` + `IfcRelVoidsElement` (pending) |
//!    | Column/Beam | `IfcColumn` / `IfcBeam` (pending) |
//!    | Family (RFA) | `IfcTypeObject` + `IfcRepresentationMap` (pending) |
//!    | Uniformat / OmniClass codes | `IfcClassificationReference` (done) |
//!    | Material | `IfcMaterial` / `IfcMaterialLayerSet` (pending) |
//!    | Parameters | `IfcPropertySet` + `IfcPropertySingleValue` (pending) |
//!    | Host geometry | `IfcShapeRepresentation` (pending Phase 5) |
//!
//! 4. STEP serializer writes the `IfcModel` as `.ifc` text (done at
//!    document level; extends to elements as Phase 6 lands).
//! 5. IfcOpenShell + buildingSMART validators verify output against
//!    the 11-release corpus (pending — IFC-41/43).
//!
//! # Library collaboration
//!
//! `IfcOpenShell` is the validation partner. Output is written in
//! IFC4 STEP (ISO 10303-21) so it interoperates directly with
//! IfcOpenShell, BlenderBIM, and the buildingSMART validator family.
//! No IfcOpenShell runtime dependency is needed — the STEP writer is
//! pure Rust.
//!
//! # Module index
//!
//! IFC4 exporter subsystem:
//!
//! | Module | What it does |
//! |---|---|
//! | [`category_map`] | Revit class → IFC4 type mapping (IFC-01) |
//! | [`compare`] | IFC4 STEP file comparison summaries (M5-05) |
//! | [`entities`] | IFC4 entity taxonomy (walls, floors, doors, …) |
//! | [`export_content`] | Lane Seven quality-mode content policy |
//! | [`from_decoded`] | Bridge: decoded Revit elements → IfcModel |
//! | [`step_writer`] | IfcModel → ISO-10303-21 STEP text |
//!
//! VW1 viewer data model — Rust-side primitives a browser /
//! desktop viewer binds to:
//!
//! | Module | What it does |
//! |---|---|
//! | [`scene_graph`] | Project → storey → element tree (VW1-05) + schedule (VW1-15) |
//! | [`pbr`] | Revit Material → glTF PBR mapping (VW1-06) |
//! | [`camera`] | Orbit-camera state + controls (VW1-07) |
//! | [`clipping`] | ClippingPlane + SectionBox + ViewMode (VW1-10/14) |
//! | [`measure`] | Distance / angle / polygon-area (VW1-13) |
//! | [`annotation`] | Note / leader / polyline / pin markups (VW1-12) |
//! | [`share`] | ViewerState URL-fragment serialization (VW1-24) |
//! | [`gltf`] | glTF 2.0 GLB binary exporter (VW1-04) |
//! | [`sheet`] | 2D SVG plan view emission (VW1-11) |
//! | [`schedule_csv`] | Element and room schedules as CSV (spreadsheets) |
//!
//! Typical viewer pipeline:
//!
//! 1. `IfcModel` produced via [`RvtDocExporter`]
//! 2. [`scene_graph::build_scene_graph`] for the navigation tree
//! 3. [`scene_graph::CategoryFilter`] applied per user toggles
//! 4. [`gltf::model_to_glb`] for the 3D canvas, or
//!    [`sheet::render_plan_svg`] for the 2D drawing panel
//! 5. [`camera::CameraState`] + [`clipping::ViewMode`] drive the
//!    viewport's projection + spatial filter
//! 6. [`scene_graph::element_info_panel`] powers click-to-inspect
//! 7. [`share::encode_to_fragment`] serializes the whole state into
//!    a URL for collaboration

use crate::Result;

pub mod annotation;
pub mod body_geometry;
pub mod camera;
pub mod category_map;
pub mod clipping;
pub mod compare;
pub mod entities;
pub mod export_content;
pub mod from_decoded;
pub mod gltf;
pub mod measure;
pub mod pbr;
pub mod pset_validate;
pub mod scene_graph;
pub mod schedule_csv;
pub mod share;
pub mod sheet;
pub mod step_writer;

pub use export_content::{
    ELEMENT_RECORD_PROPERTY_SET, ExportContentPolicy, is_misleading_proxy_class,
};
pub use from_decoded::{BuilderOptions, ElementInput, build_ifc_model, entity_type_histogram};
pub use step_writer::write_step;

/// In-memory IFC model — what a successful export produces. Wire format
/// (STEP or IFC-JSON) is a separate concern handled by a serializer.
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct IfcModel {
    pub project_name: Option<String>,
    pub description: Option<String>,
    pub entities: Vec<entities::IfcEntity>,
    pub classifications: Vec<entities::Classification>,
    pub units: Vec<entities::UnitAssignment>,
    /// Real building storeys derived from Revit `Level` decoders. When
    /// empty, the STEP writer falls back to a single placeholder
    /// "Level 1" storey so the spatial hierarchy is still valid
    /// IFC4. When populated, each entry emits one `IfcBuildingStorey`
    /// with the Revit level's name + elevation in metres (converted
    /// from feet at emit time).
    pub building_storeys: Vec<Storey>,
    /// Materials available for association with BuildingElements.
    /// BuildingElement.material_index points into this list.
    pub materials: Vec<MaterialInfo>,
    /// Compound material assemblies (IFC-28). Referenced by
    /// `BuildingElement.material_layer_set_index`. Each layer
    /// inside a set references a material in `materials` above by
    /// index, so the two lists share a namespace — a layer can't
    /// reference a material that hasn't been registered there first.
    pub material_layer_sets: Vec<entities::MaterialLayerSet>,
    /// Compound structural profile assignments (IFC-30). Referenced
    /// by `BuildingElement.material_profile_set_index`. Used for
    /// columns and beams with named cross-sections (W12x26, HSS,
    /// circular columns). Profiles reference materials in
    /// `materials` above by index.
    pub material_profile_sets: Vec<entities::MaterialProfileSet>,
    /// Shared geometry maps for family / type instancing (IFC-21).
    /// Any `BuildingElement` whose `representation_map_index` is
    /// `Some(i)` routes through `representation_maps[i]` via an
    /// `IfcMappedItem` instead of emitting its own body chain. Each
    /// map's shape is serialised once; instances add a ~4-entity
    /// mapped-item wrap. Empty `Vec` leaves writer behaviour
    /// unchanged.
    pub representation_maps: Vec<entities::RepresentationMap>,
    /// The GlobalIds Revit's own exporter gives the model's elements and
    /// storeys (RE-48). The writer uses them in place of generated ones.
    #[serde(default)]
    pub global_ids: RevitGlobalIds,
    /// Layered elements' layers across their thickness, by ElementId (the
    /// element's `Tag`, RE-53). The glTF export draws each layer in its
    /// material's colour.
    #[serde(default)]
    pub element_layers: std::collections::BTreeMap<u32, ElementLayers>,
    /// How each element's material layer set lies on it, by index into
    /// `entities` (RE-58). An element with a layer set and no entry here
    /// gets the IFC4 defaults.
    #[serde(default)]
    pub material_layer_usages: std::collections::BTreeMap<usize, entities::MaterialLayerSetUsage>,
    /// The materials each element's type draws its geometry in, by
    /// ElementId (RE-82).
    #[serde(default)]
    pub element_type_materials: std::collections::BTreeMap<u32, Vec<String>>,
    /// Each element's Revit type, by ElementId (RE-110). The writer types
    /// every element named `Family:Type` by an IFC type object of its type.
    #[serde(default)]
    pub element_type_ids: std::collections::BTreeMap<u32, u32>,
    /// Material constituent sets (RE-82): an element without a layer,
    /// profile or single material gets the materials its type's geometry
    /// uses, written as IFC4 `IfcMaterialConstituentSet`, as Revit's
    /// export writes family instances.
    #[serde(default)]
    pub material_constituent_sets: Vec<entities::MaterialConstituentSet>,
    /// Openings cut to their host wall's thickness (#227), by index into
    /// `entities` of the filling door or window. A filling element with no
    /// entry gets an opening the shape of its own body.
    #[serde(default)]
    pub opening_cuts: std::collections::BTreeMap<usize, entities::OpeningCut>,
}

/// A layered element's layers across its thickness (RE-53).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ElementLayers {
    /// Unit plan direction, model axes, from the element's inside to its
    /// exterior face.
    pub exterior_normal: [f64; 2],
    /// Exterior first. Membranes, which have no width, are left out.
    pub layers: Vec<LayerBand>,
    /// The layers stack from the top down, as a floor's, roof's or
    /// ceiling's do (RE-57); `exterior_normal` is unused.
    #[serde(default)]
    pub stacked: bool,
    /// The Revit system family of the element's type, which a type with
    /// layers implies (RE-61,
    /// [`crate::partition_schema_mvp::system_family`]).
    #[serde(default)]
    pub system_family: Option<String>,
}

/// One layer of an [`ElementLayers`].
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct LayerBand {
    /// Feet.
    pub width_feet: f64,
    /// The layer material's shading colour, `0x00BBGGRR`; `None` where the
    /// layer takes its category's.
    pub color_packed: Option<u32>,
    /// The layer material's name, where it is read (RE-58).
    #[serde(default)]
    pub name: Option<String>,
    /// 0 opaque to 1 fully transparent.
    pub transparency: f64,
}

/// GlobalIds Revit's own exporter gives, rebuilt from the file (RE-48,
/// [`crate::revit_global_ids`]). Empty when the file does not yield them.
#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RevitGlobalIds {
    /// The document's `Unique Document GUID` (BasicFileInfo). The GlobalIds
    /// the writer generates for entities Revit gives none are derived from
    /// it (#400), so two documents never share one.
    #[serde(default)]
    pub document: Option<String>,
    /// By index in `IfcModel::entities`: building elements and spaces.
    pub elements: std::collections::BTreeMap<usize, String>,
    /// By index in `IfcModel::building_storeys`.
    pub storeys: std::collections::BTreeMap<usize, String>,
    /// By the type's ElementId: the types of `IfcModel::element_type_ids`
    /// (RE-110).
    #[serde(default)]
    pub types: std::collections::BTreeMap<u32, String>,
}

/// A single building storey derived from a Revit `Level` element.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Storey {
    pub name: String,
    /// Elevation in feet (Revit's native unit). The STEP writer
    /// converts to metres at emit time per IFC4 convention.
    pub elevation_feet: f64,
}

/// A single material entry ready for IFC emission. Derived from
/// a decoded Revit `Material` element via
/// [`from_decoded::materials_from_revit`].
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaterialInfo {
    /// Display name ("Concrete", "Glass - Tinted", "Wood - Oak").
    pub name: String,
    /// Packed RGB `0x00BBGGRR` from the Revit material's color.
    /// `None` when the material didn't carry a color.
    pub color_packed: Option<u32>,
    /// Surface transparency in the 0..1 range. 0 = fully opaque.
    pub transparency: Option<f64>,
}

/// Stable schema version for [`ExportDiagnostics`] JSON.
pub const EXPORT_DIAGNOSTICS_SCHEMA_VERSION: u32 = 1;

/// IFC export mode represented in diagnostics sidecars.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExportDiagnosticsMode {
    Placeholder,
    Default,
    DiagnosticProxies,
}

/// Result type for callers that want both the IFC model and the
/// user/shareable export diagnostics sidecar in one pass.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportResult {
    pub model: IfcModel,
    pub diagnostics: ExportDiagnostics,
}

/// JSON-serialisable export diagnostics sidecar.
///
/// The schema is intentionally flat and conservative so CLI, Python,
/// and WASM callers can attach it to issue reports without understanding
/// Revit internals.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportDiagnostics {
    pub schema_version: u32,
    pub mode: ExportDiagnosticsMode,
    pub input: ExportInputDiagnostics,
    pub decoded: DecodedExportDiagnostics,
    pub exported: ExportedModelDiagnostics,
    pub skipped: Vec<SkippedExportItem>,
    pub unsupported_features: Vec<String>,
    pub warnings: Vec<String>,
    pub confidence: ExportConfidenceSummary,
    /// A10 source-coverage fractions measured from export/decode stats.
    ///
    /// Fractions are set only when a trustworthy denominator exists;
    /// otherwise they stay `None` (fail closed — never invent ratios).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_coverage: Option<SourceCoverageDiagnostics>,
    /// `Formats/Latest` page-boundary / strip-gate integrity (A2 / PARSE-001).
    /// `None` when the stream is absent from the container.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub formats_latest_integrity: Option<crate::compression::FormatsLatestIntegrity>,
}

/// A10 export source-coverage block (measured when denominators exist).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SourceCoverageDiagnostics {
    pub status: SourceCoverageStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decoded_element_fraction: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exported_element_fraction: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub geometry_element_fraction: Option<f32>,
}

/// Measurement state for [`SourceCoverageDiagnostics`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceCoverageStatus {
    Unset,
    Unknown,
    Measured,
}

impl SourceCoverageDiagnostics {
    /// Honest unset stub — no invented fractions.
    pub fn unset() -> Self {
        Self {
            status: SourceCoverageStatus::Unset,
            notes: Some(
                "Export source-coverage fractions are unset: no trustworthy denominator was available; fields stay null."
                    .to_string(),
            ),
            decoded_element_fraction: None,
            exported_element_fraction: None,
            geometry_element_fraction: None,
        }
    }

    /// Measure fractions from existing decode/export counts only.
    ///
    /// Definitions (fail closed when a denominator is zero or untrusted):
    /// - `decoded_element_fraction` = `production_walker_elements /
    ///   elem_table_element_count` (the distinct ElementIds
    ///   `Global/ElemTable` declares) when that parses and
    ///   `0 < walker <= declared` (leave null otherwise).
    /// - `exported_element_fraction` = `building_elements /
    ///   production_walker_elements` when walker &gt; 0 (includes
    ///   non-building production classes such as Level/Material).
    /// - `geometry_element_fraction` = `building_elements_with_geometry /
    ///   building_elements` when building_elements &gt; 0.
    pub fn measure(
        production_walker_elements: usize,
        building_elements: usize,
        building_elements_with_geometry: usize,
        elem_table_element_count: Option<usize>,
    ) -> Self {
        let mut notes: Vec<String> = Vec::new();

        let decoded_element_fraction = match elem_table_element_count {
            None => {
                notes.push(
                    "decoded_element_fraction left null: Global/ElemTable declared ElementIds unavailable."
                        .into(),
                );
                None
            }
            Some(0) => {
                notes.push(
                    "decoded_element_fraction left null: Global/ElemTable declares no ElementIds."
                        .into(),
                );
                None
            }
            Some(_declared) if production_walker_elements == 0 => {
                // Declared table present but nothing on the production path —
                // measurable zero coverage of the declared set.
                Some(0.0)
            }
            Some(declared) if production_walker_elements <= declared => {
                Some(production_walker_elements as f32 / declared as f32)
            }
            Some(declared) => {
                notes.push(format!(
                    "decoded_element_fraction left null: production walker recovered {production_walker_elements} elements but Global/ElemTable declares only {declared} ElementIds (do not invent a ratio)."
                ));
                None
            }
        };

        let exported_element_fraction = if production_walker_elements > 0 {
            Some(building_elements as f32 / production_walker_elements as f32)
        } else {
            notes.push(
                "exported_element_fraction left null: production_walker_elements is 0.".into(),
            );
            None
        };

        let geometry_element_fraction = if building_elements > 0 {
            Some(building_elements_with_geometry as f32 / building_elements as f32)
        } else {
            notes.push(
                "geometry_element_fraction left null: exported building_elements is 0.".into(),
            );
            None
        };

        let any_measured = decoded_element_fraction.is_some()
            || exported_element_fraction.is_some()
            || geometry_element_fraction.is_some();

        if !any_measured {
            return Self::unset();
        }

        notes.insert(
            0,
            "Measured from export diagnostics counts only (production walker, exported building elements, ElementIds declared by Global/ElemTable). Not a converter-grade completeness claim.".into(),
        );

        Self {
            status: SourceCoverageStatus::Measured,
            notes: Some(notes.join(" ")),
            decoded_element_fraction,
            exported_element_fraction,
            geometry_element_fraction,
        }
    }
}

/// Best-effort ElemTable header `element_count` for A10 decoded fraction.
///
/// Returns `None` when the stream is missing or fails to parse — callers
/// must leave `decoded_element_fraction` null rather than invent a total.
/// Distinct non-zero ElementIds `Global/ElemTable` declares. The header's
/// `element_count` is not this: it is the same value on every file of a
/// release (1411 on all 2024 files).
fn elem_table_declared_element_count(rf: &mut crate::RevitFile) -> Option<usize> {
    crate::elem_table::declared_element_ids(rf)
        .ok()
        .map(|ids| ids.iter().filter(|&&id| id != 0).count())
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportInputDiagnostics {
    pub revit_version: Option<u32>,
    pub build: Option<String>,
    pub original_path: Option<String>,
    pub project_name: Option<String>,
    pub stream_count: usize,
    pub has_basic_file_info: bool,
    pub has_part_atom: bool,
    pub has_formats_latest: bool,
    pub has_global_latest: bool,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DecodedExportDiagnostics {
    pub production_walker_elements: usize,
    pub diagnostic_proxy_candidates: usize,
    pub arcwall_records: usize,
    /// Diagnostic (low-confidence) candidate class histogram.
    pub class_counts: std::collections::BTreeMap<String, usize>,
    /// Production `iter_elements` class histogram (ArcWall / Level / Floor / …).
    #[serde(default)]
    pub production_class_counts: std::collections::BTreeMap<String, usize>,
    /// Count of AProperty* value carriers seen on the production path.
    /// Host↔parameter joins are not recovered yet, so this is usually
    /// 0 on real projects even when ParameterElement definitions exist
    /// in schema (#35 honest empty).
    #[serde(default)]
    pub parameter_value_count: usize,
    /// Mean provenance confidence across production `iter_elements` (M3-07).
    #[serde(default)]
    pub mean_element_confidence: Option<f32>,
    /// Elements whose provenance confidence is below
    /// [`crate::walker::DEFAULT_MIN_ELEMENT_CONFIDENCE`].
    #[serde(default)]
    pub elements_below_min_confidence: usize,
    /// Floor used for the below-min count / default export hide.
    #[serde(default = "default_min_element_confidence_serde")]
    pub min_element_confidence: f32,
    pub recovered_unit_identifiers: Vec<String>,
    pub unknown_unit_identifiers: Vec<String>,
}

fn default_min_element_confidence_serde() -> f32 {
    crate::walker::DEFAULT_MIN_ELEMENT_CONFIDENCE
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportedModelDiagnostics {
    pub total_entities: usize,
    pub building_elements: usize,
    pub building_elements_with_geometry: usize,
    /// Building elements with no body of their own because their
    /// aggregated parts carry it, as in Revit's export: stairs (RE-39) and
    /// curtain walls (RE-46). Not counted in
    /// [`Self::building_elements_with_geometry`].
    #[serde(default)]
    pub building_elements_carried_by_parts: usize,
    pub by_ifc_type: std::collections::BTreeMap<String, usize>,
    pub classification_count: usize,
    pub unit_assignment_count: usize,
    pub material_count: usize,
    pub storey_count: usize,
    /// Recovered building-storey display names (same order as
    /// [`IfcModel::building_storeys`]). Empty when no levels recovered.
    #[serde(default)]
    pub storey_names: Vec<String>,
    /// Recovered building-storey elevations in feet, same order as
    /// `storey_names`. All-zero means no elevation was recovered — the
    /// Level rows carried names only (#213).
    #[serde(default)]
    pub storey_elevations_feet: Vec<f64>,
    /// Building elements contained in a specific storey rather than
    /// falling to the writer's default container.
    #[serde(default)]
    pub storey_bound_elements: usize,
    /// Sample of recovered material display names (capped) for File
    /// Status / inspect — not a full inventory when counts are large.
    #[serde(default)]
    pub material_names_sample: Vec<String>,
    /// Elements whose compound layers and layer colours were decoded
    /// ([`IfcModel::element_layers`], RE-53). The glTF export draws each
    /// one in its layers where they add up to its body's thickness.
    #[serde(default)]
    pub layered_element_count: usize,
    /// Exported bodies by how they were derived: each record-backed
    /// element's `BodySource` property (#409), such as
    /// `partition_wall_centreline` or `partition_element_record_bbox`.
    #[serde(default)]
    pub body_sources: std::collections::BTreeMap<String, usize>,
    /// Bodies that are only the element record's bounding box: a
    /// `partition_element_record_bbox` body with no recovered plan profile.
    /// They are placed and sized correctly but are not the element's shape
    /// (#409).
    #[serde(default)]
    pub bounding_box_bodies: usize,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SkippedExportItem {
    pub reason: String,
    pub count: usize,
    pub classes: std::collections::BTreeMap<String, usize>,
    pub sample_names: Vec<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportConfidenceSummary {
    pub level: String,
    pub score: f32,
    pub has_project_metadata: bool,
    pub has_typed_elements: bool,
    pub has_geometry: bool,
    pub has_diagnostic_proxies: bool,
    pub warning_count: usize,
    /// Element records of a recovered category
    /// ([`crate::partition_element_records::RECOVERED_CATEGORIES`]) the
    /// partition scan found but could not export because no ElementId is attributable
    /// to them (the `element_record_without_element_id` skipped item,
    /// RE-30). Non-zero means the model is incomplete, and `score` is
    /// scaled down by the exported share. Zero is not a completeness claim.
    #[serde(default)]
    pub unexported_element_records: usize,
}

/// User-facing export quality requirement.
///
/// These modes do not change how bytes are decoded; they define how
/// much recovered model data a caller requires before accepting the
/// generated IFC. `Scaffold` is intentionally permissive and preserves
/// the historical `rvt-ifc` behavior. Stronger modes fail loudly instead
/// of writing an IFC that looks more complete than it is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExportQualityMode {
    Scaffold,
    TypedNoGeometry,
    Geometry,
    Strict,
}

impl ExportQualityMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Scaffold => "scaffold",
            Self::TypedNoGeometry => "typed-no-geometry",
            Self::Geometry => "geometry",
            Self::Strict => "strict",
        }
    }

    pub fn parse(value: &str) -> std::result::Result<Self, ExportQualityModeParseError> {
        match value.trim().to_ascii_lowercase().as_str() {
            "scaffold" => Ok(Self::Scaffold),
            "typed-no-geometry" | "typed_no_geometry" => Ok(Self::TypedNoGeometry),
            "geometry" => Ok(Self::Geometry),
            "strict" => Ok(Self::Strict),
            _ => Err(ExportQualityModeParseError {
                value: value.to_string(),
            }),
        }
    }

    pub fn validate(
        self,
        diagnostics: &ExportDiagnostics,
    ) -> std::result::Result<(), ExportQualityValidationError> {
        let mut failures = Vec::new();

        match self {
            Self::Scaffold => {}
            Self::TypedNoGeometry => {
                require_typed_elements(diagnostics, &mut failures);
            }
            Self::Geometry => {
                require_typed_elements(diagnostics, &mut failures);
                require_geometry(diagnostics, &mut failures);
            }
            Self::Strict => {
                require_typed_elements(diagnostics, &mut failures);
                require_geometry(diagnostics, &mut failures);
                if !diagnostics.confidence.has_project_metadata {
                    failures.push("no project metadata was recovered".to_string());
                }
                if diagnostics.exported.unit_assignment_count == 0 {
                    failures.push("no Revit unit assignment was recovered".to_string());
                }
                if diagnostics.exported.storey_count == 0 {
                    failures.push("no Revit level/storey data was recovered".to_string());
                }
                if !diagnostics.unsupported_features.is_empty() {
                    failures.push(format!(
                        "unsupported exporter features remain: {}",
                        diagnostics.unsupported_features.join(", ")
                    ));
                }
                if !diagnostics.warnings.is_empty() {
                    failures.push(format!(
                        "{} export warning(s) remain",
                        diagnostics.warnings.len()
                    ));
                }
            }
        }

        if failures.is_empty() {
            Ok(())
        } else {
            Err(ExportQualityValidationError {
                mode: self,
                reason: failures.join("; "),
                confidence_level: diagnostics.confidence.level.clone(),
            })
        }
    }
}

impl std::fmt::Display for ExportQualityMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for ExportQualityMode {
    type Err = ExportQualityModeParseError;

    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
        Self::parse(value)
    }
}

#[derive(Debug, Clone, thiserror::Error)]
#[error(
    "unknown IFC export mode `{value}`; expected scaffold, typed-no-geometry, geometry, or strict"
)]
pub struct ExportQualityModeParseError {
    pub value: String,
}

#[derive(Debug, Clone, thiserror::Error)]
#[error(
    "IFC export mode `{mode}` cannot be satisfied: {reason} (confidence level: {confidence_level})"
)]
pub struct ExportQualityValidationError {
    pub mode: ExportQualityMode,
    pub reason: String,
    pub confidence_level: String,
}

fn require_typed_elements(diagnostics: &ExportDiagnostics, failures: &mut Vec<String>) {
    if !diagnostics.confidence.has_typed_elements {
        failures.push(format!(
            "no validated typed IFC elements were exported (building_elements={}, confidence_level={})",
            diagnostics.exported.building_elements, diagnostics.confidence.level
        ));
    }
}

fn require_geometry(diagnostics: &ExportDiagnostics, failures: &mut Vec<String>) {
    if !diagnostics.confidence.has_geometry {
        failures.push(format!(
            "no exported building element has geometry (building_elements_with_geometry={})",
            diagnostics.exported.building_elements_with_geometry
        ));
    }
}

/// Trait every IFC exporter implements. Multiple implementations exist
/// as we phase this up: a null exporter that returns `NotYetImplemented`
/// for everything, a partial one that emits only project+units, and
/// eventually a full one.
pub trait Exporter {
    fn export(&self, rf: &mut crate::RevitFile) -> Result<IfcModel>;
}

/// Returned by exporters that cannot yet produce a given entity class.
#[derive(Debug, Clone, thiserror::Error)]
#[error("IFC export not yet implemented: {reason}")]
pub struct NotYetImplemented {
    pub reason: String,
}

/// Placeholder exporter — returns an `IfcModel` whose only filled
/// field is `project_name` (extracted from PartAtom if it parses).
/// Geometry, categories, and per-element entities are absent. Safe
/// to use as a stand-in for downstream tooling that wants to test
/// the `Exporter` plumbing without requiring real model data.
///
/// For the real document-level exporter with spatial hierarchy +
/// classifications, use [`RvtDocExporter`] instead.
///
/// (Renamed from `NullExporter` in v0.1.3 — the old name implied
/// it returns `NotYetImplemented`, which it does not.)
pub struct PlaceholderExporter;

impl Exporter for PlaceholderExporter {
    fn export(&self, rf: &mut crate::RevitFile) -> Result<IfcModel> {
        let project_name = rf
            .part_atom()
            .ok()
            .and_then(|pa| pa.title)
            .or_else(|| rf.basic_file_info().ok().and_then(|bfi| bfi.original_path));
        Ok(IfcModel {
            project_name,
            description: Some(
                "Partial IFC export via rvt-rs PlaceholderExporter. \
                 Geometry, categories, and elements are pending Layer 5b \
                 walker + Phase 5 geometry work."
                    .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(),
        })
    }
}

impl PlaceholderExporter {
    pub fn export_with_diagnostics(&self, rf: &mut crate::RevitFile) -> Result<ExportResult> {
        let model = self.export(rf)?;
        let diagnostics = build_export_diagnostics(rf, &model, ExportDiagnosticsMode::Placeholder);
        Ok(ExportResult { model, diagnostics })
    }
}

/// Document-level exporter — populates an `IfcModel` with project
/// metadata from PartAtom + BasicFileInfo + recovered `autodesk.unit.*`
/// records + (when locatable) ADocument's walker-read instance fields.
/// Produces a spec-valid but structurally
/// minimal IFC4 file when paired with `step_writer::write_step`.
///
/// Current coverage: project name + document description + OmniClass
/// classification references + best-effort project unit assignment.
/// Pending walker expansion: categories from the family-graph
/// references and building-element geometry.
pub struct RvtDocExporter;

impl Exporter for RvtDocExporter {
    fn export(&self, rf: &mut crate::RevitFile) -> Result<IfcModel> {
        self.export_with_limits(rf, crate::walker::WalkerLimits::default())
    }
}

impl RvtDocExporter {
    pub fn export_with_limits(
        &self,
        rf: &mut crate::RevitFile,
        limits: crate::walker::WalkerLimits,
    ) -> Result<IfcModel> {
        self.export_with_mode_and_limits(rf, ExportQualityMode::Scaffold, limits)
    }

    /// Export using a quality mode's *content* policy.
    ///
    /// Validation ([`ExportQualityMode::validate`]) is left to the
    /// caller (CLI / Python) so diagnostics can still be written when
    /// a stronger mode rejects the result.
    pub fn export_with_mode_and_limits(
        &self,
        rf: &mut crate::RevitFile,
        quality_mode: ExportQualityMode,
        limits: crate::walker::WalkerLimits,
    ) -> Result<IfcModel> {
        export_rvt_doc(rf, RvtDocExportMode::Default, quality_mode, limits)
    }

    pub fn export_with_diagnostics(&self, rf: &mut crate::RevitFile) -> Result<ExportResult> {
        self.export_with_diagnostics_and_limits(rf, crate::walker::WalkerLimits::default())
    }

    pub fn export_with_diagnostics_and_limits(
        &self,
        rf: &mut crate::RevitFile,
        limits: crate::walker::WalkerLimits,
    ) -> Result<ExportResult> {
        self.export_with_diagnostics_mode_and_limits(rf, ExportQualityMode::Scaffold, limits)
    }

    pub fn export_with_diagnostics_mode_and_limits(
        &self,
        rf: &mut crate::RevitFile,
        quality_mode: ExportQualityMode,
        limits: crate::walker::WalkerLimits,
    ) -> Result<ExportResult> {
        let model = self.export_with_mode_and_limits(rf, quality_mode, limits)?;
        let diagnostics = build_export_diagnostics_with_limits(
            rf,
            &model,
            ExportDiagnosticsMode::Default,
            limits,
        );
        Ok(ExportResult { model, diagnostics })
    }
}

/// Diagnostic document exporter.
///
/// This exporter starts from the same conservative model as
/// [`RvtDocExporter`], then appends low-confidence schema-scan hits as
/// `IFCBUILDINGELEMENTPROXY` elements with `Pset_RvtRsDiagnosticCandidate`
/// provenance. It is intended for reverse-engineering and issue
/// attachments, not for normal model exchange.
pub struct DiagnosticRvtDocExporter;

impl Exporter for DiagnosticRvtDocExporter {
    fn export(&self, rf: &mut crate::RevitFile) -> Result<IfcModel> {
        self.export_with_limits(rf, crate::walker::WalkerLimits::default())
    }
}

impl DiagnosticRvtDocExporter {
    pub fn export_with_limits(
        &self,
        rf: &mut crate::RevitFile,
        limits: crate::walker::WalkerLimits,
    ) -> Result<IfcModel> {
        // Diagnostic export keeps recovered geometry when present; it
        // does not apply typed-only / mapped-only filters.
        export_rvt_doc(
            rf,
            RvtDocExportMode::DiagnosticProxies,
            ExportQualityMode::Scaffold,
            limits,
        )
    }

    pub fn export_with_diagnostics(&self, rf: &mut crate::RevitFile) -> Result<ExportResult> {
        self.export_with_diagnostics_and_limits(rf, crate::walker::WalkerLimits::default())
    }

    pub fn export_with_diagnostics_and_limits(
        &self,
        rf: &mut crate::RevitFile,
        limits: crate::walker::WalkerLimits,
    ) -> Result<ExportResult> {
        let model = self.export_with_limits(rf, limits)?;
        let diagnostics = build_export_diagnostics_with_limits(
            rf,
            &model,
            ExportDiagnosticsMode::DiagnosticProxies,
            limits,
        );
        Ok(ExportResult { model, diagnostics })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RvtDocExportMode {
    Default,
    DiagnosticProxies,
}

fn export_rvt_doc(
    rf: &mut crate::RevitFile,
    mode: RvtDocExportMode,
    quality_mode: ExportQualityMode,
    walker_limits: crate::walker::WalkerLimits,
) -> Result<IfcModel> {
    let policy = export_content::ExportContentPolicy::for_quality_mode(quality_mode);
    // Identity from PartAtom if present; fall back to
    // BasicFileInfo's original path.
    let part = rf.part_atom().ok();
    let bfi = rf.basic_file_info().ok();
    let project_name = part
        .as_ref()
        .and_then(|pa| pa.title.clone())
        .or_else(|| bfi.as_ref().and_then(|b| b.original_path.clone()));

    let description = {
        let mut d = Vec::new();
        if let Some(b) = &bfi {
            d.push(format!("Revit {} export", b.version));
            if let Some(message) =
                crate::arc_wall_record::ArcWallRecord::standard_decoder_status(b.version)
                    .diagnostic_message()
            {
                d.push(message);
            }
        }
        if let Some(p) = &part {
            if let Some(id) = &p.id {
                d.push(format!("id={id}"));
            }
        }
        if d.is_empty() {
            None
        } else {
            Some(d.join("; "))
        }
    };

    // OmniClass / Uniformat classification references, if present
    // in PartAtom.
    let mut classifications = Vec::new();
    if let Some(p) = &part {
        let omni_items: Vec<_> = p
            .categories
            .iter()
            .filter(|c| c.term.starts_with(char::is_numeric) && c.term.contains('.'))
            .map(|c| entities::ClassificationItem {
                code: c.term.clone(),
                name: None,
            })
            .collect();
        if !omni_items.is_empty() {
            classifications.push(entities::Classification {
                source: entities::ClassificationSource::OmniClass,
                edition: None,
                items: omni_items,
            });
        }
    }

    // A single IfcProject entity at the model level (step_writer
    // emits its STEP form; other entity types are wired in below
    // from the walker's element stream).
    let mut entities = vec![entities::IfcEntity::Project {
        name: project_name.clone(),
        description: description.clone(),
        long_name: part.as_ref().and_then(|p| p.title.clone()),
    }];

    // L5B-11.7 / Lane Seven — production walker elements honour the
    // quality-mode content policy: HostObjAttr never emits, Levels
    // become storeys, and geometry/host recovery attaches only when
    // the mode asks for it. Walker failure falls through with no
    // element entities — we never regress the metadata-only baseline.
    let mut building_storeys = Vec::new();
    let mut materials = Vec::new();
    let (element_layers, element_type_materials, unplaced_wall_layers, element_type_ids) =
        append_production_walker_elements(
            rf,
            &mut entities,
            &mut building_storeys,
            &mut materials,
            policy,
            walker_limits,
        );
    if mode == RvtDocExportMode::DiagnosticProxies {
        append_diagnostic_walker_proxy_candidates(rf, &mut entities, walker_limits);
    }

    // #218 / RE-24 — the Revit `Level` elements themselves, with their
    // own names and elevations, replace whatever the walker produced.
    // Runs before the ArcWall path so its `building_storeys.is_empty()`
    // guard keeps the recovered set, and before
    // `apply_element_record_storeys`, whose replacement half is a
    // no-op once the storeys carry real, distinct elevations.
    let mut level_storey_bind = crate::level_bind::LevelStoreyBind::new();
    if let Some(revit_version) = bfi.as_ref().map(|b| b.version) {
        apply_partition_level_storeys(
            rf,
            revit_version,
            &mut entities,
            &mut building_storeys,
            &mut level_storey_bind,
        );
    }

    // RE-14.3 / RE-15 — shared partition ArcWall path. Production
    // `iter_elements` also merges validated ArcWalls as
    // `DecodedElement`s for API consumers; IFC emission of those
    // walls remains here so storey indices from recovered elevations
    // stay attached. Dedup against walker-emitted ElementIds is
    // defensive (walker→IFC currently skips ArcWall class).
    //
    // See `reports/element-framing/RE-14.3-synthesis.md` and
    // `reports/element-framing/RE-15-arcwall-trailer-synthesis.md`.
    if let Some(revit_version) = bfi.as_ref().map(|b| b.version) {
        if let Ok(scan) = crate::partition_arc_walls::scan_partition_arc_walls_with_limits(
            rf,
            revit_version,
            walker_limits,
        ) {
            let level_names = collect_partition_building_storey_names(rf);
            let recovery = crate::partition_arc_walls::recover_storeys_from_arc_walls(
                &scan.walls,
                &level_names,
            );
            if building_storeys.is_empty() {
                building_storeys = recovery.storeys;
            }
            let existing_ids: std::collections::HashSet<u32> = entities
                .iter()
                .filter_map(|e| match e {
                    entities::IfcEntity::BuildingElement { type_guid, .. } => {
                        type_guid.as_ref().and_then(|g| g.parse().ok())
                    }
                    _ => None,
                })
                .collect();
            for wall in &scan.walls {
                if let Some(id) = wall.element_id() {
                    if existing_ids.contains(&id) {
                        continue;
                    }
                }
                let geometry = if policy.include_geometry {
                    arcwall_geometry_from_partition_wall(wall)
                } else {
                    None
                };
                let storey_index = wall.base_elevation_feet().and_then(|elev| {
                    crate::partition_arc_walls::storey_index_for_elevation(&building_storeys, elev)
                });
                let property_set = arcwall_property_set(wall);
                let name = match wall.element_id() {
                    Some(id) => format!("ArcWall-{id}"),
                    None => format!("ArcWall-{}-{}", wall.partition, wall.offset),
                };
                entities.push(entities::IfcEntity::BuildingElement {
                    ifc_type: "IFCWALL".to_string(),
                    name,
                    type_guid: wall.element_id().map(|id| id.to_string()),
                    predefined_type: category_map::lookup("ArcWall")
                        .and_then(|m| m.predefined_type)
                        .map(str::to_string),
                    storey_index,
                    material_index: None,
                    property_set,
                    location_feet: geometry.as_ref().map(|(location, _, _)| *location),
                    rotation_radians: geometry.as_ref().map(|(_, rotation, _)| *rotation),
                    extrusion: geometry.map(|(_, _, extrusion)| extrusion),
                    host_element_index: None,
                    material_layer_set_index: None,
                    material_profile_set_index: None,
                    solid_shape: None,
                    representation_map_index: None,
                });
            }
        }
    }

    // #219 / RE-27 — every element whose record named exactly one
    // Revit `Level` is contained in that Level's storey. Runs before
    // the #213 elevation join because the file *states* this binding
    // where the elevation join infers one, and the elevation join
    // leaves an already-bound element alone.
    apply_record_level_reference_storeys(&mut entities, &building_storeys, &level_storey_bind);

    // #213 — element-record base elevations become storey elevations,
    // then bind. Runs after every element source has contributed so it
    // sees the whole record set, and before the geometry strip so the
    // no-geometry modes (where no record bbox was attached in the
    // first place) find nothing to bind and change nothing.
    apply_element_record_storeys(&mut entities, &mut building_storeys);

    if !policy.include_geometry {
        export_content::strip_building_element_geometry(&mut entities);
    }

    let recovered_units = recover_project_units(rf);
    let global_ids = revit_model_global_ids(rf, &entities, &building_storeys, &element_type_ids);
    let (material_layer_sets, material_layer_usages) =
        material_layer_sets_from_layers(&mut entities, &element_layers, &mut materials);
    let mut material_constituent_sets =
        material_constituent_sets_from_types(&entities, &element_type_materials, &mut materials);
    let layer_constituent_sets = layer_materials_without_layer_sets(
        &mut entities,
        &element_layers,
        &unplaced_wall_layers,
        &material_constituent_sets,
        &mut materials,
    );
    material_constituent_sets.extend(layer_constituent_sets);
    let material_profile_sets =
        material_profile_sets_from_sections(&mut entities, &mut material_constituent_sets);
    let opening_cuts = opening_cuts_through_hosts(&entities);

    Ok(IfcModel {
        project_name,
        description,
        entities,
        classifications,
        units: recovered_units.assignments,
        building_storeys,
        materials,
        material_layer_sets,
        material_profile_sets,
        representation_maps: Vec::new(),
        global_ids,
        element_layers,
        material_layer_usages,
        element_type_materials,
        element_type_ids,
        material_constituent_sets,
        opening_cuts,
    })
}

/// #227: each door or window whose body is a plain rectangular extrusion
/// cuts its host wall exactly through the wall's thickness. The host's plan
/// outline is measured along both axes of the filling element's frame; the
/// axis on which it is thin (at most 3 ft, and under half its extent on the
/// other axis) crosses the wall, and the opening takes the band the outline
/// covers there. The other axis and the height keep the body's size. A host
/// at an angle to the element, or curved, is thick on both axes and keeps
/// the body-shaped opening.
fn opening_cuts_through_hosts(
    entities: &[entities::IfcEntity],
) -> std::collections::BTreeMap<usize, entities::OpeningCut> {
    const MAX_THICKNESS_FEET: f64 = 3.0;
    let mut cuts = std::collections::BTreeMap::new();
    for (index, entity) in entities.iter().enumerate() {
        let entities::IfcEntity::BuildingElement {
            host_element_index: Some(host),
            extrusion: Some(body),
            solid_shape: None,
            representation_map_index: None,
            location_feet: Some(location),
            rotation_radians,
            ..
        } = entity
        else {
            continue;
        };
        if body.profile_override.is_some() {
            continue;
        }
        let window_cut =
            |base: Option<entities::OpeningCut>| filler_type_cut(entity, base).or(base);
        if let Some(cut) = tapered_host_window_cut(entity, &entities[*host]) {
            if let Some(cut) = window_cut(Some(cut)) {
                cuts.insert(index, cut);
            }
            continue;
        }
        let Some(entities::IfcEntity::BuildingElement {
            location_feet: host_location,
            rotation_radians: host_rotation,
            ..
        }) = entities.get(*host)
        else {
            continue;
        };
        let Some((outline, _)) =
            body_geometry::element_body(&entities[*host], &[]).and_then(|host_body| {
                let host_placement = body_geometry::Placement::new(*host_location, *host_rotation);
                body_geometry::plan_outline(host_body, &host_placement)
            })
        else {
            if let Some(cut) = window_cut(None) {
                cuts.insert(index, cut);
            }
            continue;
        };
        let angle = rotation_radians.unwrap_or(0.0);
        let axes = [[angle.cos(), angle.sin()], [-angle.sin(), angle.cos()]];
        let band = |axis: [f64; 2]| {
            outline
                .iter()
                .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &(x, y)| {
                    let v = (x - location[0]) * axis[0] + (y - location[1]) * axis[1];
                    (lo.min(v), hi.max(v))
                })
        };
        let (x_band, y_band) = (band(axes[0]), band(axes[1]));
        let (x_width, y_width) = (x_band.1 - x_band.0, y_band.1 - y_band.0);
        let cut = if y_width <= MAX_THICKNESS_FEET && y_width < x_width / 2.0 && y_width > 0.0 {
            Some(entities::OpeningCut {
                x_dim_feet: body.width_feet,
                y_dim_feet: y_width,
                centre_feet: [0.0, (y_band.0 + y_band.1) / 2.0],
                z_range_feet: None,
            })
        } else if x_width <= MAX_THICKNESS_FEET && x_width < y_width / 2.0 && x_width > 0.0 {
            Some(entities::OpeningCut {
                x_dim_feet: x_width,
                y_dim_feet: body.depth_feet,
                centre_feet: [(x_band.0 + x_band.1) / 2.0, 0.0],
                z_range_feet: None,
            })
        } else {
            None
        };
        if let Some(cut) = window_cut(cut) {
            cuts.insert(index, cut);
        }
    }
    cuts
}

/// A length property of an element's own property set, feet.
fn length_property(entity: &entities::IfcEntity, wanted: &str) -> Option<f64> {
    let entities::IfcEntity::BuildingElement {
        property_set: Some(set),
        ..
    } = entity
    else {
        return None;
    };
    set.properties
        .iter()
        .find_map(|property| match &property.value {
            entities::PropertyValue::LengthFeet(value) if property.name == wanted => Some(*value),
            _ => None,
        })
}

/// RE-89: a window's opening in a tapered wall (RE-86), as Revit's export
/// cuts it: a vertical box its host type's thickness deep across the wall,
/// centred on the window's own origin (RE-87), and the window's width along
/// it. On Snowdon Towers every Solar Wall window's opening is centred there.
/// `None` unless the filler is a window turned along its host's line with
/// its origin read, and the host is tapered with its thickness read.
fn tapered_host_window_cut(
    filler: &entities::IfcEntity,
    host: &entities::IfcEntity,
) -> Option<entities::OpeningCut> {
    let entities::IfcEntity::BuildingElement {
        ifc_type,
        location_feet: Some(location),
        rotation_radians: Some(rotation),
        extrusion: Some(body),
        ..
    } = filler
    else {
        return None;
    };
    let entities::IfcEntity::BuildingElement {
        location_feet: Some(host_location),
        rotation_radians: Some(host_rotation),
        property_set: Some(host_set),
        ..
    } = host
    else {
        return None;
    };
    if !ifc_type.eq_ignore_ascii_case("IfcWindow")
        || !host_set.properties.iter().any(|property| {
            property.name == "BodySource"
                && matches!(&property.value, entities::PropertyValue::Text(source)
                    if source == export_content::WALL_TAPERED_BODY_SOURCE)
        })
    {
        return None;
    }
    let thickness = length_property(host, "Thickness").filter(|t| t.is_finite() && *t > 0.0)?;
    let [ox, oy] =
        export_content::INSTANCE_ORIGIN_PROPERTIES.map(|name| length_property(filler, name));
    let origin = [ox?, oy?];
    // The window must run along its host's line, either way.
    if (rotation - host_rotation).sin().abs() > 1e-6 {
        return None;
    }
    let host_left = [-host_rotation.sin(), host_rotation.cos()];
    let filler_left = [-rotation.sin(), rotation.cos()];
    let side = host_left[0] * filler_left[0] + host_left[1] * filler_left[1];
    let across = |point: [f64; 2]| {
        (point[0] - host_location[0]) * host_left[0] + (point[1] - host_location[1]) * host_left[1]
    };
    let offset = side * (across(origin) - across([location[0], location[1]]));
    offset.is_finite().then_some(entities::OpeningCut {
        x_dim_feet: body.width_feet,
        y_dim_feet: thickness,
        centre_feet: [0.0, offset],
        z_range_feet: None,
    })
}

/// A real property of an element's own property set.
fn real_property(entity: &entities::IfcEntity, wanted: &str) -> Option<f64> {
    let entities::IfcEntity::BuildingElement {
        property_set: Some(set),
        ..
    } = entity
    else {
        return None;
    };
    set.properties
        .iter()
        .find_map(|property| match &property.value {
            entities::PropertyValue::Real(value) if property.name == wanted => Some(*value),
            _ => None,
        })
}

/// How far a window's record box may reach past the opening its type gives
/// it on each side, feet (RE-93): the frame and trim around the opening.
/// On Snowdon Towers it is 0.21 to 0.26 ft; a box further off, or short of
/// the opening, is a window placed otherwise (a sill moved off its type's
/// default), which keeps the opening `base` gives it.
pub const WINDOW_TRIM_MAX_FEET: f64 = 0.5;

/// RE-93, RE-94: a window's or door's opening as Revit's export cuts it,
/// from its type ([`crate::partition_schema_mvp::FillerOpening`]), centred
/// on its origin along its X axis. Across the wall it keeps `base`'s band,
/// or the body's depth. `None` unless the element reports its opening
/// ([`export_content::FILLER_OPENING_PROPERTIES`]), its width runs along
/// one of its body's axes, and its record box holds the opening with at
/// most [`WINDOW_TRIM_MAX_FEET`] to spare on each side and at top and
/// bottom.
fn filler_type_cut(
    filler: &entities::IfcEntity,
    base: Option<entities::OpeningCut>,
) -> Option<entities::OpeningCut> {
    let entities::IfcEntity::BuildingElement {
        ifc_type,
        location_feet: Some(location),
        rotation_radians,
        extrusion: Some(body),
        ..
    } = filler
    else {
        return None;
    };
    if !ifc_type.eq_ignore_ascii_case("IfcWindow") && !ifc_type.eq_ignore_ascii_case("IfcDoor") {
        return None;
    }
    let [cx, cy, ax, ay, base_z, width, height] = export_content::FILLER_OPENING_PROPERTIES;
    let centre = [length_property(filler, cx)?, length_property(filler, cy)?];
    let [ax, ay] = [real_property(filler, ax)?, real_property(filler, ay)?];
    let base_z = length_property(filler, base_z)?;
    let width = positive_length_property(filler, width)?;
    let height = positive_length_property(filler, height)?;
    let angle = rotation_radians.unwrap_or(0.0);
    let local_x = [angle.cos(), angle.sin()];
    let local_y = [-angle.sin(), angle.cos()];
    let dot = |a: [f64; 2], b: [f64; 2]| a[0] * b[0] + a[1] * b[1];
    let offset = [centre[0] - location[0], centre[1] - location[1]];
    let along_x = (dot([ax, ay], local_x).abs() - 1.0).abs() <= 1e-6;
    let along_y = (dot([ax, ay], local_y).abs() - 1.0).abs() <= 1e-6;
    // An opening edge on the box's own edge fits, whatever the round-off.
    let spare = -1e-6..=WINDOW_TRIM_MAX_FEET;
    let fits = |lo: f64, hi: f64, box_lo: f64, box_hi: f64| {
        spare.contains(&(lo - box_lo)) && spare.contains(&(box_hi - hi))
    };
    let z0 = base_z - location[2];
    if !fits(z0, z0 + height, 0.0, body.height_feet) {
        return None;
    }
    // `base` crosses the wall on the axis the window's width does not run
    // along, or it is not this window's wall.
    if along_x && base.is_none_or(|cut| cut.x_dim_feet == body.width_feet) {
        let c = dot(offset, local_x);
        let half = body.width_feet / 2.0;
        fits(c - width / 2.0, c + width / 2.0, -half, half).then(|| {
            let (y_dim_feet, y_centre) = base.map_or((body.depth_feet, 0.0), |cut| {
                (cut.y_dim_feet, cut.centre_feet[1])
            });
            entities::OpeningCut {
                x_dim_feet: width,
                y_dim_feet,
                centre_feet: [c, y_centre],
                z_range_feet: Some([z0, height]),
            }
        })
    } else if along_y && base.is_none_or(|cut| cut.y_dim_feet == body.depth_feet) {
        let c = dot(offset, local_y);
        let half = body.depth_feet / 2.0;
        fits(c - width / 2.0, c + width / 2.0, -half, half).then(|| {
            let (x_dim_feet, x_centre) = base.map_or((body.width_feet, 0.0), |cut| {
                (cut.x_dim_feet, cut.centre_feet[0])
            });
            entities::OpeningCut {
                x_dim_feet,
                y_dim_feet: width,
                centre_feet: [x_centre, c],
                z_range_feet: Some([z0, height]),
            }
        })
    } else {
        None
    }
}

/// A positive length property of an element's own property set, feet.
fn positive_length_property(entity: &entities::IfcEntity, wanted: &str) -> Option<f64> {
    let entities::IfcEntity::BuildingElement {
        property_set: Some(set),
        ..
    } = entity
    else {
        return None;
    };
    set.properties
        .iter()
        .find_map(|property| match &property.value {
            entities::PropertyValue::PositiveLengthFeet(value) if property.name == wanted => {
                Some(*value)
            }
            _ => None,
        })
}

/// RE-82: one constituent set per distinct set of type materials, for each
/// element with no layer set, profile set or single material. Constituents
/// are in name order, as Revit's export writes them; materials not yet in
/// `materials` are added by name.
/// Material profile sets for the steel members drawn as their type's I
/// section (RE-103, RE-104, RE-105): one per type, named after it, pairing
/// its one material with the I its body is. Each such member takes the
/// profile set in place of its material constituent set, so it is written
/// with an `IfcMaterialProfileSetUsage`. A member whose constituent set holds
/// other than one material keeps it.
fn material_profile_sets_from_sections(
    entities: &mut [entities::IfcEntity],
    constituent_sets: &mut Vec<entities::MaterialConstituentSet>,
) -> Vec<entities::MaterialProfileSet> {
    let mut sets: Vec<entities::MaterialProfileSet> = Vec::new();
    for (entity_index, entity) in entities.iter_mut().enumerate() {
        let entities::IfcEntity::BuildingElement {
            property_set: Some(property_set),
            extrusion,
            solid_shape,
            material_profile_set_index,
            ..
        } = entity
        else {
            continue;
        };
        let text = |wanted: &str| {
            property_set
                .properties
                .iter()
                .find_map(|property| match &property.value {
                    entities::PropertyValue::Text(text) if property.name == wanted => {
                        Some(text.clone())
                    }
                    _ => None,
                })
        };
        if text("SectionShape").as_deref() != Some("I") {
            continue;
        }
        let Some(type_name) = text("TypeName") else {
            continue;
        };
        let profile = match (solid_shape.as_ref(), extrusion.as_ref()) {
            (
                Some(entities::SolidShape::PlacedExtrusion {
                    profile: profile @ entities::ProfileDef::IShape { .. },
                    ..
                }),
                _,
            ) => profile.clone(),
            (
                None,
                Some(entities::Extrusion {
                    profile_override: Some(profile @ entities::ProfileDef::IShape { .. }),
                    ..
                }),
            ) => profile.clone(),
            _ => continue,
        };
        let Some(constituents) = constituent_sets
            .iter_mut()
            .find(|set| set.elements.contains(&entity_index))
        else {
            continue;
        };
        let [material_index] = constituents.material_indices[..] else {
            continue;
        };
        constituents
            .elements
            .retain(|&element| element != entity_index);
        let existing = sets.iter().position(|set| {
            set.name == type_name
                && set.profiles.iter().all(|held| {
                    held.material_index == material_index && held.profile.as_ref() == Some(&profile)
                })
        });
        let index = existing.unwrap_or_else(|| {
            sets.push(entities::MaterialProfileSet {
                name: type_name.clone(),
                description: None,
                profiles: vec![entities::MaterialProfile {
                    material_index,
                    profile_name: type_name.clone(),
                    description: None,
                    profile: Some(profile.clone()),
                }],
            });
            sets.len() - 1
        });
        *material_profile_set_index = Some(index);
    }
    constituent_sets.retain(|set| !set.elements.is_empty());
    sets
}

fn material_constituent_sets_from_types(
    entities: &[entities::IfcEntity],
    element_type_materials: &std::collections::BTreeMap<u32, Vec<String>>,
    materials: &mut Vec<MaterialInfo>,
) -> Vec<entities::MaterialConstituentSet> {
    let mut sets: Vec<entities::MaterialConstituentSet> = Vec::new();
    let mut set_of: std::collections::BTreeMap<Vec<usize>, usize> = Default::default();
    for (entity_index, entity) in entities.iter().enumerate() {
        let entities::IfcEntity::BuildingElement {
            type_guid,
            material_index: None,
            material_layer_set_index: None,
            material_profile_set_index: None,
            ..
        } = entity
        else {
            continue;
        };
        let Some(names) = type_guid
            .as_deref()
            .and_then(|tag| tag.parse::<u32>().ok())
            .and_then(|id| element_type_materials.get(&id))
        else {
            continue;
        };
        let mut sorted: Vec<&String> = names.iter().collect();
        sorted.sort();
        sorted.dedup();
        let indices: Vec<usize> = sorted
            .into_iter()
            .map(
                |name| match materials.iter().position(|m| &m.name == name) {
                    Some(found) => found,
                    None => {
                        materials.push(MaterialInfo {
                            name: name.clone(),
                            color_packed: None,
                            transparency: None,
                        });
                        materials.len() - 1
                    }
                },
            )
            .collect();
        let set = *set_of.entry(indices.clone()).or_insert_with(|| {
            sets.push(entities::MaterialConstituentSet {
                material_indices: indices,
                names: Vec::new(),
                elements: Vec::new(),
            });
            sets.len() - 1
        });
        sets[set].elements.push(entity_index);
    }
    sets
}

/// The index of the material named `name` in `materials`, added with the
/// band's colour when it is not there yet; a material that has no colour
/// takes the band's.
fn layer_material_index(band: &LayerBand, name: &str, materials: &mut Vec<MaterialInfo>) -> usize {
    match materials.iter().position(|m| m.name == name) {
        Some(found) => {
            let material = &mut materials[found];
            if material.color_packed.is_none() && band.color_packed.is_some() {
                material.color_packed = band.color_packed;
                material.transparency = Some(band.transparency);
            }
            found
        }
        None => {
            materials.push(MaterialInfo {
                name: name.to_string(),
                color_packed: band.color_packed,
                transparency: band.color_packed.map(|_| band.transparency),
            });
            materials.len() - 1
        }
    }
}

/// RE-88: a wall whose layers are read but whose body is not a layer set
/// (tapered, curved, cut or profiled, RE-86, RE-75) takes them as Revit's
/// export does for any wall: a type of one layer its material, and a type
/// of several an unnamed constituent set of its layers, exterior first,
/// each named after its material and a material's k-th occurrence " (k)"
/// after it. On Snowdon Towers that is Revit's association on every wall
/// rvt-rs writes a layer set for (143 of 143 single materials, 823 of 824
/// constituent sets with the same materials, order and names).
///
/// Left alone: an element with a layer set, a material, a profile set or a
/// constituent set already (`taken`), a floor's, roof's or ceiling's
/// stacked layers, and a type with any layer whose material name is not
/// read.
fn layer_materials_without_layer_sets(
    entities: &mut [entities::IfcEntity],
    element_layers: &std::collections::BTreeMap<u32, ElementLayers>,
    unplaced_wall_layers: &std::collections::BTreeMap<u32, Vec<LayerBand>>,
    taken: &[entities::MaterialConstituentSet],
    materials: &mut Vec<MaterialInfo>,
) -> Vec<entities::MaterialConstituentSet> {
    let taken: std::collections::BTreeSet<usize> = taken
        .iter()
        .flat_map(|set| set.elements.iter().copied())
        .collect();
    let mut sets: Vec<entities::MaterialConstituentSet> = Vec::new();
    let mut set_of: std::collections::BTreeMap<(Vec<usize>, Vec<String>), usize> =
        Default::default();
    for (index, entity) in entities.iter_mut().enumerate() {
        let entities::IfcEntity::BuildingElement {
            type_guid,
            material_index,
            material_layer_set_index: None,
            material_profile_set_index: None,
            ..
        } = entity
        else {
            continue;
        };
        if material_index.is_some() || taken.contains(&index) {
            continue;
        }
        let id = type_guid.as_deref().and_then(|tag| tag.parse::<u32>().ok());
        let Some(layers) = id
            .and_then(|id| element_layers.get(&id))
            .filter(|layers| !layers.stacked)
            .map(|layers| &layers.layers)
            .or_else(|| id.and_then(|id| unplaced_wall_layers.get(&id)))
            .filter(|layers| !layers.is_empty())
        else {
            continue;
        };
        let Some(names) = layers
            .iter()
            .map(|band| band.name.clone())
            .collect::<Option<Vec<String>>>()
        else {
            continue;
        };
        let indices: Vec<usize> = layers
            .iter()
            .zip(&names)
            .map(|(band, name)| layer_material_index(band, name, materials))
            .collect();
        if let [only] = indices.as_slice() {
            *material_index = Some(*only);
            continue;
        }
        let mut seen: std::collections::BTreeMap<&str, usize> = Default::default();
        let labels: Vec<String> = names
            .iter()
            .map(|name| {
                let count = seen.entry(name.as_str()).or_insert(0);
                *count += 1;
                if *count == 1 {
                    name.clone()
                } else {
                    format!("{name} ({count})")
                }
            })
            .collect();
        let set = *set_of
            .entry((indices.clone(), labels.clone()))
            .or_insert_with(|| {
                sets.push(entities::MaterialConstituentSet {
                    material_indices: indices,
                    names: labels,
                    elements: Vec::new(),
                });
                sets.len() - 1
            });
        sets[set].elements.push(index);
    }
    sets
}

/// How a layered element's layers lie on its extruded body (RE-58): a
/// floor's, roof's or ceiling's from the top of the body down its third
/// axis; a wall's from its exterior face across the plan axis its exterior
/// normal runs along. `None` unless the layers add up to the body's
/// thickness within [`body_geometry::LAYER_THICKNESS_TOLERANCE_FEET`] and
/// a wall's exterior normal runs along one of its placement's plan axes.
fn material_layer_set_usage(
    layers: &ElementLayers,
    extrusion: &entities::Extrusion,
    rotation_radians: Option<f64>,
) -> Option<entities::MaterialLayerSetUsage> {
    let total: f64 = layers.layers.iter().map(|band| band.width_feet).sum();
    let fits =
        |extent: f64| (extent - total).abs() <= body_geometry::LAYER_THICKNESS_TOLERANCE_FEET;
    if layers.stacked {
        let height = extrusion.height_feet;
        return fits(height).then_some(entities::MaterialLayerSetUsage {
            direction: entities::LayerSetDirection::Axis3,
            positive: false,
            offset_feet: height,
        });
    }
    let (outer, _) = body_geometry::extrusion_rings(extrusion)?;
    let angle = rotation_radians.unwrap_or(0.0);
    let (cos, sin) = (angle.cos(), angle.sin());
    let [nx, ny] = layers.exterior_normal;
    let local = [nx * cos + ny * sin, -nx * sin + ny * cos];
    let (axis, direction, toward) = if local[1].abs() >= local[0].abs() {
        (1, entities::LayerSetDirection::Axis2, local[1])
    } else {
        (0, entities::LayerSetDirection::Axis1, local[0])
    };
    if local[1 - axis].abs() > 1e-6 {
        return None;
    }
    let coordinate = |p: &(f64, f64)| if axis == 0 { p.0 } else { p.1 };
    let (low, high) = outer
        .iter()
        .map(coordinate)
        .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| {
            (lo.min(v), hi.max(v))
        });
    if !fits(high - low) {
        return None;
    }
    Some(if toward > 0.0 {
        entities::MaterialLayerSetUsage {
            direction,
            positive: false,
            offset_feet: high,
        }
    } else {
        entities::MaterialLayerSetUsage {
            direction,
            positive: true,
            offset_feet: low,
        }
    })
}

/// A layer set's identity: its type name, and each layer's material and
/// thickness bits.
type LayerSetKey = (String, Vec<(Option<usize>, u64)>);

/// The material layer sets of layered elements (RE-58): one per type name
/// and layer sequence, shared by its elements, each layer with its material
/// where the material's name is read (added to `materials` with its colour
/// when it is not already there) and its thickness; and each element's
/// usage of its set, by entity index. An element with a single layer and no
/// named material gets none: the set would say only what its body does.
fn material_layer_sets_from_layers(
    entities: &mut [entities::IfcEntity],
    element_layers: &std::collections::BTreeMap<u32, ElementLayers>,
    materials: &mut Vec<MaterialInfo>,
) -> (
    Vec<entities::MaterialLayerSet>,
    std::collections::BTreeMap<usize, entities::MaterialLayerSetUsage>,
) {
    let mut sets: Vec<entities::MaterialLayerSet> = Vec::new();
    let mut set_of: std::collections::BTreeMap<LayerSetKey, usize> =
        std::collections::BTreeMap::new();
    let mut usages = std::collections::BTreeMap::new();
    for (index, entity) in entities.iter_mut().enumerate() {
        let entities::IfcEntity::BuildingElement {
            type_guid,
            extrusion: Some(extrusion),
            rotation_radians,
            material_layer_set_index,
            property_set,
            ..
        } = entity
        else {
            continue;
        };
        let Some(layers) = type_guid
            .as_deref()
            .and_then(|tag| tag.parse::<u32>().ok())
            .and_then(|id| element_layers.get(&id))
        else {
            continue;
        };
        if layers.layers.len() < 2 && layers.layers.iter().all(|band| band.name.is_none()) {
            continue;
        }
        let Some(usage) = material_layer_set_usage(layers, extrusion, *rotation_radians) else {
            continue;
        };
        let type_name = property_set
            .as_ref()
            .and_then(|set| {
                set.properties
                    .iter()
                    .find_map(|property| match &property.value {
                        entities::PropertyValue::Text(text)
                            if property.name == export_content::TYPE_NAME_PROPERTY =>
                        {
                            Some(text.clone())
                        }
                        _ => None,
                    })
            })
            .unwrap_or_default();
        let key: Vec<(Option<usize>, u64)> = layers
            .layers
            .iter()
            .map(|band| {
                let material = band.name.as_ref().map(|name| {
                    match materials.iter().position(|m| &m.name == name) {
                        Some(found) => {
                            let material = &mut materials[found];
                            if material.color_packed.is_none() && band.color_packed.is_some() {
                                material.color_packed = band.color_packed;
                                material.transparency = Some(band.transparency);
                            }
                            found
                        }
                        None => {
                            materials.push(MaterialInfo {
                                name: name.clone(),
                                color_packed: band.color_packed,
                                transparency: band.color_packed.map(|_| band.transparency),
                            });
                            materials.len() - 1
                        }
                    }
                });
                (material, band.width_feet.to_bits())
            })
            .collect();
        // Revit names a layer set `Family:Type` (RE-61).
        let set_name = match &layers.system_family {
            Some(family) if !type_name.is_empty() => format!("{family}:{type_name}"),
            _ => type_name,
        };
        let set = *set_of
            .entry((set_name.clone(), key.clone()))
            .or_insert_with(|| {
                sets.push(entities::MaterialLayerSet {
                    name: set_name,
                    layers: key
                        .iter()
                        .map(|&(material_index, width)| entities::MaterialLayer {
                            material_index,
                            thickness_feet: f64::from_bits(width),
                            name: None,
                        })
                        .collect(),
                    description: None,
                });
                sets.len() - 1
            });
        *material_layer_set_index = Some(set);
        usages.insert(index, usage);
    }
    (sets, usages)
}

/// Revit's own GlobalIds (RE-48): for each building element whose `Tag`
/// is an ElementId the file gives one to, by entity index, and for each
/// storey whose name is exactly one Level's (Revit keeps Level names
/// unique), that Level's. A Tag carried by more than one entity, such as
/// the further pieces of a slab (#331), goes to the first, so no GlobalId
/// is written twice.
fn revit_model_global_ids(
    rf: &mut crate::RevitFile,
    entities: &[entities::IfcEntity],
    storeys: &[Storey],
    element_type_ids: &std::collections::BTreeMap<u32, u32>,
) -> RevitGlobalIds {
    let mut out = RevitGlobalIds {
        document: rf
            .basic_file_info()
            .ok()
            .and_then(|info| info.document_guid().map(str::to_owned)),
        ..RevitGlobalIds::default()
    };
    let Ok(ids) = crate::revit_global_ids::revit_global_ids(rf) else {
        return out;
    };
    if ids.is_empty() {
        return out;
    }
    if let Ok(version) = rf.basic_file_info().map(|info| info.version) {
        let levels = crate::partition_level_records::recover_partition_levels(rf, version)
            .unwrap_or_default();
        for (index, storey) in storeys.iter().enumerate() {
            let mut named = levels.iter().filter(|level| level.name == storey.name);
            if let (Some(level), None) = (named.next(), named.next()) {
                if let Some(global_id) = ids.get(&level.element_id) {
                    out.storeys.insert(index, global_id.clone());
                }
            }
        }
    }
    let mut seen = std::collections::BTreeSet::new();
    for (index, entity) in entities.iter().enumerate() {
        let entities::IfcEntity::BuildingElement {
            type_guid: Some(tag),
            ..
        } = entity
        else {
            continue;
        };
        let Ok(id) = tag.parse::<u32>() else {
            continue;
        };
        if !seen.insert(id) {
            continue;
        }
        if let Some(global_id) = ids.get(&id) {
            out.elements.insert(index, global_id.clone());
        }
    }
    for type_id in element_type_ids.values() {
        if let Some(global_id) = ids.get(type_id) {
            out.types.insert(*type_id, global_id.clone());
        }
    }
    out
}

/// True when an emitted `IFCSLAB` carries no resolved thickness.
///
/// The property is written positively by the record-backed slab path
/// and negatively by the plan-loop annotation path, so a slab with
/// neither — or with `false` — is one whose extrusion depth rvt-rs
/// does not know.
fn slab_thickness_unresolved(entity: &entities::IfcEntity) -> bool {
    let entities::IfcEntity::BuildingElement {
        ifc_type,
        property_set,
        ..
    } = entity
    else {
        return false;
    };
    if ifc_type != "IFCSLAB" {
        return false;
    }
    !property_set.as_ref().is_some_and(|set| {
        set.properties.iter().any(|property| {
            property.name == "ThicknessResolved"
                && matches!(property.value, entities::PropertyValue::Boolean(true))
        })
    })
}

/// Property recorded on a building element whose body came from a
/// partition element record's bounding box.
pub(crate) const RECORD_BBOX_BODY_SOURCE: &str = "partition_element_record_bbox";

/// Property name carrying how an element reached its storey. Only
/// written when a storey was actually resolved, so its absence is the
/// honest "unbound" state rather than a claim of failure.
pub(crate) const STOREY_BIND_SOURCE_PROPERTY: &str = "StoreyBindSource";

/// Value of [`STOREY_BIND_SOURCE_PROPERTY`] for the #213 join.
pub(crate) const STOREY_BIND_RECORD_ELEVATION: &str = "record_base_elevation";

/// Value of [`STOREY_BIND_SOURCE_PROPERTY`] for the plate join —
/// see [`STOREY_BIND_TOP_FACE_TYPES`].
pub(crate) const STOREY_BIND_RECORD_TOP_ELEVATION: &str = "record_top_elevation";

/// IFC types whose record **top** face sits at the storey elevation.
///
/// Revit hangs a floor plate *below* the level that hosts it, so a
/// slab's recorded base is never a storey elevation while its top
/// often is. Measured over the 100 record-backed plates on
/// `2024_Core_Interior.rvt` against the storey Revit's own export
/// assigns each of them (#212, RE-22):
///
/// | join | bound | correct | wrong |
/// |---|---:|---:|---:|
/// | base `z` equals a recovered storey elevation | 0 | 0 | 0 |
/// | top `z` equals a recovered storey elevation | 51 | 51 | 0 |
///
/// The 49 that stay unbound sit either 2 in below their level (the
/// structural-slab / architectural-topping interface) or on one of
/// the four storeys #213's column-derived elevation set does not
/// contain. They keep `storey_index: None` rather than being placed
/// by proximity.
const STOREY_BIND_TOP_FACE_TYPES: &[&str] = &["IFCSLAB", "IFCSHADINGDEVICE"];

/// IFC types whose recorded base elevation *is* a storey elevation.
///
/// Measured on `2024_Core_Interior.rvt` against the fifteen
/// `IfcBuildingStorey.Elevation` values in Revit's own export, over the
/// element records the #211 instance rule selects:
///
/// | category | distinct base elevations | equal to a storey | not a storey |
/// |---|---:|---:|---:|
/// | `OST_Columns` | 11 | 11 | 0 |
/// | `OST_Doors` | 11 | 11 | 0 |
/// | `OST_Walls` | 13 | 12 (adds −40 ft) | 1 (56.4167 ft) |
/// | `OST_Windows` | 6 | 0 | 6 (sill heights: 80.73, 95.73, …) |
///
/// A window sits at its sill height above the level that hosts it, so
/// its record base is never a storey elevation; a wall may start
/// mid-storey. Only `IFCCOLUMN` therefore *supplies* elevations, which
/// keeps #213's measured "no false positives" claim exactly as it was
/// recorded. Every record-bodied element still *binds* to the
/// resulting set by exact match — see [`record_base_elevation_feet`].
const STOREY_ELEVATION_SOURCE_TYPES: &[&str] = &["IFCCOLUMN"];

/// Measured base elevation of an element that is allowed to define a
/// storey elevation (see [`STOREY_ELEVATION_SOURCE_TYPES`]).
fn record_storey_elevation_source_feet(entity: &entities::IfcEntity) -> Option<f64> {
    let entities::IfcEntity::BuildingElement { ifc_type, .. } = entity else {
        return None;
    };
    if !STOREY_ELEVATION_SOURCE_TYPES.contains(&ifc_type.as_str()) {
        return None;
    }
    record_base_elevation_feet(entity)
}

/// Measured elevation an element binds to a storey by, plus the
/// [`STOREY_BIND_SOURCE_PROPERTY`] value that says which face it is.
///
/// Plates bind by their top face
/// ([`STOREY_BIND_TOP_FACE_TYPES`]); everything else binds by its
/// base, exactly as #213 recorded.
fn record_storey_bind_elevation_feet(entity: &entities::IfcEntity) -> Option<(f64, &'static str)> {
    let base = record_base_elevation_feet(entity)?;
    let entities::IfcEntity::BuildingElement {
        ifc_type,
        extrusion,
        ..
    } = entity
    else {
        return None;
    };
    if !STOREY_BIND_TOP_FACE_TYPES.contains(&ifc_type.as_str()) {
        return Some((base, STOREY_BIND_RECORD_ELEVATION));
    }
    // Fail closed: without a recovered body there is no top face to
    // bind by, and the base is known not to be a storey elevation.
    let height = extrusion.as_ref()?.height_feet;
    if !height.is_finite() || height <= 0.0 {
        return None;
    }
    Some((base + height, STOREY_BIND_RECORD_TOP_ELEVATION))
}

/// Measured base elevation of an element whose body came from a
/// record bbox, in feet.
fn record_base_elevation_feet(entity: &entities::IfcEntity) -> Option<f64> {
    let entities::IfcEntity::BuildingElement {
        property_set,
        location_feet,
        ..
    } = entity
    else {
        return None;
    };
    // A wall whose joins resolved (RE-26) and a column its joined
    // walls cut (#239, RE-29) carry a different `BodySource`, and
    // both are still record-backed bodies: the wall solver only moves
    // the two plan ends of the run, and on the recorded edge no
    // column cut moves the box's `z` at either end — all 256 agree
    // with Revit's own world `z` exactly — so the elevation this
    // reads is the same byte in every case.
    let from_record = property_set.as_ref().is_some_and(|set| {
        set.properties.iter().any(|property| {
            property.name == "BodySource"
                && matches!(
                    &property.value,
                    entities::PropertyValue::Text(text)
                        if text == RECORD_BBOX_BODY_SOURCE
                            || text == crate::element_record_wall_joins::WALL_BODY_JOIN_TRIMMED
                            || text == crate::element_record_column_cuts::COLUMN_BODY_JOIN_CUT
                            || text == crate::element_record_beam_cuts::BEAM_BODY_COLUMN_CUT
                )
        })
    });
    if !from_record {
        return None;
    }
    location_feet.map(|[_, _, z]| z)
}

/// #218 / RE-24: replace the storey list with the Revit `Level`
/// elements recovered from the partition streams, names and
/// elevations together.
///
/// Fail closed twice over:
///
/// - [`crate::partition_level_records::scan_partition_levels`] returns
///   nothing unless every standalone `OST_Levels` record owns exactly
///   one accepted name/elevation block and no two levels share an
///   elevation. A partial recovery is never emitted as a smaller
///   building.
/// - Storey indices recorded against the previous list are dropped,
///   because they no longer refer to the same storeys.
///
/// Unlike [`apply_element_record_storeys`] this pairs a *name* with an
/// elevation, because the file states the pairing: the elevation is
/// read out of a parameter block whose owner slot carries the Level's
/// own `ElementId`, so nothing is joined by rank. See
/// `reports/element-framing/RE-24-level-records.md`.
fn apply_partition_level_storeys(
    rf: &mut crate::RevitFile,
    revit_version: u32,
    entities: &mut [entities::IfcEntity],
    building_storeys: &mut Vec<Storey>,
    level_storey_bind: &mut crate::level_bind::LevelStoreyBind,
) {
    let Ok(levels) = crate::partition_level_records::recover_partition_levels(rf, revit_version)
    else {
        return;
    };
    if levels.is_empty() {
        return;
    }
    for entity in entities.iter_mut() {
        if let entities::IfcEntity::BuildingElement { storey_index, .. } = entity {
            *storey_index = None;
        }
    }
    // RE-118: only a building story is a storey of Revit's export; a Level
    // that is not binds no element, which the later rules place.
    *building_storeys = levels
        .into_iter()
        .filter(|level| level.building_story != Some(false))
        .enumerate()
        .map(|(index, level)| {
            // The Level's own ElementId is what a building element's
            // record names (#219, RE-27), so the storey it became is
            // reachable by id rather than by rank or elevation.
            level_storey_bind.record_level(Some(level.element_id), index);
            Storey {
                name: level.name,
                elevation_feet: level.elevation_feet,
            }
        })
        .collect();
}

/// Value of [`STOREY_BIND_SOURCE_PROPERTY`] for the #219 join.
pub(crate) const STOREY_BIND_RECORD_LEVEL_REFERENCE: &str = "record_level_reference";

/// #219 / RE-27: contain each element in the storey of the Revit
/// `Level` its partition element record names.
///
/// The record's counted reference list at `+0x88` carries the host
/// Level as a plain ElementId slot;
/// [`crate::element_record_level_refs::unique_level_reference`] accepts
/// it when exactly one recovered Level is named. A column or wall that
/// names two, its base and top constraint, takes its base constraint
/// ([`crate::element_record_level_refs::base_constraint_level`], RE-59).
///
/// Fail closed twice more here:
///
/// - a named Level that is not in `level_storey_bind` — which holds
///   only the fifteen Levels #218's recovery validated — binds nothing;
/// - an index outside `building_storeys` binds nothing.
///
/// Measured on `2024_Core_Interior.rvt` against the #213 / #212
/// elevation join, over every element both joins answer: 537 of 537
/// agree, 0 disagree. See
/// `reports/element-framing/RE-27-level-reference-storey-bind.md`.
fn apply_record_level_reference_storeys(
    entities: &mut [entities::IfcEntity],
    building_storeys: &[Storey],
    level_storey_bind: &crate::level_bind::LevelStoreyBind,
) {
    if level_storey_bind.is_empty() {
        return;
    }
    for entity in entities.iter_mut() {
        let Some(level_id) = record_level_element_id(entity) else {
            continue;
        };
        let Some(index) = level_storey_bind.storey_index_for_level_id(level_id) else {
            continue;
        };
        if index >= building_storeys.len() {
            continue;
        }
        if let entities::IfcEntity::BuildingElement {
            storey_index,
            property_set,
            ..
        } = entity
        {
            *storey_index = Some(index);
            if let Some(set) = property_set.as_mut() {
                set.properties.push(entities::Property {
                    name: STOREY_BIND_SOURCE_PROPERTY.into(),
                    value: entities::PropertyValue::Text(STOREY_BIND_RECORD_LEVEL_REFERENCE.into()),
                });
            }
        }
    }
}

/// How an emitted element reached its storey, when it reached one.
fn storey_bind_source(entity: &entities::IfcEntity) -> Option<&str> {
    let entities::IfcEntity::BuildingElement { property_set, .. } = entity else {
        return None;
    };
    property_set
        .as_ref()?
        .properties
        .iter()
        .find_map(|property| {
            if property.name != STOREY_BIND_SOURCE_PROPERTY {
                return None;
            }
            match &property.value {
                entities::PropertyValue::Text(text) => Some(text.as_str()),
                _ => None,
            }
        })
}

/// The host `Level` ElementId an emitted element carries, when its
/// record named exactly one (#219, RE-27).
fn record_level_element_id(entity: &entities::IfcEntity) -> Option<u32> {
    let entities::IfcEntity::BuildingElement { property_set, .. } = entity else {
        return None;
    };
    property_set
        .as_ref()?
        .properties
        .iter()
        .find_map(|property| {
            if property.name != crate::element_record_level_refs::LEVEL_ELEMENT_ID_PROPERTY {
                return None;
            }
            match property.value {
                entities::PropertyValue::Integer(value) => u32::try_from(value).ok(),
                _ => None,
            }
        })
}

/// #213: derive storey elevations from the element-record bounding-box
/// distribution, then contain each recorded element in the storey whose
/// elevation matches its base.
///
/// Both halves fail closed:
///
/// - The storey set is replaced **only** when the recovered storeys
///   carry no elevation of their own (all at one value, which on the
///   current corpora means every Level row defaulted to 0.0) and at
///   least [`crate::element_record_storeys::MIN_DISTINCT_ELEVATIONS`]
///   distinct elevations were measured. A file whose ArcWall trailers
///   already gave real elevations keeps them.
/// - Binding is an exact elevation match, and an element whose base
///   matches no storey — or matches more than one — keeps
///   `storey_index: None` and falls to the writer's default container.
///
/// Level *names* are not paired with the measured elevations unless
/// there is exactly one name per elevation; see
/// [`crate::element_record_storeys`] for why a rank join is not
/// defensible on `2024_Core_Interior.rvt`.
fn apply_element_record_storeys(
    entities: &mut [entities::IfcEntity],
    building_storeys: &mut Vec<Storey>,
) {
    use crate::element_record_storeys as records;

    let measured = records::distinct_base_elevations_feet(
        entities
            .iter()
            .filter_map(record_storey_elevation_source_feet),
    );
    if measured.len() < records::MIN_DISTINCT_ELEVATIONS {
        return;
    }

    if records::storeys_lack_elevation_evidence(building_storeys) {
        let level_names: Vec<String> = building_storeys
            .iter()
            .map(|storey| storey.name.clone())
            .collect();
        let recovery = records::storeys_from_base_elevations(&measured, &level_names);
        if recovery.storeys.is_empty() {
            return;
        }
        // Storey indices recorded against the previous list no longer
        // mean anything; drop them rather than silently re-point an
        // element at an unrelated storey.
        for entity in entities.iter_mut() {
            if let entities::IfcEntity::BuildingElement { storey_index, .. } = entity {
                *storey_index = None;
            }
        }
        *building_storeys = recovery.storeys;
    }

    for entity in entities.iter_mut() {
        // An element the #219 reference join already placed keeps that
        // storey: the file states it, this join infers it.
        if matches!(
            entity,
            entities::IfcEntity::BuildingElement {
                storey_index: Some(_),
                ..
            }
        ) {
            continue;
        }
        let Some((elevation, bind_source)) = record_storey_bind_elevation_feet(entity) else {
            continue;
        };
        let Some(index) = records::unique_storey_index_for_elevation(building_storeys, elevation)
        else {
            continue;
        };
        if let entities::IfcEntity::BuildingElement {
            storey_index,
            property_set,
            ..
        } = entity
        {
            *storey_index = Some(index);
            if let Some(set) = property_set.as_mut() {
                set.properties.push(entities::Property {
                    name: STOREY_BIND_SOURCE_PROPERTY.into(),
                    value: entities::PropertyValue::Text(bind_source.into()),
                });
            }
        }
    }
}

/// Placeholder thickness used only when the ArcWall trailer has no
/// recoverable width (RE-15 / #88: exact 4/6/8/10/12″ values were
/// falsified in standard trailers). Callers must surface this via
/// property-set / diagnostics — it is not a decoded value. WallType
/// width join remains future work.
pub(crate) const UNRESOLVED_ARCWALL_THICKNESS_FEET: f64 = 8.0 / 12.0;

fn collect_partition_building_storey_names(rf: &mut crate::RevitFile) -> Vec<String> {
    let Ok(records) = rf.partition_string_records() else {
        return Vec::new();
    };
    crate::partition_name_candidates::building_storey_name_candidates(
        records.iter().map(|r| r.value.as_str()),
    )
}

fn arcwall_property_set(
    wall: &crate::partition_arc_walls::PartitionArcWall,
) -> Option<entities::PropertySet> {
    let mut properties = Vec::new();
    if let Some(id) = wall.element_id() {
        properties.push(entities::Property {
            name: "ElementId".into(),
            value: entities::PropertyValue::Integer(id as i64),
        });
    }
    if let Some(id) = wall.type_id() {
        properties.push(entities::Property {
            name: "TypeId".into(),
            value: entities::PropertyValue::Integer(id as i64),
        });
    }
    if let Some(elev) = wall.base_elevation_feet() {
        properties.push(entities::Property {
            name: "BaseElevation".into(),
            value: entities::PropertyValue::LengthFeet(elev),
        });
    }
    if let Some(height) = wall.height_feet() {
        properties.push(entities::Property {
            name: "UnconnectedHeight".into(),
            value: entities::PropertyValue::LengthFeet(height),
        });
    }
    properties.push(entities::Property {
        name: "ThicknessResolved".into(),
        value: entities::PropertyValue::Boolean(wall.thickness_feet().is_some()),
    });
    properties.push(entities::Property {
        name: "PartitionOffset".into(),
        value: entities::PropertyValue::Integer(wall.offset as i64),
    });
    properties.push(entities::Property {
        name: "PartitionStream".into(),
        value: entities::PropertyValue::Text(wall.partition.clone()),
    });
    if properties.is_empty() {
        None
    } else {
        Some(entities::PropertySet {
            name: "RvtArcWall".into(),
            properties,
        })
    }
}

fn arcwall_geometry_from_partition_wall(
    wall: &crate::partition_arc_walls::PartitionArcWall,
) -> Option<([f64; 3], f64, entities::Extrusion)> {
    arcwall_geometry_from_record(&wall.record, wall.thickness_feet())
}

fn arcwall_geometry_from_record(
    record: &crate::arc_wall_record::ArcWallRecord,
    thickness_feet: Option<f64>,
) -> Option<([f64; 3], f64, entities::Extrusion)> {
    let (sx, sy, sz) = record.start_point();
    let (ex, ey, ez) = record.end_point();
    if ![sx, sy, sz, ex, ey, ez]
        .into_iter()
        .all(|coord| coord.is_finite())
    {
        return None;
    }

    let length_feet = from_decoded::wall_segment_length_feet([sx, sy], [ex, ey]);
    if !length_feet.is_finite() || length_feet < 0.01 {
        return None;
    }

    // Height must come from the record Z delta — do not invent 10 ft.
    let height_feet = record.height_feet()?;
    let depth_feet = thickness_feet.unwrap_or(UNRESOLVED_ARCWALL_THICKNESS_FEET);
    let location_feet = [(sx + ex) / 2.0, (sy + ey) / 2.0, sz.min(ez)];
    let rotation_radians = from_decoded::wall_segment_angle_radians([sx, sy], [ex, ey]);
    Some((
        location_feet,
        rotation_radians,
        entities::Extrusion {
            width_feet: length_feet,
            depth_feet,
            height_feet,
            profile_override: None,
        },
    ))
}

#[derive(Debug, Default)]
struct RecoveredProjectUnits {
    assignments: Vec<entities::UnitAssignment>,
    unknown_identifiers: Vec<String>,
}

#[derive(Debug, Clone)]
struct UnitCandidate {
    identifier: String,
    count: usize,
    mapping: String,
}

fn recover_project_units(rf: &mut crate::RevitFile) -> RecoveredProjectUnits {
    // `Global/Latest` includes Forge vocabulary tables in newer files;
    // those are catalog entries, not project-selected display units.
    // The observed project unit/spec records live in `Partitions/NN`.
    let records = rf.partition_string_records().unwrap_or_default();
    recover_project_units_from_identifiers(records.iter().map(|record| record.value.as_str()))
}

fn recover_project_units_from_identifiers<I, S>(identifiers: I) -> RecoveredProjectUnits
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut counts = std::collections::BTreeMap::<String, usize>::new();
    for identifier in identifiers {
        let value = identifier.as_ref().trim();
        if value.starts_with("autodesk.unit.") {
            *counts.entry(value.to_string()).or_insert(0) += 1;
        }
    }

    let mut per_type = std::collections::HashMap::<entities::IfcUnitType, UnitCandidate>::new();
    let mut unknown_identifiers = Vec::new();
    for (identifier, count) in counts {
        let forge_unit = entities::ForgeUnit::from_forge_identifier(&identifier);
        let Some(emission) = forge_unit.ifc_emission() else {
            unknown_identifiers.push(identifier);
            continue;
        };
        let unit_type = unit_type_for_emission(&emission);
        let candidate = UnitCandidate {
            identifier,
            count,
            mapping: ifc_mapping_label(&emission),
        };
        match per_type.get(&unit_type) {
            Some(current)
                if current.count > candidate.count
                    || (current.count == candidate.count
                        && current.identifier <= candidate.identifier) => {}
            _ => {
                per_type.insert(unit_type, candidate);
            }
        }
    }

    let assignments = [
        entities::IfcUnitType::Length,
        entities::IfcUnitType::Area,
        entities::IfcUnitType::Volume,
        entities::IfcUnitType::PlaneAngle,
        entities::IfcUnitType::Mass,
        entities::IfcUnitType::Time,
    ]
    .into_iter()
    .filter_map(|unit_type| per_type.remove(&unit_type))
    .map(|candidate| entities::UnitAssignment {
        forge_identifier: candidate.identifier,
        ifc_mapping: Some(candidate.mapping),
    })
    .collect();

    RecoveredProjectUnits {
        assignments,
        unknown_identifiers,
    }
}

fn unit_type_for_emission(emission: &entities::IfcUnitEmission) -> entities::IfcUnitType {
    match emission {
        entities::IfcUnitEmission::Si { unit_type, .. }
        | entities::IfcUnitEmission::ConversionBased { unit_type, .. } => *unit_type,
    }
}

fn ifc_mapping_label(emission: &entities::IfcUnitEmission) -> String {
    match emission {
        entities::IfcUnitEmission::Si {
            unit_type,
            prefix,
            name,
        } => match prefix {
            Some(prefix) => format!("{}:{prefix}:{name}", unit_type.as_step_token()),
            None => format!("{}:{name}", unit_type.as_step_token()),
        },
        entities::IfcUnitEmission::ConversionBased {
            unit_type,
            derived_name,
            factor_to_si,
            si_base_name,
        } => format!(
            "{}:{derived_name}:factor_to_{si_base_name}={factor_to_si}",
            unit_type.as_step_token()
        ),
    }
}

/// What the production walker's elements give beside their entities: each
/// layered element's layers (RE-53), the materials each element's type
/// draws in (RE-82), and the layers of walls their data does not place
/// (RE-88), all by ElementId.
type WalkerElementData = (
    std::collections::BTreeMap<u32, ElementLayers>,
    std::collections::BTreeMap<u32, Vec<String>>,
    std::collections::BTreeMap<u32, Vec<LayerBand>>,
    std::collections::BTreeMap<u32, u32>,
);

fn append_production_walker_elements(
    rf: &mut crate::RevitFile,
    entities: &mut Vec<entities::IfcEntity>,
    building_storeys: &mut Vec<Storey>,
    materials: &mut Vec<MaterialInfo>,
    policy: export_content::ExportContentPolicy,
    walker_limits: crate::walker::WalkerLimits,
) -> WalkerElementData {
    if let Ok(decoded_iter) = crate::walker::iter_elements_with_limits(
        rf,
        crate::walker::PRODUCTION_ELEMENT_MIN_SCORE,
        walker_limits,
    ) {
        // M3-07: hide low-confidence rows from default IFC emission.
        let filtered = decoded_iter
            .filter(|e| e.meets_confidence(crate::walker::DEFAULT_MIN_ELEMENT_CONFIDENCE));
        let append = export_content::append_typed_production_elements(
            filtered,
            entities,
            building_storeys,
            policy,
        );
        materials.extend(append.materials);
        return (
            append.element_layers,
            append.element_type_materials,
            append.unplaced_wall_layers,
            append.element_type_ids,
        );
    }
    Default::default()
}

fn append_diagnostic_walker_proxy_candidates(
    rf: &mut crate::RevitFile,
    entities: &mut Vec<entities::IfcEntity>,
    walker_limits: crate::walker::WalkerLimits,
) {
    for candidate in collect_diagnostic_walker_proxy_candidates(rf, walker_limits).candidates {
        let name = match candidate.decoded.id {
            Some(id) => format!("{}-{}", candidate.decoded.class, id),
            None => format!(
                "{}-offset-{:x}",
                candidate.decoded.class, candidate.decoded.byte_range.start
            ),
        };
        let property_set = diagnostic_candidate_property_set(&candidate.decoded, candidate.score);

        entities.push(entities::IfcEntity::BuildingElement {
            ifc_type: "IFCBUILDINGELEMENTPROXY".to_string(),
            name,
            type_guid: candidate.decoded.id.map(|id| id.to_string()),
            // Diagnostic candidates are unclassified by construction —
            // asserting a PredefinedType would be a claim the scan
            // cannot make. The slot is still written, as `$`.
            predefined_type: None,
            storey_index: None,
            material_index: None,
            property_set: Some(property_set),
            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,
        });
    }
}

#[derive(Debug, Clone)]
struct DiagnosticProxyCandidate {
    decoded: crate::walker::DecodedElement,
    score: i64,
}

#[derive(Debug, Default, Clone)]
struct DiagnosticProxyCandidateCollection {
    candidates: Vec<DiagnosticProxyCandidate>,
    warnings: Vec<String>,
}

fn collect_diagnostic_walker_proxy_candidates(
    rf: &mut crate::RevitFile,
    walker_limits: crate::walker::WalkerLimits,
) -> DiagnosticProxyCandidateCollection {
    let mut collection = DiagnosticProxyCandidateCollection::default();

    let formats_raw = match rf.read_stream(crate::streams::FORMATS_LATEST) {
        Ok(raw) => raw,
        Err(err) => {
            collection
                .warnings
                .push(format!("Unable to read Formats/Latest: {err}"));
            return collection;
        }
    };
    let formats_d = match crate::compression::inflate_stream_at(
        crate::streams::FORMATS_LATEST,
        &formats_raw,
        0,
    ) {
        Ok(bytes) => bytes,
        Err(err) => {
            collection
                .warnings
                .push(format!("Unable to inflate Formats/Latest: {err}"));
            return collection;
        }
    };
    let schema = match crate::formats::parse_schema(&formats_d) {
        Ok(schema) => schema,
        Err(err) => {
            collection
                .warnings
                .push(format!("Unable to parse Formats/Latest schema: {err}"));
            return collection;
        }
    };
    let raw = match rf.read_stream(crate::streams::GLOBAL_LATEST) {
        Ok(raw) => raw,
        Err(err) => {
            collection
                .warnings
                .push(format!("Unable to read Global/Latest: {err}"));
            return collection;
        }
    };
    let (_, latest) =
        match crate::compression::inflate_stream_auto(crate::streams::GLOBAL_LATEST, &raw) {
            Ok(inflated) => inflated,
            Err(err) => {
                collection
                    .warnings
                    .push(format!("Unable to inflate Global/Latest: {err}"));
                return collection;
            }
        };

    let class_by_name: std::collections::HashMap<&str, &crate::formats::ClassEntry> = schema
        .classes
        .iter()
        .map(|class| (class.name.as_str(), class))
        .collect();
    let scan = crate::walker::scan_candidates_with_limits(
        &schema,
        &latest,
        crate::walker::DIAGNOSTIC_ELEMENT_MIN_SCORE,
        walker_limits,
    );
    if let Some(hit) = scan.limit_hit {
        collection
            .warnings
            .push(format!("{}: {}", hit.code(), hit.message()));
    }
    let mut seen_ids = std::collections::BTreeSet::<u32>::new();
    let mut seen_offsets = std::collections::BTreeSet::<usize>::new();

    for candidate in scan.candidates {
        if candidate.score >= crate::walker::PRODUCTION_ELEMENT_MIN_SCORE {
            continue;
        }
        let Some(class) = class_by_name.get(candidate.class_name.as_str()).copied() else {
            continue;
        };
        let mut decoded = crate::walker::decode_instance_with_limits(
            &latest,
            candidate.offset,
            class,
            walker_limits,
        );
        let self_id = crate::walker::find_self_id_field(class)
            .and_then(|index| decoded.fields.get(index))
            .and_then(|(_, field)| match field {
                crate::walker::InstanceField::ElementId { id, .. } if *id != 0 => Some(*id),
                _ => None,
            });
        if let Some(id) = self_id {
            if !seen_ids.insert(id) {
                continue;
            }
            decoded.id = Some(id);
        } else if !seen_offsets.insert(candidate.offset) {
            continue;
        }

        collection.candidates.push(DiagnosticProxyCandidate {
            decoded,
            score: candidate.score,
        });
    }

    collection
}

fn diagnostic_candidate_property_set(
    decoded: &crate::walker::DecodedElement,
    score: i64,
) -> entities::PropertySet {
    let mut properties = vec![
        entities::Property {
            name: "DiagnosticReason".into(),
            value: entities::PropertyValue::Text(
                "low-confidence schema scan candidate; omitted from default export".into(),
            ),
        },
        entities::Property {
            name: "DecodedClass".into(),
            value: entities::PropertyValue::Text(decoded.class.clone()),
        },
        entities::Property {
            name: "SourceStream".into(),
            value: entities::PropertyValue::Text(crate::streams::GLOBAL_LATEST.into()),
        },
        entities::Property {
            name: "ByteStart".into(),
            value: entities::PropertyValue::Integer(usize_to_i64_saturating(
                decoded.byte_range.start,
            )),
        },
        entities::Property {
            name: "ByteEnd".into(),
            value: entities::PropertyValue::Integer(usize_to_i64_saturating(
                decoded.byte_range.end,
            )),
        },
        entities::Property {
            name: "CandidateScore".into(),
            value: entities::PropertyValue::Integer(score),
        },
    ];
    if let Some(id) = decoded.id {
        properties.push(entities::Property {
            name: "ElementId".into(),
            value: entities::PropertyValue::Integer(i64::from(id)),
        });
    }

    entities::PropertySet {
        name: "Pset_RvtRsDiagnosticCandidate".into(),
        properties,
    }
}

fn usize_to_i64_saturating(value: usize) -> i64 {
    i64::try_from(value).unwrap_or(i64::MAX)
}

/// Build the JSON diagnostics sidecar for an exported IFC model.
///
/// This function is intentionally best-effort: stream/schema failures are
/// reported in `warnings` instead of making the already-created IFC model
/// unusable for bug reports.
pub fn build_export_diagnostics(
    rf: &mut crate::RevitFile,
    model: &IfcModel,
    mode: ExportDiagnosticsMode,
) -> ExportDiagnostics {
    build_export_diagnostics_with_limits(rf, model, mode, crate::walker::WalkerLimits::default())
}

pub fn build_export_diagnostics_with_limits(
    rf: &mut crate::RevitFile,
    model: &IfcModel,
    mode: ExportDiagnosticsMode,
    walker_limits: crate::walker::WalkerLimits,
) -> ExportDiagnostics {
    let bfi = rf.basic_file_info().ok();
    let part = rf.part_atom().ok();
    let stream_names = rf.stream_names();
    let diagnostic_candidates = collect_diagnostic_walker_proxy_candidates(rf, walker_limits);
    let exported = exported_model_diagnostics(model);
    let diagnostic_proxy_elements = count_diagnostic_proxy_elements(model);
    let arcwall_records = count_arcwall_records(model);
    let candidate_class_counts = diagnostic_candidate_class_counts(&diagnostic_candidates);
    let walker_stats = production_walker_stats(rf, walker_limits);
    let production_class_counts = walker_stats.class_counts.clone();
    // Match Python `decoded_elements()` / `element_counts()["total"]`:
    // count every production `iter_elements` hit (Levels/Materials
    // included), not only IFC BuildingElement rows.
    let production_walker_elements: usize = production_class_counts.values().copied().sum();

    let mut skipped = Vec::new();
    if walker_stats.elements_below_min_confidence > 0 {
        skipped.push(SkippedExportItem {
            reason: "below_min_element_confidence".into(),
            count: walker_stats.elements_below_min_confidence,
            classes: std::collections::BTreeMap::new(),
            sample_names: Vec::new(),
        });
    }
    if mode == ExportDiagnosticsMode::Default && !diagnostic_candidates.candidates.is_empty() {
        skipped.push(SkippedExportItem {
            reason: "low_confidence_schema_scan_candidate".into(),
            count: diagnostic_candidates.candidates.len(),
            classes: candidate_class_counts.clone(),
            sample_names: diagnostic_candidates
                .candidates
                .iter()
                .take(12)
                .map(diagnostic_candidate_display_name)
                .collect(),
        });
    }
    let geometry_gaps = geometry_gap_skipped_items(model);
    skipped.extend(geometry_gaps.iter().cloned());
    // RE-30: element frames of a recovered category that carry no
    // attributable ElementId are rejected by the fail-closed decode, so a
    // file made mostly of them exports a fraction of its model while
    // looking complete. Count them so the sidecar says so.
    let unattributed_frames = bfi
        .as_ref()
        .and_then(|b| {
            crate::partition_element_records::scan_unattributed_frames(rf, b.version).ok()
        })
        .unwrap_or_default();
    let unattributed_total: usize = unattributed_frames.values().sum();
    if unattributed_total > 0 {
        skipped.push(SkippedExportItem {
            reason: "element_record_without_element_id".into(),
            count: unattributed_total,
            classes: unattributed_frames,
            sample_names: Vec::new(),
        });
    }
    // #309: placed instances with no 3D body are left out by design, as
    // Revit's own export leaves them out. They are not missing, so they
    // do not count toward `unexported_element_records`.
    let volumeless = bfi
        .as_ref()
        .and_then(|b| {
            crate::partition_element_records::scan_volumeless_instances(rf, b.version).ok()
        })
        .unwrap_or_default();
    let volumeless_total: usize = volumeless.values().sum();
    if volumeless_total > 0 {
        skipped.push(SkippedExportItem {
            reason: "element_record_without_volume".into(),
            count: volumeless_total,
            classes: volumeless,
            sample_names: Vec::new(),
        });
    }
    // #319: elements in a non-primary design option are left out as
    // Revit's own export leaves them out. They are not missing either.
    let non_primary = bfi
        .as_ref()
        .and_then(|b| {
            crate::partition_design_options::scan_non_primary_option_instances(rf, b.version).ok()
        })
        .unwrap_or_default();
    let non_primary_total: usize = non_primary.values().sum();
    if non_primary_total > 0 {
        skipped.push(SkippedExportItem {
            reason: "element_record_in_non_primary_design_option".into(),
            count: non_primary_total,
            classes: non_primary,
            sample_names: Vec::new(),
        });
    }
    // #309: empty curtain panels are left out as Revit's own export leaves
    // them out, recognised by their family's name. A type of theirs with a
    // material set would contradict that name, and is reported.
    let empty_panels = bfi
        .as_ref()
        .and_then(|b| crate::partition_schema_mvp::scan_empty_curtain_panels(rf, b.version).ok())
        .unwrap_or_default();
    if empty_panels.count > 0 {
        skipped.push(SkippedExportItem {
            reason: "element_record_empty_curtain_panel".into(),
            count: empty_panels.count,
            classes: std::collections::BTreeMap::from([(
                "CurtainWallPanel".to_string(),
                empty_panels.count,
            )]),
            sample_names: Vec::new(),
        });
    }

    let recovered_units = recover_project_units(rf);
    let mut warnings = diagnostic_candidates.warnings;
    if !empty_panels.types_with_material.is_empty() {
        warnings.push(format!(
            "{} empty curtain panel type(s) carry a material, which an empty panel should not: {:?}",
            empty_panels.types_with_material.len(),
            empty_panels.types_with_material
        ));
    }
    // Surface ArcWall partition-scan limit hits so crafted large
    // Partitions/* streams are visible in the diagnostics sidecar.
    if let Some(version) = bfi.as_ref().map(|b| b.version) {
        if let Ok(scan) = crate::partition_arc_walls::scan_partition_arc_walls_with_limits(
            rf,
            version,
            walker_limits,
        ) {
            if let Some(hit) = scan.limit_hit {
                warnings.push(format!("{}: {}", hit.code(), hit.message()));
            }
        }
    }
    if exported.building_elements == 0 {
        warnings.push("No building elements were exported; output is scaffold-only.".into());
    } else if bfi.as_ref().map(|b| b.version)
        == Some(crate::partition_element_records_2023::REVIT_2023)
    {
        // RE-81, RE-102, RE-107, RE-109, RE-111 to RE-115: what a 2023 export carries, and what it does not.
        warnings.push(
            "Revit 2023: elements come from their records with their ElementId, category and \
             bounding box, doors and windows with their host wall, rooms with their outline, \
             and, where its Levels are read, each element on the storey of the Level its \
             record names; family instances, walls, floors and roofs carry their family and \
             type names, and family instances their type's materials. Layers become \
             material layer sets where their materials are named, a layer that takes its \
             category's material taking the object styles' one, and walls keep their record box. \
             Wall joins and profiles, design options, parameters and \
             \"Export to IFC As\" overrides are not read for 2023, and components nested in \
             doors and windows are left out."
                .into(),
        );
    }
    append_geometry_gap_warnings(&mut warnings, &exported, &geometry_gaps);
    if model.units.is_empty() {
        warnings
            .push("No Revit display units were recovered; the IFC declares the SI units its values are written in.".into());
    }
    let mut unmapped_unit_values: Vec<_> = recovered_units
        .unknown_identifiers
        .iter()
        .filter(|identifier| identifier.starts_with("autodesk.unit.unit:"))
        .cloned()
        .collect();
    if !unmapped_unit_values.is_empty() {
        let sample = {
            unmapped_unit_values.truncate(8);
            unmapped_unit_values
        };
        warnings.push(format!(
            "Unmapped Revit unit identifiers were preserved in diagnostics: {}",
            sample.join(", ")
        ));
    }
    if model.building_storeys.is_empty() {
        warnings.push(
            "No Revit levels were recovered; STEP output uses the fallback spatial storey.".into(),
        );
    } else {
        let elevation_fallback = model
            .building_storeys
            .iter()
            .filter(|storey| storey.name.starts_with("Elevation "))
            .count();
        let named = model.building_storeys.len() - elevation_fallback;
        // #219 / RE-27: how many elements reached their storey through
        // the Level ElementId their record names, rather than through
        // an inferred elevation match.
        let level_reference_bound = model
            .entities
            .iter()
            .filter(|entity| storey_bind_source(entity) == Some(STOREY_BIND_RECORD_LEVEL_REFERENCE))
            .count();
        if named > 0 && level_reference_bound == 0 {
            warnings.push(format!(
                "{named} building storey name(s) came from partition Level-like strings (RE-15/#86 via PR #117); ElementId↔Level binding is still pending."
            ));
        } else if named > 0 {
            warnings.push(format!(
                "{named} building storey name(s) came from partition Level records; {level_reference_bound} building element(s) reached their storey through the Level ElementId their own element record names (#219, RE-27; the base constraint where it names two, RE-59), the rest through a measured elevation match."
            ));
        }
        if elevation_fallback > 0 {
            warnings.push(format!(
                "{elevation_fallback} building storey(s) lack a confident partition Level name and keep elevation fallback labels."
            ));
        }
        // #213: when the storey elevations were measured from element
        // records, say so, and say how many recovered Level names went
        // unplaced — a reader comparing `storey_count` against the
        // recovered `Level` class count should not have to guess why
        // the two differ.
        let level_names = production_class_counts
            .get("Level")
            .copied()
            .unwrap_or_default();
        if elevation_fallback == model.building_storeys.len() && exported.storey_bound_elements > 0
        {
            warnings.push(format!(
                "{} building storey elevation(s) were measured from partition element-record bounding boxes and {} building element(s) bound to them by an exact record-face elevation match (base face, or top face for slabs and shading devices) (#213, #212); the {level_names} recovered Level name string(s) could not be paired with those elevations and are not asserted as storey names.",
                model.building_storeys.len(),
                exported.storey_bound_elements,
            ));
        }
    }
    let unresolved_thickness = model
        .entities
        .iter()
        .filter(|entity| {
            matches!(
                entity,
                entities::IfcEntity::BuildingElement {
                    name,
                    property_set: Some(pset),
                    ..
                } if name.starts_with("ArcWall-")
                    && pset.properties.iter().any(|p| {
                        p.name == "ThicknessResolved"
                            && matches!(p.value, entities::PropertyValue::Boolean(false))
                    })
            )
        })
        .count();
    if unresolved_thickness > 0 {
        warnings.push(format!(
            "{unresolved_thickness} ArcWall records lack recovered thickness; RE-15/#88 falsified exact inch widths in the standard trailer, so IFC depth uses an unresolved placeholder pending WallType width join."
        ));
    }
    if let Some(item) = skipped
        .iter()
        .find(|item| item.reason == "low_confidence_schema_scan_candidate")
    {
        warnings.push(format!(
            "Suppressed {} low-confidence schema scan candidates from default export.",
            item.count
        ));
    }
    if unattributed_total > 0 {
        // First, because it is the one that changes what the output is
        // good for, and the viewer shows only the first warning inline.
        warnings.insert(
            0,
            format!(
                "{unattributed_total} model element record(s) in this file use an element-record layout whose ElementId this release cannot locate, so they are not exported and the model is incomplete (RE-30)."
            ),
        );
    }
    if mode == ExportDiagnosticsMode::DiagnosticProxies && diagnostic_proxy_elements > 0 {
        warnings.push(
            "Diagnostic proxy elements are low-confidence scan candidates, not validated model elements."
                .into(),
        );
    }
    if mode == ExportDiagnosticsMode::Placeholder {
        warnings.push("Placeholder export mode omits decoded elements by design.".into());
    }

    let formats_latest_integrity = match rf.read_stream(crate::streams::FORMATS_LATEST) {
        Ok(stored) => {
            let diag = crate::compression::diagnose_formats_latest_integrity(&stored);
            if diag.integrity_status == crate::compression::FormatsIntegrityStatus::Uncertain {
                warnings.push(format!(
                    "Formats/Latest multipage integrity uncertain (checksum-page strip disabled; {}).",
                    crate::compression::RVT_FORMATS_MULTIPAGE_UNVERIFIED
                ));
            }
            Some(diag)
        }
        Err(_) => None,
    };

    let has_project_metadata = model.project_name.is_some()
        || bfi.is_some()
        || part.as_ref().and_then(|p| p.title.as_ref()).is_some();
    let confidence = export_confidence_summary(
        mode,
        &exported,
        has_project_metadata,
        diagnostic_proxy_elements,
        warnings.len(),
        unattributed_total,
    );

    ExportDiagnostics {
        schema_version: EXPORT_DIAGNOSTICS_SCHEMA_VERSION,
        mode,
        input: ExportInputDiagnostics {
            revit_version: bfi.as_ref().map(|b| b.version),
            build: bfi.as_ref().and_then(|b| b.build.clone()),
            original_path: bfi
                .as_ref()
                .and_then(|b| b.original_path.as_ref())
                .map(|path| crate::redact::redact_sensitive(path)),
            project_name: model
                .project_name
                .clone()
                .or_else(|| part.as_ref().and_then(|p| p.title.clone())),
            stream_count: stream_names.len(),
            has_basic_file_info: bfi.is_some(),
            has_part_atom: part.is_some(),
            has_formats_latest: stream_names
                .iter()
                .any(|name| name == crate::streams::FORMATS_LATEST),
            has_global_latest: stream_names
                .iter()
                .any(|name| name == crate::streams::GLOBAL_LATEST),
        },
        decoded: DecodedExportDiagnostics {
            production_walker_elements,
            diagnostic_proxy_candidates: diagnostic_candidates.candidates.len(),
            arcwall_records,
            class_counts: candidate_class_counts,
            parameter_value_count: parameter_value_count_from_class_counts(
                &production_class_counts,
            ),
            production_class_counts,
            mean_element_confidence: walker_stats.mean_element_confidence,
            elements_below_min_confidence: walker_stats.elements_below_min_confidence,
            min_element_confidence: crate::walker::DEFAULT_MIN_ELEMENT_CONFIDENCE,
            recovered_unit_identifiers: model
                .units
                .iter()
                .map(|unit| unit.forge_identifier.clone())
                .collect(),
            unknown_unit_identifiers: recovered_units.unknown_identifiers,
        },
        source_coverage: {
            let coverage = SourceCoverageDiagnostics::measure(
                production_walker_elements,
                exported.building_elements,
                exported.building_elements_with_geometry,
                elem_table_declared_element_count(rf),
            );
            Some(coverage)
        },
        exported,
        skipped,
        unsupported_features: unsupported_export_features(model),
        warnings,
        confidence,
        formats_latest_integrity,
    }
}

fn exported_model_diagnostics(model: &IfcModel) -> ExportedModelDiagnostics {
    let mut by_ifc_type = std::collections::BTreeMap::<String, usize>::new();
    let mut building_elements = 0usize;
    let mut building_elements_with_geometry = 0usize;
    let mut storey_bound_elements = 0usize;
    let wholes: std::collections::BTreeSet<usize> = model
        .entities
        .iter()
        .filter_map(|entity| match entity {
            entities::IfcEntity::Aggregate { whole, .. } => Some(*whole),
            _ => None,
        })
        .collect();
    let mut building_elements_carried_by_parts = 0usize;
    let mut body_sources = std::collections::BTreeMap::<String, usize>::new();
    let mut bounding_box_bodies = 0usize;
    for (index, entity) in model.entities.iter().enumerate() {
        if let entities::IfcEntity::BuildingElement {
            ifc_type,
            location_feet,
            extrusion,
            solid_shape,
            representation_map_index,
            storey_index,
            property_set,
            ..
        } = entity
        {
            // An opening (RE-84) is listed by type but is not a building
            // element: it has no body of its own, only the void it cuts.
            if ifc_type == "IFCOPENINGELEMENT" {
                *by_ifc_type.entry(ifc_type.clone()).or_insert(0) += 1;
                continue;
            }
            let properties = property_set.iter().flat_map(|set| &set.properties);
            let mut source = None;
            let mut profile_resolved = false;
            for property in properties {
                match (property.name.as_str(), &property.value) {
                    ("BodySource", entities::PropertyValue::Text(text)) => source = Some(text),
                    ("ProfileResolved", entities::PropertyValue::Boolean(true)) => {
                        profile_resolved = true
                    }
                    _ => {}
                }
            }
            if let Some(source) = source {
                *body_sources.entry(source.clone()).or_insert(0) += 1;
                if source == export_content::RECORD_BBOX_BODY_SOURCE && !profile_resolved {
                    bounding_box_bodies += 1;
                }
            }
            building_elements += 1;
            *by_ifc_type.entry(ifc_type.clone()).or_insert(0) += 1;
            if storey_index.is_some() {
                storey_bound_elements += 1;
            }
            if location_feet.is_some()
                && (extrusion.is_some()
                    || solid_shape.is_some()
                    || representation_map_index.is_some())
            {
                building_elements_with_geometry += 1;
            } else if wholes.contains(&index) {
                building_elements_carried_by_parts += 1;
            }
        }
    }

    const MATERIAL_NAME_SAMPLE_CAP: usize = 12;
    ExportedModelDiagnostics {
        total_entities: model.entities.len(),
        building_elements,
        building_elements_with_geometry,
        building_elements_carried_by_parts,
        by_ifc_type,
        classification_count: model.classifications.len(),
        unit_assignment_count: model.units.len(),
        material_count: model.materials.len(),
        storey_count: model.building_storeys.len(),
        storey_names: model
            .building_storeys
            .iter()
            .map(|s| s.name.clone())
            .collect(),
        storey_elevations_feet: model
            .building_storeys
            .iter()
            .map(|s| s.elevation_feet)
            .collect(),
        storey_bound_elements,
        material_names_sample: model
            .materials
            .iter()
            .take(MATERIAL_NAME_SAMPLE_CAP)
            .map(|m| m.name.clone())
            .collect(),
        layered_element_count: model.element_layers.len(),
        body_sources,
        bounding_box_bodies,
    }
}

#[derive(Debug)]
struct GeometryGapBucket {
    reason: &'static str,
    count: usize,
    classes: std::collections::BTreeMap<String, usize>,
    sample_names: Vec<String>,
}

impl GeometryGapBucket {
    fn new(reason: &'static str) -> Self {
        Self {
            reason,
            count: 0,
            classes: std::collections::BTreeMap::new(),
            sample_names: Vec::new(),
        }
    }

    fn add(&mut self, ifc_type: &str, name: &str) {
        self.count += 1;
        *self.classes.entry(ifc_type.to_string()).or_insert(0) += 1;
        if self.sample_names.len() < 12 {
            self.sample_names.push(name.to_string());
        }
    }

    fn into_item(self) -> Option<SkippedExportItem> {
        (self.count > 0).then(|| SkippedExportItem {
            reason: self.reason.into(),
            count: self.count,
            classes: self.classes,
            sample_names: self.sample_names,
        })
    }
}

fn geometry_gap_skipped_items(model: &IfcModel) -> Vec<SkippedExportItem> {
    let mut unsupported_curve = GeometryGapBucket::new("unsupported_geometry_curve");
    let mut unsupported_profile = GeometryGapBucket::new("unsupported_geometry_profile");
    let mut unresolved_host = GeometryGapBucket::new("unsupported_geometry_unresolved_host");
    let mut missing_level = GeometryGapBucket::new("unsupported_geometry_missing_level");
    let mut missing_dimensions = GeometryGapBucket::new("unsupported_geometry_missing_dimensions");
    let mut floor_boundary_only = GeometryGapBucket::new("floor_boundary_annotation_only");
    let mut opening_index_only = GeometryGapBucket::new("opening_index_without_host_geometry");

    for entity in &model.entities {
        let entities::IfcEntity::BuildingElement {
            ifc_type,
            name,
            storey_index,
            location_feet,
            extrusion,
            host_element_index,
            solid_shape,
            representation_map_index,
            property_set,
            ..
        } = entity
        else {
            continue;
        };

        let has_body_shape =
            extrusion.is_some() || solid_shape.is_some() || representation_map_index.is_some();
        let floor_annotation = property_set
            .as_ref()
            .is_some_and(|p| p.name == "RvtFloorGeometry");
        let opening_annotation = property_set
            .as_ref()
            .is_some_and(|p| p.name == "RvtArcWallRectOpening");

        // Honest partial recovers: do not dump them into the hard
        // "unsupported_geometry_*" buckets used for walls missing curves.
        if floor_annotation && !has_body_shape {
            floor_boundary_only.add(ifc_type, name);
            continue;
        }
        if opening_annotation {
            opening_index_only.add(ifc_type, name);
            continue;
        }

        if storey_index.is_none() {
            missing_level.add(ifc_type, name);
        }
        if location_feet.is_none() {
            unsupported_curve.add(ifc_type, name);
        }
        if !has_body_shape {
            missing_dimensions.add(ifc_type, name);
        }
        if location_feet.is_some() && !has_body_shape {
            unsupported_profile.add(ifc_type, name);
        }
        if hosted_geometry_type(ifc_type) && host_element_index.is_none() {
            unresolved_host.add(ifc_type, name);
        }
    }

    [
        unsupported_curve,
        unsupported_profile,
        unresolved_host,
        missing_level,
        missing_dimensions,
        floor_boundary_only,
        opening_index_only,
    ]
    .into_iter()
    .filter_map(GeometryGapBucket::into_item)
    .collect()
}

fn hosted_geometry_type(ifc_type: &str) -> bool {
    matches!(
        ifc_type,
        "IFCDOOR" | "IFCWINDOW" | "IFCOPENINGELEMENT" | "IFCOPENINGSTANDARDCASE"
    )
}

fn append_geometry_gap_warnings(
    warnings: &mut Vec<String>,
    exported: &ExportedModelDiagnostics,
    geometry_gaps: &[SkippedExportItem],
) {
    if exported.building_elements > 0 && exported.building_elements_with_geometry == 0 {
        warnings.push(
            "No exported building elements include decoded geometry; see skipped diagnostics for missing curve/profile/dimension data."
                .into(),
        );
    }
    if geometry_gaps.is_empty() {
        return;
    }

    let summary = geometry_gaps
        .iter()
        .map(|item| format!("{}={}", item.reason, item.count))
        .collect::<Vec<_>>()
        .join(", ");
    warnings.push(format!(
        "Unsupported or incomplete geometry was reported: {summary}."
    ));
}

fn count_arcwall_records(model: &IfcModel) -> usize {
    model
        .entities
        .iter()
        .filter(|entity| {
            matches!(
                entity,
                entities::IfcEntity::BuildingElement { name, .. } if name.starts_with("ArcWall-")
            )
        })
        .count()
}

fn count_diagnostic_proxy_elements(model: &IfcModel) -> usize {
    model
        .entities
        .iter()
        .filter(|entity| {
            matches!(
                entity,
                entities::IfcEntity::BuildingElement {
                    property_set: Some(property_set),
                    ..
                } if property_set.name == "Pset_RvtRsDiagnosticCandidate"
            )
        })
        .count()
}

fn diagnostic_candidate_class_counts(
    collection: &DiagnosticProxyCandidateCollection,
) -> std::collections::BTreeMap<String, usize> {
    let mut out = std::collections::BTreeMap::new();
    for candidate in &collection.candidates {
        *out.entry(candidate.decoded.class.clone()).or_insert(0) += 1;
    }
    out
}

fn diagnostic_candidate_display_name(candidate: &DiagnosticProxyCandidate) -> String {
    match candidate.decoded.id {
        Some(id) => format!("{}-{id}", candidate.decoded.class),
        None => format!(
            "{}-offset-{:x}",
            candidate.decoded.class, candidate.decoded.byte_range.start
        ),
    }
}

fn unsupported_export_features(model: &IfcModel) -> Vec<String> {
    let exported = exported_model_diagnostics(model);
    let mut features = Vec::new();
    if model.units.is_empty() {
        features.push("project_units_from_revit_bytes".into());
    }
    if model.building_storeys.is_empty() {
        features.push("revit_levels_to_ifc_storeys".into());
    }
    if exported.building_elements_with_geometry == 0 {
        features.push("real_file_element_geometry".into());
    } else if exported.building_elements_with_geometry < exported.building_elements {
        // Some categories carry a recovered body and others do not — a
        // narrower, still-honest claim than "no geometry at all" (#204
        // landed IFCCOLUMN bodies while Floors/Rooms stay annotations).
        features.push("partial_element_geometry".into());
    }
    // Compound assemblies (layer widths) remain open even when display
    // Material names are recovered into IfcMaterial.
    features.push("revit_compound_assemblies_and_walltype_widths".into());
    if model.materials.is_empty() {
        features.push("revit_material_display_names".into());
    }
    let slab_count = exported.by_ifc_type.get("IFCSLAB").copied().unwrap_or(0);
    if slab_count == 0 {
        features.push("floor_plan_loop_slab_export".into());
    } else if model.entities.iter().any(slab_thickness_unresolved) {
        // A plan-loop slab is a boundary annotation with no thickness.
        // A record-backed slab carries the recorded bbox `z` extent,
        // which agrees with the reference export's
        // `IfcExtrudedAreaSolid.Depth` on 79 of 80 slabs and sums to
        // it on the 80th (#212, RE-22), so it does not raise this.
        features.push("floor_slab_extrusion_thickness".into());
    }
    let has_typed_door = exported.by_ifc_type.get("IFCDOOR").copied().unwrap_or(0) > 0;
    let has_typed_window = exported.by_ifc_type.get("IFCWINDOW").copied().unwrap_or(0) > 0;
    if !has_typed_door || !has_typed_window {
        features.push("typed_door_window_discrimination_and_host_binding".into());
    } else if model.entities.iter().any(|e| {
        matches!(
            e,
            entities::IfcEntity::BuildingElement { ifc_type, host_element_index, .. }
                if (ifc_type == "IFCDOOR" || ifc_type == "IFCWINDOW")
                    && host_element_index.is_none()
        )
    }) {
        // Typed Door/Window recovered (#211) but not attached to a host
        // wall — the discrimination half of the old composite feature is
        // closed, the host-binding half is not.
        features.push("door_window_host_wall_binding".into());
    }
    // Opening-index rows may be present in production_class_counts without
    // IFC emission until host Wall ElementIds join.
    features.push("opening_index_to_ifc_openingelement_host_join".into());
    // RE-19 stands: an `IFCWALL` recovered from a partition element record
    // (#211) is not a schema-field wall decode. Only a wall carrying a
    // non-element-record body clears this feature.
    let has_schema_wall = model.entities.iter().any(|e| {
        matches!(
            e,
            entities::IfcEntity::BuildingElement { ifc_type, name, property_set, .. }
                if ifc_type == "IFCWALL"
                    && name.starts_with("Wall-")
                    && !matches!(
                        property_set,
                        Some(set) if set.name == ELEMENT_RECORD_PROPERTY_SET
                    )
        )
    });
    if !has_schema_wall {
        features.push("schema_field_wall_instances".into());
    }
    // #35: no exported property set carries Revit element parameters —
    // every set emitted today is rvt-rs provenance about a recovered body.
    let has_parameter_property_set = model.entities.iter().any(|e| {
        matches!(
            e,
            entities::IfcEntity::BuildingElement { property_set: Some(set), .. }
                if !set.name.starts_with("Rvt")
        )
    });
    if !has_parameter_property_set {
        features.push("revit_element_parameters_to_ifc_property_sets".into());
    }
    features
}

#[derive(Debug, Default)]
struct ProductionWalkerStats {
    class_counts: std::collections::BTreeMap<String, usize>,
    mean_element_confidence: Option<f32>,
    elements_below_min_confidence: usize,
}

fn production_walker_stats(
    rf: &mut crate::RevitFile,
    walker_limits: crate::walker::WalkerLimits,
) -> ProductionWalkerStats {
    let mut stats = ProductionWalkerStats::default();
    let Ok(iter) = crate::walker::iter_elements_with_limits(
        rf,
        crate::walker::PRODUCTION_ELEMENT_MIN_SCORE,
        walker_limits,
    ) else {
        return stats;
    };
    let mut sum = 0.0_f32;
    let mut n = 0usize;
    let min_c = crate::walker::DEFAULT_MIN_ELEMENT_CONFIDENCE;
    for el in iter {
        *stats.class_counts.entry(el.class.clone()).or_insert(0) += 1;
        sum += el.provenance.confidence;
        n += 1;
        if !el.meets_confidence(min_c) {
            stats.elements_below_min_confidence += 1;
        }
    }
    if n > 0 {
        stats.mean_element_confidence = Some(sum / n as f32);
    }
    stats
}

fn parameter_value_count_from_class_counts(
    class_counts: &std::collections::BTreeMap<String, usize>,
) -> usize {
    class_counts
        .iter()
        .filter(|(class, _)| crate::elements::parameters::is_aproperty_class(class))
        .map(|(_, n)| *n)
        .sum()
}

fn export_confidence_summary(
    mode: ExportDiagnosticsMode,
    exported: &ExportedModelDiagnostics,
    has_project_metadata: bool,
    diagnostic_proxy_elements: usize,
    warning_count: usize,
    unexported_element_records: usize,
) -> ExportConfidenceSummary {
    let has_typed_elements = exported
        .by_ifc_type
        .iter()
        .any(|(ifc_type, count)| *count > 0 && ifc_type != "IFCBUILDINGELEMENTPROXY");
    let has_geometry = exported.building_elements_with_geometry > 0;
    let has_diagnostic_proxies = diagnostic_proxy_elements > 0;
    let level = if mode == ExportDiagnosticsMode::Placeholder || exported.building_elements == 0 {
        "scaffold"
    } else if has_geometry {
        "geometry"
    } else if has_diagnostic_proxies {
        "diagnostic_partial"
    } else if has_typed_elements {
        "typed_no_geometry"
    } else {
        "proxy_only"
    };

    let mut score = 0.10f32;
    if has_project_metadata {
        score += 0.15;
    }
    if exported.unit_assignment_count > 0 {
        score += 0.10;
    }
    let mut element_score = 0.0f32;
    if exported.building_elements > 0 {
        element_score += 0.20;
    }
    if has_typed_elements {
        element_score += 0.20;
    }
    if has_geometry {
        element_score += 0.25;
    }
    // Records the scan found but could not export (RE-30) are elements the
    // IFC is missing, so the element terms only count for the exported
    // share. Metadata and units are recovered either way.
    if unexported_element_records > 0 {
        let exported_elements = exported.building_elements as f32;
        element_score *=
            exported_elements / (exported_elements + unexported_element_records as f32);
    }
    score += element_score;
    if has_diagnostic_proxies {
        score -= 0.05;
    }

    ExportConfidenceSummary {
        level: level.into(),
        score: score.clamp(0.0, 1.0),
        has_project_metadata,
        has_typed_elements,
        has_geometry,
        has_diagnostic_proxies,
        warning_count,
        unexported_element_records,
    }
}

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

    /// A `Column` in the shape
    /// `partition_schema_mvp::columns_from_partition_category_records`
    /// produces: plan centre + record base `z`, bbox extents, and the
    /// `partition_element_record` source marker.
    fn column_record_element(
        id: u32,
        centre: (f64, f64),
        base_z: f64,
    ) -> crate::walker::DecodedElement {
        use crate::walker::{DecodedElement, ElementProvenance, InstanceField};
        let float = |value: f64| InstanceField::Float { value, size: 8 };
        DecodedElement {
            id: Some(id),
            class: "Column".into(),
            fields: vec![
                ("m_locationX".into(), float(centre.0)),
                ("m_locationY".into(), float(centre.1)),
                ("m_locationZ".into(), float(base_z)),
                ("m_bboxWidth".into(), float(2.0)),
                ("m_bboxDepth".into(), float(2.0)),
                ("m_bboxHeight".into(), float(15.0)),
                (
                    "m_source".into(),
                    InstanceField::String("partition_element_record".into()),
                ),
            ],
            byte_range: 0..88,
            provenance: ElementProvenance::partition(
                "Partitions/46",
                0,
                "partition_element_record",
                "partition_schema_mvp::column_category_record",
                0.8,
                Some("level_binding_unresolved"),
            ),
        }
    }

    fn append_columns(decoded: Vec<crate::walker::DecodedElement>) -> Vec<entities::IfcEntity> {
        let mut entities = Vec::new();
        let mut storeys = Vec::new();
        export_content::append_typed_production_elements(
            decoded.into_iter(),
            &mut entities,
            &mut storeys,
            export_content::ExportContentPolicy::for_quality_mode(ExportQualityMode::Geometry),
        );
        entities
    }

    fn record_element_of_class(id: u32, class: &str, base_z: f64) -> crate::walker::DecodedElement {
        let mut decoded = column_record_element(id, (10.0, 10.0), base_z);
        decoded.class = class.into();
        decoded
    }

    /// #211: walls, doors and windows carry record bboxes too, but only
    /// a column base is a storey elevation — a window sits at its sill
    /// height above the level that hosts it. They must still *bind* to
    /// the column-derived set.
    #[test]
    fn only_column_records_supply_storey_elevations() {
        let mut entities = append_columns(vec![
            record_element_of_class(1, "Column", 0.0),
            record_element_of_class(2, "Column", 31.0),
            record_element_of_class(3, "Window", 35.73),
            record_element_of_class(4, "Wall", 31.0),
            record_element_of_class(5, "Door", 0.0),
        ]);
        let mut storeys = vec![Storey {
            name: "Level 1".into(),
            elevation_feet: 0.0,
        }];
        apply_element_record_storeys(&mut entities, &mut storeys);

        assert_eq!(
            storeys.iter().map(|s| s.elevation_feet).collect::<Vec<_>>(),
            vec![0.0, 31.0],
            "the window sill height must not become a storey"
        );
        let bound: Vec<Option<usize>> = entities
            .iter()
            .map(|entity| match entity {
                entities::IfcEntity::BuildingElement { storey_index, .. } => *storey_index,
                _ => None,
            })
            .collect();
        assert_eq!(
            bound,
            vec![Some(0), Some(1), None, Some(1), Some(0)],
            "walls and doors bind by exact match; the window stays unbound"
        );
    }

    /// #212 / RE-22: Revit hangs a floor plate below its level, so a
    /// slab binds by its recorded *top* face while everything else
    /// keeps the #213 base-face join. A plate whose top matches no
    /// storey stays unbound rather than being placed by proximity.
    #[test]
    fn slabs_bind_to_a_storey_by_their_top_face() {
        let mut slab = record_element_of_class(3, "Floor", 30.8333);
        // A 2 in architectural topping: base 30.8333 ft, top 31 ft.
        slab.fields.retain(|(n, _)| n != "m_bboxHeight");
        slab.fields.push((
            "m_bboxHeight".into(),
            crate::walker::InstanceField::Float {
                value: 0.1667,
                size: 8,
            },
        ));
        let mut interface = record_element_of_class(4, "Floor", 30.3333);
        interface.fields.retain(|(n, _)| n != "m_bboxHeight");
        interface.fields.push((
            "m_bboxHeight".into(),
            crate::walker::InstanceField::Float {
                value: 0.5,
                size: 8,
            },
        ));

        let mut entities = append_columns(vec![
            record_element_of_class(1, "Column", 0.0),
            record_element_of_class(2, "Column", 31.0),
            slab,
            interface,
        ]);
        let mut storeys = vec![Storey {
            name: "Level 1".into(),
            elevation_feet: 0.0,
        }];
        apply_element_record_storeys(&mut entities, &mut storeys);

        let bound: Vec<Option<usize>> = entities
            .iter()
            .map(|entity| match entity {
                entities::IfcEntity::BuildingElement { storey_index, .. } => *storey_index,
                _ => None,
            })
            .collect();
        assert_eq!(
            bound,
            vec![Some(0), Some(1), Some(1), None],
            "the topping's top (31 ft) binds; the structural slab's top              (30.8333 ft) matches no storey and stays unbound"
        );
    }

    /// A plate with no recovered body has no top face to bind by, and
    /// its base is known not to be a storey elevation — so it must not
    /// fall back to the base join.
    #[test]
    fn a_bodyless_slab_does_not_bind_by_its_base() {
        let mut slab = record_element_of_class(3, "Floor", 31.0);
        slab.fields.retain(|(n, _)| n != "m_bboxHeight");
        let mut entities = append_columns(vec![
            record_element_of_class(1, "Column", 0.0),
            record_element_of_class(2, "Column", 31.0),
            slab,
        ]);
        let mut storeys = vec![Storey {
            name: "Level 1".into(),
            elevation_feet: 0.0,
        }];
        apply_element_record_storeys(&mut entities, &mut storeys);
        match &entities[2] {
            entities::IfcEntity::BuildingElement { storey_index, .. } => {
                assert_eq!(*storey_index, None);
            }
            _ => panic!("expected building element"),
        }
    }

    /// #219 / RE-27: a record that names exactly one recovered Level
    /// is contained in that Level's storey, even when no face of its
    /// bounding box is a storey elevation — which is the whole point,
    /// because a floor plate hangs 2 in below its level and a window
    /// sits at its sill height above it.
    #[test]
    fn a_named_level_reference_binds_an_element_no_elevation_join_reaches() {
        let mut slab = record_element_of_class(3, "Floor", 30.6667);
        slab.fields.retain(|(n, _)| n != "m_bboxHeight");
        slab.fields.push((
            "m_bboxHeight".into(),
            crate::walker::InstanceField::Float {
                value: 0.1667,
                size: 8,
            },
        ));
        // Top face 30.8333 ft — 2 in below Level 3 at 31 ft, so the
        // #212 top-face join cannot reach it.
        slab.fields.push((
            crate::element_record_level_refs::LEVEL_REFERENCE_FIELD.into(),
            crate::walker::InstanceField::ElementId { tag: 0, id: 20274 },
        ));
        let mut window = record_element_of_class(4, "Window", 35.73);
        window.fields.push((
            crate::element_record_level_refs::LEVEL_REFERENCE_FIELD.into(),
            crate::walker::InstanceField::ElementId { tag: 0, id: 20274 },
        ));

        let mut entities = append_columns(vec![slab, window]);
        let storeys = vec![
            Storey {
                name: "Level 1".into(),
                elevation_feet: 0.0,
            },
            Storey {
                name: "Level 3".into(),
                elevation_feet: 31.0,
            },
        ];
        let mut bind = crate::level_bind::LevelStoreyBind::new();
        bind.record_level(Some(20268), 0);
        bind.record_level(Some(20274), 1);
        apply_record_level_reference_storeys(&mut entities, &storeys, &bind);

        let bound: Vec<Option<usize>> = entities
            .iter()
            .map(|entity| match entity {
                entities::IfcEntity::BuildingElement { storey_index, .. } => *storey_index,
                _ => None,
            })
            .collect();
        assert_eq!(bound, vec![Some(1), Some(1)]);

        let entities::IfcEntity::BuildingElement { property_set, .. } = &entities[0] else {
            panic!("expected a building element");
        };
        assert!(
            property_set
                .as_ref()
                .expect("record element carries RvtElementRecordGeometry")
                .properties
                .iter()
                .any(|p| p.name == STOREY_BIND_SOURCE_PROPERTY
                    && matches!(&p.value, entities::PropertyValue::Text(text)
                        if text == STOREY_BIND_RECORD_LEVEL_REFERENCE)),
            "a level-reference bind must say so rather than claim the elevation join"
        );
    }

    /// An element that names a Level the storey set does not carry
    /// stays unbound — the reference is never turned into an index by
    /// rank or by proximity.
    #[test]
    fn an_unknown_level_reference_stays_unbound() {
        let mut slab = record_element_of_class(3, "Floor", 30.6667);
        slab.fields.push((
            crate::element_record_level_refs::LEVEL_REFERENCE_FIELD.into(),
            crate::walker::InstanceField::ElementId { tag: 0, id: 99_999 },
        ));
        let mut entities = append_columns(vec![slab]);
        let storeys = vec![Storey {
            name: "Level 1".into(),
            elevation_feet: 0.0,
        }];
        let mut bind = crate::level_bind::LevelStoreyBind::new();
        bind.record_level(Some(20268), 0);
        apply_record_level_reference_storeys(&mut entities, &storeys, &bind);

        match &entities[0] {
            entities::IfcEntity::BuildingElement { storey_index, .. } => {
                assert_eq!(*storey_index, None);
            }
            _ => panic!("expected building element"),
        }
    }

    /// The level-reference join runs before the elevation join and
    /// must not be undone by it: an element the reference placed keeps
    /// that storey and that bind source.
    #[test]
    fn the_elevation_join_leaves_a_level_reference_bind_alone() {
        let mut slab = record_element_of_class(3, "Floor", 30.6667);
        slab.fields.retain(|(n, _)| n != "m_bboxHeight");
        slab.fields.push((
            "m_bboxHeight".into(),
            crate::walker::InstanceField::Float {
                value: 0.1667,
                size: 8,
            },
        ));
        slab.fields.push((
            crate::element_record_level_refs::LEVEL_REFERENCE_FIELD.into(),
            crate::walker::InstanceField::ElementId { tag: 0, id: 20274 },
        ));

        let mut entities = append_columns(vec![
            column_record_element(1, (10.0, 10.0), 0.0),
            column_record_element(2, (30.0, 10.0), 31.0),
            slab,
        ]);
        let mut storeys = vec![
            Storey {
                name: "Level 1".into(),
                elevation_feet: 0.0,
            },
            Storey {
                name: "Level 3".into(),
                elevation_feet: 31.0,
            },
        ];
        let mut bind = crate::level_bind::LevelStoreyBind::new();
        bind.record_level(Some(20274), 1);
        apply_record_level_reference_storeys(&mut entities, &storeys, &bind);
        apply_element_record_storeys(&mut entities, &mut storeys);

        let bound: Vec<Option<usize>> = entities
            .iter()
            .map(|entity| match entity {
                entities::IfcEntity::BuildingElement { storey_index, .. } => *storey_index,
                _ => None,
            })
            .collect();
        assert_eq!(bound, vec![Some(0), Some(1), Some(1)]);
        let entities::IfcEntity::BuildingElement { property_set, .. } = &entities[2] else {
            panic!("expected a building element");
        };
        let sources: Vec<&str> = property_set
            .as_ref()
            .expect("record element carries RvtElementRecordGeometry")
            .properties
            .iter()
            .filter(|p| p.name == STOREY_BIND_SOURCE_PROPERTY)
            .filter_map(|p| match &p.value {
                entities::PropertyValue::Text(text) => Some(text.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(sources, vec![STOREY_BIND_RECORD_LEVEL_REFERENCE]);
    }

    /// The #213 join reads the record base elevation back off an
    /// element the production path built, so the `BodySource` marker
    /// the two sides agree on cannot drift apart silently.
    #[test]
    fn record_base_elevation_round_trips_through_the_production_path() {
        let entities = append_columns(vec![column_record_element(1, (10.0, 10.0), 76.0)]);
        assert_eq!(entities.len(), 1);
        assert_eq!(record_base_elevation_feet(&entities[0]), Some(76.0));
    }

    /// Storeys with no elevation of their own are replaced by the
    /// measured distribution, and every recorded element lands in the
    /// storey at its own base.
    #[test]
    fn element_records_supply_storey_elevations_and_containment() {
        let mut entities = append_columns(vec![
            column_record_element(1, (10.0, 10.0), 0.0),
            column_record_element(2, (30.0, 10.0), 0.0),
            column_record_element(3, (10.0, 30.0), 15.0),
            column_record_element(4, (30.0, 30.0), 31.0),
        ]);
        // What the partition Level rows give today: names, no elevation.
        let mut storeys = vec![
            Storey {
                name: "Level 1".into(),
                elevation_feet: 0.0,
            },
            Storey {
                name: "Roof".into(),
                elevation_feet: 0.0,
            },
        ];
        apply_element_record_storeys(&mut entities, &mut storeys);

        assert_eq!(
            storeys.iter().map(|s| s.elevation_feet).collect::<Vec<_>>(),
            vec![0.0, 15.0, 31.0],
        );
        // 2 names against 3 measured elevations is not a pairing.
        assert_eq!(storeys[0].name, "Elevation 0.000 ft");

        let bound: Vec<Option<usize>> = entities
            .iter()
            .map(|entity| match entity {
                entities::IfcEntity::BuildingElement { storey_index, .. } => *storey_index,
                _ => None,
            })
            .collect();
        assert_eq!(bound, vec![Some(0), Some(0), Some(1), Some(2)]);

        let entities::IfcEntity::BuildingElement { property_set, .. } = &entities[3] else {
            panic!("expected a building element");
        };
        assert!(
            property_set
                .as_ref()
                .expect("record element carries RvtElementRecordGeometry")
                .properties
                .iter()
                .any(|p| p.name == STOREY_BIND_SOURCE_PROPERTY),
            "a bound element must record how it reached its storey"
        );
    }

    /// Storeys that already carry real elevations (the 2023 ArcWall
    /// path) are not replaced, and an element whose base matches none
    /// of them stays unbound rather than being placed by proximity.
    #[test]
    fn existing_elevations_survive_and_unmatched_elements_stay_unbound() {
        let mut entities = append_columns(vec![
            column_record_element(1, (10.0, 10.0), 12.0),
            column_record_element(2, (30.0, 10.0), 7.5),
        ]);
        let mut storeys = vec![
            Storey {
                name: "Ground".into(),
                elevation_feet: 0.0,
            },
            Storey {
                name: "First".into(),
                elevation_feet: 12.0,
            },
        ];
        apply_element_record_storeys(&mut entities, &mut storeys);

        assert_eq!(storeys.len(), 2);
        assert_eq!(storeys[1].name, "First");
        let bound: Vec<Option<usize>> = entities
            .iter()
            .map(|entity| match entity {
                entities::IfcEntity::BuildingElement { storey_index, .. } => *storey_index,
                _ => None,
            })
            .collect();
        assert_eq!(bound, vec![Some(1), None]);
    }

    #[test]
    fn exported_diagnostics_include_storey_and_material_name_samples() {
        let model = IfcModel {
            building_storeys: vec![
                Storey {
                    name: "Level 1".into(),
                    elevation_feet: 0.0,
                },
                Storey {
                    name: "Roof".into(),
                    elevation_feet: 10.0,
                },
            ],
            materials: vec![
                MaterialInfo {
                    name: "Concrete".into(),
                    color_packed: None,
                    transparency: None,
                },
                MaterialInfo {
                    name: "Glass".into(),
                    color_packed: None,
                    transparency: None,
                },
            ],
            ..Default::default()
        };
        let exported = exported_model_diagnostics(&model);
        assert_eq!(exported.storey_count, 2);
        assert_eq!(exported.storey_names, vec!["Level 1", "Roof"]);
        assert_eq!(exported.material_count, 2);
        assert_eq!(exported.material_names_sample, vec!["Concrete", "Glass"]);
    }

    #[test]
    fn placeholder_exporter_default_model_has_no_name() {
        let m = IfcModel::default();
        assert!(m.project_name.is_none());
    }

    fn arcwall_record_with_coords(coords: [f64; 6]) -> crate::arc_wall_record::ArcWallRecord {
        crate::arc_wall_record::ArcWallRecord {
            tag: crate::arc_wall_record::ARC_WALL_TAG,
            variant: crate::arc_wall_record::ARC_WALL_VARIANT_STANDARD,
            fixed_header_0: crate::arc_wall_record::SCHEMA_FAMILY_MARKER,
            count_version: 1,
            type_code: 3,
            coords,
            coords_dup: coords,
            trailer: crate::arc_wall_record::RECORD_TRAILER,
        }
    }

    #[test]
    fn arcwall_geometry_uses_midpoint_rotation_length_and_decoded_height() {
        let record = arcwall_record_with_coords([0.0, 0.0, 2.0, 3.0, 4.0, 14.0]);
        let (location, rotation, extrusion) =
            arcwall_geometry_from_record(&record, Some(0.5)).expect("valid geometry");

        assert_eq!(location, [1.5, 2.0, 2.0]);
        assert!((rotation - 4.0f64.atan2(3.0)).abs() < 1e-9);
        assert!((extrusion.width_feet - 5.0).abs() < 1e-9);
        assert!((extrusion.depth_feet - 0.5).abs() < 1e-9);
        assert!((extrusion.height_feet - 12.0).abs() < 1e-9);
    }

    #[test]
    fn arcwall_geometry_rejects_missing_height_instead_of_inventing() {
        // Identical Z → no recoverable height; must not invent 10 ft.
        let record = arcwall_record_with_coords([0.0, 0.0, 5.0, 3.0, 4.0, 5.0]);
        assert!(arcwall_geometry_from_record(&record, Some(0.5)).is_none());
    }

    #[test]
    fn arcwall_geometry_uses_unresolved_thickness_placeholder_when_missing() {
        let record = arcwall_record_with_coords([0.0, 0.0, 0.0, 4.0, 0.0, 8.0]);
        let (_, _, extrusion) =
            arcwall_geometry_from_record(&record, None).expect("height present");
        assert!((extrusion.depth_feet - UNRESOLVED_ARCWALL_THICKNESS_FEET).abs() < 1e-9);
        assert!((extrusion.height_feet - 8.0).abs() < 1e-9);
    }

    #[test]
    fn arcwall_geometry_rejects_degenerate_xy_segment() {
        let record = arcwall_record_with_coords([1.0, 2.0, 0.0, 1.0, 2.0, 10.0]);
        assert!(arcwall_geometry_from_record(&record, Some(0.5)).is_none());
    }

    fn diagnostic_building_element(
        ifc_type: &str,
        name: &str,
        storey_index: Option<usize>,
        location_feet: Option<[f64; 3]>,
        extrusion: Option<entities::Extrusion>,
        host_element_index: Option<usize>,
    ) -> entities::IfcEntity {
        entities::IfcEntity::BuildingElement {
            ifc_type: ifc_type.to_string(),
            name: name.to_string(),
            type_guid: None,
            predefined_type: None,
            storey_index,
            material_index: None,
            property_set: None,
            location_feet,
            rotation_radians: None,
            extrusion,
            host_element_index,
            material_layer_set_index: None,
            material_profile_set_index: None,
            solid_shape: None,
            representation_map_index: None,
        }
    }

    #[test]
    fn geometry_gap_diagnostics_report_missing_curve_profile_host_level_and_dimensions() {
        let model = IfcModel {
            entities: vec![
                diagnostic_building_element(
                    "IFCWALL",
                    "WallWithoutGeometry",
                    None,
                    None,
                    None,
                    None,
                ),
                diagnostic_building_element(
                    "IFCWINDOW",
                    "WindowWithoutHostOrProfile",
                    Some(0),
                    Some([1.0, 2.0, 3.0]),
                    None,
                    None,
                ),
            ],
            ..IfcModel::default()
        };

        let gaps = geometry_gap_skipped_items(&model);
        let by_reason: std::collections::BTreeMap<&str, usize> = gaps
            .iter()
            .map(|item| (item.reason.as_str(), item.count))
            .collect();

        assert_eq!(by_reason["unsupported_geometry_curve"], 1);
        assert_eq!(by_reason["unsupported_geometry_profile"], 1);
        assert_eq!(by_reason["unsupported_geometry_unresolved_host"], 1);
        assert_eq!(by_reason["unsupported_geometry_missing_level"], 1);
        assert_eq!(by_reason["unsupported_geometry_missing_dimensions"], 2);
        assert!(gaps.iter().any(|item| {
            item.sample_names
                .iter()
                .any(|name| name == "WindowWithoutHostOrProfile")
        }));

        let exported = exported_model_diagnostics(&model);
        let mut warnings = Vec::new();
        append_geometry_gap_warnings(&mut warnings, &exported, &gaps);
        assert!(warnings.iter().any(|warning| {
            warning.contains("No exported building elements include decoded geometry")
        }));
        assert!(
            warnings
                .iter()
                .any(|warning| warning.contains("unsupported_geometry_unresolved_host=1"))
        );
    }

    #[test]
    fn project_unit_recovery_selects_modal_metric_units() {
        let recovered = recover_project_units_from_identifiers([
            "autodesk.unit.unit:meters-1.0.0",
            "autodesk.unit.unit:meters-1.0.0",
            "autodesk.unit.unit:millimeters-1.0.1",
            "autodesk.unit.unit:squareMeters-1.0.1",
            "autodesk.unit.unit:cubicMeters-1.0.1",
            "autodesk.unit.unit:degrees-1.0.1",
        ]);

        let ids: Vec<_> = recovered
            .assignments
            .iter()
            .map(|unit| unit.forge_identifier.as_str())
            .collect();
        assert!(ids.contains(&"autodesk.unit.unit:meters-1.0.0"));
        assert!(ids.contains(&"autodesk.unit.unit:squareMeters-1.0.1"));
        assert!(ids.contains(&"autodesk.unit.unit:cubicMeters-1.0.1"));
        assert!(ids.contains(&"autodesk.unit.unit:degrees-1.0.1"));
        assert!(!ids.contains(&"autodesk.unit.unit:millimeters-1.0.1"));
        assert!(recovered.unknown_identifiers.is_empty());
    }

    #[test]
    fn project_unit_recovery_maps_imperial_and_preserves_unknowns() {
        let recovered = recover_project_units_from_identifiers([
            "autodesk.unit.unit:feet-1.0.1",
            "autodesk.unit.unit:feet-1.0.1",
            "autodesk.unit.unit:meters-1.0.0",
            "autodesk.unit.unit:squareFeet-1.0.1",
            "autodesk.unit.unit:cubicFeet-1.0.1",
            "autodesk.unit.unit:pounds-1.0.1",
            "autodesk.unit.symbol:degree-1.0.1",
        ]);

        let ids: Vec<_> = recovered
            .assignments
            .iter()
            .map(|unit| unit.forge_identifier.as_str())
            .collect();
        assert!(ids.contains(&"autodesk.unit.unit:feet-1.0.1"));
        assert!(ids.contains(&"autodesk.unit.unit:squareFeet-1.0.1"));
        assert!(ids.contains(&"autodesk.unit.unit:cubicFeet-1.0.1"));
        assert!(ids.contains(&"autodesk.unit.unit:pounds-1.0.1"));
        assert_eq!(
            recovered.unknown_identifiers,
            vec!["autodesk.unit.symbol:degree-1.0.1"]
        );
    }

    #[test]
    fn source_coverage_measures_export_and_geometry_fractions() {
        let cov = SourceCoverageDiagnostics::measure(
            /* walker */ 74,
            /* building */ 29,
            /* with geometry */ 24,
            Some(1370),
        );
        assert_eq!(cov.status, SourceCoverageStatus::Measured);
        assert!((cov.decoded_element_fraction.unwrap() - (74.0 / 1370.0)).abs() < 1e-6);
        assert!((cov.exported_element_fraction.unwrap() - (29.0 / 74.0)).abs() < 1e-6);
        assert!((cov.geometry_element_fraction.unwrap() - (24.0 / 29.0)).abs() < 1e-6);
        assert!(
            cov.notes
                .as_deref()
                .unwrap_or("")
                .contains("Measured from export diagnostics")
        );
    }

    #[test]
    fn source_coverage_fail_closed_when_walker_exceeds_elem_table_header() {
        // Core Interior-style: partition MVP recoveries exceed u16 header.
        let cov = SourceCoverageDiagnostics::measure(3353, 82, 0, Some(1411));
        assert_eq!(cov.status, SourceCoverageStatus::Measured);
        assert_eq!(cov.decoded_element_fraction, None);
        assert!((cov.exported_element_fraction.unwrap() - (82.0 / 3353.0)).abs() < 1e-6);
        assert!((cov.geometry_element_fraction.unwrap() - 0.0).abs() < 1e-6);
        assert!(
            cov.notes
                .as_deref()
                .unwrap_or("")
                .contains("decoded_element_fraction left null")
        );
    }

    #[test]
    fn source_coverage_unset_when_no_denominators() {
        let cov = SourceCoverageDiagnostics::measure(0, 0, 0, None);
        assert_eq!(cov.status, SourceCoverageStatus::Unset);
        assert_eq!(cov.decoded_element_fraction, None);
        assert_eq!(cov.exported_element_fraction, None);
        assert_eq!(cov.geometry_element_fraction, None);
    }

    #[test]
    fn source_coverage_zero_decoded_when_table_present_but_walker_empty() {
        let cov = SourceCoverageDiagnostics::measure(0, 0, 0, Some(100));
        assert_eq!(cov.status, SourceCoverageStatus::Measured);
        assert_eq!(cov.decoded_element_fraction, Some(0.0));
        assert_eq!(cov.exported_element_fraction, None);
        assert_eq!(cov.geometry_element_fraction, None);
    }

    fn walls_with_geometry(count: usize) -> ExportedModelDiagnostics {
        ExportedModelDiagnostics {
            total_entities: count,
            building_elements: count,
            building_elements_with_geometry: count,
            building_elements_carried_by_parts: 0,
            by_ifc_type: [("IFCWALL".to_string(), count)].into_iter().collect(),
            classification_count: 0,
            unit_assignment_count: 1,
            material_count: 0,
            storey_count: 0,
            storey_names: Vec::new(),
            storey_elevations_feet: Vec::new(),
            storey_bound_elements: 0,
            material_names_sample: Vec::new(),
            layered_element_count: 0,
            body_sources: Default::default(),
            bounding_box_bodies: 0,
        }
    }

    #[test]
    fn unexported_element_records_scale_the_element_terms_of_the_score() {
        let exported = walls_with_geometry(20);
        let complete =
            export_confidence_summary(ExportDiagnosticsMode::Default, &exported, true, 0, 0, 0);
        assert_eq!(complete.level, "geometry");
        assert!((complete.score - 1.0).abs() < 1e-6);
        assert_eq!(complete.unexported_element_records, 0);

        // RE1 Architecture (Revit 2025): 20 exported, 18 doors unattributed.
        let partial =
            export_confidence_summary(ExportDiagnosticsMode::Default, &exported, true, 0, 1, 18);
        assert_eq!(partial.level, "geometry");
        assert_eq!(partial.unexported_element_records, 18);
        let expected = 0.35 + 0.65 * 20.0 / 38.0;
        assert!((partial.score - expected).abs() < 1e-6, "{}", partial.score);
    }

    #[test]
    fn metadata_terms_survive_when_every_element_record_is_unexported() {
        let exported = walls_with_geometry(0);
        let summary =
            export_confidence_summary(ExportDiagnosticsMode::Default, &exported, true, 0, 1, 50);
        assert_eq!(summary.level, "scaffold");
        assert!((summary.score - 0.35).abs() < 1e-6, "{}", summary.score);
    }
}