mtrack 0.12.0

A multitrack audio and MIDI player for live performances.
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
// Copyright (C) 2026 Michael Wilson <mike@mdwn.dev>
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
//

use super::common::*;
#[cfg(test)]
use crate::lighting::effects::*;
use crate::lighting::engine::EffectEngine;
use std::collections::HashMap;
use std::time::Duration;

#[test]
fn test_layering_demo() {
    println!("\n=== Effect Layering Demo ===");

    let mut engine = EffectEngine::new();
    let fixture = create_test_fixture("rgb_par_1", 1, 1);
    engine.register_fixture(fixture.clone());

    // Create layered effects: Static blue + Dimmer + Strobe
    let mut blue_params = HashMap::new();
    blue_params.insert("red".to_string(), 0.0);
    blue_params.insert("green".to_string(), 0.0);
    blue_params.insert("blue".to_string(), 1.0);

    let blue_effect = create_effect_with_layering(
        "static_blue".to_string(),
        EffectType::Static {
            parameters: blue_params,
            duration: Duration::from_secs(5),
        },
        vec!["rgb_par_1".to_string()],
        EffectLayer::Background,
        BlendMode::Replace,
    );

    let dimmer_effect = create_effect_with_layering(
        "dimmer".to_string(),
        EffectType::Dimmer {
            start_level: 1.0,
            end_level: 0.5,
            duration: Duration::from_secs(2), // Shorter for demo
            curve: DimmerCurve::Linear,
        },
        vec!["rgb_par_1".to_string()],
        EffectLayer::Midground,
        BlendMode::Multiply,
    );

    let strobe_effect = create_effect_with_layering(
        "strobe".to_string(),
        EffectType::Strobe {
            frequency: TempoAwareFrequency::Fixed(2.0), // 2 Hz strobe
            duration: Duration::from_secs(5),
        },
        vec!["rgb_par_1".to_string()],
        EffectLayer::Foreground,
        BlendMode::Overlay,
    );

    // Start all effects
    engine.start_effect(blue_effect).unwrap();
    engine.start_effect(dimmer_effect).unwrap();
    engine.start_effect(strobe_effect).unwrap();

    println!("Effects started:");
    println!("- Static blue (Background, Replace)");
    println!("- Dimmer 100%->50% over 2s (Midground, Multiply)");
    println!("- Strobe 2Hz (Foreground, Overlay)");
    println!();

    // Simulate for 3 seconds
    let mut time = 0.0;
    let dt = Duration::from_millis(200); // 5 FPS for demo

    while time < 3.0 {
        let commands = engine.update(dt, None).unwrap();

        // Print state every 0.4 seconds
        if (time * 5.0) as i32 % 2 == 0 {
            println!("Time: {:.1}s", time);

            for cmd in commands {
                let channel_name = match cmd.channel {
                    1 => "Red",
                    2 => "Green",
                    3 => "Blue",
                    4 => "Dimmer",
                    5 => "Strobe",
                    _ => "Unknown",
                };
                println!(
                    "  {}: {} ({:.1}%)",
                    channel_name,
                    cmd.value,
                    cmd.value as f64 / 255.0 * 100.0
                );
            }
            println!();
        }

        time += dt.as_secs_f64();
    }

    println!("Demo complete! This shows how effects layer together:");
    println!("1. Blue color starts at full intensity");
    println!("2. Dimmer slowly reduces brightness from 100% to 50%");
    println!("3. Strobe effect overlays on top, creating a strobing effect");
    println!("4. The final result is a strobing, dimmed blue light");
}
#[test]
fn test_multiple_effects_simultaneous() {
    use super::super::effects::*;
    use super::super::engine::EffectEngine;

    // Initialize tracing

    // Create 4 fixtures (like in your real application)
    let mut engine = EffectEngine::new();

    for i in 1..=4 {
        let mut channels = HashMap::new();
        channels.insert("red".to_string(), 1);
        channels.insert("green".to_string(), 2);
        channels.insert("blue".to_string(), 3);
        channels.insert("strobe".to_string(), 4);

        let fixture = FixtureInfo::new(
            format!("fixture_{}", i),
            1,
            (i - 1) * 4 + 1, // Each fixture takes 4 channels
            "Astera-PixelBrick".to_string(),
            channels,
            Some(25.0), // Astera-PixelBrick max strobe frequency
        );

        engine.register_fixture(fixture);
    }

    // Test 1: Static blue on all fixtures
    let mut static_params = HashMap::new();
    static_params.insert("red".to_string(), 0.0);
    static_params.insert("green".to_string(), 0.0);
    static_params.insert("blue".to_string(), 1.0);

    let static_effect = create_effect_with_layering(
        "static_blue".to_string(),
        EffectType::Static {
            parameters: static_params,
            duration: Duration::from_secs(5),
        },
        vec![
            "fixture_1".to_string(),
            "fixture_2".to_string(),
            "fixture_3".to_string(),
            "fixture_4".to_string(),
        ],
        EffectLayer::Background,
        BlendMode::Replace,
    );

    engine.start_effect(static_effect).unwrap();

    // Check at 0s
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("=== At 0s (Static blue on 4 fixtures) ===");
    for cmd in commands {
        let fixture_num = ((cmd.channel - 1) / 4) + 1;
        let channel_in_fixture = ((cmd.channel - 1) % 4) + 1;
        let channel_name = match channel_in_fixture {
            1 => "Red",
            2 => "Green",
            3 => "Blue",
            4 => "Strobe",
            _ => "Unknown",
        };
        println!(
            "  Fixture {} {} (Ch{}): {}",
            fixture_num, channel_name, cmd.channel, cmd.value
        );
    }

    // Test 2: Add dimmer with multiply blend mode
    let dimmer_effect = create_effect_with_layering(
        "dimmer_multiply".to_string(),
        EffectType::Dimmer {
            start_level: 1.0,
            end_level: 0.5,
            duration: Duration::from_secs(5),
            curve: DimmerCurve::Linear,
        },
        vec![
            "fixture_1".to_string(),
            "fixture_2".to_string(),
            "fixture_3".to_string(),
            "fixture_4".to_string(),
        ],
        EffectLayer::Midground,
        BlendMode::Multiply,
    );

    engine.start_effect(dimmer_effect).unwrap();

    // Check at 2s (dimmer start)
    let commands = engine.update(Duration::from_secs(2), None).unwrap();
    println!("\n=== At 2s (Dimmer starts on 4 fixtures) ===");
    for cmd in commands {
        let fixture_num = ((cmd.channel - 1) / 4) + 1;
        let channel_in_fixture = ((cmd.channel - 1) % 4) + 1;
        let channel_name = match channel_in_fixture {
            1 => "Red",
            2 => "Green",
            3 => "Blue",
            4 => "Strobe",
            _ => "Unknown",
        };
        println!(
            "  Fixture {} {} (Ch{}): {}",
            fixture_num, channel_name, cmd.channel, cmd.value
        );
    }

    // Check at 4.5s (50% through dimmer)
    engine.update(Duration::from_secs(2), None).unwrap();
    let commands = engine
        .update(Duration::from_secs(0), None)
        .unwrap()
        .to_vec();
    println!("\n=== At 4.5s (50% through dimmer on 4 fixtures) ===");

    // Advance to 25s to trigger debug logging
    engine.update(Duration::from_secs(20), None).unwrap();
    let commands_25s = engine.update(Duration::from_secs(0), None).unwrap();
    println!("\n=== At 25s (Debug logging should appear) ===");
    println!("Commands at 25s: {} commands", commands_25s.len());
    for cmd in commands_25s {
        println!("  Channel {}: {}", cmd.channel, cmd.value);
    }
    for cmd in &commands {
        let fixture_num = ((cmd.channel - 1) / 4) + 1;
        let channel_in_fixture = ((cmd.channel - 1) % 4) + 1;
        let channel_name = match channel_in_fixture {
            1 => "Red",
            2 => "Green",
            3 => "Blue",
            4 => "Strobe",
            _ => "Unknown",
        };
        println!(
            "  Fixture {} {} (Ch{}): {}",
            fixture_num, channel_name, cmd.channel, cmd.value
        );
    }

    // Final analysis
    let red_commands: Vec<_> = commands
        .iter()
        .filter(|cmd| ((cmd.channel - 1) % 4) + 1 == 1)
        .collect();
    let green_commands: Vec<_> = commands
        .iter()
        .filter(|cmd| ((cmd.channel - 1) % 4) + 1 == 2)
        .collect();
    let blue_commands: Vec<_> = commands
        .iter()
        .filter(|cmd| ((cmd.channel - 1) % 4) + 1 == 3)
        .collect();

    println!("\n=== FINAL ANALYSIS ===");
    println!(
        "Red channels: {:?}",
        red_commands.iter().map(|cmd| cmd.value).collect::<Vec<_>>()
    );
    println!(
        "Green channels: {:?}",
        green_commands
            .iter()
            .map(|cmd| cmd.value)
            .collect::<Vec<_>>()
    );
    println!(
        "Blue channels: {:?}",
        blue_commands
            .iter()
            .map(|cmd| cmd.value)
            .collect::<Vec<_>>()
    );

    // Check if all RGB values are the same (the problem you're seeing)
    let all_red_same = red_commands.windows(2).all(|w| w[0].value == w[1].value);
    let all_green_same = green_commands.windows(2).all(|w| w[0].value == w[1].value);
    let all_blue_same = blue_commands.windows(2).all(|w| w[0].value == w[1].value);

    if all_red_same && all_green_same && all_blue_same {
        println!("❌ ALL RGB VALUES ARE THE SAME ACROSS ALL FIXTURES!");
        println!("❌ This matches what you're seeing in OLA!");
    } else {
        println!("✅ RGB values vary across fixtures - this is correct");
    }
}
#[test]
fn test_astera_pixelblock_real_behavior() {
    use super::super::effects::*;
    use super::super::engine::EffectEngine;

    // Initialize tracing

    // Create Astera PixelBlock fixture (exactly as you described)
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);
    channels.insert("strobe".to_string(), 4);
    // NO dimmer channel!

    let fixture = FixtureInfo::new(
        "front_wash".to_string(),
        1,
        1,
        "Astera-PixelBrick".to_string(),
        channels,
        Some(20.0), // Test fixture with strobe
    );

    println!("Fixture capabilities: {:?}", fixture.capabilities());
    println!(
        "Has RGB_COLOR: {}",
        fixture.has_capability(FixtureCapabilities::RGB_COLOR)
    );
    println!(
        "Has DIMMING: {}",
        fixture.has_capability(FixtureCapabilities::DIMMING)
    );

    let mut engine = EffectEngine::new();
    engine.register_fixture(fixture);

    // Test static blue (with dimmer parameter)
    let mut static_params = HashMap::new();
    static_params.insert("red".to_string(), 0.0);
    static_params.insert("green".to_string(), 0.0);
    static_params.insert("blue".to_string(), 1.0);
    static_params.insert("dimmer".to_string(), 1.0); // This should be ignored!

    let static_effect = create_effect_with_layering(
        "static_blue".to_string(),
        EffectType::Static {
            parameters: static_params,
            duration: Duration::from_secs(5),
        },
        vec!["front_wash".to_string()],
        EffectLayer::Background,
        BlendMode::Replace,
    );

    engine.start_effect(static_effect).unwrap();

    // Check at 0s
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("\n=== At 0s (Static blue) ===");
    for cmd in commands {
        let channel_name = match cmd.channel {
            1 => "Red",
            2 => "Green",
            3 => "Blue",
            4 => "Strobe",
            _ => "Unknown",
        };
        println!("  {} (Ch{}): {}", channel_name, cmd.channel, cmd.value);
    }

    // Add dimmer with multiply blend mode
    let dimmer_effect = create_effect_with_layering(
        "dimmer_multiply".to_string(),
        EffectType::Dimmer {
            start_level: 1.0,
            end_level: 0.5,
            duration: Duration::from_secs(5),
            curve: DimmerCurve::Linear,
        },
        vec!["front_wash".to_string()],
        EffectLayer::Midground,
        BlendMode::Multiply,
    );

    // Advance to 2s and start dimmer
    engine.update(Duration::from_secs(2), None).unwrap();
    engine.start_effect(dimmer_effect).unwrap();

    // Check at 2s (dimmer start)
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("\n=== At 2s (Dimmer starts) ===");
    for cmd in commands {
        let channel_name = match cmd.channel {
            1 => "Red",
            2 => "Green",
            3 => "Blue",
            4 => "Strobe",
            _ => "Unknown",
        };
        println!("  {} (Ch{}): {}", channel_name, cmd.channel, cmd.value);
    }

    // Check at 4.5s (50% through dimmer)
    engine.update(Duration::from_secs(2), None).unwrap();
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("\n=== At 4.5s (50% through dimmer) ===");
    for cmd in commands {
        let channel_name = match cmd.channel {
            1 => "Red",
            2 => "Green",
            3 => "Blue",
            4 => "Strobe",
            _ => "Unknown",
        };
        println!("  {} (Ch{}): {}", channel_name, cmd.channel, cmd.value);
    }

    // Final analysis
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1);
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2);
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3);

    if let (Some(red), Some(green), Some(blue)) = (red_cmd, green_cmd, blue_cmd) {
        println!("\n=== FINAL ANALYSIS ===");
        println!(
            "Red: {}, Green: {}, Blue: {}",
            red.value, green.value, blue.value
        );

        if red.value == green.value && green.value == blue.value {
            println!("❌ ALL RGB VALUES ARE THE SAME - THIS IS THE PROBLEM!");
            println!("❌ The dimmer is setting all RGB channels to the same value");
            println!("❌ This matches what you're seeing in OLA!");
        } else if red.value == 0 && green.value == 0 && blue.value > 0 {
            println!("✅ Only blue is set - this is correct behavior");
        } else {
            println!("❓ Unexpected behavior - need to investigate further");
        }
    }
}
#[test]
fn test_permanent_vs_temporary_effects() {
    // Test that permanent effects lock channels while temporary effects don't
    let mut engine = EffectEngine::new();

    // Register test fixture
    let mut channels = HashMap::new();
    channels.insert("dimmer".to_string(), 1);
    channels.insert("red".to_string(), 2);
    channels.insert("green".to_string(), 3);
    channels.insert("blue".to_string(), 4);

    let fixture = FixtureInfo::new(
        "test_fixture".to_string(),
        1,
        1,
        "Dimmer".to_string(),
        channels,
        None,
    );

    engine.register_fixture(fixture);

    // Test 1: Permanent effect (Static) should be indefinite and active
    let mut static_effect = EffectInstance::new(
        "static_red".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 1.0);
                params.insert("green".to_string(), 0.0);
                params.insert("blue".to_string(), 0.0);
                params.insert("dimmer".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5), // Indefinite static effect
        },
        vec!["test_fixture".to_string()],
        None,
        None,
        None,
    );
    static_effect.layer = EffectLayer::Foreground;
    static_effect.blend_mode = BlendMode::Replace;

    engine.start_effect(static_effect).unwrap();

    // Let the static effect run for a bit
    engine.update(Duration::from_secs(1), None).unwrap();

    // Now add a background effect that should be blocked by the locked channels
    let mut background_effect = EffectInstance::new(
        "background_blue".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 0.0);
                params.insert("green".to_string(), 0.0);
                params.insert("blue".to_string(), 1.0);
                params.insert("dimmer".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5),
        },
        vec!["test_fixture".to_string()],
        None,
        None,
        None,
    );
    background_effect.layer = EffectLayer::Background;
    background_effect.blend_mode = BlendMode::Replace;

    engine.start_effect(background_effect).unwrap();

    // The background effect should not be able to override the foreground static effect
    let commands = engine.update(Duration::from_secs(1), None).unwrap();

    println!("Testing permanent effect behavior:");
    for cmd in commands {
        let channel_name = match cmd.channel {
            1 => "Dimmer",
            2 => "Red",
            3 => "Green",
            4 => "Blue",
            _ => "Unknown",
        };
        println!(
            "  {}: {} ({:.1}%)",
            channel_name,
            cmd.value,
            cmd.value as f64 / 255.0 * 100.0
        );
    }

    // Red should be 255 (foreground static effect takes precedence)
    // Blue should be 0 (background effect can't override foreground effect)
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 2);
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 4);

    assert_eq!(
        red_cmd.map(|cmd| cmd.value).unwrap_or(0),
        255,
        "Red should be 255 (foreground static effect)"
    );
    assert_eq!(
        blue_cmd.map(|cmd| cmd.value).unwrap_or(0),
        0,
        "Blue should be 0 (background effect blocked by foreground)"
    );

    println!("✅ Permanent effect behavior test passed!");
}
#[test]
fn test_grandma_style_fade_out() {
    // Test that fade-out effects work like grandMA - final state persists
    let mut engine = EffectEngine::new();

    // Register test fixtures
    let mut front_wash_channels = HashMap::new();
    front_wash_channels.insert("dimmer".to_string(), 1);
    front_wash_channels.insert("red".to_string(), 2);
    front_wash_channels.insert("green".to_string(), 3);
    front_wash_channels.insert("blue".to_string(), 4);

    let front_wash = FixtureInfo::new(
        "front_wash".to_string(),
        1,
        1,
        "Dimmer".to_string(),
        front_wash_channels,
        None,
    );

    engine.register_fixture(front_wash);

    // Start with a static blue background effect (indefinite)
    let mut blue_effect = EffectInstance::new(
        "blue_bg".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 0.0);
                params.insert("green".to_string(), 0.0);
                params.insert("blue".to_string(), 1.0);
                params.insert("dimmer".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5),
        },
        vec!["front_wash".to_string()],
        None,
        None,
        None,
    );
    blue_effect.layer = EffectLayer::Background;
    blue_effect.blend_mode = BlendMode::Replace;

    engine.start_effect(blue_effect).unwrap();

    // Let the blue effect run for a bit
    engine.update(Duration::from_secs(1), None).unwrap();

    // Now add a fade-out effect (2 seconds) - crossfade all channels to black
    let mut fade_out_effect = EffectInstance::new(
        "fade_out".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 0.0);
                params.insert("green".to_string(), 0.0);
                params.insert("blue".to_string(), 0.0);
                params.insert("dimmer".to_string(), 0.0);
                params
            },
            duration: Duration::from_secs(2), // Make it timed
        },
        vec!["front_wash".to_string()],
        Some(Duration::from_secs(0)), // up_time
        Some(Duration::from_secs(0)), // hold_time
        Some(Duration::from_secs(2)), // down_time
    );
    fade_out_effect.layer = EffectLayer::Foreground;
    fade_out_effect.blend_mode = BlendMode::Replace;

    engine.start_effect(fade_out_effect).unwrap();

    println!("Testing grandMA-style fade-out behavior");

    // Test during fade-out
    let commands_1s = engine.update(Duration::from_secs(1), None).unwrap();
    println!("\nAt 1s (50% through fade-out):");
    for cmd in commands_1s {
        let channel_name = match cmd.channel {
            1 => "Dimmer",
            2 => "Red",
            3 => "Green",
            4 => "Blue",
            _ => "Unknown",
        };
        println!(
            "  {}: {} ({:.1}%)",
            channel_name,
            cmd.value,
            cmd.value as f64 / 255.0 * 100.0
        );
    }

    // Test at end of fade-out
    let commands_2s = engine.update(Duration::from_secs(1), None).unwrap();
    println!("\nAt 2s (end of fade-out):");
    for cmd in commands_2s {
        let channel_name = match cmd.channel {
            1 => "Dimmer",
            2 => "Red",
            3 => "Green",
            4 => "Blue",
            _ => "Unknown",
        };
        println!(
            "  {}: {} ({:.1}%)",
            channel_name,
            cmd.value,
            cmd.value as f64 / 255.0 * 100.0
        );
    }

    // Test after fade-out (should stay at 0 - grandMA behavior)
    let commands_3s = engine.update(Duration::from_secs(1), None).unwrap();
    println!("\nAt 3s (after fade-out - should stay at 0):");
    for cmd in commands_3s {
        let channel_name = match cmd.channel {
            1 => "Dimmer",
            2 => "Red",
            3 => "Green",
            4 => "Blue",
            _ => "Unknown",
        };
        println!(
            "  {}: {} ({:.1}%)",
            channel_name,
            cmd.value,
            cmd.value as f64 / 255.0 * 100.0
        );
    }

    // Verify that background effect takes over after timed effect ends
    let final_dimmer = commands_3s
        .iter()
        .find(|cmd| cmd.channel == 1)
        .map(|cmd| cmd.value)
        .unwrap_or(0);
    let final_blue = commands_3s
        .iter()
        .find(|cmd| cmd.channel == 4)
        .map(|cmd| cmd.value)
        .unwrap_or(0);

    assert_eq!(
        final_dimmer, 255,
        "Dimmer should be 255 (background effect takes over after timed effect ends)"
    );
    assert_eq!(
        final_blue, 255,
        "Blue should be 255 (background effect takes over after timed effect ends)"
    );

    println!("✅ grandMA-style fade-out test completed - final state persists!");
}
#[test]
fn test_real_layering_show_file() {
    use super::super::effects::*;
    use super::super::engine::EffectEngine;
    use super::super::parser::parse_light_shows;

    // Initialize tracing

    // Read the actual layering show file
    let dsl_content = std::fs::read_to_string("examples/lighting/shows/layering_show.light")
        .expect("Failed to read layering show file");

    let shows = match parse_light_shows(&dsl_content) {
        Ok(s) => s,
        Err(e) => {
            println!("Parser error: {}", e);
            panic!("Failed to parse layering show DSL: {}", e);
        }
    };

    let show = shows.get("Effect Layering Demo").unwrap();

    // Create a test fixture (Astera PixelBlock style)
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);
    channels.insert("strobe".to_string(), 4);

    let fixture = FixtureInfo::new(
        "front_wash".to_string(),
        1,
        1,
        "Astera-PixelBrick".to_string(),
        channels,
        Some(20.0), // Test fixture with strobe
    );

    let mut engine = EffectEngine::new();
    engine.register_fixture(fixture);

    // Also register back_wash fixture
    let mut back_channels = HashMap::new();
    back_channels.insert("red".to_string(), 1);
    back_channels.insert("green".to_string(), 2);
    back_channels.insert("blue".to_string(), 3);
    back_channels.insert("strobe".to_string(), 4);

    let back_fixture = FixtureInfo::new(
        "back_wash".to_string(),
        1,
        5, // Different address
        "Astera-PixelBrick".to_string(),
        back_channels,
        Some(20.0), // Test fixture with strobe
    );
    engine.register_fixture(back_fixture);

    // Convert DSL effects to EffectInstances and start them
    for cue in &show.cues {
        for effect in &cue.effects {
            let effect_instance = create_effect_with_layering(
                format!("dsl_effect_{:?}", effect.effect_type),
                effect.effect_type.clone(),
                effect.groups.clone(),
                effect.layer.unwrap_or(EffectLayer::Background),
                effect.blend_mode.unwrap_or(BlendMode::Replace),
            );

            engine.start_effect(effect_instance).unwrap();
        }
    }

    // Test at different time points
    println!("\n=== Testing REAL Layering Show File ===");

    // At 0 seconds - should have static blue
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("At 0s (static blue):");
    for cmd in commands {
        println!("  Channel {}: {}", cmd.channel, cmd.value);
    }

    // At 2 seconds - should have static blue + dimmer starting
    engine.update(Duration::from_secs(2), None).unwrap();
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("\nAt 2s (static blue + dimmer start):");
    for cmd in commands {
        println!("  Channel {}: {}", cmd.channel, cmd.value);
    }

    // At 4.5 seconds - should have dimmed blue (50% through dimmer)
    engine.update(Duration::from_secs(2), None).unwrap();
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("\nAt 4.5s (50% through dimmer):");
    for cmd in commands {
        println!("  Channel {}: {}", cmd.channel, cmd.value);
    }

    // Check what's actually happening
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1);
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2);
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3);

    if let (Some(red), Some(green), Some(blue)) = (red_cmd, green_cmd, blue_cmd) {
        println!("\nREAL BEHAVIOR:");
        println!("  Red: {}", red.value);
        println!("  Green: {}", green.value);
        println!("  Blue: {}", blue.value);

        if red.value == green.value && green.value == blue.value {
            println!("  ❌ ALL RGB VALUES ARE THE SAME - THIS IS THE PROBLEM!");
            println!("  ❌ The dimmer is setting all RGB channels to the same value (white)");
        } else if red.value == 0 && green.value == 0 && blue.value > 0 {
            println!("  ✅ Only blue is set - this is correct behavior");
        } else {
            println!("  ❓ Unexpected behavior - need to investigate");
        }
    }
}
#[test]
fn test_layering_show_effect_execution() {
    use super::super::effects::*;
    use super::super::engine::EffectEngine;
    use super::super::parser::parse_light_shows;

    // Initialize tracing

    // Test the exact DSL from layering_show.light
    let dsl_content = r#"show "Effect Layering Demo" {
    @00:00.000
    front_wash: static color: "blue", duration: 5s, dimmer: 100%, layer: background, blend_mode: replace

    @00:02.000
    front_wash: dimmer start_level: 1.0, end_level: 0.5, duration: 5s, layer: midground, blend_mode: multiply
}"#;

    let shows = match parse_light_shows(dsl_content) {
        Ok(s) => s,
        Err(e) => {
            println!("Parser error: {}", e);
            panic!("Failed to parse layering show DSL: {}", e);
        }
    };

    let show = shows.get("Effect Layering Demo").unwrap();

    // Create a test fixture (Astera PixelBlock style)
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);
    channels.insert("strobe".to_string(), 4);

    let fixture = FixtureInfo::new(
        "front_wash".to_string(),
        1,
        1,
        "Astera-PixelBrick".to_string(),
        channels,
        Some(20.0), // Test fixture with strobe
    );

    let mut engine = EffectEngine::new();
    engine.register_fixture(fixture);

    // Also register back_wash fixture
    let mut back_channels = HashMap::new();
    back_channels.insert("red".to_string(), 1);
    back_channels.insert("green".to_string(), 2);
    back_channels.insert("blue".to_string(), 3);
    back_channels.insert("strobe".to_string(), 4);

    let back_fixture = FixtureInfo::new(
        "back_wash".to_string(),
        1,
        5, // Different address
        "Astera-PixelBrick".to_string(),
        back_channels,
        Some(20.0), // Test fixture with strobe
    );
    engine.register_fixture(back_fixture);

    // Convert DSL effects to EffectInstances and start them
    for cue in &show.cues {
        for effect in &cue.effects {
            let effect_instance = create_effect_with_layering(
                format!("dsl_effect_{:?}", effect.effect_type),
                effect.effect_type.clone(),
                effect.groups.clone(),
                effect.layer.unwrap_or(EffectLayer::Background),
                effect.blend_mode.unwrap_or(BlendMode::Replace),
            );

            engine.start_effect(effect_instance).unwrap();
        }
    }

    // Test at different time points
    println!("\n=== Testing DSL Effect Execution ===");

    // At 0 seconds - should have static blue
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("At 0s (static blue):");
    for cmd in commands {
        println!("  Channel {}: {}", cmd.channel, cmd.value);
    }

    // At 2 seconds - should have static blue + dimmer starting
    engine.update(Duration::from_secs(2), None).unwrap();
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("\nAt 2s (static blue + dimmer start):");
    for cmd in commands {
        println!("  Channel {}: {}", cmd.channel, cmd.value);
    }

    // At 4.5 seconds - should have dimmed blue (50% through dimmer)
    engine.update(Duration::from_secs(2), None).unwrap();
    let commands = engine.update(Duration::from_secs(0), None).unwrap();
    println!("\nAt 4.5s (50% through dimmer):");
    for cmd in commands {
        println!("  Channel {}: {}", cmd.channel, cmd.value);
    }

    // Check that blue is dimmed but not white
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1);
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2);
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3);

    if let (Some(red), Some(green), Some(blue)) = (red_cmd, green_cmd, blue_cmd) {
        println!("\nColor analysis:");
        println!("  Red: {} (should be 0)", red.value);
        println!("  Green: {} (should be 0)", green.value);
        println!("  Blue: {} (should be dimmed, not 255)", blue.value);

        // With multiply blend mode, red and green should be 0, blue should be dimmed
        assert_eq!(red.value, 0, "Red should be 0 with multiply blend mode");
        assert_eq!(green.value, 0, "Green should be 0 with multiply blend mode");
        assert!(
            blue.value < 255,
            "Blue should be dimmed, not full brightness"
        );
        assert!(blue.value > 0, "Blue should not be completely off");
    }

    println!("\n✅ DSL effect execution test passed!");
    println!("✅ Dimmer with multiply blend mode preserves blue color");
}
#[test]
fn test_custom_rgb_dimming() {
    use super::super::effects::*;
    use super::super::engine::EffectEngine;

    // Create a fixture with RGB channels only (no dedicated dimmer)
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);

    let fixture = FixtureInfo::new(
        "rgb_fixture".to_string(),
        1,
        1,
        "RGB_Par".to_string(),
        channels,
        Some(20.0), // Test fixture with strobe
    );

    let mut engine = EffectEngine::new();
    engine.register_fixture(fixture.clone());

    // Test 1: Custom RGB static effect
    println!("\n1. Custom RGB static effect:");
    let mut static_params = HashMap::new();
    static_params.insert("red".to_string(), 1.0); // Full red
    static_params.insert("green".to_string(), 0.5); // Half green
    static_params.insert("blue".to_string(), 0.25); // Quarter blue

    let rgb_effect = create_effect_with_layering(
        "rgb_static".to_string(),
        EffectType::Static {
            parameters: static_params,
            duration: Duration::from_secs(5),
        },
        vec!["rgb_fixture".to_string()],
        EffectLayer::Background,
        BlendMode::Replace,
    );

    engine.start_effect(rgb_effect).unwrap();
    let commands = engine.update(Duration::from_millis(0), None).unwrap();

    println!("Commands: {:?}", commands);
    for cmd in commands {
        let channel_name = match cmd.channel {
            1 => "Red",
            2 => "Green",
            3 => "Blue",
            _ => "Unknown",
        };
        println!(
            "  {}: {} ({:.1}%)",
            channel_name,
            cmd.value,
            cmd.value as f64 / 255.0 * 100.0
        );
    }

    // Test 2: Add dimmer effect (1.0 -> 0.0)
    println!("\n2. Adding dimmer effect (1.0 -> 0.0):");
    let dimmer_effect = create_effect_with_layering(
        "dimmer".to_string(),
        EffectType::Dimmer {
            start_level: 1.0,
            end_level: 0.0,
            duration: Duration::from_secs(2),
            curve: DimmerCurve::Linear,
        },
        vec!["rgb_fixture".to_string()],
        EffectLayer::Midground,
        BlendMode::Replace,
    );

    engine.start_effect(dimmer_effect).unwrap();

    // Check at different time points
    let mut last_time = 0;
    for (time_ms, description) in [(0, "Start"), (500, "25%"), (1000, "50%"), (2000, "End")] {
        let delta_ms = time_ms - last_time;
        let commands = engine
            .update(Duration::from_millis(delta_ms), None)
            .unwrap();
        println!("\n  At {} ({}ms):", description, time_ms);
        last_time = time_ms;
        for cmd in commands {
            let channel_name = match cmd.channel {
                1 => "Red",
                2 => "Green",
                3 => "Blue",
                _ => "Unknown",
            };
            println!(
                "    {}: {} ({:.1}%)",
                channel_name,
                cmd.value,
                cmd.value as f64 / 255.0 * 100.0
            );
        }
    }

    println!("\nCurrent behavior analysis:");
    println!("- All RGB channels get the same dimmer value applied");
    println!("- Red: 255 * dimmer_value");
    println!("- Green: 127 * dimmer_value");
    println!("- Blue: 63 * dimmer_value");
    println!("- This maintains the relative brightness ratios between colors");

    // Verify the behavior is correct
    let final_commands = engine.update(Duration::from_millis(2000), None).unwrap();
    assert_eq!(final_commands.len(), 3); // RGB channels only

    // At the end (4000ms), the dimmer effect has completed and been removed.
    // The underlying static RGB effect shows through at full brightness.
    let red_cmd = final_commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    let green_cmd = final_commands.iter().find(|cmd| cmd.channel == 2).unwrap();
    let blue_cmd = final_commands.iter().find(|cmd| cmd.channel == 3).unwrap();

    assert_eq!(red_cmd.value, 255); // Static red returns to full
    assert_eq!(green_cmd.value, 127); // Static green returns to 50%
    assert_eq!(blue_cmd.value, 63); // Static blue returns to 25%

    println!("✅ Custom RGB dimming test passed!");
    println!("✅ Dimmer maintains relative brightness ratios between colors");
}
#[test]
fn test_parse_layering_show() {
    use super::super::parser::parse_light_shows;

    let dsl_content = std::fs::read_to_string("examples/lighting/shows/layering_show.light")
        .expect("Failed to read layering show file");

    let shows = match parse_light_shows(&dsl_content) {
        Ok(s) => s,
        Err(e) => {
            println!("Parser error: {}", e);
            panic!("Failed to parse layering show: {}", e);
        }
    };

    let show = shows.get("Effect Layering Demo").unwrap();
    assert_eq!(show.name, "Effect Layering Demo");
    assert_eq!(show.cues.len(), 8);

    // Check that group names are parsed correctly (not including comments)
    for cue in &show.cues {
        for effect in &cue.effects {
            for group in &effect.groups {
                assert!(
                    !group.contains("#"),
                    "Group name '{}' contains comment",
                    group
                );
                assert!(
                    !group.contains("Add a"),
                    "Group name '{}' contains comment text",
                    group
                );
            }
        }
    }

    println!("Layering show parsing test passed!");
    println!(
        "Successfully parsed {} cues with proper group names",
        show.cues.len()
    );
}
#[test]
fn test_software_strobing_rgb_only_fixture() {
    let mut engine = EffectEngine::new();

    // Create RGB-only fixture (no strobe or dimmer channels)
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);
    // No strobe or dimmer channels!

    let fixture = FixtureInfo::new(
        "rgb_only_fixture".to_string(),
        1,
        1,
        "RGB_Par".to_string(),
        channels,
        None, // No strobe capability
    );
    engine.register_fixture(fixture);

    // Create strobe effect - should use software strobing
    let strobe_effect = create_effect_with_layering(
        "strobe_effect".to_string(),
        EffectType::Strobe {
            frequency: TempoAwareFrequency::Fixed(2.0), // 2 Hz for easy testing
            duration: Duration::from_secs(5),
        },
        vec!["rgb_only_fixture".to_string()],
        EffectLayer::Foreground,
        BlendMode::Overlay,
    );

    // Start the strobe effect
    engine.start_effect(strobe_effect).unwrap();

    // Test at different time points to verify strobing behavior
    // At t=0ms (start of cycle) - should be ON
    let commands = engine.update(Duration::from_millis(0), None).unwrap();
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2).unwrap();
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3).unwrap();

    assert_eq!(red_cmd.value, 255); // Should be ON (1.0 * 255)
    assert_eq!(green_cmd.value, 255);
    assert_eq!(blue_cmd.value, 255);

    // At t=125ms (1/4 cycle) - should still be ON
    let commands = engine.update(Duration::from_millis(125), None).unwrap();
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    assert_eq!(red_cmd.value, 255); // Should still be ON

    // At t=250ms (1/2 cycle) - should be OFF
    let commands = engine.update(Duration::from_millis(125), None).unwrap(); // 125ms more = 250ms total
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2).unwrap();
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3).unwrap();

    assert_eq!(red_cmd.value, 0); // Should be OFF (0.0 * 255)
    assert_eq!(green_cmd.value, 0);
    assert_eq!(blue_cmd.value, 0);

    // At t=375ms (3/4 cycle) - should still be OFF
    let commands = engine.update(Duration::from_millis(125), None).unwrap(); // 125ms more = 375ms total
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    assert_eq!(red_cmd.value, 0); // Should still be OFF

    // At t=500ms (full cycle) - should be ON again
    let commands = engine.update(Duration::from_millis(125), None).unwrap(); // 125ms more = 500ms total
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    assert_eq!(red_cmd.value, 255); // Should be ON again
}
#[test]
fn test_software_strobing_with_layering() {
    let mut engine = EffectEngine::new();

    // Create RGB-only fixture
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);

    let fixture = FixtureInfo::new(
        "rgb_fixture".to_string(),
        1,
        1,
        "RGB_Par".to_string(),
        channels,
        None, // No strobe capability
    );
    engine.register_fixture(fixture);

    // Create static blue effect (background layer)
    let blue_effect = create_effect_with_layering(
        "static_blue".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 0.0);
                params.insert("green".to_string(), 0.0);
                params.insert("blue".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5),
        },
        vec!["rgb_fixture".to_string()],
        EffectLayer::Background,
        BlendMode::Replace,
    );

    // Create strobe effect (foreground layer)
    let strobe_effect = create_effect_with_layering(
        "strobe_effect".to_string(),
        EffectType::Strobe {
            frequency: TempoAwareFrequency::Fixed(2.0), // 2 Hz
            duration: Duration::from_secs(5),
        },
        vec!["rgb_fixture".to_string()],
        EffectLayer::Foreground,
        BlendMode::Overlay,
    );

    // Start both effects
    engine.start_effect(blue_effect).unwrap();
    engine.start_effect(strobe_effect).unwrap();

    // Test that layering works with software strobing
    // At t=0ms (strobe ON) - should see blue light
    let commands = engine.update(Duration::from_millis(0), None).unwrap();
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2).unwrap();
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3).unwrap();

    assert_eq!(red_cmd.value, 0); // Red should be 0 (static effect)
    assert_eq!(green_cmd.value, 0); // Green should be 0 (static effect)
    assert_eq!(blue_cmd.value, 255); // Blue should be 255 (static + strobe overlay)

    // At t=250ms (strobe OFF) - should see no light
    let commands = engine.update(Duration::from_millis(250), None).unwrap();
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2).unwrap();
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3).unwrap();

    assert_eq!(red_cmd.value, 0); // Red should be 0
    assert_eq!(green_cmd.value, 0); // Green should be 0
    assert_eq!(blue_cmd.value, 0); // Blue should be 0 (strobe OFF overrides static)
}
#[test]
fn test_software_strobing_simple() {
    let mut engine = EffectEngine::new();

    // Create RGB-only fixture
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);

    let fixture = FixtureInfo::new(
        "rgb_fixture".to_string(),
        1,
        1,
        "RGB_Par".to_string(),
        channels,
        None, // No strobe capability
    );
    engine.register_fixture(fixture);

    // Create strobe effect only (no other effects)
    let strobe_effect = create_effect_with_layering(
        "strobe_effect".to_string(),
        EffectType::Strobe {
            frequency: TempoAwareFrequency::Fixed(2.0), // 2 Hz
            duration: Duration::from_secs(5),
        },
        vec!["rgb_fixture".to_string()],
        EffectLayer::Foreground,
        BlendMode::Overlay,
    );

    // Start strobe effect
    engine.start_effect(strobe_effect).unwrap();

    // Test basic strobe functionality
    // At t=0ms (strobe ON) - should see white light
    let commands = engine.update(Duration::from_millis(0), None).unwrap();
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2).unwrap();
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3).unwrap();

    assert_eq!(red_cmd.value, 255); // Should be ON (1.0 * 255)
    assert_eq!(green_cmd.value, 255);
    assert_eq!(blue_cmd.value, 255);

    // At t=250ms (strobe OFF) - should see no light
    let commands = engine.update(Duration::from_millis(250), None).unwrap();
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2).unwrap();
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3).unwrap();

    assert_eq!(red_cmd.value, 0); // Should be OFF (0.0 * 255)
    assert_eq!(green_cmd.value, 0);
    assert_eq!(blue_cmd.value, 0);
}
#[test]
fn test_software_strobing_frequency_zero() {
    let mut engine = EffectEngine::new();

    // Create RGB-only fixture
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);

    let fixture = FixtureInfo::new(
        "rgb_fixture".to_string(),
        1,
        1,
        "RGB_Par".to_string(),
        channels,
        None,
    );
    engine.register_fixture(fixture);

    // Create static blue effect
    let blue_effect = create_effect_with_layering(
        "static_blue".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 0.0);
                params.insert("green".to_string(), 0.0);
                params.insert("blue".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5),
        },
        vec!["rgb_fixture".to_string()],
        EffectLayer::Background,
        BlendMode::Replace,
    );

    // Create strobe effect with frequency 0 (off)
    let strobe_effect = create_effect_with_layering(
        "strobe_off".to_string(),
        EffectType::Strobe {
            frequency: TempoAwareFrequency::Fixed(0.0), // Off
            duration: Duration::from_secs(5),
        },
        vec!["rgb_fixture".to_string()],
        EffectLayer::Foreground,
        BlendMode::Overlay,
    );

    // Start both effects
    engine.start_effect(blue_effect).unwrap();
    engine.start_effect(strobe_effect).unwrap();

    // Test that strobe off defers to parent layers
    let commands = engine.update(Duration::from_millis(0), None).unwrap();
    let red_cmd = commands.iter().find(|cmd| cmd.channel == 1).unwrap();
    let green_cmd = commands.iter().find(|cmd| cmd.channel == 2).unwrap();
    let blue_cmd = commands.iter().find(|cmd| cmd.channel == 3).unwrap();

    // Should see blue light (static effect) - strobe should not interfere
    assert_eq!(red_cmd.value, 0); // Red should be 0 (static effect)
    assert_eq!(green_cmd.value, 0); // Green should be 0 (static effect)
    assert_eq!(blue_cmd.value, 255); // Blue should be 255 (static effect only)
}
#[test]
fn test_full_layering_show_sequence_with_replace() {
    // Test the full sequence from layering_show.light to see what interferes with fade-out
    let mut engine = EffectEngine::new();

    // Register test fixtures
    let mut channels = HashMap::new();
    channels.insert("dimmer".to_string(), 1);
    channels.insert("red".to_string(), 2);
    channels.insert("green".to_string(), 3);
    channels.insert("blue".to_string(), 4);

    let front_wash = FixtureInfo::new(
        "front_wash".to_string(),
        1,
        1,
        "Dimmer".to_string(),
        channels.clone(),
        Some(10.0),
    );

    let back_wash = FixtureInfo::new(
        "back_wash".to_string(),
        1,
        5,
        "Dimmer".to_string(),
        channels.clone(),
        Some(10.0),
    );

    engine.register_fixture(front_wash);
    engine.register_fixture(back_wash);

    println!("Testing full layering show sequence");

    // Simulate the show sequence
    // @00:00.000 - Static blue background
    let static_blue = create_effect_with_layering(
        "static_blue".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("blue".to_string(), 1.0);
                params.insert("red".to_string(), 0.0);
                params.insert("green".to_string(), 0.0);
                params.insert("dimmer".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5),
        },
        vec!["front_wash".to_string()],
        EffectLayer::Background,
        BlendMode::Replace,
    );
    engine.start_effect(static_blue).unwrap();

    // @00:02.000 - Dimmer effect
    let dimmer_effect = create_effect_with_layering(
        "dimmer_effect".to_string(),
        EffectType::Dimmer {
            start_level: 1.0,
            end_level: 0.5,
            duration: Duration::from_secs(5), // 1s up + 3s hold + 1s down
            curve: DimmerCurve::Linear,
        },
        vec!["front_wash".to_string()],
        EffectLayer::Midground,
        BlendMode::Multiply,
    );
    engine.start_effect(dimmer_effect).unwrap();

    // @00:12.000 - Color cycle on back_wash
    let color_cycle = create_effect_with_layering(
        "color_cycle".to_string(),
        EffectType::ColorCycle {
            colors: vec![
                Color {
                    r: 255,
                    g: 0,
                    b: 0,
                    w: None,
                },
                Color {
                    r: 0,
                    g: 255,
                    b: 0,
                    w: None,
                },
                Color {
                    r: 0,
                    g: 0,
                    b: 255,
                    w: None,
                },
            ],
            speed: TempoAwareSpeed::Fixed(1.0),
            direction: CycleDirection::Forward,
            transition: CycleTransition::Snap,
            duration: Duration::from_secs(10),
        },
        vec!["back_wash".to_string()],
        EffectLayer::Midground,
        BlendMode::Replace,
    );
    engine.start_effect(color_cycle).unwrap();

    // @00:15.000 - Dimmer effect on back_wash
    let back_dimmer = create_effect_with_layering(
        "back_dimmer".to_string(),
        EffectType::Dimmer {
            start_level: 1.0,
            end_level: 0.3,
            duration: Duration::from_secs(3), // 0.5s up + 2s hold + 0.5s down
            curve: DimmerCurve::Linear,
        },
        vec!["back_wash".to_string()],
        EffectLayer::Foreground,
        BlendMode::Multiply,
    );
    engine.start_effect(back_dimmer).unwrap();

    // @00:18.000 - Pulse effect on back_wash
    let pulse_effect = create_effect_with_layering(
        "pulse_effect".to_string(),
        EffectType::Pulse {
            base_level: 0.5,
            pulse_amplitude: 0.5,
            frequency: TempoAwareFrequency::Fixed(4.0),
            duration: Duration::from_secs(7), // 1s up + 5s hold + 1s down
        },
        vec!["back_wash".to_string()],
        EffectLayer::Foreground,
        BlendMode::Overlay,
    );
    engine.start_effect(pulse_effect).unwrap();

    // Check state before fade-out
    println!("\nAt 25s (before fade-out):");
    let commands = engine.update(Duration::from_secs(25), None).unwrap();
    for cmd in commands {
        let fixture = if cmd.channel <= 4 {
            "front_wash"
        } else {
            "back_wash"
        };
        let channel_name = match cmd.channel {
            1 | 5 => "Dimmer",
            2 | 6 => "Red",
            3 | 7 => "Green",
            4 | 8 => "Blue",
            _ => "Unknown",
        };
        println!(
            "  {} {}: {} ({:.1}%)",
            fixture,
            channel_name,
            cmd.value,
            cmd.value as f64 / 255.0 * 100.0
        );
    }

    // @00:25.000 - Fade out effects (also set RGB to 0)
    // Create static effects that set RGB to 0 and dimmer to fade-out value
    let front_wash_fade = create_effect_with_layering(
        "front_wash_fade".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 0.0);
                params.insert("green".to_string(), 0.0);
                params.insert("blue".to_string(), 0.0);
                params.insert("dimmer".to_string(), 0.5); // Start at 50%
                params
            },
            duration: Duration::from_secs(2), // 2 second fade out
        },
        vec!["front_wash".to_string()],
        EffectLayer::Foreground,
        BlendMode::Replace,
    );

    let back_wash_fade = create_effect_with_layering(
        "back_wash_fade".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 0.0);
                params.insert("green".to_string(), 0.0);
                params.insert("blue".to_string(), 0.0);
                params.insert("dimmer".to_string(), 0.3); // Start at 30%
                params
            },
            duration: Duration::from_secs(2), // 2 second fade out
        },
        vec!["back_wash".to_string()],
        EffectLayer::Foreground,
        BlendMode::Replace,
    );

    engine.start_effect(front_wash_fade).unwrap();
    engine.start_effect(back_wash_fade).unwrap();

    // Test fade-out behavior
    for (time_ms, description) in [
        (0, "Fade start"),
        (500, "25%"),
        (1000, "50%"),
        (1500, "75%"),
        (2000, "End"),
    ] {
        let commands = engine.update(Duration::from_millis(time_ms), None).unwrap();
        println!("\nAt {} ({}ms):", description, time_ms);

        for cmd in commands {
            let fixture = if cmd.channel <= 4 {
                "front_wash"
            } else {
                "back_wash"
            };
            let channel_name = match cmd.channel {
                1 | 5 => "Dimmer",
                2 | 6 => "Red",
                3 | 7 => "Green",
                4 | 8 => "Blue",
                _ => "Unknown",
            };
            println!(
                "  {} {}: {} ({:.1}%)",
                fixture,
                channel_name,
                cmd.value,
                cmd.value as f64 / 255.0 * 100.0
            );
        }
    }

    println!("✅ Full layering show sequence test completed");
}
#[test]
fn test_complex_multi_layer_multi_effect_scenarios() {
    let mut engine = EffectEngine::new();

    // Create test fixtures
    let mut channels = HashMap::new();
    channels.insert("red".to_string(), 1);
    channels.insert("green".to_string(), 2);
    channels.insert("blue".to_string(), 3);
    channels.insert("strobe".to_string(), 4);

    let fixture1 = FixtureInfo::new(
        "fixture1".to_string(),
        1,
        1,
        "RGB_Par".to_string(),
        channels.clone(),
        Some(20.0),
    );

    let fixture2 = FixtureInfo::new(
        "fixture2".to_string(),
        1,
        2,
        "RGB_Par".to_string(),
        channels.clone(),
        Some(20.0),
    );

    engine.register_fixture(fixture1);
    engine.register_fixture(fixture2);

    // Complex scenario: Multiple effects across different layers and fixtures
    let background_static = create_effect_with_layering(
        "background_static".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("red".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5),
        },
        vec!["fixture1".to_string(), "fixture2".to_string()],
        EffectLayer::Background,
        BlendMode::Replace,
    );

    let midground_dimmer = create_effect_with_layering(
        "midground_dimmer".to_string(),
        EffectType::Dimmer {
            start_level: 1.0,
            end_level: 0.5,
            duration: Duration::from_secs(1),
            curve: DimmerCurve::Linear,
        },
        vec!["fixture1".to_string()],
        EffectLayer::Midground,
        BlendMode::Multiply,
    );

    let midground_pulse = create_effect_with_layering(
        "midground_pulse".to_string(),
        EffectType::Pulse {
            base_level: 0.5,
            pulse_amplitude: 0.3,
            frequency: TempoAwareFrequency::Fixed(2.0),
            duration: Duration::from_secs(5),
        },
        vec!["fixture1".to_string()],
        EffectLayer::Midground,
        BlendMode::Multiply,
    );

    let foreground_strobe = create_effect_with_layering(
        "foreground_strobe".to_string(),
        EffectType::Strobe {
            frequency: TempoAwareFrequency::Fixed(2.0),
            duration: Duration::from_secs(5),
        },
        vec!["fixture2".to_string()],
        EffectLayer::Foreground,
        BlendMode::Overlay,
    );

    // Start all effects
    engine.start_effect(background_static).unwrap();
    engine.start_effect(midground_dimmer).unwrap();
    engine.start_effect(midground_pulse).unwrap();
    engine.start_effect(foreground_strobe).unwrap();

    // All should coexist (different layers, compatible types)
    assert_eq!(engine.active_effects_count(), 4);
    assert!(engine.has_effect("background_static"));
    assert!(engine.has_effect("midground_dimmer"));
    assert!(engine.has_effect("midground_pulse"));
    assert!(engine.has_effect("foreground_strobe"));

    // Add conflicting effects
    let conflicting_static = create_effect_with_layering(
        "conflicting_static".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("blue".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5),
        },
        vec!["fixture1".to_string()],
        EffectLayer::Background, // Same layer as background_static
        BlendMode::Replace,
    );

    let conflicting_strobe = create_effect_with_layering(
        "conflicting_strobe".to_string(),
        EffectType::Strobe {
            frequency: TempoAwareFrequency::Fixed(4.0),
            duration: Duration::from_secs(5),
        },
        vec!["fixture2".to_string()],
        EffectLayer::Foreground, // Same layer as foreground_strobe
        BlendMode::Replace,
    );

    engine.start_effect(conflicting_static).unwrap();
    engine.start_effect(conflicting_strobe).unwrap();

    // With replacement semantics removed, all effects coexist
    assert_eq!(engine.active_effects_count(), 6);
    assert!(engine.has_effect("background_static"));
    assert!(engine.has_effect("midground_dimmer"));
    assert!(engine.has_effect("midground_pulse"));
    assert!(engine.has_effect("foreground_strobe"));
    assert!(engine.has_effect("conflicting_static"));
    assert!(engine.has_effect("conflicting_strobe"));

    // Add another effect - all should coexist
    let high_priority_effect = create_effect_with_layering(
        "high_priority_effect".to_string(),
        EffectType::Static {
            parameters: {
                let mut params = HashMap::new();
                params.insert("green".to_string(), 1.0);
                params
            },
            duration: Duration::from_secs(5),
        },
        vec!["fixture1".to_string()],
        EffectLayer::Background,
        BlendMode::Replace,
    )
    .with_priority(100);

    engine.start_effect(high_priority_effect).unwrap();

    // All effects coexist (no automatic replacement)
    assert_eq!(engine.active_effects_count(), 7);
    assert!(engine.has_effect("conflicting_static"));
    assert!(engine.has_effect("high_priority_effect"));
    assert!(engine.has_effect("conflicting_strobe"));
}
#[test]
fn test_example_files_parse() {
    use crate::lighting::parser::parse_light_shows;
    use std::fs;

    let example_files = [
        "examples/lighting/shows/crossfade_show.light",
        "examples/lighting/shows/layering_show.light",
        "examples/lighting/shows/comprehensive_show.light",
        "examples/lighting/shows/layer_control_demo.light",
    ];

    for file_path in example_files {
        let content = fs::read_to_string(file_path).expect("Failed to read example file");
        let result = parse_light_shows(&content);
        assert!(
            result.is_ok(),
            "Failed to parse {}: {:?}",
            file_path,
            result.err()
        );

        let shows = result.unwrap();
        assert!(!shows.is_empty(), "No shows found in {}", file_path);

        println!(
            "{} parsed successfully with {} shows",
            file_path,
            shows.len()
        );
    }
}