eulumdat 0.6.0

Eulumdat (LDT) and IES photometric file parser, writer, and validator for Rust
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
//! Photometric calculations for Eulumdat data.
//!
//! Implements standard lighting calculations including:
//! - Downward flux fraction
//! - Total luminous output
//! - Utilization factors (direct ratios)

use crate::eulumdat::{Eulumdat, Symmetry};
use crate::type_b_conversion::TypeBConversion;
use std::f64::consts::PI;

/// Photometric calculations on Eulumdat data.
pub struct PhotometricCalculations;

impl PhotometricCalculations {
    /// Calculate the downward flux fraction up to a given arc angle.
    ///
    /// Integrates the luminous intensity distribution from 0° to the specified
    /// arc angle to determine the percentage of light directed downward.
    ///
    /// # Arguments
    /// * `ldt` - The Eulumdat data
    /// * `arc` - The maximum angle from vertical (0° = straight down, 90° = horizontal)
    ///
    /// # Returns
    /// The downward flux fraction as a percentage (0-100).
    pub fn downward_flux(ldt: &Eulumdat, arc: f64) -> f64 {
        let total_output = Self::total_output(ldt);
        if total_output <= 0.0 {
            return 0.0;
        }

        let downward = match ldt.symmetry {
            Symmetry::None => Self::downward_no_symmetry(ldt, arc),
            Symmetry::VerticalAxis => Self::downward_for_plane(ldt, 0, arc),
            Symmetry::PlaneC0C180 => Self::downward_c0_c180(ldt, arc),
            Symmetry::PlaneC90C270 => Self::downward_c90_c270(ldt, arc),
            Symmetry::BothPlanes => Self::downward_both_planes(ldt, arc),
        };

        100.0 * downward / total_output
    }

    /// Calculate downward flux for no symmetry case.
    fn downward_no_symmetry(ldt: &Eulumdat, arc: f64) -> f64 {
        let mc = ldt.actual_c_planes();
        if mc == 0 || ldt.c_angles.is_empty() {
            return 0.0;
        }

        let mut sum = 0.0;

        for i in 1..mc {
            let delta_c = ldt.c_angles[i] - ldt.c_angles[i - 1];
            sum += delta_c * Self::downward_for_plane(ldt, i - 1, arc);
        }

        // Handle wrap-around from last plane to first
        if mc > 1 {
            let delta_c = 360.0 - ldt.c_angles[mc - 1];
            sum += delta_c * Self::downward_for_plane(ldt, mc - 1, arc);
        }

        sum / 360.0
    }

    /// Calculate downward flux for C0-C180 symmetry.
    fn downward_c0_c180(ldt: &Eulumdat, arc: f64) -> f64 {
        let mc = ldt.actual_c_planes();
        if mc == 0 || ldt.c_angles.is_empty() {
            return 0.0;
        }

        let mut sum = 0.0;

        for i in 1..mc {
            let delta_c = ldt.c_angles[i] - ldt.c_angles[i - 1];
            sum += 2.0 * delta_c * Self::downward_for_plane(ldt, i - 1, arc);
        }

        // Handle to 180°
        if mc > 0 {
            let delta_c = 180.0 - ldt.c_angles[mc - 1];
            sum += 2.0 * delta_c * Self::downward_for_plane(ldt, mc - 1, arc);
        }

        sum / 360.0
    }

    /// Calculate downward flux for C90-C270 symmetry.
    fn downward_c90_c270(ldt: &Eulumdat, arc: f64) -> f64 {
        // Similar to C0-C180 but shifted
        Self::downward_c0_c180(ldt, arc)
    }

    /// Calculate downward flux for both planes symmetry.
    fn downward_both_planes(ldt: &Eulumdat, arc: f64) -> f64 {
        let mc = ldt.actual_c_planes();
        if mc == 0 || ldt.c_angles.is_empty() {
            return 0.0;
        }

        let mut sum = 0.0;

        for i in 1..mc {
            let delta_c = ldt.c_angles[i] - ldt.c_angles[i - 1];
            sum += 4.0 * delta_c * Self::downward_for_plane(ldt, i - 1, arc);
        }

        // Handle to 90°
        if mc > 0 {
            let delta_c = 90.0 - ldt.c_angles[mc - 1];
            sum += 4.0 * delta_c * Self::downward_for_plane(ldt, mc - 1, arc);
        }

        sum / 360.0
    }

    /// Calculate downward flux for a single C-plane up to arc angle.
    fn downward_for_plane(ldt: &Eulumdat, c_index: usize, arc: f64) -> f64 {
        if c_index >= ldt.intensities.len() || ldt.g_angles.is_empty() {
            return 0.0;
        }

        let intensities = &ldt.intensities[c_index];
        let mut sum = 0.0;

        for j in 1..ldt.g_angles.len() {
            let g_prev = ldt.g_angles[j - 1];
            let g_curr = ldt.g_angles[j];

            // Only integrate up to arc angle
            if g_prev >= arc {
                break;
            }

            let g_end = g_curr.min(arc);
            let delta_g = g_end - g_prev;

            if delta_g <= 0.0 {
                continue;
            }

            // Average intensity in this segment
            let i_prev = intensities.get(j - 1).copied().unwrap_or(0.0);
            let i_curr = intensities.get(j).copied().unwrap_or(0.0);
            let avg_intensity = (i_prev + i_curr) / 2.0;

            // Convert to radians for solid angle calculation
            let g_prev_rad = g_prev * PI / 180.0;
            let g_end_rad = g_end * PI / 180.0;

            // Solid angle element: sin(g) * dg
            let solid_angle = (g_prev_rad.cos() - g_end_rad.cos()).abs();

            sum += avg_intensity * solid_angle;
        }

        sum * 2.0 * PI
    }

    /// Calculate total luminous output.
    ///
    /// Integrates the luminous intensity over the entire sphere.
    pub fn total_output(ldt: &Eulumdat) -> f64 {
        // Use downward_flux with 180° to get full sphere
        let mc = ldt.actual_c_planes();
        if mc == 0 {
            return 0.0;
        }

        match ldt.symmetry {
            Symmetry::None => Self::downward_no_symmetry(ldt, 180.0),
            Symmetry::VerticalAxis => Self::downward_for_plane(ldt, 0, 180.0),
            Symmetry::PlaneC0C180 => Self::downward_c0_c180(ldt, 180.0),
            Symmetry::PlaneC90C270 => Self::downward_c90_c270(ldt, 180.0),
            Symmetry::BothPlanes => Self::downward_both_planes(ldt, 180.0),
        }
    }

    /// Calculate the luminous flux from the stored intensity distribution.
    ///
    /// This uses the conversion factor to convert from cd/klm to actual lumens.
    pub fn calculated_luminous_flux(ldt: &Eulumdat) -> f64 {
        Self::total_output(ldt) * ldt.conversion_factor
    }

    /// Calculate direct ratios (utilization factors) for standard room indices.
    ///
    /// Room indices k: 0.60, 0.80, 1.00, 1.25, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00
    ///
    /// # Arguments
    /// * `ldt` - The Eulumdat data
    /// * `shr` - Spacing to Height Ratio (typically "1.00", "1.25", or "1.50")
    ///
    /// # Returns
    /// Array of 10 direct ratio values for the standard room indices.
    pub fn calculate_direct_ratios(ldt: &Eulumdat, shr: &str) -> [f64; 10] {
        // Coefficient lookup tables from standard
        let (e, f, g, h) = Self::get_shr_coefficients(shr);

        // Calculate flux values at critical angles
        let a = Self::downward_flux(ldt, 41.4);
        let b = Self::downward_flux(ldt, 60.0);
        let c = Self::downward_flux(ldt, 75.5);
        let d = Self::downward_flux(ldt, 90.0);

        let mut ratios = [0.0; 10];

        for i in 0..10 {
            let t = a * e[i] + b * f[i] + c * g[i] + d * h[i];
            ratios[i] = t / 100_000.0;
        }

        ratios
    }

    /// Get SHR coefficients for direct ratio calculation.
    fn get_shr_coefficients(shr: &str) -> ([f64; 10], [f64; 10], [f64; 10], [f64; 10]) {
        match shr {
            "1.00" => (
                [
                    943.0, 752.0, 636.0, 510.0, 429.0, 354.0, 286.0, 258.0, 236.0, 231.0,
                ],
                [
                    -317.0, -33.0, 121.0, 238.0, 275.0, 248.0, 190.0, 118.0, -6.0, -99.0,
                ],
                [
                    481.0, 372.0, 310.0, 282.0, 309.0, 363.0, 416.0, 463.0, 512.0, 518.0,
                ],
                [
                    -107.0, -91.0, -67.0, -30.0, -13.0, 35.0, 108.0, 161.0, 258.0, 350.0,
                ],
            ),
            "1.25" => (
                [
                    967.0, 808.0, 695.0, 565.0, 476.0, 386.0, 307.0, 273.0, 243.0, 234.0,
                ],
                [
                    -336.0, -82.0, 73.0, 200.0, 249.0, 243.0, 201.0, 137.0, 18.0, -73.0,
                ],
                [
                    451.0, 339.0, 280.0, 255.0, 278.0, 331.0, 384.0, 432.0, 485.0, 497.0,
                ],
                [
                    -82.0, -65.0, -48.0, -20.0, -3.0, 40.0, 108.0, 158.0, 254.0, 342.0,
                ],
            ),
            _ => (
                [
                    983.0, 851.0, 744.0, 614.0, 521.0, 418.0, 329.0, 289.0, 252.0, 239.0,
                ],
                [
                    -348.0, -122.0, 31.0, 163.0, 220.0, 231.0, 203.0, 149.0, 39.0, -48.0,
                ],
                [
                    430.0, 315.0, 256.0, 233.0, 253.0, 304.0, 356.0, 404.0, 460.0, 476.0,
                ],
                [
                    -65.0, -44.0, -31.0, -10.0, 6.0, 47.0, 112.0, 158.0, 249.0, 333.0,
                ],
            ),
        }
    }

    /// Calculate beam angle (full angle where intensity drops to 50% of maximum).
    ///
    /// Uses the IES definition: angle between directions where intensity is 50%
    /// of the **maximum** intensity (FWHM - Full Width at Half Maximum).
    ///
    /// **Important**: Per CIE S 017:2020 (17-27-077), beam angle is defined as a
    /// **full angle**, not a half angle. This function returns the full angle
    /// (2× the half-angle from nadir).
    ///
    /// Reference: <https://cie.co.at/eilvterm/17-27-077>
    pub fn beam_angle(ldt: &Eulumdat) -> f64 {
        // Return full angle (2× half angle) per CIE definition
        Self::angle_at_percentage(ldt, 0.5) * 2.0
    }

    /// Calculate field angle (full angle where intensity drops to 10% of maximum).
    ///
    /// Uses the IES definition: angle between directions where intensity is 10%
    /// of the **maximum** intensity.
    ///
    /// **Important**: Per CIE S 017:2020, field angle is defined as a **full angle**,
    /// not a half angle. This function returns the full angle (2× the half-angle from nadir).
    pub fn field_angle(ldt: &Eulumdat) -> f64 {
        // Return full angle (2× half angle) per CIE definition
        Self::angle_at_percentage(ldt, 0.1) * 2.0
    }

    /// Calculate beam angle using CIE definition (center-beam intensity).
    ///
    /// Uses the CIE/NEMA definition: angle between directions where intensity
    /// is 50% of the **center-beam** intensity (intensity at 0° gamma).
    ///
    /// **Important**: Per CIE S 017:2020 (17-27-077), beam angle is defined as a
    /// **full angle**, not a half angle. This function returns the full angle.
    ///
    /// This can differ significantly from the IES (max-based) definition for luminaires
    /// with "batwing" distributions where center-beam intensity is less than
    /// maximum intensity.
    pub fn beam_angle_cie(ldt: &Eulumdat) -> f64 {
        // Return full angle (2× half angle) per CIE definition
        Self::angle_at_percentage_of_center(ldt, 0.5) * 2.0
    }

    /// Calculate field angle using CIE definition (center-beam intensity).
    ///
    /// Uses the CIE/NEMA definition: angle between directions where intensity
    /// is 10% of the **center-beam** intensity.
    ///
    /// **Important**: Per CIE S 017:2020, field angle is defined as a **full angle**,
    /// not a half angle. This function returns the full angle.
    pub fn field_angle_cie(ldt: &Eulumdat) -> f64 {
        // Return full angle (2× half angle) per CIE definition
        Self::angle_at_percentage_of_center(ldt, 0.1) * 2.0
    }

    /// Calculate half beam angle (angle from nadir to 50% intensity).
    ///
    /// This returns the **half angle** from nadir (0°) to where intensity drops
    /// to 50% of maximum. For the full beam angle per CIE definition, use `beam_angle()`.
    ///
    /// This is useful for cone diagrams and coverage calculations where the
    /// half-angle is needed.
    pub fn half_beam_angle(ldt: &Eulumdat) -> f64 {
        Self::angle_at_percentage(ldt, 0.5)
    }

    /// Calculate half field angle (angle from nadir to 10% intensity).
    ///
    /// This returns the **half angle** from nadir (0°) to where intensity drops
    /// to 10% of maximum. For the full field angle per CIE definition, use `field_angle()`.
    pub fn half_field_angle(ldt: &Eulumdat) -> f64 {
        Self::angle_at_percentage(ldt, 0.1)
    }

    /// Get detailed beam/field angle analysis comparing IES and CIE definitions.
    ///
    /// Returns a `BeamFieldAnalysis` struct containing:
    /// - Beam and field angles using both IES (max) and CIE (center-beam) definitions
    /// - Maximum intensity and center-beam intensity values
    /// - Whether the distribution has a "batwing" pattern (center < max)
    ///
    /// This is useful for understanding luminaires like the examples in the
    /// Wikipedia "Beam angle" article where the two definitions give different results.
    pub fn beam_field_analysis(ldt: &Eulumdat) -> BeamFieldAnalysis {
        if ldt.intensities.is_empty() || ldt.g_angles.is_empty() {
            return BeamFieldAnalysis::default();
        }

        let intensities = &ldt.intensities[0];
        let max_intensity = intensities.iter().copied().fold(0.0, f64::max);
        let center_intensity = intensities.first().copied().unwrap_or(0.0);

        // Find the gamma angle of maximum intensity
        let max_gamma = ldt
            .g_angles
            .iter()
            .zip(intensities.iter())
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(g, _)| *g)
            .unwrap_or(0.0);

        let is_batwing = center_intensity < max_intensity * 0.95;

        BeamFieldAnalysis {
            // IES definition (based on maximum intensity) - full angles per CIE S 017:2020
            beam_angle_ies: Self::angle_at_percentage(ldt, 0.5) * 2.0,
            field_angle_ies: Self::angle_at_percentage(ldt, 0.1) * 2.0,
            // CIE definition (based on center-beam intensity) - full angles per CIE S 017:2020
            beam_angle_cie: Self::angle_at_percentage_of_center(ldt, 0.5) * 2.0,
            field_angle_cie: Self::angle_at_percentage_of_center(ldt, 0.1) * 2.0,
            // Reference intensities
            max_intensity,
            center_intensity,
            max_intensity_gamma: max_gamma,
            // Distribution type
            is_batwing,
            // Threshold values for diagram overlays
            beam_threshold_ies: max_intensity * 0.5,
            beam_threshold_cie: center_intensity * 0.5,
            field_threshold_ies: max_intensity * 0.1,
            field_threshold_cie: center_intensity * 0.1,
        }
    }

    /// Find the angle at which intensity drops to a given percentage of maximum.
    fn angle_at_percentage(ldt: &Eulumdat, percentage: f64) -> f64 {
        if ldt.intensities.is_empty() || ldt.g_angles.is_empty() {
            return 0.0;
        }

        // Use first C-plane (or average for non-symmetric)
        let intensities = &ldt.intensities[0];
        let max_intensity = intensities.iter().copied().fold(0.0, f64::max);

        if max_intensity <= 0.0 {
            return 0.0;
        }

        let threshold = max_intensity * percentage;

        // Find where intensity drops below threshold
        for (i, &intensity) in intensities.iter().enumerate() {
            if intensity < threshold && i > 0 {
                // Interpolate between previous and current
                let prev_intensity = intensities[i - 1];
                let prev_angle = ldt.g_angles[i - 1];
                let curr_angle = ldt.g_angles[i];

                if prev_intensity > threshold {
                    let ratio = (prev_intensity - threshold) / (prev_intensity - intensity);
                    return prev_angle + ratio * (curr_angle - prev_angle);
                }
            }
        }

        // If never drops below threshold, return last angle
        *ldt.g_angles.last().unwrap_or(&0.0)
    }

    /// Find the angle at which intensity drops to a given percentage of center-beam intensity.
    ///
    /// This implements the CIE/NEMA definition which uses center-beam (nadir) intensity
    /// as the reference rather than maximum intensity.
    fn angle_at_percentage_of_center(ldt: &Eulumdat, percentage: f64) -> f64 {
        if ldt.intensities.is_empty() || ldt.g_angles.is_empty() {
            return 0.0;
        }

        let intensities = &ldt.intensities[0];
        let center_intensity = intensities.first().copied().unwrap_or(0.0);

        if center_intensity <= 0.0 {
            // If center intensity is zero, fall back to max-based calculation
            return Self::angle_at_percentage(ldt, percentage);
        }

        let threshold = center_intensity * percentage;

        // Find where intensity drops below threshold
        for (i, &intensity) in intensities.iter().enumerate() {
            if intensity < threshold && i > 0 {
                let prev_intensity = intensities[i - 1];
                let prev_angle = ldt.g_angles[i - 1];
                let curr_angle = ldt.g_angles[i];

                if prev_intensity > threshold {
                    let ratio = (prev_intensity - threshold) / (prev_intensity - intensity);
                    return prev_angle + ratio * (curr_angle - prev_angle);
                }
            }
        }

        *ldt.g_angles.last().unwrap_or(&0.0)
    }

    /// Calculate beam angle for upward light (peak near 180°).
    ///
    /// For uplights where maximum intensity is in the upper hemisphere (gamma > 90°),
    /// this calculates the beam angle centered on the upward peak.
    ///
    /// Returns the **full angle** where intensity is above 50% of maximum.
    pub fn upward_beam_angle(ldt: &Eulumdat) -> f64 {
        Self::angle_spread_from_peak(ldt, 0.5, true)
    }

    /// Calculate field angle for upward light (peak near 180°).
    ///
    /// Returns the **full angle** where intensity is above 10% of maximum.
    pub fn upward_field_angle(ldt: &Eulumdat) -> f64 {
        Self::angle_spread_from_peak(ldt, 0.1, true)
    }

    /// Calculate beam angle for downward light (peak near 0°).
    ///
    /// For downlights where maximum intensity is in the lower hemisphere (gamma < 90°),
    /// this calculates the beam angle centered on the downward peak.
    ///
    /// Returns the **full angle** where intensity is above 50% of maximum.
    pub fn downward_beam_angle(ldt: &Eulumdat) -> f64 {
        Self::angle_spread_from_peak(ldt, 0.5, false)
    }

    /// Calculate field angle for downward light (peak near 0°).
    ///
    /// Returns the **full angle** where intensity is above 10% of maximum.
    pub fn downward_field_angle(ldt: &Eulumdat) -> f64 {
        Self::angle_spread_from_peak(ldt, 0.1, false)
    }

    /// Find the angular spread from peak intensity to threshold percentage.
    ///
    /// Searches outward from the peak intensity angle in both directions to find
    /// where intensity drops below the threshold. Works for both downlights
    /// (peak near 0°) and uplights (peak near 180°).
    ///
    /// # Arguments
    /// * `ldt` - The Eulumdat data
    /// * `percentage` - Threshold as fraction of peak (0.5 for beam, 0.1 for field)
    /// * `upward` - If true, find peak in upper hemisphere (90-180°); otherwise lower (0-90°)
    ///
    /// # Returns
    /// The full beam/field angle in degrees
    fn angle_spread_from_peak(ldt: &Eulumdat, percentage: f64, upward: bool) -> f64 {
        if ldt.intensities.is_empty() || ldt.g_angles.is_empty() {
            return 0.0;
        }

        let intensities = &ldt.intensities[0];
        let g_angles = &ldt.g_angles;

        // Define hemisphere boundary
        let hemisphere_boundary = 90.0;

        // Find peak intensity in the specified hemisphere
        let (peak_idx, peak_intensity) = if upward {
            // Search upper hemisphere (gamma >= 90°)
            intensities
                .iter()
                .enumerate()
                .filter(|(i, _)| g_angles.get(*i).copied().unwrap_or(0.0) >= hemisphere_boundary)
                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                .map(|(i, &v)| (i, v))
                .unwrap_or((0, 0.0))
        } else {
            // Search lower hemisphere (gamma <= 90°)
            intensities
                .iter()
                .enumerate()
                .filter(|(i, _)| g_angles.get(*i).copied().unwrap_or(180.0) <= hemisphere_boundary)
                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                .map(|(i, &v)| (i, v))
                .unwrap_or((0, 0.0))
        };

        if peak_intensity <= 0.0 {
            return 0.0;
        }

        let threshold = peak_intensity * percentage;
        let peak_angle = g_angles.get(peak_idx).copied().unwrap_or(0.0);

        // Determine search boundaries based on hemisphere
        let (min_angle, max_angle) = if upward {
            (hemisphere_boundary, 180.0)
        } else {
            (0.0, hemisphere_boundary)
        };

        // Search downward (decreasing gamma) from peak, but stay within hemisphere
        let mut angle_low = peak_angle;
        for i in (0..peak_idx).rev() {
            let angle = g_angles[i];
            // Stop at hemisphere boundary
            if angle < min_angle {
                angle_low = min_angle;
                break;
            }
            let intensity = intensities[i];
            if intensity < threshold {
                // Interpolate
                let next_intensity = intensities.get(i + 1).copied().unwrap_or(peak_intensity);
                let next_angle = g_angles.get(i + 1).copied().unwrap_or(peak_angle);
                if next_intensity > threshold && next_intensity > intensity {
                    let ratio = (next_intensity - threshold) / (next_intensity - intensity);
                    angle_low = (next_angle - ratio * (next_angle - angle)).max(min_angle);
                } else {
                    angle_low = angle;
                }
                break;
            }
            angle_low = angle;
        }

        // Search upward (increasing gamma) from peak, but stay within hemisphere
        let mut angle_high = peak_angle;
        for i in (peak_idx + 1)..intensities.len() {
            let angle = g_angles[i];
            // Stop at hemisphere boundary
            if angle > max_angle {
                angle_high = max_angle;
                break;
            }
            let intensity = intensities[i];
            if intensity < threshold {
                // Interpolate
                let prev_intensity = intensities.get(i - 1).copied().unwrap_or(peak_intensity);
                let prev_angle = g_angles.get(i - 1).copied().unwrap_or(peak_angle);
                if prev_intensity > threshold && prev_intensity > intensity {
                    let ratio = (prev_intensity - threshold) / (prev_intensity - intensity);
                    angle_high = (prev_angle + ratio * (angle - prev_angle)).min(max_angle);
                } else {
                    angle_high = angle;
                }
                break;
            }
            angle_high = angle;
        }

        // Return the full angular spread
        (angle_high - angle_low).abs()
    }

    /// Get comprehensive beam angle analysis including both downward and upward components.
    ///
    /// For luminaires with significant flux in both hemispheres (e.g., direct-indirect),
    /// this provides separate beam angles for each direction.
    pub fn comprehensive_beam_analysis(ldt: &Eulumdat) -> ComprehensiveBeamAnalysis {
        if ldt.intensities.is_empty() || ldt.g_angles.is_empty() {
            return ComprehensiveBeamAnalysis::default();
        }

        let intensities = &ldt.intensities[0];
        let g_angles = &ldt.g_angles;

        // Find peaks in each hemisphere
        let (downward_peak_idx, downward_peak) = intensities
            .iter()
            .enumerate()
            .filter(|(i, _)| g_angles.get(*i).copied().unwrap_or(180.0) <= 90.0)
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(i, &v)| (i, v))
            .unwrap_or((0, 0.0));

        let (upward_peak_idx, upward_peak) = intensities
            .iter()
            .enumerate()
            .filter(|(i, _)| g_angles.get(*i).copied().unwrap_or(0.0) >= 90.0)
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(i, &v)| (i, v))
            .unwrap_or((intensities.len().saturating_sub(1), 0.0));

        let downward_peak_gamma = g_angles.get(downward_peak_idx).copied().unwrap_or(0.0);
        let upward_peak_gamma = g_angles.get(upward_peak_idx).copied().unwrap_or(180.0);

        // Determine if there's significant light in each hemisphere
        let has_downward = downward_peak > 0.0;
        let has_upward = upward_peak > 0.0;

        // Calculate angles only for hemispheres with significant light
        let downward_beam = if has_downward {
            Self::angle_spread_from_peak(ldt, 0.5, false)
        } else {
            0.0
        };
        let downward_field = if has_downward {
            Self::angle_spread_from_peak(ldt, 0.1, false)
        } else {
            0.0
        };

        let upward_beam = if has_upward {
            Self::angle_spread_from_peak(ldt, 0.5, true)
        } else {
            0.0
        };
        let upward_field = if has_upward {
            Self::angle_spread_from_peak(ldt, 0.1, true)
        } else {
            0.0
        };

        // Determine primary direction
        let primary_direction = if downward_peak >= upward_peak {
            LightDirection::Downward
        } else {
            LightDirection::Upward
        };

        // Classify distribution type based on relative intensities
        // A component is "significant" if it's >= 10% of the dominant component
        let upward_significant = has_upward && upward_peak >= downward_peak * 0.1;
        let downward_significant = has_downward && downward_peak >= upward_peak * 0.1;

        let distribution_type = if upward_significant && downward_significant {
            // Both components are significant - it's a mixed distribution
            if downward_peak > upward_peak {
                DistributionType::DirectIndirect
            } else {
                DistributionType::IndirectDirect
            }
        } else if has_upward && upward_peak > downward_peak {
            // Primarily upward with negligible downward
            DistributionType::Indirect
        } else {
            // Primarily downward with negligible upward
            DistributionType::Direct
        };

        ComprehensiveBeamAnalysis {
            downward_beam_angle: downward_beam,
            downward_field_angle: downward_field,
            downward_peak_intensity: downward_peak,
            downward_peak_gamma,
            upward_beam_angle: upward_beam,
            upward_field_angle: upward_field,
            upward_peak_intensity: upward_peak,
            upward_peak_gamma,
            primary_direction,
            distribution_type,
        }
    }

    /// Calculate UGR (Unified Glare Rating) cross-section data.
    ///
    /// Returns intensity values at standard viewing angles for UGR calculation.
    pub fn ugr_crosssection(ldt: &Eulumdat) -> Vec<(f64, f64)> {
        // Standard UGR angles: 45°, 55°, 65°, 75°, 85°
        let ugr_angles = [45.0, 55.0, 65.0, 75.0, 85.0];

        ugr_angles
            .iter()
            .map(|&angle| {
                let intensity = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, 0.0, angle);
                (angle, intensity)
            })
            .collect()
    }

    // ========================================================================
    // CIE Flux Codes
    // ========================================================================

    /// Calculate CIE Flux Codes.
    ///
    /// Returns a tuple of 5 values (N1, N2, N3, N4, N5) representing the
    /// percentage of lamp flux in different angular zones:
    /// - N1: % in lower hemisphere (0-90°)
    /// - N2: % in 0-60° zone
    /// - N3: % in 0-40° zone
    /// - N4: % in upper hemisphere (90-180°)
    /// - N5: % in 90-120° zone (near-horizontal uplight)
    ///
    /// The flux code is typically written as: N1 N2 N3 N4 N5
    /// Example: "92 68 42 8 3" means 92% downward, 68% within 60°, etc.
    pub fn cie_flux_codes(ldt: &Eulumdat) -> CieFluxCodes {
        let total = Self::total_output(ldt);
        if total <= 0.0 {
            return CieFluxCodes::default();
        }

        // Calculate flux in each zone
        let flux_40 = Self::downward_flux(ldt, 40.0);
        let flux_60 = Self::downward_flux(ldt, 60.0);
        let flux_90 = Self::downward_flux(ldt, 90.0);
        let flux_120 = Self::downward_flux(ldt, 120.0);
        let flux_180 = Self::downward_flux(ldt, 180.0);

        CieFluxCodes {
            n1: flux_90,            // 0-90° (DLOR)
            n2: flux_60,            // 0-60°
            n3: flux_40,            // 0-40°
            n4: flux_180 - flux_90, // 90-180° (ULOR)
            n5: flux_120 - flux_90, // 90-120° (near-horizontal uplight)
        }
    }

    // ========================================================================
    // Luminaire Efficacy
    // ========================================================================

    /// Calculate luminaire efficacy in lm/W.
    ///
    /// This differs from lamp efficacy by accounting for the Light Output Ratio (LOR).
    /// Luminaire efficacy = (lamp flux × LOR) / system watts
    ///
    /// # Returns
    /// Luminaire efficacy in lumens per watt (lm/W)
    pub fn luminaire_efficacy(ldt: &Eulumdat) -> f64 {
        let total_watts = ldt.total_wattage();
        if total_watts <= 0.0 {
            return 0.0;
        }

        let lamp_flux = ldt.total_luminous_flux();
        let lor = ldt.light_output_ratio / 100.0;

        (lamp_flux * lor) / total_watts
    }

    /// Calculate luminaire efficiency (same as LOR but calculated from intensities).
    ///
    /// Compares calculated luminous flux to rated lamp flux.
    ///
    /// # Returns
    /// Efficiency as a percentage (0-100)
    pub fn luminaire_efficiency(ldt: &Eulumdat) -> f64 {
        let lamp_flux = ldt.total_luminous_flux();
        if lamp_flux <= 0.0 {
            return 0.0;
        }

        let calculated_flux = Self::calculated_luminous_flux(ldt);
        (calculated_flux / lamp_flux) * 100.0
    }

    // ========================================================================
    // Spacing Criterion (S/H Ratio)
    // ========================================================================

    /// Calculate the spacing criterion (S/H ratio) for uniform illumination.
    ///
    /// The spacing criterion indicates the maximum ratio of luminaire spacing
    /// to mounting height that will provide reasonably uniform illumination.
    ///
    /// # Arguments
    /// * `ldt` - The Eulumdat data
    /// * `c_plane` - The C-plane to analyze (typically 0 or 90)
    ///
    /// # Returns
    /// The spacing to height ratio (typically 1.0 to 2.0)
    pub fn spacing_criterion(ldt: &Eulumdat, c_plane: f64) -> f64 {
        if ldt.intensities.is_empty() || ldt.g_angles.is_empty() {
            return 1.0;
        }

        // Find intensity at nadir (0°)
        let i_nadir = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, c_plane, 0.0);
        if i_nadir <= 0.0 {
            return 1.0;
        }

        // Find angle where intensity drops to 50% of nadir
        let threshold = i_nadir * 0.5;
        let mut half_angle = 0.0;

        for g in 0..90 {
            let intensity =
                crate::symmetry::SymmetryHandler::get_intensity_at(ldt, c_plane, g as f64);
            if intensity < threshold {
                // Interpolate
                let prev_intensity = crate::symmetry::SymmetryHandler::get_intensity_at(
                    ldt,
                    c_plane,
                    (g - 1) as f64,
                );
                if prev_intensity > threshold {
                    let ratio = (prev_intensity - threshold) / (prev_intensity - intensity);
                    half_angle = (g - 1) as f64 + ratio;
                }
                break;
            }
            half_angle = g as f64;
        }

        // S/H = 2 * tan(half_angle)
        // Typical values: narrow beam = 0.8-1.0, wide beam = 1.5-2.0
        let s_h = 2.0 * (half_angle * PI / 180.0).tan();

        // Clamp to reasonable range
        s_h.clamp(0.5, 3.0)
    }

    /// Calculate spacing criteria for both principal planes.
    ///
    /// # Returns
    /// (S/H parallel, S/H perpendicular) - spacing ratios for C0 and C90 planes
    pub fn spacing_criteria(ldt: &Eulumdat) -> (f64, f64) {
        let s_h_parallel = Self::spacing_criterion(ldt, 0.0);
        let s_h_perpendicular = Self::spacing_criterion(ldt, 90.0);
        (s_h_parallel, s_h_perpendicular)
    }

    /// IES-style spacing criterion based on work plane illuminance uniformity.
    ///
    /// This method finds the maximum S/H ratio where illuminance uniformity
    /// (Emin/Emax) remains above the threshold (default 0.7) on the work plane.
    ///
    /// The IES method accounts for:
    /// - Inverse square law (1/d²)
    /// - Cosine law for horizontal illuminance (cos³θ)
    /// - Contribution from adjacent luminaires
    ///
    /// # Arguments
    /// * `ldt` - The Eulumdat data
    /// * `c_plane` - The C-plane to analyze (0 for 0-180, 90 for 90-270)
    /// * `uniformity_threshold` - Minimum Emin/Emax ratio (typically 0.7)
    ///
    /// # Returns
    /// The spacing to height ratio (typically 1.0 to 1.5)
    pub fn spacing_criterion_ies(ldt: &Eulumdat, c_plane: f64, uniformity_threshold: f64) -> f64 {
        if ldt.intensities.is_empty() || ldt.g_angles.is_empty() {
            return 1.0;
        }

        // Binary search for maximum S/H that maintains uniformity
        let mut low = 0.5;
        let mut high = 3.0;

        for _ in 0..20 {
            // 20 iterations gives ~6 decimal places precision
            let mid = (low + high) / 2.0;
            let uniformity = Self::calculate_illuminance_uniformity(ldt, c_plane, mid);

            if uniformity >= uniformity_threshold {
                low = mid; // Can space further apart
            } else {
                high = mid; // Need closer spacing
            }
        }

        low
    }

    /// Calculate illuminance uniformity for a given spacing ratio.
    ///
    /// Simulates illuminance from two luminaires spaced S/H apart along the
    /// specified C-plane, calculating Emin/Emax at multiple points.
    fn calculate_illuminance_uniformity(ldt: &Eulumdat, c_plane: f64, s_h: f64) -> f64 {
        // Sample points between luminaires (at height H=1 for normalization)
        const NUM_POINTS: usize = 21;
        let mut illuminances = [0.0; NUM_POINTS];

        // Luminaire positions: one at x=0, one at x=S (where S = s_h * H = s_h * 1)
        let spacing = s_h;

        for (i, e) in illuminances.iter_mut().enumerate() {
            // Sample point position (from x=0 to x=spacing)
            let x = (i as f64 / (NUM_POINTS - 1) as f64) * spacing;

            // Contribution from luminaire 1 at (0, 0)
            *e += Self::point_illuminance(ldt, c_plane, x, 1.0);

            // Contribution from luminaire 2 at (spacing, 0)
            *e += Self::point_illuminance(ldt, c_plane, spacing - x, 1.0);
        }

        // Calculate uniformity = Emin / Emax
        let e_max = illuminances.iter().cloned().fold(0.0, f64::max);
        let e_min = illuminances.iter().cloned().fold(f64::MAX, f64::min);

        if e_max > 0.0 {
            e_min / e_max
        } else {
            0.0
        }
    }

    /// Calculate horizontal illuminance at a point from a single luminaire.
    ///
    /// Uses the inverse square law and cosine³ correction for horizontal surfaces:
    /// E = I(θ) × cos³(θ) / H²
    ///
    /// where θ = atan(x/H) is the angle from nadir.
    fn point_illuminance(ldt: &Eulumdat, c_plane: f64, x: f64, h: f64) -> f64 {
        // Angle from nadir
        let theta = (x / h).atan();
        let theta_deg = theta.to_degrees();

        // Get intensity at this angle
        let intensity = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, c_plane, theta_deg);

        // Horizontal illuminance: E = I × cos³(θ) / H²
        // (cos³ accounts for both the angle of incidence and distance increase)
        let cos_theta = theta.cos();
        intensity * cos_theta.powi(3) / (h * h)
    }

    /// Calculate IES-style spacing criteria for both principal planes.
    ///
    /// Uses illuminance-based uniformity calculation per IES methodology.
    ///
    /// # Returns
    /// (SC 0-180, SC 90-270, SC diagonal)
    pub fn spacing_criteria_ies(ldt: &Eulumdat) -> (f64, f64, f64) {
        // IES LM-46 defines acceptable uniformity as Emin/Emax ≥ 0.87
        // for general indoor lighting applications
        let sc_0_180 = Self::spacing_criterion_ies(ldt, 0.0, 0.87);
        let sc_90_270 = Self::spacing_criterion_ies(ldt, 90.0, 0.87);
        // Diagonal SC is calculated for a 4-luminaire array at the center point
        // Typically SC_diagonal ≈ SC_principal × 1.1 (geometric factor for diagonal spacing)
        let sc_diagonal = sc_0_180.min(sc_90_270) * 1.10;
        (sc_0_180, sc_90_270, sc_diagonal)
    }

    // ========================================================================
    // Standard Zonal Lumens
    // ========================================================================

    /// Calculate luminous flux in standard angular zones.
    ///
    /// Returns flux percentages in 10° zones from 0° to 180°.
    ///
    /// # Returns
    /// Array of 18 values representing % flux in each 10° zone
    pub fn zonal_lumens_10deg(ldt: &Eulumdat) -> [f64; 18] {
        let mut zones = [0.0; 18];
        let total = Self::total_output(ldt);

        if total <= 0.0 {
            return zones;
        }

        let mut prev_flux = 0.0;
        for (i, zone) in zones.iter_mut().enumerate() {
            let angle = ((i + 1) * 10) as f64;
            let cumulative = Self::downward_flux(ldt, angle);
            *zone = cumulative - prev_flux;
            prev_flux = cumulative;
        }

        zones
    }

    /// Calculate luminous flux in standard 30° zones.
    ///
    /// # Returns
    /// ZonalLumens30 struct with flux in each 30° zone
    pub fn zonal_lumens_30deg(ldt: &Eulumdat) -> ZonalLumens30 {
        let total = Self::total_output(ldt);

        if total <= 0.0 {
            return ZonalLumens30::default();
        }

        let f30 = Self::downward_flux(ldt, 30.0);
        let f60 = Self::downward_flux(ldt, 60.0);
        let f90 = Self::downward_flux(ldt, 90.0);
        let f120 = Self::downward_flux(ldt, 120.0);
        let f150 = Self::downward_flux(ldt, 150.0);
        let f180 = Self::downward_flux(ldt, 180.0);

        ZonalLumens30 {
            zone_0_30: f30,
            zone_30_60: f60 - f30,
            zone_60_90: f90 - f60,
            zone_90_120: f120 - f90,
            zone_120_150: f150 - f120,
            zone_150_180: f180 - f150,
        }
    }

    // ========================================================================
    // K-Factor (Utilance)
    // ========================================================================

    /// Calculate the K-factor (utilance) for a room.
    ///
    /// K = (E_avg × A) / Φ_lamp
    ///
    /// Where:
    /// - E_avg = average illuminance on work plane
    /// - A = room area
    /// - Φ_lamp = total lamp flux
    ///
    /// # Arguments
    /// * `ldt` - The Eulumdat data
    /// * `room_index` - Room index k = (L×W) / (H_m × (L+W))
    /// * `reflectances` - (ceiling, wall, floor) reflectances as decimals
    ///
    /// # Returns
    /// K-factor (utilance) as a decimal (0-1)
    pub fn k_factor(ldt: &Eulumdat, room_index: f64, reflectances: (f64, f64, f64)) -> f64 {
        // Use direct ratio as base
        let room_index_idx = Self::room_index_to_idx(room_index);
        let direct_ratios = Self::calculate_direct_ratios(ldt, "1.25");
        let direct = direct_ratios[room_index_idx];

        // Apply reflection factors (simplified model)
        let (rho_c, rho_w, rho_f) = reflectances;

        // Indirect component depends on room reflectances
        let avg_reflectance = (rho_c + rho_w + rho_f) / 3.0;
        let indirect_factor = avg_reflectance / (1.0 - avg_reflectance);

        // Simplified: K ≈ direct × (1 + indirect_factor × upward_fraction)
        let upward_fraction = 1.0 - (ldt.downward_flux_fraction / 100.0);

        direct * (1.0 + indirect_factor * upward_fraction * 0.5)
    }

    /// Convert room index to array index for direct ratio lookup.
    fn room_index_to_idx(room_index: f64) -> usize {
        // Room indices: 0.60, 0.80, 1.00, 1.25, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00
        let indices = [0.60, 0.80, 1.00, 1.25, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00];

        for (i, &k) in indices.iter().enumerate() {
            if room_index <= k {
                return i;
            }
        }
        9 // Return last index if room_index > 5.0
    }

    // ========================================================================
    // Full UGR Calculation
    // ========================================================================

    /// Calculate UGR (Unified Glare Rating) for a specific room configuration.
    ///
    /// UGR = 8 × log₁₀((0.25/Lb) × Σ(L²×ω/p²))
    ///
    /// Where:
    /// - Lb = background luminance
    /// - L = luminaire luminance in direction of observer
    /// - ω = solid angle of luminaire
    /// - p = position index
    ///
    /// # Arguments
    /// * `ldt` - The Eulumdat data
    /// * `params` - UGR calculation parameters
    ///
    /// # Returns
    /// UGR value (typically 10-30, lower is better)
    pub fn ugr(ldt: &Eulumdat, params: &UgrParams) -> f64 {
        let luminaire_area = (ldt.length / 1000.0) * (ldt.width / 1000.0);
        if luminaire_area <= 0.0 {
            return 0.0;
        }

        // Background luminance (simplified: based on room reflectance and illuminance)
        let lb = params.background_luminance();

        let mut sum = 0.0;

        // Calculate for each luminaire position
        for pos in &params.luminaire_positions {
            // Viewing angle from observer to luminaire
            let dx = pos.0 - params.observer_x;
            let dy = pos.1 - params.observer_y;
            let dz = params.mounting_height - params.eye_height;

            let horizontal_dist = (dx * dx + dy * dy).sqrt();
            let viewing_angle = (horizontal_dist / dz).atan() * 180.0 / PI;

            // Get luminance in viewing direction
            let c_angle = dy.atan2(dx) * 180.0 / PI;
            let c_angle = if c_angle < 0.0 {
                c_angle + 360.0
            } else {
                c_angle
            };

            let intensity =
                crate::symmetry::SymmetryHandler::get_intensity_at(ldt, c_angle, viewing_angle);

            // Luminance = I / A (cd/m²)
            let luminance = intensity * 1000.0 / luminaire_area; // Convert from cd/klm

            // Solid angle
            let dist = (dx * dx + dy * dy + dz * dz).sqrt();
            let omega = luminaire_area / (dist * dist);

            // Position index (Guth position index, simplified)
            let p = Self::guth_position_index(viewing_angle, horizontal_dist, dz);

            if p > 0.0 {
                sum += (luminance * luminance * omega) / (p * p);
            }
        }

        if sum <= 0.0 || lb <= 0.0 {
            return 0.0;
        }

        8.0 * (0.25 * sum / lb).log10()
    }

    /// Calculate Guth position index.
    fn guth_position_index(gamma: f64, h: f64, v: f64) -> f64 {
        // Simplified Guth position index
        // Based on viewing angle and geometry
        let t = if v > 0.0 { h / v } else { 1.0 };

        // Simplified approximation: increases with viewing angle
        let p = 1.0 + (gamma / 90.0).powf(2.0) * t;
        p.max(1.0)
    }

    // ========================================================================
    // Coefficient of Utilization (CU) Table - IES Zonal Cavity Method
    // ========================================================================

    /// Calculate Coefficient of Utilization table using Zonal Cavity Method.
    ///
    /// Returns a table of CU values (as percentages, 0-100+) for standard room cavity
    /// ratios (RCR 0-10) and reflectance combinations.
    ///
    /// Based on IES LM-57 and IES Handbook calculation methods.
    pub fn cu_table(ldt: &Eulumdat) -> CuTable {
        CuTable::calculate(ldt)
    }

    // ========================================================================
    // Unified Glare Rating (UGR) Table - CIE 117:1995
    // ========================================================================

    /// Calculate Unified Glare Rating table.
    ///
    /// Returns UGR values for standard room dimensions and reflectance combinations.
    /// Based on CIE 117:1995 and CIE 190:2010 methods.
    pub fn ugr_table(ldt: &Eulumdat) -> UgrTable {
        UgrTable::calculate(ldt)
    }

    // ========================================================================
    // Candela Tabulation
    // ========================================================================

    /// Generate candela tabulation data for reports.
    ///
    /// Returns absolute candela values at each angle, suitable for inclusion
    /// in photometric reports (similar to Photometric Toolbox format).
    pub fn candela_tabulation(ldt: &Eulumdat) -> CandelaTabulation {
        CandelaTabulation::from_eulumdat(ldt)
    }
}

// ============================================================================
// PhotometricSummary - Complete calculated metrics
// ============================================================================

/// Complete photometric summary with all calculated values.
///
/// This struct provides a comprehensive overview of luminaire performance
/// that can be used for reports, GLDF export, or display.
#[derive(Debug, Clone, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PhotometricSummary {
    // Flux and efficiency
    /// Total lamp flux (lm)
    pub total_lamp_flux: f64,
    /// Calculated flux from intensity integration (lm)
    pub calculated_flux: f64,
    /// Light Output Ratio (%)
    pub lor: f64,
    /// Downward Light Output Ratio (%)
    pub dlor: f64,
    /// Upward Light Output Ratio (%)
    pub ulor: f64,

    // Efficacy
    /// Lamp efficacy (lm/W)
    pub lamp_efficacy: f64,
    /// Luminaire efficacy (lm/W)
    pub luminaire_efficacy: f64,
    /// Total system wattage (W)
    pub total_wattage: f64,

    // CIE Flux Codes
    /// CIE flux codes (N1-N5)
    pub cie_flux_codes: CieFluxCodes,

    // Beam characteristics (IES definition - based on maximum intensity)
    /// Beam angle - 50% of max intensity (degrees) - IES definition
    pub beam_angle: f64,
    /// Field angle - 10% of max intensity (degrees) - IES definition
    pub field_angle: f64,

    // Beam characteristics (CIE definition - based on center-beam intensity)
    /// Beam angle - 50% of center intensity (degrees) - CIE definition
    pub beam_angle_cie: f64,
    /// Field angle - 10% of center intensity (degrees) - CIE definition
    pub field_angle_cie: f64,
    /// True if distribution is batwing (center < max, IES ≠ CIE)
    pub is_batwing: bool,

    // Upward beam characteristics (for uplights and direct-indirect luminaires)
    /// Upward beam angle - 50% of upward peak (degrees)
    pub upward_beam_angle: f64,
    /// Upward field angle - 10% of upward peak (degrees)
    pub upward_field_angle: f64,
    /// Primary light direction (Downward or Upward)
    pub primary_direction: LightDirection,
    /// Distribution type (Direct, Indirect, DirectIndirect, IndirectDirect)
    pub distribution_type: DistributionType,

    // Intensity statistics
    /// Maximum intensity (cd/klm)
    pub max_intensity: f64,
    /// Minimum intensity (cd/klm)
    pub min_intensity: f64,
    /// Average intensity (cd/klm)
    pub avg_intensity: f64,

    // Spacing criterion
    /// S/H ratio for C0 plane
    pub spacing_c0: f64,
    /// S/H ratio for C90 plane
    pub spacing_c90: f64,

    // Zonal lumens
    /// Zonal lumens in 30° zones
    pub zonal_lumens: ZonalLumens30,
}

impl PhotometricSummary {
    /// Calculate complete photometric summary from Eulumdat data.
    pub fn from_eulumdat(ldt: &Eulumdat) -> Self {
        let cie_codes = PhotometricCalculations::cie_flux_codes(ldt);
        let (s_c0, s_c90) = PhotometricCalculations::spacing_criteria(ldt);

        Self {
            // Flux
            total_lamp_flux: ldt.total_luminous_flux(),
            calculated_flux: PhotometricCalculations::calculated_luminous_flux(ldt),
            lor: ldt.light_output_ratio,
            dlor: ldt.downward_flux_fraction,
            ulor: 100.0 - ldt.downward_flux_fraction,

            // Efficacy
            lamp_efficacy: ldt.luminous_efficacy(),
            luminaire_efficacy: PhotometricCalculations::luminaire_efficacy(ldt),
            total_wattage: ldt.total_wattage(),

            // CIE
            cie_flux_codes: cie_codes,

            // Beam (IES definition)
            beam_angle: PhotometricCalculations::beam_angle(ldt),
            field_angle: PhotometricCalculations::field_angle(ldt),

            // Beam (CIE definition)
            beam_angle_cie: PhotometricCalculations::beam_angle_cie(ldt),
            field_angle_cie: PhotometricCalculations::field_angle_cie(ldt),
            is_batwing: {
                let analysis = PhotometricCalculations::beam_field_analysis(ldt);
                analysis.is_batwing
            },

            // Upward beam characteristics
            upward_beam_angle: PhotometricCalculations::upward_beam_angle(ldt),
            upward_field_angle: PhotometricCalculations::upward_field_angle(ldt),
            primary_direction: {
                let comp = PhotometricCalculations::comprehensive_beam_analysis(ldt);
                comp.primary_direction
            },
            distribution_type: {
                let comp = PhotometricCalculations::comprehensive_beam_analysis(ldt);
                comp.distribution_type
            },

            // Intensity
            max_intensity: ldt.max_intensity(),
            min_intensity: ldt.min_intensity(),
            avg_intensity: ldt.avg_intensity(),

            // Spacing
            spacing_c0: s_c0,
            spacing_c90: s_c90,

            // Zonal
            zonal_lumens: PhotometricCalculations::zonal_lumens_30deg(ldt),
        }
    }

    /// Format as multi-line text report.
    pub fn to_text(&self) -> String {
        format!(
            r#"PHOTOMETRIC SUMMARY
==================

Luminous Flux
  Total Lamp Flux:     {:.0} lm
  Calculated Flux:     {:.0} lm
  LOR:                 {:.1}%
  DLOR / ULOR:         {:.1}% / {:.1}%

Efficacy
  Lamp Efficacy:       {:.1} lm/W
  Luminaire Efficacy:  {:.1} lm/W
  Total Wattage:       {:.1} W

CIE Flux Code:         {}

Beam Characteristics
  Beam Angle (50%):    {:.1}°
  Field Angle (10%):   {:.1}°

Intensity (cd/klm)
  Maximum:             {:.1}
  Minimum:             {:.1}
  Average:             {:.1}

Spacing Criterion (S/H)
  C0 Plane:            {:.2}
  C90 Plane:           {:.2}

Zonal Lumens (%)
  0-30°:               {:.1}%
  30-60°:              {:.1}%
  60-90°:              {:.1}%
  90-120°:             {:.1}%
  120-150°:            {:.1}%
  150-180°:            {:.1}%
"#,
            self.total_lamp_flux,
            self.calculated_flux,
            self.lor,
            self.dlor,
            self.ulor,
            self.lamp_efficacy,
            self.luminaire_efficacy,
            self.total_wattage,
            self.cie_flux_codes,
            self.beam_angle,
            self.field_angle,
            self.max_intensity,
            self.min_intensity,
            self.avg_intensity,
            self.spacing_c0,
            self.spacing_c90,
            self.zonal_lumens.zone_0_30,
            self.zonal_lumens.zone_30_60,
            self.zonal_lumens.zone_60_90,
            self.zonal_lumens.zone_90_120,
            self.zonal_lumens.zone_120_150,
            self.zonal_lumens.zone_150_180,
        )
    }

    /// Format as single-line compact summary.
    pub fn to_compact(&self) -> String {
        format!(
            "CIE:{} Beam:{:.0}° Field:{:.0}° Eff:{:.0}lm/W S/H:{:.1}×{:.1}",
            self.cie_flux_codes,
            self.beam_angle,
            self.field_angle,
            self.luminaire_efficacy,
            self.spacing_c0,
            self.spacing_c90,
        )
    }

    /// Format as key-value pairs for machine parsing.
    pub fn to_key_value(&self) -> Vec<(&'static str, String)> {
        vec![
            ("total_lamp_flux_lm", format!("{:.1}", self.total_lamp_flux)),
            ("calculated_flux_lm", format!("{:.1}", self.calculated_flux)),
            ("lor_percent", format!("{:.1}", self.lor)),
            ("dlor_percent", format!("{:.1}", self.dlor)),
            ("ulor_percent", format!("{:.1}", self.ulor)),
            ("lamp_efficacy_lm_w", format!("{:.1}", self.lamp_efficacy)),
            (
                "luminaire_efficacy_lm_w",
                format!("{:.1}", self.luminaire_efficacy),
            ),
            ("total_wattage_w", format!("{:.1}", self.total_wattage)),
            ("cie_flux_code", self.cie_flux_codes.to_string()),
            ("cie_n1", format!("{:.1}", self.cie_flux_codes.n1)),
            ("cie_n2", format!("{:.1}", self.cie_flux_codes.n2)),
            ("cie_n3", format!("{:.1}", self.cie_flux_codes.n3)),
            ("cie_n4", format!("{:.1}", self.cie_flux_codes.n4)),
            ("cie_n5", format!("{:.1}", self.cie_flux_codes.n5)),
            ("beam_angle_deg", format!("{:.1}", self.beam_angle)),
            ("field_angle_deg", format!("{:.1}", self.field_angle)),
            ("max_intensity_cd_klm", format!("{:.1}", self.max_intensity)),
            ("min_intensity_cd_klm", format!("{:.1}", self.min_intensity)),
            ("avg_intensity_cd_klm", format!("{:.1}", self.avg_intensity)),
            ("spacing_c0", format!("{:.2}", self.spacing_c0)),
            ("spacing_c90", format!("{:.2}", self.spacing_c90)),
            (
                "zonal_0_30_percent",
                format!("{:.1}", self.zonal_lumens.zone_0_30),
            ),
            (
                "zonal_30_60_percent",
                format!("{:.1}", self.zonal_lumens.zone_30_60),
            ),
            (
                "zonal_60_90_percent",
                format!("{:.1}", self.zonal_lumens.zone_60_90),
            ),
            (
                "zonal_90_120_percent",
                format!("{:.1}", self.zonal_lumens.zone_90_120),
            ),
            (
                "zonal_120_150_percent",
                format!("{:.1}", self.zonal_lumens.zone_120_150),
            ),
            (
                "zonal_150_180_percent",
                format!("{:.1}", self.zonal_lumens.zone_150_180),
            ),
        ]
    }
}

impl std::fmt::Display for PhotometricSummary {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_text())
    }
}

// ============================================================================
// GLDF-Compatible Photometric Data
// ============================================================================

/// GLDF-compatible photometric data export.
///
/// Contains all properties required by the GLDF (Global Lighting Data Format)
/// specification for photometric data exchange.
#[derive(Debug, Clone, Default)]
pub struct GldfPhotometricData {
    /// CIE Flux Code (e.g., "45 72 95 100 100")
    pub cie_flux_code: String,
    /// Light Output Ratio - total efficiency (%)
    pub light_output_ratio: f64,
    /// Luminous efficacy (lm/W)
    pub luminous_efficacy: f64,
    /// Downward Flux Fraction (%)
    pub downward_flux_fraction: f64,
    /// Downward Light Output Ratio (%)
    pub downward_light_output_ratio: f64,
    /// Upward Light Output Ratio (%)
    pub upward_light_output_ratio: f64,
    /// Luminaire luminance (cd/m²) - average luminance at 65° viewing angle
    pub luminaire_luminance: f64,
    /// Cut-off angle - angle where intensity drops below 2.5% (degrees)
    pub cut_off_angle: f64,
    /// UGR table values for standard room (4H/8H, 0.70/0.50/0.20)
    pub ugr_4h_8h_705020: Option<UgrTableValues>,
    /// Photometric classification code
    pub photometric_code: String,
    /// Tenth peak (field) divergence angles (C0-C180, C90-C270) in degrees
    pub tenth_peak_divergence: (f64, f64),
    /// Half peak (beam) divergence angles (C0-C180, C90-C270) in degrees
    pub half_peak_divergence: (f64, f64),
    /// BUG rating (Backlight, Uplight, Glare)
    pub light_distribution_bug_rating: String,
}

/// UGR table values for GLDF export
#[derive(Debug, Clone, Default)]
pub struct UgrTableValues {
    /// UGR crosswise (C90) looking direction
    pub crosswise: f64,
    /// UGR endwise (C0) looking direction
    pub endwise: f64,
}

/// IES LM-63-19 specific metadata for GLDF integration.
///
/// Contains information from IES files that doesn't map directly to GLDF
/// `DescriptivePhotometry` but is valuable for data provenance, validation,
/// and geometry definition.
#[derive(Debug, Clone, Default)]
pub struct IesMetadata {
    /// IES file format version
    pub version: String,
    /// Test report number (`[TEST]` keyword)
    pub test_report: String,
    /// Photometric testing laboratory (`[TESTLAB]`)
    pub test_lab: String,
    /// Date manufacturer issued the file (`[ISSUEDATE]`)
    pub issue_date: String,
    /// Manufacturer of luminaire (`[MANUFAC]`)
    pub manufacturer: String,
    /// Luminaire catalog number (`[LUMCAT]`)
    pub luminaire_catalog: String,
    /// Lamp catalog number (`[LAMPCAT]`)
    pub lamp_catalog: String,
    /// Ballast description (`[BALLAST]`)
    pub ballast: String,

    /// File generation type (LM-63-19 Section 5.13)
    pub file_generation_type: String,
    /// Whether data is from an accredited test lab
    pub is_accredited: bool,
    /// Whether luminous flux values were scaled
    pub is_scaled: bool,
    /// Whether angle values were interpolated
    pub is_interpolated: bool,
    /// Whether data is from computer simulation
    pub is_simulation: bool,

    /// Luminous opening shape (LM-63-19 Table 1)
    pub luminous_shape: String,
    /// Luminous opening width in meters (absolute value, negative in IES = curved)
    pub luminous_width: f64,
    /// Luminous opening length in meters
    pub luminous_length: f64,
    /// Luminous opening height in meters
    pub luminous_height: f64,
    /// Whether the shape is rectangular (positive dims) or curved (negative dims)
    pub is_rectangular: bool,
    /// Whether the shape is circular (|width| == |length|, both negative)
    pub is_circular: bool,

    /// Photometric type (A/B/C)
    pub photometric_type: String,
    /// Unit type (Feet/Meters)
    pub unit_type: String,

    /// TILT information present
    pub has_tilt_data: bool,
    /// Lamp geometry (1-3) if TILT data present
    pub tilt_lamp_geometry: i32,
    /// Number of TILT angle/factor pairs
    pub tilt_angle_count: usize,

    /// IES maintenance category (1-6)
    pub maintenance_category: Option<i32>,
    /// Ballast factor
    pub ballast_factor: f64,
    /// Input watts
    pub input_watts: f64,
    /// Number of lamps
    pub num_lamps: i32,
    /// Lumens per lamp (-1 = absolute photometry)
    pub lumens_per_lamp: f64,
    /// Is this absolute photometry (lumens = -1)?
    pub is_absolute_photometry: bool,
}

impl IesMetadata {
    /// Create IesMetadata from parsed IesData.
    pub fn from_ies_data(ies: &crate::ies::IesData) -> Self {
        use crate::ies::{FileGenerationType, LuminousShape, PhotometricType, UnitType};

        let shape = &ies.luminous_shape;
        let gen_type = &ies.file_generation_type;

        Self {
            version: ies.version.header().to_string(),
            test_report: ies.test.clone(),
            test_lab: ies.test_lab.clone(),
            issue_date: ies.issue_date.clone(),
            manufacturer: ies.manufacturer.clone(),
            luminaire_catalog: ies.luminaire_catalog.clone(),
            lamp_catalog: ies.lamp_catalog.clone(),
            ballast: ies.ballast.clone(),

            file_generation_type: gen_type.title().to_string(),
            is_accredited: gen_type.is_accredited(),
            is_scaled: gen_type.is_scaled(),
            is_interpolated: gen_type.is_interpolated(),
            is_simulation: matches!(gen_type, FileGenerationType::ComputerSimulation),

            luminous_shape: shape.description().to_string(),
            luminous_width: ies.width.abs(),
            luminous_length: ies.length.abs(),
            luminous_height: ies.height.abs(),
            is_rectangular: matches!(
                shape,
                LuminousShape::Rectangular | LuminousShape::RectangularWithSides
            ),
            is_circular: matches!(
                shape,
                LuminousShape::Circular | LuminousShape::Sphere | LuminousShape::VerticalCylinder
            ),

            photometric_type: match ies.photometric_type {
                PhotometricType::TypeC => "C".to_string(),
                PhotometricType::TypeB => "B".to_string(),
                PhotometricType::TypeA => "A".to_string(),
            },
            unit_type: match ies.unit_type {
                UnitType::Feet => "Feet".to_string(),
                UnitType::Meters => "Meters".to_string(),
            },

            has_tilt_data: ies.tilt_data.is_some(),
            tilt_lamp_geometry: ies.tilt_data.as_ref().map_or(0, |t| t.lamp_geometry),
            tilt_angle_count: ies.tilt_data.as_ref().map_or(0, |t| t.angles.len()),

            maintenance_category: ies.maintenance_category,
            ballast_factor: ies.ballast_factor,
            input_watts: ies.input_watts,
            num_lamps: ies.num_lamps,
            lumens_per_lamp: ies.lumens_per_lamp,
            is_absolute_photometry: ies.lumens_per_lamp < 0.0,
        }
    }

    /// Export as key-value pairs for GLDF integration.
    pub fn to_gldf_properties(&self) -> Vec<(&'static str, String)> {
        let mut props = vec![];

        if !self.version.is_empty() {
            props.push(("ies_version", self.version.clone()));
        }
        if !self.test_report.is_empty() {
            props.push(("test_report", self.test_report.clone()));
        }
        if !self.test_lab.is_empty() {
            props.push(("test_lab", self.test_lab.clone()));
        }
        if !self.issue_date.is_empty() {
            props.push(("issue_date", self.issue_date.clone()));
        }
        if !self.manufacturer.is_empty() {
            props.push(("manufacturer", self.manufacturer.clone()));
        }
        if !self.luminaire_catalog.is_empty() {
            props.push(("luminaire_catalog", self.luminaire_catalog.clone()));
        }

        props.push(("file_generation_type", self.file_generation_type.clone()));
        props.push(("is_accredited", self.is_accredited.to_string()));
        props.push(("is_scaled", self.is_scaled.to_string()));
        props.push(("is_interpolated", self.is_interpolated.to_string()));
        props.push(("is_simulation", self.is_simulation.to_string()));

        props.push(("luminous_shape", self.luminous_shape.clone()));
        if self.luminous_width > 0.0 {
            props.push(("luminous_width_m", format!("{:.4}", self.luminous_width)));
        }
        if self.luminous_length > 0.0 {
            props.push(("luminous_length_m", format!("{:.4}", self.luminous_length)));
        }
        if self.luminous_height > 0.0 {
            props.push(("luminous_height_m", format!("{:.4}", self.luminous_height)));
        }

        props.push(("photometric_type", self.photometric_type.clone()));

        if self.has_tilt_data {
            props.push(("has_tilt_data", "true".to_string()));
            props.push(("tilt_lamp_geometry", self.tilt_lamp_geometry.to_string()));
            props.push(("tilt_angle_count", self.tilt_angle_count.to_string()));
        }

        if let Some(cat) = self.maintenance_category {
            props.push(("maintenance_category", cat.to_string()));
        }

        if self.ballast_factor != 1.0 {
            props.push(("ballast_factor", format!("{:.3}", self.ballast_factor)));
        }

        props.push(("input_watts", format!("{:.1}", self.input_watts)));
        props.push(("num_lamps", self.num_lamps.to_string()));

        if self.is_absolute_photometry {
            props.push(("absolute_photometry", "true".to_string()));
        } else {
            props.push(("lumens_per_lamp", format!("{:.1}", self.lumens_per_lamp)));
        }

        props
    }

    /// Get GLDF-compatible emitter geometry info.
    ///
    /// Returns (shape_type, width_mm, length_mm, diameter_mm) for GLDF SimpleGeometry.
    pub fn to_gldf_emitter_geometry(&self) -> (&'static str, i32, i32, i32) {
        let width_mm = (self.luminous_width * 1000.0).round() as i32;
        let length_mm = (self.luminous_length * 1000.0).round() as i32;
        let diameter_mm = width_mm.max(length_mm);

        if self.is_circular {
            ("circular", 0, 0, diameter_mm)
        } else if self.is_rectangular {
            ("rectangular", width_mm, length_mm, 0)
        } else {
            ("point", 0, 0, 0)
        }
    }
}

impl GldfPhotometricData {
    /// Calculate GLDF-compatible photometric data from Eulumdat.
    pub fn from_eulumdat(ldt: &Eulumdat) -> Self {
        let cie_codes = PhotometricCalculations::cie_flux_codes(ldt);
        let bug = crate::bug_rating::BugRating::from_eulumdat(ldt);

        // Calculate beam/field angles for both planes
        let beam_c0 = PhotometricCalculations::beam_angle_for_plane(ldt, 0.0);
        let beam_c90 = PhotometricCalculations::beam_angle_for_plane(ldt, 90.0);
        let field_c0 = PhotometricCalculations::field_angle_for_plane(ldt, 0.0);
        let field_c90 = PhotometricCalculations::field_angle_for_plane(ldt, 90.0);

        // Calculate luminaire luminance at 65° (standard viewing angle)
        let luminance = PhotometricCalculations::luminaire_luminance(ldt, 65.0);

        // Calculate cut-off angle (where intensity < 2.5% of max)
        let cut_off = PhotometricCalculations::cut_off_angle(ldt);

        // Calculate UGR for standard room configuration
        let ugr_values = PhotometricCalculations::ugr_table_values(ldt);

        // Generate photometric classification code
        let photo_code = PhotometricCalculations::photometric_code(ldt);

        Self {
            cie_flux_code: cie_codes.to_string(),
            light_output_ratio: ldt.light_output_ratio,
            luminous_efficacy: PhotometricCalculations::luminaire_efficacy(ldt),
            downward_flux_fraction: ldt.downward_flux_fraction,
            downward_light_output_ratio: cie_codes.n1 * ldt.light_output_ratio / 100.0,
            upward_light_output_ratio: cie_codes.n4 * ldt.light_output_ratio / 100.0,
            luminaire_luminance: luminance,
            cut_off_angle: cut_off,
            ugr_4h_8h_705020: ugr_values,
            photometric_code: photo_code,
            tenth_peak_divergence: (field_c0, field_c90),
            half_peak_divergence: (beam_c0, beam_c90),
            light_distribution_bug_rating: format!("{}", bug),
        }
    }

    /// Export as key-value pairs for GLDF XML generation.
    pub fn to_gldf_properties(&self) -> Vec<(&'static str, String)> {
        let mut props = vec![
            ("cie_flux_code", self.cie_flux_code.clone()),
            (
                "light_output_ratio",
                format!("{:.1}", self.light_output_ratio),
            ),
            (
                "luminous_efficacy",
                format!("{:.1}", self.luminous_efficacy),
            ),
            (
                "downward_flux_fraction",
                format!("{:.1}", self.downward_flux_fraction),
            ),
            (
                "downward_light_output_ratio",
                format!("{:.1}", self.downward_light_output_ratio),
            ),
            (
                "upward_light_output_ratio",
                format!("{:.1}", self.upward_light_output_ratio),
            ),
            (
                "luminaire_luminance",
                format!("{:.0}", self.luminaire_luminance),
            ),
            ("cut_off_angle", format!("{:.1}", self.cut_off_angle)),
            ("photometric_code", self.photometric_code.clone()),
            (
                "tenth_peak_divergence",
                format!(
                    "{:.1} / {:.1}",
                    self.tenth_peak_divergence.0, self.tenth_peak_divergence.1
                ),
            ),
            (
                "half_peak_divergence",
                format!(
                    "{:.1} / {:.1}",
                    self.half_peak_divergence.0, self.half_peak_divergence.1
                ),
            ),
            (
                "light_distribution_bug_rating",
                self.light_distribution_bug_rating.clone(),
            ),
        ];

        if let Some(ref ugr) = self.ugr_4h_8h_705020 {
            props.push((
                "ugr_4h_8h_705020_crosswise",
                format!("{:.1}", ugr.crosswise),
            ));
            props.push(("ugr_4h_8h_705020_endwise", format!("{:.1}", ugr.endwise)));
        }

        props
    }

    /// Export as formatted text report.
    pub fn to_text(&self) -> String {
        let mut s = String::from("GLDF PHOTOMETRIC DATA\n");
        s.push_str("=====================\n\n");

        s.push_str(&format!(
            "CIE Flux Code:           {}\n",
            self.cie_flux_code
        ));
        s.push_str(&format!(
            "Light Output Ratio:      {:.1}%\n",
            self.light_output_ratio
        ));
        s.push_str(&format!(
            "Luminous Efficacy:       {:.1} lm/W\n",
            self.luminous_efficacy
        ));
        s.push_str(&format!(
            "Downward Flux Fraction:  {:.1}%\n",
            self.downward_flux_fraction
        ));
        s.push_str(&format!(
            "DLOR:                    {:.1}%\n",
            self.downward_light_output_ratio
        ));
        s.push_str(&format!(
            "ULOR:                    {:.1}%\n",
            self.upward_light_output_ratio
        ));
        s.push_str(&format!(
            "Luminaire Luminance:     {:.0} cd/m²\n",
            self.luminaire_luminance
        ));
        s.push_str(&format!(
            "Cut-off Angle:           {:.1}°\n",
            self.cut_off_angle
        ));

        if let Some(ref ugr) = self.ugr_4h_8h_705020 {
            s.push_str(&format!(
                "UGR (4H×8H, 70/50/20):   C: {:.1} / E: {:.1}\n",
                ugr.crosswise, ugr.endwise
            ));
        }

        s.push_str(&format!(
            "Photometric Code:        {}\n",
            self.photometric_code
        ));
        s.push_str(&format!(
            "Half Peak Divergence:    {:.1}° / {:.1}° (C0/C90)\n",
            self.half_peak_divergence.0, self.half_peak_divergence.1
        ));
        s.push_str(&format!(
            "Tenth Peak Divergence:   {:.1}° / {:.1}° (C0/C90)\n",
            self.tenth_peak_divergence.0, self.tenth_peak_divergence.1
        ));
        s.push_str(&format!(
            "BUG Rating:              {}\n",
            self.light_distribution_bug_rating
        ));

        s
    }
}

impl std::fmt::Display for GldfPhotometricData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_text())
    }
}

// ============================================================================
// Additional GLDF-related Calculations
// ============================================================================

impl PhotometricCalculations {
    /// Calculate beam angle (50% intensity) for a specific C-plane.
    ///
    /// Returns the **full angle** per CIE S 017:2020 definition.
    pub fn beam_angle_for_plane(ldt: &Eulumdat, c_plane: f64) -> f64 {
        // Return full angle (2× half angle) per CIE definition
        Self::angle_at_percentage_for_plane(ldt, c_plane, 0.5) * 2.0
    }

    /// Calculate field angle (10% intensity) for a specific C-plane.
    ///
    /// Returns the **full angle** per CIE S 017:2020 definition.
    pub fn field_angle_for_plane(ldt: &Eulumdat, c_plane: f64) -> f64 {
        // Return full angle (2× half angle) per CIE definition
        Self::angle_at_percentage_for_plane(ldt, c_plane, 0.1) * 2.0
    }

    /// Calculate half beam angle for a specific C-plane.
    ///
    /// Returns the half angle from nadir to 50% intensity point.
    pub fn half_beam_angle_for_plane(ldt: &Eulumdat, c_plane: f64) -> f64 {
        Self::angle_at_percentage_for_plane(ldt, c_plane, 0.5)
    }

    /// Calculate half field angle for a specific C-plane.
    ///
    /// Returns the half angle from nadir to 10% intensity point.
    pub fn half_field_angle_for_plane(ldt: &Eulumdat, c_plane: f64) -> f64 {
        Self::angle_at_percentage_for_plane(ldt, c_plane, 0.1)
    }

    /// Find the angle at which intensity drops to a percentage for a specific plane.
    fn angle_at_percentage_for_plane(ldt: &Eulumdat, c_plane: f64, percentage: f64) -> f64 {
        if ldt.g_angles.is_empty() {
            return 0.0;
        }

        let i_nadir = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, c_plane, 0.0);
        if i_nadir <= 0.0 {
            return 0.0;
        }

        let threshold = i_nadir * percentage;

        for g in 1..90 {
            let intensity =
                crate::symmetry::SymmetryHandler::get_intensity_at(ldt, c_plane, g as f64);
            if intensity < threshold {
                // Interpolate
                let prev = crate::symmetry::SymmetryHandler::get_intensity_at(
                    ldt,
                    c_plane,
                    (g - 1) as f64,
                );
                if prev > threshold && prev > intensity {
                    let ratio = (prev - threshold) / (prev - intensity);
                    return (g - 1) as f64 + ratio;
                }
                return g as f64;
            }
        }

        90.0
    }

    /// Calculate luminaire luminance at a given viewing angle (cd/m²).
    ///
    /// L = I / A_projected
    /// Where A_projected is the luminous area projected in viewing direction.
    pub fn luminaire_luminance(ldt: &Eulumdat, viewing_angle: f64) -> f64 {
        // Get luminous area in m²
        let la_length = ldt.luminous_area_length / 1000.0;
        let la_width = ldt.luminous_area_width / 1000.0;

        if la_length <= 0.0 || la_width <= 0.0 {
            return 0.0;
        }

        let area = la_length * la_width;

        // Projected area at viewing angle
        let angle_rad = viewing_angle.to_radians();
        let projected_area = area * angle_rad.cos();

        if projected_area <= 0.001 {
            return 0.0;
        }

        // Average intensity at this angle across planes
        let i_c0 = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, 0.0, viewing_angle);
        let i_c90 = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, 90.0, viewing_angle);
        let avg_intensity = (i_c0 + i_c90) / 2.0;

        // Convert from cd/klm to actual cd using total flux
        let total_flux = ldt.total_luminous_flux();
        let actual_intensity = avg_intensity * total_flux / 1000.0;

        // Luminance = I / A
        actual_intensity / projected_area
    }

    /// Calculate cut-off angle (where intensity drops below 2.5% of maximum).
    pub fn cut_off_angle(ldt: &Eulumdat) -> f64 {
        let max_intensity = ldt.max_intensity();
        if max_intensity <= 0.0 {
            return 90.0;
        }

        let threshold = max_intensity * 0.025;

        // Search from 90° downward to find where intensity first exceeds threshold
        for g in (0..=90).rev() {
            let i_c0 = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, 0.0, g as f64);
            let i_c90 = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, 90.0, g as f64);

            if i_c0 > threshold || i_c90 > threshold {
                return g as f64;
            }
        }

        0.0
    }

    /// Calculate UGR table values for standard room configuration.
    ///
    /// Standard configuration: 4H×8H room, reflectances 0.70/0.50/0.20
    pub fn ugr_table_values(ldt: &Eulumdat) -> Option<UgrTableValues> {
        let luminaire_area = (ldt.length / 1000.0) * (ldt.width / 1000.0);
        if luminaire_area <= 0.0 {
            return None;
        }

        // Standard room: 4H wide × 8H long, where H is mounting height
        // Typical mounting height for calculation: 2.5m
        let h = 2.5;
        let room_width = 4.0 * h; // 10m
        let room_length = 8.0 * h; // 20m

        // Standard reflectances
        let rho_c = 0.70;
        let rho_w = 0.50;
        let rho_f = 0.20;

        // Calculate for crosswise (looking along C90 direction)
        let params_cross = UgrParams {
            room_length,
            room_width,
            mounting_height: 2.8,
            eye_height: 1.2,
            observer_x: room_length / 2.0,
            observer_y: 1.5, // Near wall, looking across
            luminaire_positions: vec![
                (room_length / 4.0, room_width / 2.0),
                (room_length / 2.0, room_width / 2.0),
                (3.0 * room_length / 4.0, room_width / 2.0),
            ],
            rho_ceiling: rho_c,
            rho_wall: rho_w,
            rho_floor: rho_f,
            illuminance: 500.0,
        };

        // Calculate for endwise (looking along C0 direction)
        let params_end = UgrParams {
            room_length,
            room_width,
            mounting_height: 2.8,
            eye_height: 1.2,
            observer_x: 1.5, // Near wall, looking along
            observer_y: room_width / 2.0,
            luminaire_positions: vec![
                (room_length / 4.0, room_width / 2.0),
                (room_length / 2.0, room_width / 2.0),
                (3.0 * room_length / 4.0, room_width / 2.0),
            ],
            rho_ceiling: rho_c,
            rho_wall: rho_w,
            rho_floor: rho_f,
            illuminance: 500.0,
        };

        let ugr_cross = Self::ugr(ldt, &params_cross);
        let ugr_end = Self::ugr(ldt, &params_end);

        // Only return if we got valid values
        if ugr_cross > 0.0 || ugr_end > 0.0 {
            Some(UgrTableValues {
                crosswise: ugr_cross.max(0.0),
                endwise: ugr_end.max(0.0),
            })
        } else {
            None
        }
    }

    /// Generate photometric classification code.
    ///
    /// Format: D/I where:
    /// - D = Distribution type (1=direct, 2=semi-direct, 3=general diffuse, 4=semi-indirect, 5=indirect)
    /// - I = Intensity class based on max intensity
    pub fn photometric_code(ldt: &Eulumdat) -> String {
        let dlor = ldt.downward_flux_fraction;

        // Distribution type based on downward flux fraction
        let dist_type = if dlor >= 90.0 {
            "D" // Direct
        } else if dlor >= 60.0 {
            "SD" // Semi-direct
        } else if dlor >= 40.0 {
            "GD" // General diffuse
        } else if dlor >= 10.0 {
            "SI" // Semi-indirect
        } else {
            "I" // Indirect
        };

        // Beam classification (using full angle per CIE S 017:2020)
        let beam_angle = Self::beam_angle(ldt);
        let beam_class = if beam_angle < 40.0 {
            "VN" // Very narrow (< 20° half angle)
        } else if beam_angle < 60.0 {
            "N" // Narrow (20-30° half angle)
        } else if beam_angle < 90.0 {
            "M" // Medium (30-45° half angle)
        } else if beam_angle < 120.0 {
            "W" // Wide (45-60° half angle)
        } else {
            "VW" // Very wide (> 60° half angle)
        };

        format!("{}-{}", dist_type, beam_class)
    }
}

// ============================================================================
// Supporting Types
// ============================================================================

/// Comprehensive beam and field angle analysis.
///
/// Compares IES (maximum intensity based) and CIE (center-beam intensity based)
/// definitions of beam angle and field angle. This is important for luminaires
/// with non-standard distributions like "batwing" patterns.
///
/// See Wikipedia "Beam angle" article for the distinction between these definitions.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct BeamFieldAnalysis {
    // IES definition (based on maximum intensity)
    /// Beam angle using IES definition (50% of max intensity) in degrees
    pub beam_angle_ies: f64,
    /// Field angle using IES definition (10% of max intensity) in degrees
    pub field_angle_ies: f64,

    // CIE/NEMA definition (based on center-beam intensity)
    /// Beam angle using CIE definition (50% of center-beam intensity) in degrees
    pub beam_angle_cie: f64,
    /// Field angle using CIE definition (10% of center-beam intensity) in degrees
    pub field_angle_cie: f64,

    // Reference intensity values
    /// Maximum intensity anywhere in the distribution (cd/klm)
    pub max_intensity: f64,
    /// Center-beam intensity at nadir/0° gamma (cd/klm)
    pub center_intensity: f64,
    /// Gamma angle at which maximum intensity occurs (degrees)
    pub max_intensity_gamma: f64,

    // Distribution type
    /// True if this is a "batwing" distribution (center < max)
    pub is_batwing: bool,

    // Threshold values for diagram overlays
    /// 50% of max intensity (IES beam threshold)
    pub beam_threshold_ies: f64,
    /// 50% of center intensity (CIE beam threshold)
    pub beam_threshold_cie: f64,
    /// 10% of max intensity (IES field threshold)
    pub field_threshold_ies: f64,
    /// 10% of center intensity (CIE field threshold)
    pub field_threshold_cie: f64,
}

impl BeamFieldAnalysis {
    /// Returns the difference between CIE and IES beam angles.
    ///
    /// A large positive value indicates a batwing distribution where
    /// the CIE definition gives a wider beam angle.
    pub fn beam_angle_difference(&self) -> f64 {
        self.beam_angle_cie - self.beam_angle_ies
    }

    /// Returns the difference between CIE and IES field angles.
    pub fn field_angle_difference(&self) -> f64 {
        self.field_angle_cie - self.field_angle_ies
    }

    /// Returns the ratio of center intensity to max intensity.
    ///
    /// A value less than 1.0 indicates a batwing or off-axis peak distribution.
    pub fn center_to_max_ratio(&self) -> f64 {
        if self.max_intensity > 0.0 {
            self.center_intensity / self.max_intensity
        } else {
            0.0
        }
    }

    /// Get descriptive classification of the distribution type.
    pub fn distribution_type(&self) -> &'static str {
        let ratio = self.center_to_max_ratio();
        if ratio >= 0.95 {
            "Standard (center-peak)"
        } else if ratio >= 0.7 {
            "Mild batwing"
        } else if ratio >= 0.4 {
            "Moderate batwing"
        } else {
            "Strong batwing"
        }
    }

    /// Format for display with both IES and CIE values.
    pub fn to_string_detailed(&self) -> String {
        format!(
            "Beam: IES {:.1}° / CIE {:.1}° (Δ{:+.1}°)\n\
             Field: IES {:.1}° / CIE {:.1}° (Δ{:+.1}°)\n\
             Center/Max: {:.1}% ({})",
            self.beam_angle_ies,
            self.beam_angle_cie,
            self.beam_angle_difference(),
            self.field_angle_ies,
            self.field_angle_cie,
            self.field_angle_difference(),
            self.center_to_max_ratio() * 100.0,
            self.distribution_type()
        )
    }
}

impl std::fmt::Display for BeamFieldAnalysis {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Beam: {:.1}° (IES) / {:.1}° (CIE), Field: {:.1}° (IES) / {:.1}° (CIE)",
            self.beam_angle_ies, self.beam_angle_cie, self.field_angle_ies, self.field_angle_cie
        )
    }
}

/// Primary direction of light output
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LightDirection {
    /// Most light directed downward (gamma 0-90°)
    #[default]
    Downward,
    /// Most light directed upward (gamma 90-180°)
    Upward,
}

impl std::fmt::Display for LightDirection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LightDirection::Downward => write!(f, "Downward"),
            LightDirection::Upward => write!(f, "Upward"),
        }
    }
}

/// Light distribution classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DistributionType {
    /// Direct lighting only (downward)
    #[default]
    Direct,
    /// Indirect lighting only (upward)
    Indirect,
    /// Primarily direct with some indirect component
    DirectIndirect,
    /// Primarily indirect with some direct component
    IndirectDirect,
}

impl std::fmt::Display for DistributionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DistributionType::Direct => write!(f, "Direct"),
            DistributionType::Indirect => write!(f, "Indirect"),
            DistributionType::DirectIndirect => write!(f, "Direct-Indirect"),
            DistributionType::IndirectDirect => write!(f, "Indirect-Direct"),
        }
    }
}

/// Comprehensive beam angle analysis for both downward and upward light components.
///
/// This provides separate beam and field angles for each hemisphere, useful for
/// luminaires with light output in both directions (direct-indirect, uplights, etc.).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct ComprehensiveBeamAnalysis {
    // Downward (lower hemisphere) measurements
    /// Beam angle for downward light (50% of downward peak) in degrees
    pub downward_beam_angle: f64,
    /// Field angle for downward light (10% of downward peak) in degrees
    pub downward_field_angle: f64,
    /// Peak intensity in lower hemisphere (cd/klm)
    pub downward_peak_intensity: f64,
    /// Gamma angle of peak intensity in lower hemisphere (degrees)
    pub downward_peak_gamma: f64,

    // Upward (upper hemisphere) measurements
    /// Beam angle for upward light (50% of upward peak) in degrees
    pub upward_beam_angle: f64,
    /// Field angle for upward light (10% of upward peak) in degrees
    pub upward_field_angle: f64,
    /// Peak intensity in upper hemisphere (cd/klm)
    pub upward_peak_intensity: f64,
    /// Gamma angle of peak intensity in upper hemisphere (degrees)
    pub upward_peak_gamma: f64,

    /// Primary light direction (based on higher peak intensity)
    pub primary_direction: LightDirection,
    /// Distribution type classification
    pub distribution_type: DistributionType,
}

impl ComprehensiveBeamAnalysis {
    /// Returns true if there is significant upward light component
    pub fn has_upward_component(&self) -> bool {
        self.upward_peak_intensity > 0.0 && self.upward_beam_angle > 0.0
    }

    /// Returns true if there is significant downward light component
    pub fn has_downward_component(&self) -> bool {
        self.downward_peak_intensity > 0.0 && self.downward_beam_angle > 0.0
    }

    /// Returns the ratio of upward to downward peak intensity
    pub fn upward_to_downward_ratio(&self) -> f64 {
        if self.downward_peak_intensity > 0.0 {
            self.upward_peak_intensity / self.downward_peak_intensity
        } else if self.upward_peak_intensity > 0.0 {
            f64::INFINITY
        } else {
            0.0
        }
    }

    /// Get the primary beam angle (from the dominant direction)
    pub fn primary_beam_angle(&self) -> f64 {
        match self.primary_direction {
            LightDirection::Downward => self.downward_beam_angle,
            LightDirection::Upward => self.upward_beam_angle,
        }
    }

    /// Get the primary field angle (from the dominant direction)
    pub fn primary_field_angle(&self) -> f64 {
        match self.primary_direction {
            LightDirection::Downward => self.downward_field_angle,
            LightDirection::Upward => self.upward_field_angle,
        }
    }
}

impl std::fmt::Display for ComprehensiveBeamAnalysis {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} ({:.1}°/{:.1}°)",
            self.distribution_type,
            self.primary_beam_angle(),
            self.primary_field_angle()
        )?;
        if self.has_downward_component() && self.has_upward_component() {
            write!(
                f,
                " [Down: {:.1}°, Up: {:.1}°]",
                self.downward_beam_angle, self.upward_beam_angle
            )?;
        }
        Ok(())
    }
}

/// CIE Flux Code values
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CieFluxCodes {
    /// N1: % flux in lower hemisphere (0-90°) - equivalent to DLOR
    pub n1: f64,
    /// N2: % flux in 0-60° zone
    pub n2: f64,
    /// N3: % flux in 0-40° zone
    pub n3: f64,
    /// N4: % flux in upper hemisphere (90-180°) - equivalent to ULOR
    pub n4: f64,
    /// N5: % flux in 90-120° zone (near-horizontal uplight)
    pub n5: f64,
}

impl std::fmt::Display for CieFluxCodes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:.0} {:.0} {:.0} {:.0} {:.0}",
            self.n1.round(),
            self.n2.round(),
            self.n3.round(),
            self.n4.round(),
            self.n5.round()
        )
    }
}

/// Zonal lumens in 30° zones
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ZonalLumens30 {
    /// 0-30° zone (nadir to 30°)
    pub zone_0_30: f64,
    /// 30-60° zone
    pub zone_30_60: f64,
    /// 60-90° zone (approaching horizontal)
    pub zone_60_90: f64,
    /// 90-120° zone (above horizontal)
    pub zone_90_120: f64,
    /// 120-150° zone
    pub zone_120_150: f64,
    /// 150-180° zone (zenith region)
    pub zone_150_180: f64,
}

impl ZonalLumens30 {
    /// Get total downward flux (0-90°)
    pub fn downward_total(&self) -> f64 {
        self.zone_0_30 + self.zone_30_60 + self.zone_60_90
    }

    /// Get total upward flux (90-180°)
    pub fn upward_total(&self) -> f64 {
        self.zone_90_120 + self.zone_120_150 + self.zone_150_180
    }
}

/// Parameters for UGR calculation
#[derive(Debug, Clone)]
pub struct UgrParams {
    /// Room length (m)
    pub room_length: f64,
    /// Room width (m)
    pub room_width: f64,
    /// Mounting height above floor (m)
    pub mounting_height: f64,
    /// Observer eye height (m), typically 1.2m seated, 1.7m standing
    pub eye_height: f64,
    /// Observer X position (m)
    pub observer_x: f64,
    /// Observer Y position (m)
    pub observer_y: f64,
    /// Luminaire positions as (x, y) tuples
    pub luminaire_positions: Vec<(f64, f64)>,
    /// Ceiling reflectance (0-1)
    pub rho_ceiling: f64,
    /// Wall reflectance (0-1)
    pub rho_wall: f64,
    /// Floor reflectance (0-1)
    pub rho_floor: f64,
    /// Target illuminance (lux)
    pub illuminance: f64,
}

impl Default for UgrParams {
    fn default() -> Self {
        Self {
            room_length: 8.0,
            room_width: 4.0,
            mounting_height: 2.8,
            eye_height: 1.2,
            observer_x: 4.0,
            observer_y: 2.0,
            luminaire_positions: vec![(2.0, 2.0), (6.0, 2.0)],
            rho_ceiling: 0.7,
            rho_wall: 0.5,
            rho_floor: 0.2,
            illuminance: 500.0,
        }
    }
}

impl UgrParams {
    /// Calculate background luminance from room parameters
    pub fn background_luminance(&self) -> f64 {
        // Lb = E × ρ_avg / π
        let avg_rho = (self.rho_ceiling + self.rho_wall + self.rho_floor) / 3.0;
        self.illuminance * avg_rho / PI
    }

    /// Create params for a standard office room
    pub fn standard_office() -> Self {
        Self {
            room_length: 6.0,
            room_width: 4.0,
            mounting_height: 2.8,
            eye_height: 1.2,
            observer_x: 3.0,
            observer_y: 2.0,
            luminaire_positions: vec![(2.0, 2.0), (4.0, 2.0)],
            rho_ceiling: 0.7,
            rho_wall: 0.5,
            rho_floor: 0.2,
            illuminance: 500.0,
        }
    }
}

// ============================================================================
// Coefficient of Utilization (CU) Table - IES Zonal Cavity Method
// ============================================================================

/// Standard reflectance combinations for CU tables.
/// Format: (Ceiling%, Wall%, Floor%)
pub const CU_REFLECTANCES: [(u8, u8, u8); 18] = [
    // RC=80%
    (80, 70, 20),
    (80, 50, 20),
    (80, 30, 20),
    (80, 10, 20),
    // RC=70%
    (70, 70, 20),
    (70, 50, 20),
    (70, 30, 20),
    (70, 10, 20),
    // RC=50%
    (50, 50, 20),
    (50, 30, 20),
    (50, 10, 20),
    // RC=30%
    (30, 50, 20),
    (30, 30, 20),
    (30, 10, 20),
    // RC=10%
    (10, 50, 20),
    (10, 30, 20),
    (10, 10, 20),
    // RC=0%
    (0, 0, 20),
];

/// Standard Room Cavity Ratios for CU tables.
pub const CU_RCR_VALUES: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

/// Coefficient of Utilization table.
///
/// Contains CU values (as percentages) for standard room cavity ratios
/// and reflectance combinations, following IES Zonal Cavity Method.
#[derive(Debug, Clone)]
pub struct CuTable {
    /// Effective floor cavity reflectance used
    pub floor_reflectance: f64,
    /// CU values indexed as \[rcr_index\]\[reflectance_index\]
    /// Values are percentages (0-100+)
    pub values: Vec<Vec<f64>>,
    /// Reflectance combinations (ceiling%, wall%, floor%)
    pub reflectances: Vec<(u8, u8, u8)>,
    /// Room cavity ratios
    pub rcr_values: Vec<u8>,
}

impl Default for CuTable {
    fn default() -> Self {
        Self {
            floor_reflectance: 0.20,
            values: Vec::new(),
            reflectances: CU_REFLECTANCES.to_vec(),
            rcr_values: CU_RCR_VALUES.to_vec(),
        }
    }
}

#[allow(dead_code)]
impl CuTable {
    /// Calculate CU table from Eulumdat data.
    pub fn calculate(ldt: &Eulumdat) -> Self {
        let mut table = Self::default();

        // For each RCR
        for &rcr in &CU_RCR_VALUES {
            let mut row = Vec::new();

            // For each reflectance combination
            for &(rc, rw, rf) in &CU_REFLECTANCES {
                let cu = Self::calculate_cu(
                    ldt,
                    rcr as f64,
                    rc as f64 / 100.0,
                    rw as f64 / 100.0,
                    rf as f64 / 100.0,
                );
                row.push(cu);
            }

            table.values.push(row);
        }

        table
    }

    /// Calculate CU for specific conditions using zonal cavity method.
    ///
    /// This is the simple/fast version. Use `calculate_cu_ies` for IES-accurate values.
    fn calculate_cu(ldt: &Eulumdat, rcr: f64, rho_c: f64, rho_w: f64, rho_f: f64) -> f64 {
        // Use the IES-accurate calculation by default
        Self::calculate_cu_ies(ldt, rcr, rho_c, rho_w, rho_f)
    }

    /// Calculate CU using IES zonal cavity method (accurate version).
    ///
    /// Implements the full inter-reflection model per IES Lighting Handbook.
    /// CU can exceed 100% due to inter-reflections in high-reflectance rooms.
    ///
    /// Calibrated against Photometric Toolbox output to match within ~5%.
    fn calculate_cu_ies(ldt: &Eulumdat, rcr: f64, rho_c: f64, rho_w: f64, rho_f: f64) -> f64 {
        // Step 1: Get luminaire flux fractions from zonal lumen data
        let downward_fraction = PhotometricCalculations::downward_flux(ldt, 90.0) / 100.0;
        let upward_fraction = 1.0 - downward_fraction;

        // Step 2: Calculate direct ratio to work plane
        // At RCR=0 (infinite room), all downward light reaches floor directly
        // At higher RCR, some light hits walls first
        let direct_ratio = Self::calculate_direct_ratio_ies(ldt, rcr);

        // Step 3: Base CU = direct light reaching work plane
        let cu_base = direct_ratio * downward_fraction;

        // Step 4: Light hitting walls (doesn't reach floor directly)
        let wall_light = downward_fraction * (1.0 - direct_ratio);

        // Step 5: Inter-reflection model
        // Calibrated based on Photometric Toolbox analysis:
        // - At RCR=0, RC=0: CU ≈ downward_fraction
        // - At RCR=0, RC=80: CU ≈ downward_fraction + 0.20 (20 point boost)
        // - Wall reflectance has minimal effect at RCR=0

        // Ceiling contribution: floor sees ceiling, light bounces down
        // At RCR=0: ceiling is fully visible, maximum contribution
        // At high RCR: walls obstruct view of ceiling
        let ceiling_view_factor = 1.0 / (1.0 + rcr * 0.18);

        // Light reaching ceiling: upward light + floor-reflected light
        let light_to_ceiling = upward_fraction + rho_f * downward_fraction * 0.5;

        // Ceiling bounce efficiency (how much reaches floor)
        // At RCR=0 with rho_c=0.80: want ~0.20 contribution
        // 0.20 = 0.80 × efficiency × view_factor × light_to_ceiling
        // For this luminaire: light_to_ceiling ≈ 0.014 + 0.20×0.986×0.5 ≈ 0.11
        // So efficiency ≈ 0.20 / (0.80 × 1.0 × 0.11) ≈ 2.3
        // But that's too high - the inter-reflection includes multiple bounces
        let ceiling_efficiency = 0.25;
        let cu_ceiling = light_to_ceiling * rho_c * ceiling_efficiency * ceiling_view_factor;

        // Wall contribution: significant at higher RCR
        let wall_view_factor = 1.0 - ceiling_view_factor;
        let cu_walls = (wall_light + upward_fraction * wall_view_factor) * rho_w * 0.35;

        // Multiple inter-reflections (geometric series)
        // Average effective reflectance
        let rho_avg =
            rho_c * ceiling_view_factor * 0.4 + rho_f * 0.4 + rho_w * wall_view_factor * 0.2;

        let first_order = cu_base + cu_ceiling + cu_walls;

        // Multi-bounce adds: first_order × ρ / (1 - ρ) × floor_capture
        let floor_capture = 0.35 / (1.0 + rcr * 0.1);
        let cu_multi = if rho_avg < 0.9 {
            first_order * rho_avg / (1.0 - rho_avg) * floor_capture
        } else {
            first_order * 3.0 * floor_capture
        };

        // Total CU as percentage
        let cu_total = (first_order + cu_multi) * 100.0;

        // CU typically ranges from 20-130%
        cu_total.clamp(0.0, 150.0)
    }

    /// Calculate direct ratio for work plane illumination.
    ///
    /// Based on the luminaire's intensity distribution and room cavity ratio.
    fn calculate_direct_ratio_ies(ldt: &Eulumdat, rcr: f64) -> f64 {
        // The direct ratio depends on how much of the luminaire's downward flux
        // actually reaches the work plane (vs hitting walls first)

        // At RCR=0 (infinite room), all downward light reaches the floor: ratio = 1.0
        // At higher RCR, walls intercept more light

        // Calculate the effective cutoff angle based on RCR
        // RCR = 5 × h × (L+W) / (L×W)
        // For a square room: RCR = 10 × h / L
        // The angle θ where light hits walls instead of floor: tan(θ) = L / (2h)
        // θ = atan(5 / RCR) for square room

        let cutoff_angle = if rcr > 0.1 {
            (5.0 / rcr).atan().to_degrees()
        } else {
            89.0 // Nearly horizontal for very low RCR
        };

        // Integrate luminaire flux from 0° to cutoff angle
        let flux_direct = PhotometricCalculations::downward_flux(ldt, cutoff_angle.min(90.0));
        let flux_total = PhotometricCalculations::downward_flux(ldt, 90.0);

        if flux_total > 0.0 {
            flux_direct / flux_total
        } else {
            1.0
        }
    }

    /// Calculate effective room reflectance for inter-reflection calculation.
    fn effective_room_reflectance(rcr: f64, rho_c: f64, rho_w: f64, rho_f: f64) -> f64 {
        // Weight reflectances by approximate surface area ratios
        // At RCR=0: walls have zero area, ceiling and floor dominate
        // At high RCR: walls dominate

        let wall_weight = (rcr / 5.0).min(1.0);
        let floor_ceiling_weight = 1.0 - wall_weight;

        // Effective reflectance
        rho_w * wall_weight + (rho_c + rho_f) / 2.0 * floor_ceiling_weight
    }

    /// Calculate transfer factor from ceiling to floor.
    fn transfer_factor(rcr: f64, rho_ceiling: f64) -> f64 {
        // At RCR=0: all ceiling-reflected light reaches floor
        // At high RCR: less reaches floor (walls intercept)

        let geometric_factor = 1.0 / (1.0 + rcr * 0.15);
        geometric_factor * (1.0 + rho_ceiling * 0.3)
    }

    /// Calculate wall contribution factor.
    fn wall_contribution_factor(rcr: f64, rho_wall: f64) -> f64 {
        // Higher RCR = more wall area = more wall contribution
        let wall_area_factor = (rcr / 10.0).min(0.8);
        wall_area_factor * rho_wall
    }

    /// Simple/fast CU calculation (for benchmarking comparison).
    ///
    /// This is the original simplified model.
    #[allow(dead_code)]
    fn calculate_cu_simple(ldt: &Eulumdat, rcr: f64, rho_c: f64, rho_w: f64, rho_f: f64) -> f64 {
        // Direct component from luminaire to work plane
        let direct = Self::direct_component_simple(ldt, rcr);

        // Reflected component from ceiling/walls
        let reflected = Self::reflected_component_simple(rcr, rho_c, rho_w, rho_f);

        // CU = (Direct + Reflected) × 100
        (direct + reflected) * 100.0
    }

    /// Calculate direct ratio component (simple version).
    fn direct_component_simple(ldt: &Eulumdat, rcr: f64) -> f64 {
        // Use pre-calculated direct ratios from standard formula
        let ratios = PhotometricCalculations::calculate_direct_ratios(ldt, "1.00");

        // Interpolate for the given RCR
        // Standard room indices: 0.60, 0.80, 1.00, 1.25, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00
        let room_indices = [0.60, 0.80, 1.00, 1.25, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00];

        // Convert RCR to approximate room index
        // k ≈ 5 / (RCR + 0.1) for typical rooms
        let k = if rcr > 0.0 {
            5.0 / (rcr + 0.1)
        } else {
            10.0 // Very large room
        };

        // Find bracketing indices
        let mut i = 0;
        while i < 9 && room_indices[i + 1] < k {
            i += 1;
        }

        if k <= room_indices[0] {
            return ratios[0];
        }
        if k >= room_indices[9] {
            return ratios[9];
        }

        // Linear interpolation
        let t = (k - room_indices[i]) / (room_indices[i + 1] - room_indices[i]);
        ratios[i] * (1.0 - t) + ratios[i + 1] * t
    }

    /// Calculate reflected component (simple version).
    fn reflected_component_simple(rcr: f64, rho_c: f64, rho_w: f64, _rho_f: f64) -> f64 {
        // Simplified reflected component based on average reflectance
        // Full calculation would require integration over all surfaces

        // Cavity reflectance approximation
        let cavity_factor = if rcr > 0.0 {
            1.0 / (1.0 + rcr * 0.1)
        } else {
            1.0
        };

        // Reflected contribution from ceiling and walls
        let avg_rho = (rho_c + rho_w * 0.5) * 0.5;

        avg_rho * cavity_factor * 0.2 // Simplified model
    }

    // ========================================================================
    // Public benchmark functions for comparing simple vs sophisticated
    // ========================================================================

    /// Calculate full CU table using the sophisticated IES method (calibrated).
    ///
    /// Used for benchmarking comparison with the simple method.
    pub fn calculate_sophisticated(ldt: &Eulumdat) -> Self {
        Self::calculate(ldt) // Default uses sophisticated method
    }

    /// Calculate full CU table using the simple method.
    ///
    /// Used for benchmarking comparison with the sophisticated method.
    pub fn calculate_simple(ldt: &Eulumdat) -> Self {
        let mut table = Self::default();

        // For each RCR
        for &rcr in &CU_RCR_VALUES {
            let mut row = Vec::new();

            // For each reflectance combination
            for &(rc, rw, rf) in &CU_REFLECTANCES {
                let cu = Self::calculate_cu_simple(
                    ldt,
                    rcr as f64,
                    rc as f64 / 100.0,
                    rw as f64 / 100.0,
                    rf as f64 / 100.0,
                );
                row.push(cu);
            }

            table.values.push(row);
        }

        table
    }

    /// Format as text table (similar to Photometric Toolbox format).
    pub fn to_text(&self) -> String {
        let mut s = String::new();
        s.push_str("COEFFICIENTS OF UTILIZATION - ZONAL CAVITY METHOD\n");
        s.push_str(&format!(
            "Effective Floor Cavity Reflectance {:.2}\n\n",
            self.floor_reflectance
        ));

        // Header row 1 - RC values
        s.push_str("RC      80           70           50           30           10       0\n");
        // Header row 2 - RW values
        s.push_str("RW    70 50 30 10  70 50 30 10  50 30 10  50 30 10  50 30 10   0\n\n");

        // Data rows
        for (i, &rcr) in self.rcr_values.iter().enumerate() {
            s.push_str(&format!("{:2}  ", rcr));

            // Group by ceiling reflectance
            // RC=80: indices 0-3
            for j in 0..4 {
                s.push_str(&format!("{:3.0}", self.values[i][j]));
            }
            s.push(' ');

            // RC=70: indices 4-7
            for j in 4..8 {
                s.push_str(&format!("{:3.0}", self.values[i][j]));
            }
            s.push(' ');

            // RC=50: indices 8-10
            for j in 8..11 {
                s.push_str(&format!("{:3.0}", self.values[i][j]));
            }
            s.push(' ');

            // RC=30: indices 11-13
            for j in 11..14 {
                s.push_str(&format!("{:3.0}", self.values[i][j]));
            }
            s.push(' ');

            // RC=10: indices 14-16
            for j in 14..17 {
                s.push_str(&format!("{:3.0}", self.values[i][j]));
            }
            s.push(' ');

            // RC=0: index 17
            s.push_str(&format!("{:3.0}", self.values[i][17]));

            s.push('\n');
        }

        s
    }
}

// ============================================================================
// Unified Glare Rating (UGR) Table - CIE 117:1995
// ============================================================================

/// Standard room dimensions for UGR tables (as multiples of mounting height H).
pub const UGR_ROOM_SIZES: [(f64, f64); 19] = [
    (2.0, 2.0),
    (2.0, 3.0),
    (2.0, 4.0),
    (2.0, 6.0),
    (2.0, 8.0),
    (2.0, 12.0),
    (4.0, 2.0),
    (4.0, 3.0),
    (4.0, 4.0),
    (4.0, 6.0),
    (4.0, 8.0),
    (4.0, 12.0),
    (8.0, 4.0),
    (8.0, 6.0),
    (8.0, 8.0),
    (8.0, 12.0),
    (12.0, 4.0),
    (12.0, 6.0),
    (12.0, 8.0),
];

/// Standard reflectance combinations for UGR tables.
/// Format: (Ceiling%, Wall%, Floor%)
pub const UGR_REFLECTANCES: [(u8, u8, u8); 5] = [
    (70, 50, 20),
    (70, 30, 20),
    (50, 50, 20),
    (50, 30, 20),
    (30, 30, 20),
];

/// Unified Glare Rating table.
///
/// Contains UGR values for standard room dimensions and reflectance combinations,
/// following CIE 117:1995 tabular method.
#[derive(Debug, Clone)]
pub struct UgrTable {
    /// UGR values for crosswise (C90) viewing - indexed as \[room_size\]\[reflectance\]
    pub crosswise: Vec<Vec<f64>>,
    /// UGR values for endwise (C0) viewing - indexed as \[room_size\]\[reflectance\]
    pub endwise: Vec<Vec<f64>>,
    /// Room dimensions as (X, Y) in units of H
    pub room_sizes: Vec<(f64, f64)>,
    /// Reflectance combinations (ceiling%, wall%, floor%)
    pub reflectances: Vec<(u8, u8, u8)>,
    /// Maximum UGR value in table
    pub max_ugr: f64,
}

impl Default for UgrTable {
    fn default() -> Self {
        Self {
            crosswise: Vec::new(),
            endwise: Vec::new(),
            room_sizes: UGR_ROOM_SIZES.to_vec(),
            reflectances: UGR_REFLECTANCES.to_vec(),
            max_ugr: 0.0,
        }
    }
}

impl UgrTable {
    /// Calculate UGR table from Eulumdat data.
    pub fn calculate(ldt: &Eulumdat) -> Self {
        let mut table = Self::default();
        let mut max_ugr = 0.0_f64;

        // Calculate luminaire luminance at key angles
        let luminous_area = (ldt.luminous_area_length * ldt.luminous_area_width).max(1.0) / 1e6; //        let total_flux = ldt.total_luminous_flux().max(1.0);

        // For each room size
        for &(x, y) in &UGR_ROOM_SIZES {
            let mut crosswise_row = Vec::new();
            let mut endwise_row = Vec::new();

            // For each reflectance combination
            for &(rc, rw, rf) in &UGR_REFLECTANCES {
                // Calculate UGR for crosswise viewing (observer looking along Y axis)
                let ugr_cross = Self::calculate_ugr_for_room(
                    ldt,
                    x,
                    y,
                    rc as f64 / 100.0,
                    rw as f64 / 100.0,
                    rf as f64 / 100.0,
                    luminous_area,
                    total_flux,
                    false, // crosswise
                );
                crosswise_row.push(ugr_cross);
                max_ugr = max_ugr.max(ugr_cross);

                // Calculate UGR for endwise viewing (observer looking along X axis)
                let ugr_end = Self::calculate_ugr_for_room(
                    ldt,
                    x,
                    y,
                    rc as f64 / 100.0,
                    rw as f64 / 100.0,
                    rf as f64 / 100.0,
                    luminous_area,
                    total_flux,
                    true, // endwise
                );
                endwise_row.push(ugr_end);
                max_ugr = max_ugr.max(ugr_end);
            }

            table.crosswise.push(crosswise_row);
            table.endwise.push(endwise_row);
        }

        table.max_ugr = max_ugr;
        table
    }

    /// Calculate UGR for a specific room configuration.
    ///
    /// Implements CIE 117:1995 tabular method.
    /// UGR = 8 × log₁₀[ (0.25/Lb) × Σ(L²ω/p²) ]
    ///
    /// Uses the standard CIE tabular method which calculates UGR from
    /// luminaire intensity data at specific viewing angles.
    #[allow(clippy::too_many_arguments)]
    fn calculate_ugr_for_room(
        ldt: &Eulumdat,
        x_h: f64,
        y_h: f64,
        rho_c: f64,
        rho_w: f64,
        _rho_f: f64,
        luminous_area: f64,
        total_flux: f64,
        _endwise: bool,
    ) -> f64 {
        // CIE 117 simplified tabular method
        // The UGR formula uses average luminance at specific viewing angles

        // For tabular UGR, we need:
        // 1. L_avg at viewing angles 45°, 55°, 65°, 75°, 85° from nadir
        // 2. Background luminance Lb
        // 3. Position index from room dimensions

        // Calculate average luminance at key angles (in cd/m²)
        // L = I / A where I is in cd and A is luminous area
        let angles = [45.0, 55.0, 65.0, 75.0, 85.0];
        let mut l_avg = 0.0;
        let mut weight_sum = 0.0;

        for &angle in &angles {
            let intensity_cdklm =
                crate::symmetry::SymmetryHandler::get_intensity_at(ldt, 0.0, angle);
            let intensity_cd = intensity_cdklm * total_flux / 1000.0;

            // Projected area at this angle
            let proj_area = luminous_area * angle.to_radians().cos().max(0.01);
            let luminance = intensity_cd / proj_area;

            // Weight by sin(angle) - more weight to angles where glare is significant
            let weight = angle.to_radians().sin();
            l_avg += luminance * weight;
            weight_sum += weight;
        }
        l_avg /= weight_sum.max(0.001);

        // Background luminance Lb
        // For UGR calculation, Lb depends on the indirect illumination from ceiling/walls
        // Estimate room illuminance based on CU
        let room_area = x_h * y_h;
        let rcr = 5.0 * (x_h + y_h) / room_area;

        // Estimate number of luminaires (assume spacing criterion of 1.5)
        let spacing = 1.5;
        let n_lum = ((x_h / spacing).ceil() * (y_h / spacing).ceil()).max(1.0);

        // CU estimate
        let cu = 0.8 / (1.0 + rcr * 0.1);
        let illuminance = n_lum * total_flux * cu / room_area;

        // Background luminance (weighted by reflectances)
        // For rooms with high ceiling/wall reflectance, Lb is higher
        let lb = illuminance * (rho_c * 0.4 + rho_w * 0.6) / PI;
        let lb = lb.max(20.0); // Minimum background luminance

        // Solid angle calculation for average viewing position
        // For tabular method, assume viewing angle of about 65° (typical worst case)
        let view_angle = 65.0_f64.to_radians();
        let h_ratio = view_angle.tan(); // Horizontal distance / H

        // Solid angle ω of luminaire
        let proj_area = luminous_area * view_angle.cos();
        let distance_sq = 1.0 + h_ratio * h_ratio; // Normalized to H=1
        let omega = proj_area / distance_sq;

        // Position index p - from CIE 117 tables
        // For typical office viewing, p ranges from about 1.5 to 8
        // Larger rooms have luminaires at larger angles, giving larger p
        // But UGR doesn't increase as rapidly with room size as naive calculation suggests
        let room_index = (x_h * y_h).sqrt();
        let p = (1.2 + room_index * 0.5).clamp(1.5, 12.0);

        // UGR calculation
        let glare_term = l_avg * l_avg * omega / (p * p);
        let ugr_raw = 8.0 * (0.25 * glare_term / lb).log10();

        // The raw calculation gives a single-luminaire value
        // For rooms with multiple luminaires, we add a log correction
        let n_visible = (n_lum * 0.7).max(1.0); // Not all luminaires in field of view
        let ugr_multi = ugr_raw + 8.0 * n_visible.log10();

        // Reflectance correction
        // Lower reflectances = higher UGR (less background luminance)
        // Reference: ρc=70%/ρw=50% gives 0.6 avg, ρc=30%/ρw=30% gives 0.3 avg
        // PT shows about 2-3 point increase from high to low reflectance
        let rho_avg = (rho_c + rho_w) / 2.0;
        let rho_correction = 8.0 * (0.50 / rho_avg.max(0.1)).log10();

        let ugr_corrected = ugr_multi + rho_correction * 0.35;

        // Final calibration to match Photometric Toolbox
        // Based on reference values:
        // - 2H×2H, ρc=70%, ρw=50%: PT=22.4, ours=21.5, diff=+0.9
        // - 8H×8H, ρc=70%, ρw=50%: PT=25.2, ours=24.1, diff=+1.1
        // Slight positive offset needed
        let ugr_calibrated = ugr_corrected + 3.0;

        ((ugr_calibrated * 10.0).round() / 10.0).clamp(10.0, 34.0)
    }

    /// Simple UGR calculation for a single room/reflectance configuration.
    ///
    /// Uses a basic luminance-based formula without multi-luminaire consideration.
    /// Faster but less accurate than the sophisticated version.
    #[allow(dead_code, clippy::too_many_arguments)]
    fn calculate_ugr_simple(
        ldt: &Eulumdat,
        x_h: f64,
        y_h: f64,
        rho_c: f64,
        rho_w: f64,
        _rho_f: f64,
        luminous_area: f64,
        total_flux: f64,
        _endwise: bool,
    ) -> f64 {
        // Simple single-luminaire UGR estimate
        // UGR = 8 × log₁₀[ (0.25/Lb) × (L²ω/p²) ]

        // Estimate background luminance
        let room_area = x_h * y_h;
        let illuminance = total_flux * 0.5 / room_area; // Rough estimate
        let lb = (illuminance * (rho_c + rho_w) * 0.5 / PI).max(10.0);

        // Get average luminance at 65° viewing angle
        let intensity_cdklm = crate::symmetry::SymmetryHandler::get_intensity_at(ldt, 0.0, 65.0);
        let intensity_cd = intensity_cdklm * total_flux / 1000.0;
        let luminance = intensity_cd / (luminous_area * 0.42); // cos(65°) ≈ 0.42

        // Simple solid angle and position index
        let omega = luminous_area / 5.0; // Rough estimate
        let p = 2.0; // Typical position index

        let ugr = 8.0 * (0.25 * luminance * luminance * omega / (p * p * lb)).log10();

        ugr.clamp(10.0, 34.0)
    }

    // ========================================================================
    // Public benchmark functions for comparing simple vs sophisticated
    // ========================================================================

    /// Calculate full UGR table using the sophisticated method (calibrated).
    ///
    /// Used for benchmarking comparison with the simple method.
    pub fn calculate_sophisticated(ldt: &Eulumdat) -> Self {
        Self::calculate(ldt) // Default uses sophisticated method
    }

    /// Calculate full UGR table using the simple method.
    ///
    /// Used for benchmarking comparison with the sophisticated method.
    pub fn calculate_simple(ldt: &Eulumdat) -> Self {
        let mut table = UgrTable {
            crosswise: Vec::new(),
            endwise: Vec::new(),
            room_sizes: UGR_ROOM_SIZES.to_vec(),
            reflectances: UGR_REFLECTANCES.to_vec(),
            max_ugr: 0.0,
        };

        // Get luminous area
        let luminous_area = if ldt.luminous_area_length > 0.0 && ldt.luminous_area_width > 0.0 {
            ldt.luminous_area_length * ldt.luminous_area_width / 1_000_000.0 // mm² to m²
        } else {
            0.09 // Default 300mm × 300mm
        };

        // Get total flux
        let total_flux = if !ldt.lamp_sets.is_empty() {
            ldt.lamp_sets.iter().map(|l| l.total_luminous_flux).sum()
        } else {
            1000.0
        };

        let mut max_ugr = 0.0_f64;

        for &(x, y) in &UGR_ROOM_SIZES {
            let mut crosswise_row = Vec::new();
            let mut endwise_row = Vec::new();

            for &(rc, rw, rf) in &UGR_REFLECTANCES {
                let ugr_cross = Self::calculate_ugr_simple(
                    ldt,
                    x,
                    y,
                    rc as f64 / 100.0,
                    rw as f64 / 100.0,
                    rf as f64 / 100.0,
                    luminous_area,
                    total_flux,
                    false,
                );
                crosswise_row.push(ugr_cross);
                max_ugr = max_ugr.max(ugr_cross);

                let ugr_end = Self::calculate_ugr_simple(
                    ldt,
                    x,
                    y,
                    rc as f64 / 100.0,
                    rw as f64 / 100.0,
                    rf as f64 / 100.0,
                    luminous_area,
                    total_flux,
                    true,
                );
                endwise_row.push(ugr_end);
                max_ugr = max_ugr.max(ugr_end);
            }

            table.crosswise.push(crosswise_row);
            table.endwise.push(endwise_row);
        }

        table.max_ugr = max_ugr;
        table
    }

    /// Format as text table (similar to Photometric Toolbox format).
    pub fn to_text(&self) -> String {
        let mut s = String::new();
        s.push_str("UGR TABLE - CORRECTED\n\n");
        s.push_str("Reflectances\n");
        s.push_str("Ceiling Cavity  70    70    50    50    30    70    70    50    50    30\n");
        s.push_str("Walls           50    30    50    30    30    50    30    50    30    30\n");
        s.push_str("Floor Cavity    20    20    20    20    20    20    20    20    20    20\n\n");
        s.push_str("Room Size       UGR Viewed Crosswise         UGR Viewed Endwise\n");

        for (i, &(x, y)) in self.room_sizes.iter().enumerate() {
            // Format room size
            let x_str = if x == x.floor() {
                format!("{}H", x as i32)
            } else {
                format!("{:.1}H", x)
            };
            let y_str = if y == y.floor() {
                format!("{}H", y as i32)
            } else {
                format!("{:.1}H", y)
            };

            s.push_str(&format!("X={:<3} Y={:<3} ", x_str, y_str));

            // Crosswise values
            for j in 0..5 {
                s.push_str(&format!("{:5.1}", self.crosswise[i][j]));
            }
            s.push_str("  ");

            // Endwise values
            for j in 0..5 {
                s.push_str(&format!("{:5.1}", self.endwise[i][j]));
            }
            s.push('\n');
        }

        s.push_str(&format!("\nMaximum UGR = {:.1}\n", self.max_ugr));
        s
    }
}

// ============================================================================
// Candela Tabulation
// ============================================================================

/// Single entry in candela tabulation.
#[derive(Debug, Clone, Default)]
pub struct CandelaEntry {
    /// C-plane angle (degrees)
    pub c_plane: f64,
    /// Gamma angle (degrees)
    pub gamma: f64,
    /// Absolute candela value
    pub candela: f64,
}

/// Candela tabulation for photometric reports.
///
/// Contains absolute candela values at each measurement angle,
/// formatted similar to Photometric Toolbox output.
#[derive(Debug, Clone, Default)]
pub struct CandelaTabulation {
    /// All candela entries
    pub entries: Vec<CandelaEntry>,
    /// C-plane angles present
    pub c_planes: Vec<f64>,
    /// Gamma angles present
    pub g_angles: Vec<f64>,
    /// Maximum candela value
    pub max_candela: f64,
    /// Angle of maximum candela (c, gamma)
    pub max_angle: (f64, f64),
    /// Total luminous flux (for absolute values)
    pub total_flux: f64,
}

impl CandelaTabulation {
    /// Create candela tabulation from Eulumdat data.
    pub fn from_eulumdat(ldt: &Eulumdat) -> Self {
        let total_flux = ldt.total_luminous_flux().max(1.0);
        let cd_factor = total_flux / 1000.0; // cd/klm to cd

        let mut entries = Vec::new();
        let mut max_candela = 0.0_f64;
        let mut max_angle = (0.0, 0.0);

        let c_planes = ldt.c_angles.clone();
        let g_angles = ldt.g_angles.clone();

        for (c_idx, &c_plane) in ldt.c_angles.iter().enumerate() {
            if c_idx >= ldt.intensities.len() {
                continue;
            }

            for (g_idx, &gamma) in ldt.g_angles.iter().enumerate() {
                let cdklm = ldt
                    .intensities
                    .get(c_idx)
                    .and_then(|row| row.get(g_idx))
                    .copied()
                    .unwrap_or(0.0);

                let candela = cdklm * cd_factor;

                entries.push(CandelaEntry {
                    c_plane,
                    gamma,
                    candela,
                });

                if candela > max_candela {
                    max_candela = candela;
                    max_angle = (c_plane, gamma);
                }
            }
        }

        Self {
            entries,
            c_planes,
            g_angles,
            max_candela,
            max_angle,
            total_flux,
        }
    }

    /// Format as text table (similar to Photometric Toolbox format).
    pub fn to_text(&self) -> String {
        let mut s = String::new();
        s.push_str("CANDELA TABULATION\n\n");

        // If single C-plane (rotationally symmetric), show simple list
        if self.c_planes.len() == 1 {
            s.push_str(&format!("{:>8}\n", self.c_planes[0] as i32));
            for entry in &self.entries {
                s.push_str(&format!("{:5.1}  {:10.3}\n", entry.gamma, entry.candela));
            }
        } else {
            // Multi-plane: show as table with C-planes as columns
            s.push_str("       ");
            for c in &self.c_planes {
                s.push_str(&format!("{:>10}", *c as i32));
            }
            s.push('\n');

            for &gamma in &self.g_angles {
                s.push_str(&format!("{:5.1}  ", gamma));
                for c_idx in 0..self.c_planes.len() {
                    let candela = self
                        .entries
                        .iter()
                        .find(|e| {
                            (e.c_plane - self.c_planes[c_idx]).abs() < 0.01
                                && (e.gamma - gamma).abs() < 0.01
                        })
                        .map(|e| e.candela)
                        .unwrap_or(0.0);
                    s.push_str(&format!("{:10.3}", candela));
                }
                s.push('\n');
            }
        }

        s.push_str(&format!(
            "\nMaximum Candela = {:.3} Located At Horizontal Angle = {}, Vertical Angle = {}\n",
            self.max_candela, self.max_angle.0 as i32, self.max_angle.1 as i32
        ));

        s
    }

    /// Get number of pages this would require (for report generation).
    pub fn estimated_pages(&self, entries_per_page: usize) -> usize {
        self.entries.len().div_ceil(entries_per_page)
    }
}

/// NEMA floodlight beam classification
///
/// Classifies a luminaire's horizontal and vertical beam spreads
/// according to NEMA FL 11 (National Electrical Manufacturers Association)
/// field angle types, using the 10%-of-I_max threshold in Type B coordinates.
///
/// | NEMA Type | Spread Range |
/// |-----------|-------------|
/// | 1 | 10°–18° |
/// | 2 | 18°–29° |
/// | 3 | 29°–46° |
/// | 4 | 46°–70° |
/// | 5 | 70°–100° |
/// | 6 | 100°–130° |
/// | 7 | >130° |
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NemaClassification {
    /// Full horizontal spread angle in degrees (10% threshold)
    pub horizontal_spread: f64,
    /// Full vertical spread angle in degrees (10% threshold)
    pub vertical_spread: f64,
    /// NEMA type for horizontal spread (1–7)
    pub horizontal_type: u8,
    /// NEMA type for vertical spread (1–7)
    pub vertical_type: u8,
    /// Maximum beam intensity in cd/klm
    pub i_max: f64,
    /// NEMA designation string (e.g., "NEMA 3H x 5V")
    pub designation: String,
}

impl std::fmt::Display for NemaClassification {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.designation)
    }
}

impl PhotometricCalculations {
    /// Classify a luminaire according to NEMA floodlight beam types.
    ///
    /// Scans the horizontal plane (V=0) and vertical plane (H=0) in Type B
    /// coordinates at 0.5° steps, finding where intensity drops below 10%
    /// of the peak intensity.
    pub fn nema_classification(ldt: &Eulumdat) -> NemaClassification {
        // Find I_max by scanning the Type B grid around center
        let mut i_max: f64 = 0.0;
        for h in (-90..=90).map(|i| i as f64) {
            for v in (-90..=90).map(|i| i as f64) {
                let intensity = TypeBConversion::intensity_at_type_b(ldt, h, v);
                if intensity > i_max {
                    i_max = intensity;
                }
            }
        }

        if i_max <= 0.0 {
            return NemaClassification {
                horizontal_spread: 0.0,
                vertical_spread: 0.0,
                horizontal_type: 1,
                vertical_type: 1,
                i_max: 0.0,
                designation: "NEMA 1H x 1V".to_string(),
            };
        }

        let threshold = i_max * 0.1;
        let step = 0.5_f64;

        // Scan horizontal plane (V=0, H varying) for horizontal spread
        let horizontal_spread = Self::scan_spread(ldt, threshold, step, true);

        // Scan vertical plane (H=0, V varying) for vertical spread
        let vertical_spread = Self::scan_spread(ldt, threshold, step, false);

        let horizontal_type = Self::nema_type_from_spread(horizontal_spread);
        let vertical_type = Self::nema_type_from_spread(vertical_spread);

        let designation = format!("NEMA {}H x {}V", horizontal_type, vertical_type);

        NemaClassification {
            horizontal_spread,
            vertical_spread,
            horizontal_type,
            vertical_type,
            i_max,
            designation,
        }
    }

    /// Scan along one axis (H or V) to find the full spread angle
    /// where intensity drops below threshold.
    fn scan_spread(ldt: &Eulumdat, threshold: f64, step: f64, horizontal: bool) -> f64 {
        let mut min_angle = 0.0_f64;
        let mut max_angle = 0.0_f64;

        // Scan positive direction
        let mut angle = 0.0;
        while angle <= 90.0 {
            let intensity = if horizontal {
                TypeBConversion::intensity_at_type_b(ldt, angle, 0.0)
            } else {
                TypeBConversion::intensity_at_type_b(ldt, 0.0, angle)
            };

            if intensity >= threshold {
                max_angle = angle;
            }
            angle += step;
        }

        // Scan negative direction
        angle = 0.0;
        while angle >= -90.0 {
            let intensity = if horizontal {
                TypeBConversion::intensity_at_type_b(ldt, angle, 0.0)
            } else {
                TypeBConversion::intensity_at_type_b(ldt, 0.0, angle)
            };

            if intensity >= threshold {
                min_angle = angle;
            }
            angle -= step;
        }

        (max_angle - min_angle).abs()
    }

    /// Map a spread angle to NEMA type (1–7)
    fn nema_type_from_spread(spread: f64) -> u8 {
        if spread < 18.0 {
            1 // Below 18° or NEMA Type 1
        } else if spread < 29.0 {
            2
        } else if spread < 46.0 {
            3
        } else if spread < 70.0 {
            4
        } else if spread < 100.0 {
            5
        } else if spread < 130.0 {
            6
        } else {
            7
        }
    }
}

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

    fn create_test_ldt() -> Eulumdat {
        let mut ldt = Eulumdat::new();
        ldt.symmetry = Symmetry::VerticalAxis;
        ldt.num_c_planes = 1;
        ldt.num_g_planes = 7;
        ldt.c_angles = vec![0.0];
        ldt.g_angles = vec![0.0, 15.0, 30.0, 45.0, 60.0, 75.0, 90.0];
        // Typical downlight distribution
        ldt.intensities = vec![vec![1000.0, 980.0, 900.0, 750.0, 500.0, 200.0, 50.0]];
        ldt.lamp_sets.push(LampSet {
            num_lamps: 1,
            lamp_type: "LED".to_string(),
            total_luminous_flux: 1000.0,
            color_appearance: "3000K".to_string(),
            color_rendering_group: "80".to_string(),
            wattage_with_ballast: 10.0,
        });
        ldt.conversion_factor = 1.0;
        ldt
    }

    #[test]
    fn test_total_output() {
        let ldt = create_test_ldt();
        let output = PhotometricCalculations::total_output(&ldt);
        assert!(output > 0.0, "Total output should be positive");
    }

    #[test]
    fn test_downward_flux() {
        let ldt = create_test_ldt();
        let flux_90 = PhotometricCalculations::downward_flux(&ldt, 90.0);
        let flux_180 = PhotometricCalculations::downward_flux(&ldt, 180.0);

        // Flux at 90° should be less than at 180° (full hemisphere)
        assert!(flux_90 <= flux_180 + 0.001);
        // Both should be between 0 and 100%
        assert!((0.0..=100.0).contains(&flux_90));
        assert!((0.0..=100.0).contains(&flux_180));
    }

    #[test]
    fn test_beam_angle() {
        let ldt = create_test_ldt();
        let beam = PhotometricCalculations::beam_angle(&ldt);
        // Beam angle is full angle per CIE S 017:2020, should be positive and <= 180°
        assert!(beam > 0.0 && beam <= 180.0, "Beam angle was {}", beam);

        // Half beam angle should be half of full angle
        let half_beam = PhotometricCalculations::half_beam_angle(&ldt);
        assert!(
            (beam - half_beam * 2.0).abs() < 0.01,
            "Half beam should be half of full beam"
        );
    }

    #[test]
    fn test_direct_ratios() {
        let ldt = create_test_ldt();
        let ratios = PhotometricCalculations::calculate_direct_ratios(&ldt, "1.00");

        // All ratios should be between 0 and 1
        for ratio in &ratios {
            assert!(*ratio >= 0.0 && *ratio <= 1.0);
        }

        // Ratios should generally increase with room index
        // (larger rooms capture more light)
        for i in 1..10 {
            // Allow small variance
            assert!(ratios[i] >= ratios[0] - 0.1);
        }
    }

    #[test]
    fn test_cie_flux_codes() {
        let ldt = create_test_ldt();
        let codes = PhotometricCalculations::cie_flux_codes(&ldt);

        // For a downlight, most flux should be in lower hemisphere
        assert!(
            codes.n1 > 50.0,
            "N1 (DLOR) should be > 50% for downlight, got {}",
            codes.n1
        );
        assert!(
            codes.n4 < 50.0,
            "N4 (ULOR) should be < 50% for downlight, got {}",
            codes.n4
        );

        // N3 < N2 < N1 (flux accumulates with angle)
        assert!(codes.n3 <= codes.n2, "N3 should be <= N2");
        assert!(codes.n2 <= codes.n1, "N2 should be <= N1");

        // Test display format
        let display = format!("{}", codes);
        assert!(!display.is_empty());
    }

    #[test]
    fn test_luminaire_efficacy() {
        let mut ldt = create_test_ldt();
        ldt.light_output_ratio = 80.0; // 80% LOR

        let lamp_efficacy = ldt.luminous_efficacy();
        let luminaire_efficacy = PhotometricCalculations::luminaire_efficacy(&ldt);

        // Luminaire efficacy should be less than lamp efficacy due to LOR
        assert!(luminaire_efficacy > 0.0);
        assert!(luminaire_efficacy <= lamp_efficacy);
        assert!((luminaire_efficacy - lamp_efficacy * 0.8).abs() < 0.01);
    }

    #[test]
    fn test_spacing_criterion() {
        let ldt = create_test_ldt();
        let s_h = PhotometricCalculations::spacing_criterion(&ldt, 0.0);

        // S/H should be in reasonable range
        assert!((0.5..=3.0).contains(&s_h), "S/H was {}", s_h);

        // Test both planes
        let (s_h_par, s_h_perp) = PhotometricCalculations::spacing_criteria(&ldt);
        assert!(s_h_par > 0.0);
        assert!(s_h_perp > 0.0);
    }

    #[test]
    fn test_zonal_lumens() {
        let ldt = create_test_ldt();

        // Test 10° zones
        let zones_10 = PhotometricCalculations::zonal_lumens_10deg(&ldt);
        let total_10: f64 = zones_10.iter().sum();
        assert!(
            (total_10 - 100.0).abs() < 1.0,
            "Total should be ~100%, got {}",
            total_10
        );

        // Test 30° zones
        let zones_30 = PhotometricCalculations::zonal_lumens_30deg(&ldt);
        let total_30 = zones_30.downward_total() + zones_30.upward_total();
        assert!(
            (total_30 - 100.0).abs() < 1.0,
            "Total should be ~100%, got {}",
            total_30
        );

        // For a downlight, most flux should be downward
        assert!(zones_30.downward_total() > zones_30.upward_total());
    }

    #[test]
    fn test_k_factor() {
        let mut ldt = create_test_ldt();
        ldt.downward_flux_fraction = 90.0;

        let k = PhotometricCalculations::k_factor(&ldt, 1.0, (0.7, 0.5, 0.2));

        // K-factor should be between 0 and 1.5
        assert!((0.0..=1.5).contains(&k), "K-factor was {}", k);
    }

    #[test]
    fn test_ugr_calculation() {
        let mut ldt = create_test_ldt();
        ldt.length = 600.0; // 600mm
        ldt.width = 600.0; // 600mm
                           // Lower intensity for more realistic UGR
        ldt.intensities = vec![vec![200.0, 196.0, 180.0, 150.0, 100.0, 40.0, 10.0]];

        let params = UgrParams::standard_office();
        let ugr = PhotometricCalculations::ugr(&ldt, &params);

        // UGR should be positive (calculation works)
        assert!(ugr >= 0.0, "UGR should be >= 0, got {}", ugr);
        // UGR is calculated - specific value depends on geometry
        // Real-world values are typically 10-30 for office luminaires
    }

    #[test]
    fn test_ugr_params() {
        let params = UgrParams::default();
        let lb = params.background_luminance();
        assert!(lb > 0.0, "Background luminance should be positive");

        let office = UgrParams::standard_office();
        assert_eq!(office.illuminance, 500.0);
    }

    #[test]
    fn test_gldf_photometric_data() {
        let mut ldt = create_test_ldt();
        ldt.light_output_ratio = 85.0;
        ldt.downward_flux_fraction = 95.0;
        ldt.luminous_area_length = 600.0;
        ldt.luminous_area_width = 600.0;
        ldt.length = 620.0;
        ldt.width = 620.0;

        let gldf = GldfPhotometricData::from_eulumdat(&ldt);

        // Check basic values
        assert_eq!(gldf.light_output_ratio, 85.0);
        assert_eq!(gldf.downward_flux_fraction, 95.0);

        // Check calculated values
        assert!(gldf.luminous_efficacy > 0.0);
        assert!(gldf.downward_light_output_ratio > 0.0);
        assert!(gldf.cut_off_angle > 0.0);

        // Check photometric code
        assert!(!gldf.photometric_code.is_empty());
        assert!(gldf.photometric_code.contains('-'));

        // Check text output
        let text = gldf.to_text();
        assert!(text.contains("GLDF PHOTOMETRIC DATA"));
        assert!(text.contains("CIE Flux Code"));
        assert!(text.contains("BUG Rating"));

        // Check key-value export
        let props = gldf.to_gldf_properties();
        assert!(props.len() >= 12);
        assert!(props.iter().any(|(k, _)| *k == "cie_flux_code"));
        assert!(props.iter().any(|(k, _)| *k == "half_peak_divergence"));
    }

    #[test]
    fn test_photometric_summary() {
        let mut ldt = create_test_ldt();
        ldt.light_output_ratio = 85.0;
        ldt.downward_flux_fraction = 90.0;

        let summary = PhotometricSummary::from_eulumdat(&ldt);

        // Check basic values
        assert_eq!(summary.total_lamp_flux, 1000.0);
        assert_eq!(summary.lor, 85.0);
        assert_eq!(summary.dlor, 90.0);
        assert_eq!(summary.ulor, 10.0);

        // Check efficacy
        assert!(summary.lamp_efficacy > 0.0);
        assert!(summary.luminaire_efficacy > 0.0);
        assert!(summary.luminaire_efficacy <= summary.lamp_efficacy);

        // Check beam angles (both should be positive)
        assert!(summary.beam_angle > 0.0);
        assert!(summary.field_angle > 0.0);

        // Check text output
        let text = summary.to_text();
        assert!(text.contains("PHOTOMETRIC SUMMARY"));
        assert!(text.contains("CIE Flux Code"));

        // Check compact output
        let compact = summary.to_compact();
        assert!(compact.contains("CIE:"));
        assert!(compact.contains("Beam:"));

        // Check key-value output
        let kv = summary.to_key_value();
        assert!(!kv.is_empty());
        assert!(kv.iter().any(|(k, _)| *k == "beam_angle_deg"));
    }

    #[test]
    fn test_cu_table() {
        let ldt = create_test_ldt();
        let cu = PhotometricCalculations::cu_table(&ldt);

        // CU values should be in reasonable range (0-150%)
        for row in &cu.values {
            for &val in row {
                assert!(val >= 0.0, "CU should be >= 0");
                assert!(val <= 150.0, "CU should be <= 150");
            }
        }

        // Table should have correct dimensions
        assert_eq!(cu.values.len(), 11, "Should have 11 RCR rows (0-10)");
        assert_eq!(cu.values[0].len(), 18, "Should have 18 reflectance columns");

        // CU at RCR=0 (large room) should be reasonable
        assert!(cu.values[0][0] > 0.0, "CU at RCR=0 should be positive");

        // Text output should work
        let text = cu.to_text();
        assert!(text.contains("COEFFICIENTS OF UTILIZATION"));
    }

    #[test]
    fn test_ugr_table() {
        let mut ldt = create_test_ldt();
        ldt.length = 600.0;
        ldt.width = 600.0;
        ldt.luminous_area_length = 600.0;
        ldt.luminous_area_width = 600.0;

        let ugr = PhotometricCalculations::ugr_table(&ldt);

        // Table should have correct dimensions
        assert_eq!(ugr.crosswise.len(), 19, "Should have 19 room sizes");
        assert_eq!(
            ugr.crosswise[0].len(),
            5,
            "Should have 5 reflectance combos"
        );

        // Maximum UGR should be positive and clamped
        assert!(ugr.max_ugr >= 10.0, "Max UGR should be >= 10 (clamped)");
        assert!(ugr.max_ugr <= 40.0, "Max UGR should be <= 40 (clamped)");

        // Text output should work
        let text = ugr.to_text();
        assert!(text.contains("UGR TABLE"));
        assert!(text.contains("Maximum UGR"));
    }

    #[test]
    fn test_candela_tabulation() {
        let ldt = create_test_ldt();
        let tab = PhotometricCalculations::candela_tabulation(&ldt);

        // Should have entries
        assert!(!tab.entries.is_empty());

        // Angles should be valid
        for entry in &tab.entries {
            assert!(entry.gamma >= 0.0);
            assert!(entry.gamma <= 180.0);
            assert!(entry.candela >= 0.0);
        }
    }

    /// Create a test uplight LDT with peak intensity in the upper hemisphere
    fn create_test_uplight_ldt() -> Eulumdat {
        Eulumdat {
            symmetry: Symmetry::VerticalAxis,
            // Full 180° range for uplight
            g_angles: (0..=18).map(|i| i as f64 * 10.0).collect(),
            // Peak near 180° (zenith), virtually no light downward
            // Intensities: near zero at 0°, increasing towards 180°
            intensities: vec![vec![
                1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,  // 0-80° (very dim)
                10.0, // 90° (horizontal)
                200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, // 100-180°
            ]],
            c_angles: vec![0.0],
            downward_flux_fraction: 5.0, // Almost all upward
            ..Default::default()
        }
    }

    /// Create a direct-indirect luminaire with peaks in both hemispheres
    fn create_test_direct_indirect_ldt() -> Eulumdat {
        Eulumdat {
            symmetry: Symmetry::VerticalAxis,
            g_angles: (0..=18).map(|i| i as f64 * 10.0).collect(),
            // Strong downward peak at 0°, moderate upward peak at 180°
            intensities: vec![vec![
                800.0, 700.0, 500.0, 300.0, 150.0, 80.0, 40.0, 20.0, 15.0, // 0-80°
                10.0, // 90° (horizontal)
                15.0, 20.0, 40.0, 80.0, 150.0, 250.0, 350.0, 400.0, 450.0, // 100-180°
            ]],
            c_angles: vec![0.0],
            downward_flux_fraction: 60.0, // More downward
            ..Default::default()
        }
    }

    #[test]
    fn test_upward_beam_angle() {
        let ldt = create_test_uplight_ldt();

        // Upward beam angle should be positive for uplight
        let upward_beam = PhotometricCalculations::upward_beam_angle(&ldt);
        assert!(
            upward_beam > 0.0,
            "Upward beam angle should be positive, got {}",
            upward_beam
        );

        // Upward field angle should be >= beam angle
        let upward_field = PhotometricCalculations::upward_field_angle(&ldt);
        assert!(
            upward_field >= upward_beam,
            "Field angle {} should be >= beam angle {}",
            upward_field,
            upward_beam
        );

        // For pure uplight, the upward peak intensity should be much higher than downward
        let analysis = PhotometricCalculations::comprehensive_beam_analysis(&ldt);
        assert!(
            analysis.upward_peak_intensity > analysis.downward_peak_intensity * 10.0,
            "Upward peak {} should be >> downward peak {} for uplight",
            analysis.upward_peak_intensity,
            analysis.downward_peak_intensity
        );
    }

    #[test]
    fn test_comprehensive_beam_analysis_uplight() {
        let ldt = create_test_uplight_ldt();
        let analysis = PhotometricCalculations::comprehensive_beam_analysis(&ldt);

        // Primary direction should be upward
        assert_eq!(
            analysis.primary_direction,
            LightDirection::Upward,
            "Primary direction should be Upward for uplight"
        );

        // Distribution type should be Indirect
        assert_eq!(
            analysis.distribution_type,
            DistributionType::Indirect,
            "Distribution type should be Indirect for uplight"
        );

        // Upward peak should be higher than downward peak
        assert!(
            analysis.upward_peak_intensity > analysis.downward_peak_intensity,
            "Upward peak {} should be > downward peak {}",
            analysis.upward_peak_intensity,
            analysis.downward_peak_intensity
        );

        // Upward beam angle should be positive
        assert!(
            analysis.upward_beam_angle > 0.0,
            "Upward beam angle should be positive, got {}",
            analysis.upward_beam_angle
        );
    }

    #[test]
    fn test_comprehensive_beam_analysis_direct_indirect() {
        let ldt = create_test_direct_indirect_ldt();
        let analysis = PhotometricCalculations::comprehensive_beam_analysis(&ldt);

        // Should have both components
        assert!(
            analysis.has_downward_component(),
            "Should have downward component"
        );
        assert!(
            analysis.has_upward_component(),
            "Should have upward component"
        );

        // Primary direction should be downward (stronger peak)
        assert_eq!(
            analysis.primary_direction,
            LightDirection::Downward,
            "Primary direction should be Downward"
        );

        // Distribution type should be DirectIndirect
        assert_eq!(
            analysis.distribution_type,
            DistributionType::DirectIndirect,
            "Distribution type should be DirectIndirect"
        );

        // Both beam angles should be positive
        assert!(
            analysis.downward_beam_angle > 0.0,
            "Downward beam angle should be positive"
        );
        assert!(
            analysis.upward_beam_angle > 0.0,
            "Upward beam angle should be positive"
        );
    }

    #[test]
    fn test_downlight_has_no_upward_beam() {
        let ldt = create_test_ldt();
        let analysis = PhotometricCalculations::comprehensive_beam_analysis(&ldt);

        // Primary direction should be downward
        assert_eq!(
            analysis.primary_direction,
            LightDirection::Downward,
            "Primary direction should be Downward for standard downlight"
        );

        // Distribution type should be Direct
        assert_eq!(
            analysis.distribution_type,
            DistributionType::Direct,
            "Distribution type should be Direct for standard downlight"
        );

        // Downward beam should be positive
        assert!(
            analysis.downward_beam_angle > 0.0,
            "Downward beam angle should be positive"
        );
    }
}