bimifc-parser 0.3.0

High-performance IFC parser with IFC4 (STEP) and IFC5 (IFCX) support
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Lighting data extraction from IFC files
//!
//! This module extracts light fixtures, light sources, and photometric data
//! from IFC files for use with lighting analysis and GLDF viewers.

use bimifc_model::{AttributeValue, DecodedEntity, EntityResolver, IfcType};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};

/// Extracted light fixture data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LightFixtureData {
    /// Entity ID
    pub id: u64,
    /// GlobalId (GUID)
    pub global_id: Option<String>,
    /// Name
    pub name: Option<String>,
    /// Description
    pub description: Option<String>,
    /// Object type (predefined or user-defined)
    pub object_type: Option<String>,
    /// Position (X, Y, Z) in meters
    pub position: (f64, f64, f64),
    /// Associated storey name
    pub storey: Option<String>,
    /// Storey elevation
    pub storey_elevation: Option<f64>,
    /// Light fixture type reference
    pub fixture_type: Option<LightFixtureTypeData>,
    /// Light sources
    pub light_sources: Vec<LightSourceData>,
    /// Properties from property sets
    pub properties: FxHashMap<String, PropertySetData>,
}

/// Light fixture type definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LightFixtureTypeData {
    pub id: u64,
    pub name: Option<String>,
    pub description: Option<String>,
    pub predefined_type: Option<String>,
}

/// Light source data (goniometric, positional, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LightSourceData {
    pub id: u64,
    pub source_type: String,
    /// Color temperature in Kelvin
    pub color_temperature: Option<f64>,
    /// Luminous flux in lumens
    pub luminous_flux: Option<f64>,
    /// Light emission source (LED, FLUORESCENT, etc.)
    pub emission_source: Option<String>,
    /// Intensity (cd)
    pub intensity: Option<f64>,
    /// Color RGB
    pub color_rgb: Option<(f64, f64, f64)>,
    /// Light distribution data
    pub distribution: Option<LightDistributionData>,
}

/// Light distribution/photometry data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LightDistributionData {
    /// Distribution type (TYPE_A, TYPE_B, TYPE_C)
    pub distribution_type: String,
    /// Distribution planes (C-planes for Type C)
    pub planes: Vec<DistributionPlane>,
}

/// A single distribution plane
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistributionPlane {
    /// Main plane angle (C-angle for Type C)
    pub main_angle: f64,
    /// Intensity values at secondary angles (gamma angles)
    pub intensities: Vec<(f64, f64)>, // (angle, intensity in cd)
}

/// Property set with values
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropertySetData {
    pub name: String,
    pub properties: FxHashMap<String, String>,
}

/// Complete lighting data from an IFC file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LightingExport {
    /// Schema version
    pub schema: String,
    /// Project name
    pub project_name: Option<String>,
    /// Building name
    pub building_name: Option<String>,
    /// Building storeys
    pub storeys: Vec<StoreyData>,
    /// Light fixtures
    pub light_fixtures: Vec<LightFixtureData>,
    /// Light fixture types
    pub light_fixture_types: Vec<LightFixtureTypeData>,
    /// Summary statistics
    pub summary: LightingSummary,
}

/// Building storey data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoreyData {
    pub id: u64,
    pub name: String,
    pub elevation: f64,
}

/// Summary of lighting data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LightingSummary {
    pub total_fixtures: usize,
    pub total_light_sources: usize,
    pub fixtures_per_storey: FxHashMap<String, usize>,
    pub fixture_types_used: Vec<String>,
    /// Total luminous flux if available
    pub total_luminous_flux: Option<f64>,
}

/// Extract lighting data from an IFC model
pub fn extract_lighting_data(resolver: &dyn EntityResolver) -> LightingExport {
    let mut export = LightingExport {
        schema: String::new(),
        project_name: None,
        building_name: None,
        storeys: Vec::new(),
        light_fixtures: Vec::new(),
        light_fixture_types: Vec::new(),
        summary: LightingSummary {
            total_fixtures: 0,
            total_light_sources: 0,
            fixtures_per_storey: FxHashMap::default(),
            fixture_types_used: Vec::new(),
            total_luminous_flux: None,
        },
    };

    // Extract project info
    let projects = resolver.entities_by_type(&IfcType::IfcProject);
    if let Some(project) = projects.first() {
        export.project_name = project.get_string(2).map(|s| s.to_string());
    }

    // Extract building info
    let buildings = resolver.entities_by_type(&IfcType::IfcBuilding);
    if let Some(building) = buildings.first() {
        export.building_name = building.get_string(2).map(|s| s.to_string());
    }

    // Extract storeys
    let storeys = resolver.entities_by_type(&IfcType::IfcBuildingStorey);
    for storey in storeys {
        let name = storey
            .get_string(2)
            .map(|s| s.to_string())
            .unwrap_or_default();
        let elevation = storey.get_float(9).unwrap_or(0.0);
        export.storeys.push(StoreyData {
            id: storey.id.0 as u64,
            name,
            elevation,
        });
    }

    // Extract light fixture types
    let fixture_types = resolver.entities_by_type(&IfcType::IfcLightFixtureType);
    for fixture_type in fixture_types {
        let type_data = extract_fixture_type(&fixture_type);
        export.light_fixture_types.push(type_data);
    }

    // Extract light fixtures
    let fixtures = resolver.entities_by_type(&IfcType::IfcLightFixture);
    let mut total_flux: f64 = 0.0;
    let mut has_flux = false;

    for fixture in fixtures {
        let fixture_data = extract_fixture(&fixture, resolver);

        // Update summary
        if let Some(ref storey) = fixture_data.storey {
            *export
                .summary
                .fixtures_per_storey
                .entry(storey.clone())
                .or_insert(0) += 1;
        }

        for source in &fixture_data.light_sources {
            if let Some(flux) = source.luminous_flux {
                total_flux += flux;
                has_flux = true;
            }
        }

        export.summary.total_light_sources += fixture_data.light_sources.len();
        export.light_fixtures.push(fixture_data);
    }

    export.summary.total_fixtures = export.light_fixtures.len();
    if has_flux {
        export.summary.total_luminous_flux = Some(total_flux);
    }

    // Collect unique fixture types used
    for fixture in &export.light_fixtures {
        if let Some(ref ft) = fixture.fixture_type {
            if let Some(ref name) = ft.name {
                if !export.summary.fixture_types_used.contains(name) {
                    export.summary.fixture_types_used.push(name.clone());
                }
            }
        }
    }

    export
}

/// Extract data from a light fixture type entity
fn extract_fixture_type(entity: &DecodedEntity) -> LightFixtureTypeData {
    LightFixtureTypeData {
        id: entity.id.0 as u64,
        name: entity.get_string(2).map(|s| s.to_string()),
        description: entity.get_string(3).map(|s| s.to_string()),
        predefined_type: entity.get_enum(9).map(|s| s.to_string()),
    }
}

/// Extract data from a light fixture entity
fn extract_fixture(entity: &DecodedEntity, resolver: &dyn EntityResolver) -> LightFixtureData {
    let global_id = entity.get_string(0).map(|s| s.to_string());
    let name = entity.get_string(2).map(|s| s.to_string());
    let description = entity.get_string(3).map(|s| s.to_string());
    let object_type = entity.get_string(4).map(|s| s.to_string());

    // Get position from placement
    let position = extract_position(entity, resolver);

    // Get fixture type
    let fixture_type = entity.get_ref(5).and_then(|type_ref| {
        resolver
            .get(type_ref)
            .map(|type_entity| extract_fixture_type(&type_entity))
    });

    // Extract light sources associated with this fixture
    // In IFC, light sources are typically referenced through the representation
    let light_sources = extract_light_sources(entity, resolver);

    LightFixtureData {
        id: entity.id.0 as u64,
        global_id,
        name,
        description,
        object_type,
        position,
        storey: None, // Could be populated from spatial containment
        storey_elevation: None,
        fixture_type,
        light_sources,
        properties: FxHashMap::default(),
    }
}

/// Extract position from entity placement
fn extract_position(entity: &DecodedEntity, resolver: &dyn EntityResolver) -> (f64, f64, f64) {
    // ObjectPlacement is typically at index 5 for IfcProduct
    let placement_ref = match entity.get_ref(5) {
        Some(id) => id,
        None => return (0.0, 0.0, 0.0),
    };

    let placement = match resolver.get(placement_ref) {
        Some(p) => p,
        None => return (0.0, 0.0, 0.0),
    };

    // IfcLocalPlacement has RelativePlacement at index 1
    if placement.ifc_type == IfcType::IfcLocalPlacement {
        if let Some(rel_placement_ref) = placement.get_ref(1) {
            if let Some(axis_placement) = resolver.get(rel_placement_ref) {
                return extract_cartesian_point(&axis_placement, resolver);
            }
        }
    }

    (0.0, 0.0, 0.0)
}

/// Extract coordinates from axis placement
fn extract_cartesian_point(
    axis_placement: &DecodedEntity,
    resolver: &dyn EntityResolver,
) -> (f64, f64, f64) {
    // IfcAxis2Placement3D has Location at index 0
    let point_ref = match axis_placement.get_ref(0) {
        Some(id) => id,
        None => return (0.0, 0.0, 0.0),
    };

    let point = match resolver.get(point_ref) {
        Some(p) => p,
        None => return (0.0, 0.0, 0.0),
    };

    if point.ifc_type == IfcType::IfcCartesianPoint {
        // Coordinates are in a list at index 0
        if let Some(coords) = point.get_list(0) {
            let x = coords.first().and_then(|v| v.as_float()).unwrap_or(0.0);
            let y = coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0);
            let z = coords.get(2).and_then(|v| v.as_float()).unwrap_or(0.0);
            return (x, y, z);
        }
    }

    (0.0, 0.0, 0.0)
}

/// Extract light sources from a fixture via IFCRELASSIGNSTOGROUP
///
/// GLDF-exported IFC files use IFCRELASSIGNSTOGROUP to link light sources
/// to their parent fixture. The relationship has:
/// - Attribute 5: RelatedObjects (list of light sources)
/// - Attribute 6: RelatingGroup (the fixture entity)
fn extract_light_sources(
    fixture: &DecodedEntity,
    resolver: &dyn EntityResolver,
) -> Vec<LightSourceData> {
    let fixture_id = fixture.id;

    // Find IFCRELASSIGNSTOGROUP where RelatingGroup (attr 6) points to this fixture
    let group_rels = resolver.entities_by_type(&IfcType::IfcRelAssignsToGroup);
    for rel in &group_rels {
        if let Some(group_ref) = rel.get_ref(6) {
            if group_ref == fixture_id {
                // Found the group assignment for this fixture
                if let Some(related_list) = rel.get_list(5) {
                    return related_list
                        .iter()
                        .filter_map(|item| {
                            if let AttributeValue::EntityRef(source_id) = item {
                                resolver.get(*source_id).and_then(|source| {
                                    if source.ifc_type == IfcType::IfcLightSourceGoniometric {
                                        Some(extract_goniometric_source(&source, resolver))
                                    } else {
                                        None
                                    }
                                })
                            } else {
                                None
                            }
                        })
                        .collect();
                }
            }
        }
    }

    // Fallback: walk fixture's Representation → ShapeRepresentations to find
    // IfcLightSourceGoniometric (used by Relux-exported IFC files which embed
    // goniometric sources directly in the fixture's representation geometry).
    let mut sources = Vec::new();

    // IfcProduct.Representation is at index 6
    if let Some(pds_id) = fixture.get_ref(6) {
        if let Some(pds) = resolver.get(pds_id) {
            // IfcProductDefinitionShape.Representations at index 2
            if let Some(rep_refs) = pds.get_refs(2) {
                for rep_id in rep_refs {
                    if let Some(rep) = resolver.get(rep_id) {
                        // ShapeRepresentation.Items at index 3
                        find_goniometric_in_items(&rep, resolver, &mut sources);
                    }
                }
            }
        }
    }

    // Also check type's RepresentationMaps (for instanced fixtures)
    if sources.is_empty() {
        let type_rels = resolver.entities_by_type(&IfcType::IfcRelDefinesByType);
        for rel in &type_rels {
            if let Some(related_list) = rel.get_list(4) {
                let is_related = related_list
                    .iter()
                    .any(|v| v.as_entity_ref() == Some(fixture_id));
                if is_related {
                    if let Some(type_id) = rel.get_ref(5) {
                        if let Some(type_entity) = resolver.get(type_id) {
                            // IfcTypeProduct.RepresentationMaps at index 6
                            if let Some(map_refs) = type_entity.get_refs(6) {
                                for map_id in map_refs {
                                    if let Some(map) = resolver.get(map_id) {
                                        // RepresentationMap.MappedRepresentation at index 1
                                        if let Some(mapped_rep_id) = map.get_ref(1) {
                                            if let Some(mapped_rep) = resolver.get(mapped_rep_id) {
                                                find_goniometric_in_items(
                                                    &mapped_rep,
                                                    resolver,
                                                    &mut sources,
                                                );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    sources
}

/// Recursively find IfcLightSourceGoniometric in representation items (direct or via MappedItem)
fn find_goniometric_in_items(
    rep: &DecodedEntity,
    resolver: &dyn EntityResolver,
    sources: &mut Vec<LightSourceData>,
) {
    let item_refs = match rep.get_refs(3) {
        Some(refs) => refs,
        None => return,
    };

    for item_id in item_refs {
        if let Some(item) = resolver.get(item_id) {
            match item.ifc_type {
                IfcType::IfcLightSourceGoniometric => {
                    sources.push(extract_goniometric_source(&item, resolver));
                }
                IfcType::IfcMappedItem => {
                    // Follow MappedItem → RepresentationMap → ShapeRepresentation
                    if let Some(map_id) = item.get_ref(0) {
                        if let Some(map) = resolver.get(map_id) {
                            if let Some(mapped_rep_id) = map.get_ref(1) {
                                if let Some(mapped_rep) = resolver.get(mapped_rep_id) {
                                    find_goniometric_in_items(&mapped_rep, resolver, sources);
                                }
                            }
                        }
                    }
                }
                _ => {}
            }
        }
    }
}

/// Extract data from a goniometric light source
fn extract_goniometric_source(
    entity: &DecodedEntity,
    resolver: &dyn EntityResolver,
) -> LightSourceData {
    // IfcLightSourceGoniometric attributes:
    // 0: Name
    // 1: LightColour (IfcColourRgb)
    // 2: AmbientIntensity
    // 3: Intensity
    // 4: Position (IfcAxis2Placement3D)
    // 5: ColourAppearance (IfcColourRgb)
    // 6: ColourTemperature
    // 7: LuminousFlux
    // 8: LightEmissionSource
    // 9: LightDistributionDataSource

    let color_temperature = entity.get_float(6);
    let luminous_flux = entity.get_float(7);
    let emission_source = entity.get_enum(8).map(|s| s.to_string());
    let intensity = entity.get_float(3);

    // Extract color RGB
    let color_rgb = entity.get_ref(1).and_then(|color_ref| {
        resolver.get(color_ref).and_then(|color| {
            let r = color.get_float(1)?;
            let g = color.get_float(2)?;
            let b = color.get_float(3)?;
            Some((r, g, b))
        })
    });

    // Extract distribution data
    let distribution = entity.get_ref(9).and_then(|dist_ref| {
        resolver
            .get(dist_ref)
            .map(|dist| extract_distribution(&dist, resolver))
    });

    LightSourceData {
        id: entity.id.0 as u64,
        source_type: "GONIOMETRIC".to_string(),
        color_temperature,
        luminous_flux,
        emission_source,
        intensity,
        color_rgb,
        distribution,
    }
}

/// Extract light intensity distribution data
fn extract_distribution(
    entity: &DecodedEntity,
    resolver: &dyn EntityResolver,
) -> LightDistributionData {
    // IfcLightIntensityDistribution attributes:
    // 0: LightDistributionCurve (enum: TYPE_A, TYPE_B, TYPE_C)
    // 1: DistributionData (list of IfcLightDistributionData)

    let distribution_type = entity
        .get_enum(0)
        .map(|s| s.to_string())
        .unwrap_or_else(|| "TYPE_C".to_string());

    let mut planes = Vec::new();

    if let Some(data_list) = entity.get_list(1) {
        for data_item in data_list {
            if let AttributeValue::EntityRef(data_ref) = data_item {
                if let Some(data_entity) = resolver.get(*data_ref) {
                    // IfcLightDistributionData:
                    // 0: MainPlaneAngle
                    // 1: SecondaryPlaneAngle (list)
                    // 2: LuminousIntensity (list)

                    let main_angle = data_entity.get_float(0).unwrap_or(0.0);
                    let mut intensities = Vec::new();

                    if let (Some(angles), Some(values)) =
                        (data_entity.get_list(1), data_entity.get_list(2))
                    {
                        for (angle, value) in angles.iter().zip(values.iter()) {
                            let a = angle.as_float().unwrap_or(0.0);
                            let v = value.as_float().unwrap_or(0.0);
                            intensities.push((a, v));
                        }
                    }

                    planes.push(DistributionPlane {
                        main_angle,
                        intensities,
                    });
                }
            }
        }
    }

    LightDistributionData {
        distribution_type,
        planes,
    }
}

/// Convert a `LightSourceData` (from IFC goniometric extraction) to an `Eulumdat` struct.
///
/// Returns `None` if the source has no distribution data or no distribution planes.
pub fn light_source_to_eulumdat(source: &LightSourceData) -> Option<eulumdat::Eulumdat> {
    let dist = source.distribution.as_ref()?;
    if dist.planes.is_empty() {
        return None;
    }

    let c_angles: Vec<f64> = dist.planes.iter().map(|p| p.main_angle).collect();
    let g_angles: Vec<f64> = dist.planes[0].intensities.iter().map(|(a, _)| *a).collect();
    let flux = source.luminous_flux.unwrap_or(0.0);
    let temp = source.color_temperature.unwrap_or(0.0);
    let emitter = source.emission_source.clone().unwrap_or_default();

    let intensities: Vec<Vec<f64>> = dist
        .planes
        .iter()
        .map(|p| p.intensities.iter().map(|(_, v)| *v).collect())
        .collect();

    Some(build_eulumdat(
        String::new(),
        &c_angles,
        &g_angles,
        flux,
        temp,
        &emitter,
        &intensities,
    ))
}

/// Convenience wrapper: convert `LightSourceData` → LDT string.
///
/// Returns `None` if the source has no distribution data.
pub fn light_source_to_ldt(source: &LightSourceData) -> Option<String> {
    light_source_to_eulumdat(source).map(|ldt| ldt.to_ldt())
}

/// Convert a `GoniometricData` (from `PropertyReader::goniometric_sources()`) to `Eulumdat`.
pub fn goniometric_to_eulumdat(src: &bimifc_model::GoniometricData) -> eulumdat::Eulumdat {
    let c_angles: Vec<f64> = src.planes.iter().map(|p| p.c_angle).collect();
    let g_angles: Vec<f64> = if src.planes.is_empty() {
        Vec::new()
    } else {
        src.planes[0].gamma_angles.clone()
    };

    let intensities: Vec<Vec<f64>> = src.planes.iter().map(|p| p.intensities.clone()).collect();

    build_eulumdat(
        src.name.clone(),
        &c_angles,
        &g_angles,
        src.luminous_flux,
        src.colour_temperature,
        &src.emitter_type,
        &intensities,
    )
}

/// Convenience wrapper: convert `GoniometricData` → LDT string.
pub fn goniometric_to_ldt(src: &bimifc_model::GoniometricData) -> String {
    goniometric_to_eulumdat(src).to_ldt()
}

/// Shared helper that builds an `Eulumdat` struct from raw photometric parameters.
fn build_eulumdat(
    name: String,
    c_angles: &[f64],
    g_angles: &[f64],
    luminous_flux: f64,
    colour_temperature: f64,
    emitter_type: &str,
    intensities_cd: &[Vec<f64>],
) -> eulumdat::Eulumdat {
    use eulumdat::{Eulumdat, LampSet, Symmetry};

    let mut ldt = Eulumdat::new();
    ldt.luminaire_name = name;

    ldt.c_angles = c_angles.to_vec();
    ldt.g_angles = g_angles.to_vec();
    ldt.num_c_planes = ldt.c_angles.len();
    ldt.num_g_planes = ldt.g_angles.len();

    if ldt.num_c_planes > 1 {
        ldt.c_plane_distance = ldt.c_angles[1] - ldt.c_angles[0];
    }
    if ldt.num_g_planes > 1 {
        ldt.g_plane_distance = ldt.g_angles[1] - ldt.g_angles[0];
    }

    // Determine symmetry from C-plane coverage
    let max_c = ldt.c_angles.last().copied().unwrap_or(0.0);
    ldt.symmetry = if max_c <= 1.0 {
        Symmetry::VerticalAxis
    } else if max_c <= 91.0 {
        Symmetry::BothPlanes
    } else if max_c <= 181.0 {
        Symmetry::PlaneC0C180
    } else {
        Symmetry::None
    };

    // Convert absolute cd → cd/klm by dividing by (flux/1000)
    let flux_factor = if luminous_flux > 0.0 {
        luminous_flux / 1000.0
    } else {
        1.0
    };

    ldt.intensities = intensities_cd
        .iter()
        .map(|plane| plane.iter().map(|&v| v / flux_factor).collect())
        .collect();

    // Lamp set
    let cct_str = if colour_temperature > 0.0 {
        format!("{:.0}K", colour_temperature)
    } else {
        String::new()
    };
    ldt.lamp_sets.push(LampSet {
        num_lamps: 1,
        lamp_type: emitter_type.to_string(),
        total_luminous_flux: luminous_flux,
        color_appearance: cct_str,
        color_rendering_group: String::new(),
        wattage_with_ballast: 0.0,
    });

    ldt.conversion_factor = flux_factor;

    ldt
}

/// Export lighting data to JSON format compatible with gldf-ifc-viewer
pub fn export_to_json(export: &LightingExport) -> String {
    serde_json::to_string_pretty(export).unwrap_or_else(|_| "{}".to_string())
}

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

    #[test]
    fn test_light_fixture_data_serialization() {
        let fixture = LightFixtureData {
            id: 123,
            global_id: Some("abc-def".to_string()),
            name: Some("Test Fixture".to_string()),
            description: None,
            object_type: None,
            position: (1.0, 2.0, 3.0),
            storey: Some("Ground Floor".to_string()),
            storey_elevation: Some(0.0),
            fixture_type: None,
            light_sources: vec![],
            properties: FxHashMap::default(),
        };

        let json = serde_json::to_string(&fixture).unwrap();
        assert!(json.contains("Test Fixture"));
        assert!(json.contains("123"));
    }

    #[test]
    fn test_gldf_light_sources_per_fixture() {
        // Test that extract_light_sources correctly uses IFCRELASSIGNSTOGROUP
        // to assign sources to their specific fixture (not all sources to all fixtures)
        let gldf_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("ifc/gldf-exported.ifc");

        if !gldf_path.exists() {
            // Skip if file not available
            return;
        }

        let content = std::fs::read_to_string(&gldf_path).unwrap();
        let parser = crate::StepParser::new();
        let model = parser.parse(&content).unwrap();
        let export = extract_lighting_data(model.resolver());

        // GLDF file has 3 fixtures, each with exactly 2 light sources
        assert_eq!(export.light_fixtures.len(), 3);
        for fixture in &export.light_fixtures {
            eprintln!(
                "Fixture #{} '{}': {} sources",
                fixture.id,
                fixture.name.as_deref().unwrap_or("?"),
                fixture.light_sources.len()
            );
            for s in &fixture.light_sources {
                eprintln!(
                    "  Source #{}: flux={:?} dist={}",
                    s.id,
                    s.luminous_flux,
                    s.distribution
                        .as_ref()
                        .map(|d| format!("{} planes", d.planes.len()))
                        .unwrap_or_else(|| "none".to_string())
                );
            }
            assert_eq!(
                fixture.light_sources.len(),
                2,
                "Fixture '{}' (#{}) should have 2 sources, got {}",
                fixture.name.as_deref().unwrap_or("?"),
                fixture.id,
                fixture.light_sources.len()
            );
        }
        // Total: 6 sources (not 18 from the old bug)
        assert_eq!(export.summary.total_light_sources, 6);
    }

    #[test]
    fn test_relux_light_sources_via_representation() {
        // Test that extract_light_sources falls back to representation walking
        // for Relux-exported IFC files (no IfcRelAssignsToGroup)
        let relux_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("ifc/relux-test.ifc");

        if !relux_path.exists() {
            return;
        }

        let content = std::fs::read_to_string(&relux_path).unwrap();
        let parser = crate::StepParser::new();
        let model = parser.parse(&content).unwrap();
        let export = extract_lighting_data(model.resolver());

        eprintln!("Relux fixtures: {}", export.light_fixtures.len());
        for fixture in &export.light_fixtures {
            eprintln!(
                "Fixture #{} '{}': {} sources",
                fixture.id,
                fixture.name.as_deref().unwrap_or("?"),
                fixture.light_sources.len()
            );
            for s in &fixture.light_sources {
                eprintln!(
                    "  Source #{}: flux={:?} dist={}",
                    s.id,
                    s.luminous_flux,
                    s.distribution
                        .as_ref()
                        .map(|d| format!("{} ({} planes)", d.distribution_type, d.planes.len()))
                        .unwrap_or_else(|| "none".to_string())
                );
            }
        }

        // Relux file should have fixtures with light sources found via representation
        assert!(
            !export.light_fixtures.is_empty(),
            "Expected light fixtures in relux-test.ifc"
        );
        let total_sources: usize = export
            .light_fixtures
            .iter()
            .map(|f| f.light_sources.len())
            .sum();
        assert!(
            total_sources > 0,
            "Expected light sources in relux-test.ifc fixtures"
        );
    }
}