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
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
// 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::audio::Audio;
use super::controller::Controller;
use super::dmx::Dmx;
use super::lighting::Lighting;
use super::midi::Midi;
use super::profile::{AudioConfig, Profile};
use super::samples::{SampleDefinition, SampleTrigger, SamplesConfig, DEFAULT_MAX_SAMPLE_VOICES};
use super::statusevents::StatusEvents;
use super::trackmappings::TrackMappings;
use super::trigger::{MidiTriggerInput, TriggerConfig, TriggerInput};
use config::{Config, File};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use super::error::ConfigError;
use tracing::{error, info, warn};

fn default_active_playlist() -> String {
    "playlist".to_string()
}

/// The configuration for the multitrack player.
#[derive(Deserialize, Serialize, Clone)]
pub struct Player {
    /// The controller configuration.
    controller: Option<Controller>,
    /// The controllers configuration.
    controllers: Option<Vec<Controller>>,
    /// The audio device to use. (legacy)
    audio_device: Option<String>,
    /// The audio configuration section. (legacy)
    audio: Option<Audio>,
    /// The track mappings for the player. (legacy, now optional when using profiles)
    #[serde(default)]
    track_mappings: Option<TrackMappings>,
    /// The MIDI device to use. (legacy)
    midi_device: Option<String>,
    /// The MIDI configuration section. (legacy)
    midi: Option<Midi>,
    /// The DMX configuration. (legacy)
    dmx: Option<Dmx>,
    /// Audio trigger configuration. (legacy, now in profiles)
    trigger: Option<TriggerConfig>,
    /// Unified hardware profiles, tried in priority order.
    /// Each profile contains audio (optional), MIDI (optional), and DMX (optional) configs.
    profiles: Option<Vec<Profile>>,
    /// Directory of external profile YAML files, loaded and prepended before inline profiles.
    profiles_dir: Option<String>,
    /// Events to emit to report status out via MIDI.
    status_events: Option<StatusEvents>,
    /// The path to the playlist.
    playlist: Option<String>,
    /// Directory containing playlist YAML files.
    playlists_dir: Option<String>,
    /// The active playlist name (persisted across restarts).
    #[serde(default = "default_active_playlist")]
    active_playlist: String,
    /// The path to the song definitions.
    songs: String,
    /// Inline sample definitions.
    #[serde(default)]
    samples: HashMap<String, SampleDefinition>,
    /// Path to external samples configuration file.
    samples_file: Option<String>,
    /// Sample trigger mappings.
    #[serde(default)]
    sample_triggers: Vec<SampleTrigger>,
    /// Maximum number of concurrent sample voices globally.
    max_sample_voices: Option<u32>,
}

impl Default for Player {
    fn default() -> Self {
        let mut player = Player {
            controller: None,
            controllers: None,
            audio_device: None,
            audio: None,
            track_mappings: None,
            midi_device: None,
            midi: None,
            dmx: None,
            trigger: None,
            profiles: None,
            profiles_dir: None,
            status_events: None,
            playlist: None,
            playlists_dir: None,
            active_playlist: default_active_playlist(),
            songs: "songs".to_string(),
            samples: HashMap::new(),
            samples_file: None,
            sample_triggers: Vec::new(),
            max_sample_voices: None,
        };
        player.normalize();
        player
    }
}

impl Player {
    #[cfg(test)]
    pub fn new(
        controllers: Vec<Controller>,
        audio: Option<Audio>,
        midi: Option<Midi>,
        dmx: Option<Dmx>,
        track_mappings: HashMap<String, Vec<u16>>,
        songs: &str,
    ) -> Player {
        let mut player = Player {
            controller: None,
            controllers: Some(controllers),
            audio_device: None,
            audio,
            track_mappings: Some(TrackMappings {
                track_mappings: track_mappings.into_iter().collect(),
            }),
            midi_device: None,
            midi,
            dmx,
            trigger: None,
            profiles: None,
            profiles_dir: None,
            status_events: None,
            playlist: None,
            playlists_dir: None,
            active_playlist: default_active_playlist(),
            songs: songs.to_string(),
            samples: HashMap::new(),
            samples_file: None,
            sample_triggers: Vec::new(),
            max_sample_voices: None,
        };
        player.normalize();
        player
    }

    /// Deserializes a file from the path into a player configuration struct.
    /// Legacy configs (audio + track_mappings at top level) are normalized into profiles.
    pub fn deserialize(path: &Path) -> Result<Player, ConfigError> {
        let mut player = Config::builder()
            .add_source(File::from(path))
            .build()?
            .try_deserialize::<Player>()?;
        player.load_profiles_dir(path)?;
        player.normalize();
        Ok(player)
    }

    /// Deserializes a YAML string directly into a player configuration struct.
    /// Does not load profiles_dir (no filesystem context). Runs normalize().
    pub fn deserialize_from_str(yaml: &str) -> Result<Player, ConfigError> {
        let mut player = Config::builder()
            .add_source(config::File::from_str(yaml, config::FileFormat::Yaml))
            .build()?
            .try_deserialize::<Player>()?;
        player.normalize();
        Ok(player)
    }

    /// Validates the player configuration for semantic issues that can be
    /// caught without runtime context. Call this before writing to disk.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        // Validate legacy top-level configs.
        if let Some(ref audio) = self.audio {
            if let Err(audio_errors) = audio.validate() {
                errors.extend(audio_errors);
            }
        }
        if let Some(ref midi) = self.midi {
            if let Err(midi_errors) = midi.validate() {
                errors.extend(midi_errors);
            }
        }
        if let Some(ref dmx) = self.dmx {
            if let Err(dmx_errors) = dmx.validate() {
                errors.extend(dmx_errors);
            }
        }

        // Validate track mappings (legacy top-level).
        if let Some(ref mappings) = self.track_mappings {
            for (name, channels) in mappings.track_mappings.iter() {
                for ch in channels {
                    if *ch == 0 {
                        errors.push(format!(
                            "track_mappings '{}': channel 0 is invalid (channels are 1-indexed)",
                            name
                        ));
                    }
                }
            }
        }

        // Validate profiles.
        if let Some(ref profiles) = self.profiles {
            for (i, profile) in profiles.iter().enumerate() {
                if let Err(profile_errors) = profile.validate() {
                    for e in profile_errors {
                        errors.push(format!("profile[{}]: {}", i, e));
                    }
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Loads profiles from the profiles_dir, if configured.
    /// Directory profiles replace inline profiles entirely. If the directory is
    /// empty, inline profiles are kept as a fallback.
    fn load_profiles_dir(&mut self, config_path: &Path) -> Result<(), ConfigError> {
        let profiles_dir_str = match &self.profiles_dir {
            Some(dir) => dir.clone(),
            None => return Ok(()),
        };

        let dir_path = if Path::new(&profiles_dir_str).is_absolute() {
            PathBuf::from(&profiles_dir_str)
        } else {
            let config_dir = config_path.parent().unwrap_or(Path::new("."));
            config_dir.join(&profiles_dir_str)
        };

        // codeql[rust/path-injection] profiles_dir comes from the local config file on disk.
        let entries = std::fs::read_dir(&dir_path).map_err(|source| ConfigError::Io {
            path: dir_path.clone(),
            source,
        })?;

        let mut yaml_paths: Vec<PathBuf> = Vec::new();
        for entry in entries {
            let entry = entry.map_err(|source| ConfigError::Io {
                path: dir_path.clone(),
                source,
            })?;
            let path = entry.path();
            if path.is_file() {
                if let Some(ext) = path.extension() {
                    if ext == "yaml" || ext == "yml" {
                        yaml_paths.push(path);
                    }
                }
            }
        }
        yaml_paths.sort_by(|a, b| a.file_name().cmp(&b.file_name()));

        let mut dir_profiles: Vec<Profile> = Vec::new();
        for path in &yaml_paths {
            let profile = Config::builder()
                .add_source(File::from(path.as_path()))
                .build()
                .and_then(|c| c.try_deserialize::<Profile>())
                .map_err(|source| ConfigError::ProfileParse {
                    path: path.clone(),
                    source,
                })?;
            dir_profiles.push(profile);
        }

        if !dir_profiles.is_empty() {
            // Directory profiles win — replace any inline profiles entirely.
            if self.profiles.is_some() {
                warn!("inline 'profiles' ignored; using profiles_dir");
            }
            self.profiles = Some(dir_profiles);
        }
        // If directory is empty, fall back to inline profiles (backward compat).

        Ok(())
    }

    /// Gets the profiles directory, resolved relative to the given config path.
    pub fn profiles_dir_resolved(&self, config_path: &Path) -> Option<PathBuf> {
        let dir_str = self.profiles_dir.as_ref()?;
        let dir_path = PathBuf::from(dir_str);
        if dir_path.is_absolute() {
            Some(dir_path)
        } else {
            let config_dir = config_path.parent().unwrap_or(Path::new("."));
            Some(config_dir.join(dir_path))
        }
    }

    /// Normalizes legacy configuration fields into profiles.
    /// After normalization, `profiles` is the source of truth.
    fn normalize(&mut self) {
        if self.profiles.is_some() {
            // Warn about legacy fields that will be ignored.
            if self.audio.is_some() || self.audio_device.is_some() {
                warn!("top-level 'audio'/'audio_device' ignored when 'profiles' is present");
            }
            if self.midi.is_some() || self.midi_device.is_some() {
                warn!("top-level 'midi'/'midi_device' ignored when 'profiles' is present");
            }
            if self.dmx.is_some() {
                warn!("top-level 'dmx' ignored when 'profiles' is present");
            }
            if self.trigger.is_some() {
                warn!("top-level 'trigger' ignored when 'profiles' is present");
            }
            if self.track_mappings.is_some() {
                warn!("top-level 'track_mappings' ignored when 'profiles' is present");
            }
            if !self.sample_triggers.is_empty() {
                warn!("top-level 'sample_triggers' ignored when 'profiles' is present");
            }
            if self.controller.is_some() || self.controllers.is_some() {
                warn!("top-level 'controller'/'controllers' ignored when 'profiles' is present");
            }
            if self.status_events.is_some() {
                warn!(
                    "top-level 'status_events' ignored when 'profiles' is present; move to profile"
                );
            }
            return;
        }

        // Build a single profile from legacy fields.
        let audio = if let Some(audio) = &self.audio {
            Some(audio.clone())
        } else {
            self.audio_device.as_ref().map(|d| Audio::new(d))
        };

        let audio_config = audio.map(|audio| {
            let track_mappings = self
                .track_mappings
                .as_ref()
                .map(|tm| tm.track_mappings.clone())
                .unwrap_or_default();
            AudioConfig::new(audio, track_mappings)
        });

        let midi = if let Some(midi) = &self.midi {
            Some(midi.clone())
        } else {
            self.midi_device.as_ref().map(|d| Midi::new(d, None))
        };

        let dmx = self.dmx.clone();
        let mut trigger = self.trigger.clone();

        // Convert legacy sample_triggers → TriggerInput::Midi entries
        if !self.sample_triggers.is_empty() {
            let trigger_config =
                trigger.get_or_insert_with(|| TriggerConfig::new_midi_only(vec![]));
            for st in &self.sample_triggers {
                trigger_config.add_input(TriggerInput::Midi(MidiTriggerInput::new(
                    st.trigger().clone(),
                    st.sample().to_string(),
                )));
            }
        }

        // Collect controllers from legacy top-level fields.
        let controllers = self.collect_controllers();

        let status_events = self.status_events.take();

        // Create a profile if any subsystem is configured.
        if audio_config.is_some()
            || midi.is_some()
            || dmx.is_some()
            || trigger.is_some()
            || !controllers.is_empty()
            || status_events.is_some()
        {
            let mut profile = Profile::new(None, audio_config, midi, dmx);
            profile.set_trigger(trigger);
            profile.set_controllers(controllers);
            profile.set_status_events(status_events);
            self.profiles = Some(vec![profile]);
        }
    }

    /// Collects controllers from legacy top-level fields.
    fn collect_controllers(&self) -> Vec<Controller> {
        if let Some(controllers) = &self.controllers {
            return controllers.clone();
        } else if let Some(controller) = &self.controller {
            if let Controller::Multi(multi) = controller {
                return multi.values().cloned().collect();
            }

            return vec![controller.clone()];
        }

        vec![]
    }

    /// Returns a reference to the first profile, if any.
    fn first_profile(&self) -> Option<&Profile> {
        self.profiles.as_ref().and_then(|ps| ps.first())
    }

    /// Gets the controllers configuration from the first profile.
    /// Kept for backward compatibility in tests.
    #[cfg(test)]
    pub fn controllers(&self) -> Vec<Controller> {
        self.first_profile()
            .map(|p| p.controllers().to_vec())
            .unwrap_or_default()
    }

    /// Returns profiles filtered by hostname and ordered by priority.
    /// The first matching profile should be used.
    pub fn profiles(&self, hostname: &str) -> Vec<&Profile> {
        match &self.profiles {
            Some(profiles) => profiles
                .iter()
                .filter(|p| match p.hostname() {
                    Some(h) => h == hostname,
                    None => true,
                })
                .collect(),
            None => vec![],
        }
    }

    /// Returns all profiles without hostname filtering (for verify command).
    pub fn all_profiles(&self) -> &[Profile] {
        match &self.profiles {
            Some(profiles) => profiles.as_slice(),
            None => &[],
        }
    }

    /// Gets the audio configuration from the first profile.
    /// Kept for backward compatibility in tests.
    #[cfg(test)]
    pub fn audio(&self) -> Option<Audio> {
        self.first_profile()
            .and_then(|p| p.audio_config())
            .map(|ac| ac.audio().clone())
    }

    /// Gets the track mapping configuration from the first profile.
    /// Kept for backward compatibility. Returns a HashMap since callers
    /// (verify, CLI) don't need insertion-order preservation.
    pub fn track_mappings(&self) -> HashMap<String, Vec<u16>> {
        self.first_profile()
            .and_then(|p| p.audio_config())
            .map(|ac| ac.track_mappings_hash())
            .unwrap_or_default()
    }

    /// Gets the MIDI configuration from the first profile.
    /// Kept for backward compatibility in tests.
    #[cfg(test)]
    pub fn midi(&self) -> Option<Midi> {
        self.first_profile().and_then(|p| p.midi().cloned())
    }

    /// Gets the DMX configuration from the first profile.
    /// Kept for backward compatibility.
    pub fn dmx(&self) -> Option<&Dmx> {
        self.first_profile().and_then(|p| p.dmx())
    }

    /// Gets the status events configuration.
    pub fn status_events(&self) -> Option<StatusEvents> {
        self.status_events.clone()
    }

    /// Gets the path to the playlist.
    pub fn playlist(&self) -> Option<PathBuf> {
        self.playlist.as_ref().map(PathBuf::from)
    }

    /// Gets the playlists directory, resolved relative to the given config path.
    pub fn playlists_dir(&self, config_path: &Path) -> Option<PathBuf> {
        let dir_str = self.playlists_dir.as_ref()?;
        let dir_path = PathBuf::from(dir_str);
        if dir_path.is_absolute() {
            Some(dir_path)
        } else {
            let config_dir = config_path.parent().unwrap_or(Path::new("."));
            Some(config_dir.join(dir_path))
        }
    }

    /// Gets the active playlist name.
    pub fn active_playlist(&self) -> &str {
        &self.active_playlist
    }

    /// Sets the active playlist name (for config store mutations).
    pub fn set_active_playlist(&mut self, name: String) {
        self.active_playlist = name;
    }

    /// Sets the songs path (relative or absolute).
    pub fn set_songs(&mut self, path: &str) {
        self.songs = path.to_string();
    }

    /// Gets the path to the song definitions.
    pub fn songs(&self, player_path: &Path) -> PathBuf {
        let songs_path_config = PathBuf::from(&self.songs);
        if songs_path_config.is_absolute() {
            return songs_path_config;
        }
        let player_path_directory = match player_path.parent() {
            Some(path) => path,
            None => {
                error!("Could not find parent of player path {player_path:?}");
                return songs_path_config;
            }
        };
        player_path_directory.join(&self.songs)
    }

    /// Gets the samples configuration, merging inline definitions with any external file.
    /// The player_path is used to resolve relative paths.
    pub fn samples_config(&self, player_path: &Path) -> Result<SamplesConfig, ConfigError> {
        let mut config = SamplesConfig::new(
            self.samples.clone(),
            Vec::new(),
            self.max_sample_voices.unwrap_or(DEFAULT_MAX_SAMPLE_VOICES),
        );

        // Load external samples file if specified
        if let Some(samples_file) = &self.samples_file {
            let samples_path = if Path::new(samples_file).is_absolute() {
                PathBuf::from(samples_file)
            } else {
                let player_dir = player_path.parent().unwrap_or(Path::new("."));
                player_dir.join(samples_file)
            };

            info!(path = ?samples_path, "Loading external samples configuration");

            let external_config: SamplesConfig = Config::builder()
                .add_source(File::from(samples_path.as_path()))
                .build()?
                .try_deserialize()?;

            // External config is loaded first, then inline config overrides it
            let mut merged = external_config;
            merged.merge(config);
            config = merged;
        }

        Ok(config)
    }

    /// Gets the maximum sample voices limit.
    pub fn max_sample_voices(&self) -> u32 {
        self.max_sample_voices.unwrap_or(DEFAULT_MAX_SAMPLE_VOICES)
    }

    /// Sets the audio configuration.
    pub fn set_audio(&mut self, audio: Option<Audio>) {
        self.audio = audio;
    }

    /// Sets the MIDI configuration.
    pub fn set_midi(&mut self, midi: Option<Midi>) {
        self.midi = midi;
    }

    /// Sets the DMX configuration.
    pub fn set_dmx(&mut self, dmx: Option<Dmx>) {
        self.dmx = dmx;
    }

    /// Sets the controllers configuration. Pass an empty vec or None to clear.
    pub fn set_controllers(&mut self, controllers: Vec<Controller>) {
        if controllers.is_empty() {
            self.controllers = None;
        } else {
            self.controllers = Some(controllers);
        }
    }

    /// Returns a mutable reference to the profiles list.
    pub fn profiles_mut(&mut self) -> &mut Option<Vec<Profile>> {
        &mut self.profiles
    }

    /// Sets the inline sample definitions.
    pub fn set_samples(&mut self, samples: HashMap<String, SampleDefinition>) {
        self.samples = samples;
    }

    /// Sets the global max sample voices.
    pub fn set_max_sample_voices(&mut self, max_voices: Option<u32>) {
        self.max_sample_voices = max_voices;
    }

    /// Returns the raw `profiles_dir` value (before path resolution).
    pub fn profiles_dir_raw(&self) -> Option<&str> {
        self.profiles_dir.as_deref()
    }

    /// Returns the raw `playlist` value (before path resolution).
    pub fn playlist_raw(&self) -> Option<&str> {
        self.playlist.as_deref()
    }

    /// Returns the raw inline profiles (may be None if not set or already cleared).
    pub fn inline_profiles(&self) -> Option<&[Profile]> {
        self.profiles.as_deref()
    }

    /// Sets the profiles_dir field.
    pub fn set_profiles_dir(&mut self, dir: String) {
        self.profiles_dir = Some(dir);
    }

    /// Clears inline profiles.
    pub fn clear_inline_profiles(&mut self) {
        self.profiles = None;
    }

    /// Sets the playlists_dir field.
    pub fn set_playlists_dir_value(&mut self, dir: String) {
        self.playlists_dir = Some(dir);
    }

    /// Clears the playlist field.
    pub fn clear_playlist(&mut self) {
        self.playlist = None;
    }

    /// Clears all legacy top-level fields that have been normalized into profiles.
    pub fn clear_legacy_fields(&mut self) {
        self.audio_device = None;
        self.audio = None;
        self.midi_device = None;
        self.midi = None;
        self.dmx = None;
        self.trigger = None;
        self.track_mappings = None;
        self.controller = None;
        self.controllers = None;
        self.sample_triggers = Vec::new();
    }

    /// Returns a mutable reference to the DMX config's lighting section.
    pub fn lighting_mut(&mut self) -> Option<&mut Lighting> {
        self.dmx.as_mut().and_then(|d| d.lighting_mut())
    }

    /// Returns a reference to the DMX config's lighting section (through all profiles).
    /// Checks the first profile's DMX config for lighting.
    pub fn lighting_from_profiles(&self) -> Option<&Lighting> {
        self.first_profile()
            .and_then(|p| p.dmx())
            .and_then(|d| d.lighting())
    }

    /// Deserializes a config file without running normalize() or loading profiles_dir.
    /// Used by the migrate command to inspect raw inline fields.
    pub fn deserialize_raw(path: &Path) -> Result<Player, ConfigError> {
        let player = Config::builder()
            .add_source(File::from(path))
            .build()?
            .try_deserialize::<Player>()?;
        Ok(player)
    }

    /// Returns the raw top-level DMX field (before normalization into profiles).
    pub fn dmx_raw(&self) -> Option<&Dmx> {
        self.dmx.as_ref()
    }

    /// Returns whether there are any legacy top-level fields set.
    pub fn has_legacy_fields(&self) -> bool {
        self.audio_device.is_some()
            || self.audio.is_some()
            || self.midi_device.is_some()
            || self.midi.is_some()
            || self.dmx.is_some()
            || self.trigger.is_some()
            || self.track_mappings.is_some()
            || self.controller.is_some()
            || self.controllers.is_some()
            || !self.sample_triggers.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use std::io::Write;
    use std::path::Path;

    use super::*;

    /// Helper to create a Player from a YAML string via a temp file.
    fn player_from_yaml(yaml: &str) -> Player {
        let mut temp = tempfile::NamedTempFile::with_suffix(".yaml").unwrap();
        temp.write_all(yaml.as_bytes()).unwrap();
        Player::deserialize(temp.path()).expect("Failed to deserialize")
    }

    #[test]
    fn test_legacy_config_normalizes_into_profiles() {
        let player = player_from_yaml(
            r#"
songs: songs
audio:
  device: mock-device
  sample_rate: 48000
track_mappings:
  click: [1]
  cue: [2]
midi:
  device: mock-midi
  playback_delay: 500ms
"#,
        );

        // Unified profiles should have been created from legacy fields.
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "mock-device"
        );
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().sample_rate(),
            48000
        );
        assert_eq!(
            profiles[0]
                .audio_config()
                .unwrap()
                .track_mappings()
                .get("click"),
            Some(&vec![1u16])
        );
        assert_eq!(
            profiles[0]
                .audio_config()
                .unwrap()
                .track_mappings()
                .get("cue"),
            Some(&vec![2u16])
        );
        assert!(profiles[0].hostname().is_none());
        assert!(profiles[0].midi().is_some());
        assert_eq!(profiles[0].midi().unwrap().device(), "mock-midi");

        // Backward compat getters should still work.
        assert_eq!(player.audio().unwrap().device(), "mock-device");
        assert_eq!(player.track_mappings().get("click"), Some(&vec![1u16]));
        assert_eq!(player.midi().unwrap().device(), "mock-midi");
    }

    #[test]
    fn test_legacy_audio_device_string_normalizes() {
        let player = player_from_yaml(
            r#"
songs: songs
audio_device: mock-device
track_mappings:
  drums: [1]
"#,
        );

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "mock-device"
        );
        assert_eq!(
            profiles[0]
                .audio_config()
                .unwrap()
                .track_mappings()
                .get("drums"),
            Some(&vec![1u16])
        );
    }

    #[test]
    fn test_legacy_midi_device_string_normalizes() {
        let player = player_from_yaml(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
midi_device: mock-midi
"#,
        );

        let midi = player.midi();
        assert!(midi.is_some());
        assert_eq!(midi.unwrap().device(), "mock-midi");
    }

    #[test]
    fn test_profiles_parse() {
        let player = player_from_yaml(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: mock-device-a
      sample_rate: 48000
      track_mappings:
        drums: [1]
        synth: [2]
    midi:
      device: mock-midi-a
  - hostname: pi-b
    audio:
      device: mock-device-b
      track_mappings:
        drums: [11]
        synth: [12]
    midi:
      device: mock-midi-b
    dmx:
      universes:
        - universe: 1
          name: light-show
  - audio:
      device: mock-fallback
      track_mappings:
        drums: [1]
"#,
        );

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 3);

        assert_eq!(profiles[0].hostname(), Some("pi-a"));
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "mock-device-a"
        );
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().sample_rate(),
            48000
        );
        assert!(profiles[0].midi().is_some());
        assert!(profiles[0].dmx().is_none());

        assert_eq!(profiles[1].hostname(), Some("pi-b"));
        assert_eq!(
            profiles[1].audio_config().unwrap().audio().device(),
            "mock-device-b"
        );
        assert!(profiles[1].midi().is_some());
        assert!(profiles[1].dmx().is_some());

        assert_eq!(profiles[2].hostname(), None);
        assert_eq!(
            profiles[2].audio_config().unwrap().audio().device(),
            "mock-fallback"
        );
        assert!(profiles[2].midi().is_none());
        assert!(profiles[2].dmx().is_none());
    }

    #[test]
    fn test_profiles_filter_by_hostname() {
        let player = player_from_yaml(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: mock-device-a
      track_mappings:
        drums: [1]
  - hostname: pi-b
    audio:
      device: mock-device-b
      track_mappings:
        drums: [11]
  - audio:
      device: mock-fallback
      track_mappings:
        drums: [1]
"#,
        );

        // pi-a sees its own profile + the wildcard.
        let pi_a = player.profiles("pi-a");
        assert_eq!(pi_a.len(), 2);
        assert_eq!(
            pi_a[0].audio_config().unwrap().audio().device(),
            "mock-device-a"
        );
        assert_eq!(
            pi_a[1].audio_config().unwrap().audio().device(),
            "mock-fallback"
        );

        // pi-b sees its own profile + the wildcard.
        let pi_b = player.profiles("pi-b");
        assert_eq!(pi_b.len(), 2);
        assert_eq!(
            pi_b[0].audio_config().unwrap().audio().device(),
            "mock-device-b"
        );
        assert_eq!(
            pi_b[1].audio_config().unwrap().audio().device(),
            "mock-fallback"
        );

        // Unknown host only sees the wildcard.
        let unknown = player.profiles("pi-c");
        assert_eq!(unknown.len(), 1);
        assert_eq!(
            unknown[0].audio_config().unwrap().audio().device(),
            "mock-fallback"
        );
    }

    #[test]
    fn test_profile_without_midi_dmx() {
        let player = player_from_yaml(
            r#"
songs: songs
profiles:
  - audio:
      device: mock-device
      track_mappings:
        drums: [1]
"#,
        );

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert!(profiles[0].midi().is_none());
        assert!(profiles[0].dmx().is_none());
    }

    #[test]
    fn test_profiles_take_precedence_over_legacy() {
        let player = player_from_yaml(
            r#"
songs: songs
audio:
  device: legacy-device
track_mappings:
  click: [99]
profiles:
  - audio:
      device: profile-device
      track_mappings:
        click: [1]
"#,
        );

        // Profiles should be used, not legacy.
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "profile-device"
        );
        assert_eq!(
            profiles[0]
                .audio_config()
                .unwrap()
                .track_mappings()
                .get("click"),
            Some(&vec![1u16])
        );

        // Backward compat getters return from the first profile.
        assert_eq!(player.audio().unwrap().device(), "profile-device");
        assert_eq!(player.track_mappings().get("click"), Some(&vec![1u16]));
    }

    #[test]
    fn test_no_profiles_when_no_audio_config() {
        let player = player_from_yaml(
            r#"
songs: songs
"#,
        );

        // No audio at all.
        assert!(player.all_profiles().is_empty());
        assert!(player.audio().is_none());
        assert!(player.track_mappings().is_empty());
    }

    #[test]
    fn test_profiles_without_top_level_track_mappings() {
        let player = player_from_yaml(
            r#"
songs: songs
profiles:
  - audio:
      device: mock-device
      track_mappings:
        drums: [1]
        synth: [2]
"#,
        );

        // Should work without top-level track_mappings.
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(
            profiles[0]
                .audio_config()
                .unwrap()
                .track_mappings()
                .get("drums"),
            Some(&vec![1u16])
        );

        // Backward compat getter returns from profile.
        assert_eq!(player.track_mappings().get("drums"), Some(&vec![1u16]));
    }

    #[test]
    fn test_hostname_deconfliction() {
        let player = player_from_yaml(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: "Behringer WING"
      track_mappings:
        drums: [1]
        synth: [2]
  - hostname: pi-b
    audio:
      device: "Behringer WING"
      track_mappings:
        drums: [11]
        synth: [12]
"#,
        );

        let pi_a = player.profiles("pi-a");
        assert_eq!(pi_a.len(), 1);
        assert_eq!(
            pi_a[0]
                .audio_config()
                .unwrap()
                .track_mappings()
                .get("drums"),
            Some(&vec![1u16])
        );

        let pi_b = player.profiles("pi-b");
        assert_eq!(pi_b.len(), 1);
        assert_eq!(
            pi_b[0]
                .audio_config()
                .unwrap()
                .track_mappings()
                .get("drums"),
            Some(&vec![11u16])
        );

        // Different device name, same mappings — ensures isolation.
        let pi_c = player.profiles("pi-c");
        assert!(pi_c.is_empty());
    }

    #[test]
    fn test_normalization_creates_profile() {
        let player = player_from_yaml(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
dmx:
  dim_speed_modifier: 0.25
  universes:
  - universe: 1
    name: light-show
"#,
        );

        // Legacy dmx config should be normalized into unified profile
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert!(profiles[0].dmx().is_some());
        assert_eq!(profiles[0].dmx().unwrap().dimming_speed_modifier(), 0.25);
    }

    #[test]
    fn test_trigger_only_normalizes_into_profile() {
        let player = player_from_yaml(
            r#"
songs: songs
trigger:
  device: "UltraLite-mk5"
  inputs:
    - kind: audio
      channel: 1
      sample: "kick"
"#,
        );

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert!(profiles[0].audio_config().is_none());
        assert!(profiles[0].midi().is_none());
        assert!(profiles[0].dmx().is_none());
        assert!(profiles[0].trigger().is_some());
        assert_eq!(
            profiles[0].trigger().unwrap().device(),
            Some("UltraLite-mk5")
        );
    }

    #[test]
    fn test_trigger_with_audio_normalizes_into_profile() {
        let player = player_from_yaml(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
trigger:
  device: "UltraLite-mk5"
  inputs:
    - kind: audio
      channel: 1
      sample: "kick"
"#,
        );

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert!(profiles[0].audio_config().is_some());
        assert!(profiles[0].trigger().is_some());
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "mock-device"
        );
        assert_eq!(
            profiles[0].trigger().unwrap().device(),
            Some("UltraLite-mk5")
        );
    }

    #[test]
    fn test_legacy_controllers_normalize_into_profile() {
        let player = player_from_yaml(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
controllers:
  - kind: grpc
    port: 43234
  - kind: osc
"#,
        );

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].controllers().len(), 2);
        assert_eq!(player.controllers().len(), 2);
    }

    #[test]
    fn test_controllers_only_normalize_into_profile() {
        let player = player_from_yaml(
            r#"
songs: songs
controllers:
  - kind: grpc
"#,
        );

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].controllers().len(), 1);
    }

    #[test]
    fn test_profile_controllers_not_overridden_by_legacy() {
        let player = player_from_yaml(
            r#"
songs: songs
controllers:
  - kind: grpc
profiles:
  - audio:
      device: mock-device
      track_mappings:
        drums: [1]
    controllers:
      - kind: osc
"#,
        );

        // Profile controllers should be used, not legacy.
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].controllers().len(), 1);
    }

    #[test]
    fn test_example_config_parses() {
        // The existing examples/mtrack.yaml must still parse without error.
        let config =
            Player::deserialize(Path::new("examples/mtrack.yaml")).expect("example config failed");

        // Profiles are loaded from profiles_dir.
        let profiles = config.all_profiles();
        assert!(
            profiles.len() >= 2,
            "Expected at least 2 profiles from profiles_dir"
        );

        // First profile (01-raspberry-pi-a) has audio + MIDI + DMX.
        assert!(profiles[0].audio_config().is_some());
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "Behringer WING"
        );
        assert!(profiles[0].midi().is_some());
        assert!(profiles[0].dmx().is_some());

        // Config-level accessors should return the first profile's config.
        assert!(config.audio().is_some());
        assert!(config.midi().is_some());
        assert!(config.dmx().is_some());
    }

    /// Helper to create a Player from a YAML string with an associated temp directory.
    /// The `dir_setup` closure receives the temp dir path for creating profile files.
    fn player_with_dir(yaml: &str, dir_setup: impl FnOnce(&Path)) -> Player {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(&config_path, yaml).unwrap();
        dir_setup(dir.path());
        Player::deserialize(&config_path).expect("Failed to deserialize")
    }

    fn write_profile(dir: &Path, filename: &str, yaml: &str) {
        std::fs::write(dir.join(filename), yaml).unwrap();
    }

    #[test]
    fn test_profiles_dir_loads_profiles() {
        let player = player_with_dir("songs: songs\nprofiles_dir: profiles/\n", |dir| {
            std::fs::create_dir(dir.join("profiles")).unwrap();
            write_profile(
                &dir.join("profiles"),
                "pi-a.yaml",
                "hostname: pi-a\naudio:\n  device: device-a\n  track_mappings:\n    drums: [1]\n",
            );
            write_profile(
                &dir.join("profiles"),
                "pi-b.yml",
                "hostname: pi-b\naudio:\n  device: device-b\n  track_mappings:\n    drums: [11]\n",
            );
        });

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 2);
        assert_eq!(profiles[0].hostname(), Some("pi-a"));
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "device-a"
        );
        assert_eq!(profiles[1].hostname(), Some("pi-b"));
        assert_eq!(
            profiles[1].audio_config().unwrap().audio().device(),
            "device-b"
        );
    }

    #[test]
    fn test_profiles_dir_replaces_inline() {
        let player = player_with_dir(
            concat!(
                "songs: songs\n",
                "profiles_dir: profiles/\n",
                "profiles:\n",
                "  - audio:\n",
                "      device: inline-fallback\n",
                "      track_mappings:\n",
                "        drums: [1]\n",
            ),
            |dir| {
                std::fs::create_dir(dir.join("profiles")).unwrap();
                write_profile(
                    &dir.join("profiles"),
                    "pi-a.yaml",
                    "hostname: pi-a\naudio:\n  device: dir-device\n  track_mappings:\n    drums: [1]\n",
                );
            },
        );

        let profiles = player.all_profiles();
        // Directory profiles replace inline entirely.
        assert_eq!(profiles.len(), 1);
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "dir-device"
        );
        assert_eq!(profiles[0].hostname(), Some("pi-a"));
    }

    #[test]
    fn test_profiles_dir_no_duplication_on_roundtrip() {
        // Regression test: serializing and re-deserializing a config with
        // profiles_dir must not duplicate the directory-loaded profiles.
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(&config_path, "songs: songs\nprofiles_dir: profiles/\n").unwrap();
        std::fs::create_dir(dir.path().join("profiles")).unwrap();
        write_profile(
            &dir.path().join("profiles"),
            "pi-a.yaml",
            "hostname: pi-a\naudio:\n  device: dir-device\n  track_mappings:\n    drums: [1]\n",
        );

        let player = Player::deserialize(&config_path).unwrap();
        assert_eq!(player.all_profiles().len(), 1);

        // Serialize and write back (simulates config store save).
        let yaml = crate::util::to_yaml_string(&player).unwrap();
        std::fs::write(&config_path, &yaml).unwrap();

        // Re-deserialize: should still have exactly 1 profile, not 2.
        let player2 = Player::deserialize(&config_path).unwrap();
        assert_eq!(
            player2.all_profiles().len(),
            1,
            "profiles should not be duplicated after roundtrip"
        );

        assert_eq!(
            player2.all_profiles()[0]
                .audio_config()
                .unwrap()
                .audio()
                .device(),
            "dir-device"
        );
    }

    #[test]
    fn test_profiles_dir_only_serializes_correctly() {
        // When the config has profiles_dir but no inline profiles, the
        // directory profiles should appear in serialized YAML output.
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(&config_path, "songs: songs\nprofiles_dir: profiles/\n").unwrap();
        std::fs::create_dir(dir.path().join("profiles")).unwrap();
        write_profile(
            &dir.path().join("profiles"),
            "pi-a.yaml",
            "hostname: pi-a\naudio:\n  device: device-a\n  track_mappings:\n    drums: [1]\n",
        );

        let player = Player::deserialize(&config_path).unwrap();
        assert_eq!(player.all_profiles().len(), 1);

        // Serialized YAML must include the profile from the directory.
        let yaml = crate::util::to_yaml_string(&player).unwrap();
        assert!(
            yaml.contains("pi-a"),
            "serialized YAML should contain dir profile hostname"
        );
        assert!(
            yaml.contains("device-a"),
            "serialized YAML should contain dir profile device"
        );

        // Roundtrip: re-deserialize should still have exactly 1 profile.
        std::fs::write(&config_path, &yaml).unwrap();
        let player2 = Player::deserialize(&config_path).unwrap();
        assert_eq!(
            player2.all_profiles().len(),
            1,
            "profiles should not be duplicated after roundtrip"
        );
    }

    #[test]
    fn test_profiles_dir_empty_directory() {
        let player = player_with_dir(
            concat!(
                "songs: songs\n",
                "profiles_dir: profiles/\n",
                "profiles:\n",
                "  - audio:\n",
                "      device: inline-device\n",
                "      track_mappings:\n",
                "        drums: [1]\n",
            ),
            |dir| {
                std::fs::create_dir(dir.join("profiles")).unwrap();
            },
        );

        // Only the inline profile should be present.
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "inline-device"
        );
    }

    #[test]
    fn test_profiles_dir_missing_directory_errors() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(&config_path, "songs: songs\nprofiles_dir: nonexistent/\n").unwrap();

        match Player::deserialize(&config_path) {
            Err(ConfigError::Io { path, .. }) => {
                assert!(path.to_string_lossy().contains("nonexistent"));
            }
            Err(other) => panic!("expected ConfigError::Io, got: {other}"),
            Ok(_) => panic!("expected error, got Ok"),
        }
    }

    #[test]
    fn test_profiles_dir_invalid_file_errors() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(&config_path, "songs: songs\nprofiles_dir: profiles/\n").unwrap();
        std::fs::create_dir(dir.path().join("profiles")).unwrap();
        write_profile(
            &dir.path().join("profiles"),
            "bad.yaml",
            "this is not valid profile yaml: [[[",
        );

        match Player::deserialize(&config_path) {
            Err(ConfigError::ProfileParse { path, .. }) => {
                assert!(
                    path.to_string_lossy().contains("bad.yaml"),
                    "should mention filename: {path:?}"
                );
            }
            Err(other) => panic!("expected ConfigError::ProfileParse, got: {other}"),
            Ok(_) => panic!("expected error, got Ok"),
        }
    }

    #[test]
    fn test_profiles_dir_ignores_non_yaml_files() {
        let player = player_with_dir("songs: songs\nprofiles_dir: profiles/\n", |dir| {
            std::fs::create_dir(dir.join("profiles")).unwrap();
            write_profile(
                &dir.join("profiles"),
                "pi-a.yaml",
                "hostname: pi-a\naudio:\n  device: device-a\n  track_mappings:\n    drums: [1]\n",
            );
            // These should be ignored.
            write_profile(&dir.join("profiles"), "notes.txt", "just some notes");
            write_profile(
                &dir.join("profiles"),
                "data.json",
                r#"{"not": "a profile"}"#,
            );
        });

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].hostname(), Some("pi-a"));
    }

    #[test]
    fn test_profiles_dir_sorts_by_filename() {
        let player = player_with_dir("songs: songs\nprofiles_dir: profiles/\n", |dir| {
            std::fs::create_dir(dir.join("profiles")).unwrap();
            // Write in reverse order to verify sorting.
            write_profile(
                &dir.join("profiles"),
                "03-fallback.yml",
                "audio:\n  device: fallback\n  track_mappings:\n    drums: [1]\n",
            );
            write_profile(
                &dir.join("profiles"),
                "01-pi-a.yaml",
                "hostname: pi-a\naudio:\n  device: device-a\n  track_mappings:\n    drums: [1]\n",
            );
            write_profile(
                &dir.join("profiles"),
                "02-pi-b.yaml",
                "hostname: pi-b\naudio:\n  device: device-b\n  track_mappings:\n    drums: [11]\n",
            );
        });

        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 3);
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "device-a"
        );
        assert_eq!(
            profiles[1].audio_config().unwrap().audio().device(),
            "device-b"
        );
        assert_eq!(
            profiles[2].audio_config().unwrap().audio().device(),
            "fallback"
        );
    }

    #[test]
    fn test_profiles_dir_with_hostname_filtering() {
        // With profiles_dir set, directory profiles replace inline entirely.
        // Hostname filtering works on the directory profiles only.
        let player = player_with_dir(
            concat!(
                "songs: songs\n",
                "profiles_dir: profiles/\n",
                "profiles:\n",
                "  - audio:\n",
                "      device: inline-fallback\n",
                "      track_mappings:\n",
                "        drums: [1]\n",
            ),
            |dir| {
                std::fs::create_dir(dir.join("profiles")).unwrap();
                write_profile(
                    &dir.join("profiles"),
                    "01-pi-a.yaml",
                    "hostname: pi-a\naudio:\n  device: device-a\n  track_mappings:\n    drums: [1]\n",
                );
                write_profile(
                    &dir.join("profiles"),
                    "02-pi-b.yaml",
                    "hostname: pi-b\naudio:\n  device: device-b\n  track_mappings:\n    drums: [11]\n",
                );
                // A fallback profile with no hostname in the directory.
                write_profile(
                    &dir.join("profiles"),
                    "99-fallback.yaml",
                    "audio:\n  device: dir-fallback\n  track_mappings:\n    drums: [1]\n",
                );
            },
        );

        // pi-a sees its directory profile + dir fallback.
        let pi_a = player.profiles("pi-a");
        assert_eq!(pi_a.len(), 2);
        assert_eq!(pi_a[0].audio_config().unwrap().audio().device(), "device-a");
        assert_eq!(
            pi_a[1].audio_config().unwrap().audio().device(),
            "dir-fallback"
        );

        // pi-b sees its directory profile + dir fallback.
        let pi_b = player.profiles("pi-b");
        assert_eq!(pi_b.len(), 2);
        assert_eq!(pi_b[0].audio_config().unwrap().audio().device(), "device-b");
        assert_eq!(
            pi_b[1].audio_config().unwrap().audio().device(),
            "dir-fallback"
        );

        // Unknown host sees only dir fallback.
        let unknown = player.profiles("pi-c");
        assert_eq!(unknown.len(), 1);
        assert_eq!(
            unknown[0].audio_config().unwrap().audio().device(),
            "dir-fallback"
        );
    }

    #[test]
    fn test_playlist_getter() {
        let player = player_from_yaml(
            r#"
songs: songs
playlist: my_playlist.yaml
"#,
        );
        assert_eq!(
            player.playlist().unwrap(),
            std::path::PathBuf::from("my_playlist.yaml")
        );
    }

    #[test]
    fn test_playlist_none() {
        let player = player_from_yaml(
            r#"
songs: songs
"#,
        );
        assert!(player.playlist().is_none());
    }

    #[test]
    fn test_songs_absolute_path() {
        let player = player_from_yaml(
            r#"
songs: /absolute/path/to/songs
"#,
        );
        let songs_path = player.songs(Path::new("/some/config.yaml"));
        assert_eq!(
            songs_path,
            std::path::PathBuf::from("/absolute/path/to/songs")
        );
    }

    #[test]
    fn test_songs_relative_path() {
        let player = player_from_yaml(
            r#"
songs: relative/songs
"#,
        );
        let songs_path = player.songs(Path::new("/config/dir/mtrack.yaml"));
        assert_eq!(
            songs_path,
            std::path::PathBuf::from("/config/dir/relative/songs")
        );
    }

    #[test]
    fn test_dmx_none_without_profiles() {
        let player = player_from_yaml(
            r#"
songs: songs
"#,
        );
        assert!(player.dmx().is_none());
    }

    #[test]
    fn test_profiles_none_returns_empty() {
        let player = player_from_yaml(
            r#"
songs: songs
"#,
        );
        assert!(player.profiles("any-host").is_empty());
    }

    #[test]
    fn test_legacy_single_controller_normalizes() {
        let player = player_from_yaml(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
controller:
  kind: grpc
  port: 43234
"#,
        );
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].controllers().len(), 1);
    }

    #[test]
    fn test_max_sample_voices_default() {
        let player = player_from_yaml(
            r#"
songs: songs
"#,
        );
        assert_eq!(player.max_sample_voices(), super::DEFAULT_MAX_SAMPLE_VOICES);
    }

    #[test]
    fn test_max_sample_voices_custom() {
        let player = player_from_yaml(
            r#"
songs: songs
max_sample_voices: 64
"#,
        );
        assert_eq!(player.max_sample_voices(), 64);
    }

    #[test]
    fn test_samples_config_inline() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(
            &config_path,
            r#"
songs: songs
samples:
  kick:
    file: kick.wav
    output_channels: [1, 2]
"#,
        )
        .unwrap();
        let player = Player::deserialize(&config_path).unwrap();
        let sc = player.samples_config(&config_path).unwrap();
        assert!(sc.samples().contains_key("kick"));
        assert_eq!(sc.samples().get("kick").unwrap().file(), Some("kick.wav"));
    }

    #[test]
    fn test_samples_config_with_external_file() {
        let dir = tempfile::tempdir().unwrap();

        // Write the external samples file.
        let samples_path = dir.path().join("samples.yaml");
        std::fs::write(
            &samples_path,
            r#"
samples:
  snare:
    file: snare.wav
    output_channels: [3, 4]
"#,
        )
        .unwrap();

        // Write the main config that references the external file.
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(
            &config_path,
            r#"
songs: songs
samples_file: samples.yaml
samples:
  kick:
    file: kick.wav
    output_channels: [1, 2]
"#,
        )
        .unwrap();

        let player = Player::deserialize(&config_path).unwrap();
        let sc = player.samples_config(&config_path).unwrap();
        // Both inline and external samples should be present.
        assert!(sc.samples().contains_key("kick"));
        assert!(sc.samples().contains_key("snare"));
    }

    #[test]
    fn test_profiles_dir_absolute_path() {
        let dir = tempfile::tempdir().unwrap();
        let profiles_dir = dir.path().join("abs_profiles");
        std::fs::create_dir(&profiles_dir).unwrap();
        std::fs::write(
            profiles_dir.join("host.yaml"),
            "hostname: pi-x\naudio:\n  device: dev-x\n  track_mappings:\n    drums: [1]\n",
        )
        .unwrap();

        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(
            &config_path,
            format!(
                "songs: songs\nprofiles_dir: {}\n",
                profiles_dir.to_str().unwrap()
            ),
        )
        .unwrap();

        let player = Player::deserialize(&config_path).unwrap();
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].hostname(), Some("pi-x"));
    }

    #[test]
    fn test_legacy_sample_triggers_normalize_into_trigger_config() {
        let player = player_from_yaml(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
sample_triggers:
  - trigger:
      type: note_on
      channel: 1
      key: 60
      velocity: 127
    sample: kick
"#,
        );
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert!(profiles[0].trigger().is_some());
    }

    #[test]
    fn test_songs_relative_path_no_parent() {
        // When player_path has no parent (e.g. a bare filename), the songs
        // path falls back to the raw config value.
        let player = player_from_yaml(
            r#"
songs: my_songs
"#,
        );
        // A path like "" has no parent
        let result = player.songs(Path::new(""));
        // With no parent, should return the raw songs path
        assert_eq!(result, PathBuf::from("my_songs"));
    }

    #[test]
    fn test_samples_config_absolute_external_file() {
        let dir = tempfile::tempdir().unwrap();

        // Write the external samples file at an absolute path
        let samples_path = dir.path().join("abs_samples.yaml");
        std::fs::write(
            &samples_path,
            r#"
samples:
  hat:
    file: hat.wav
    output_channels: [5, 6]
"#,
        )
        .unwrap();

        // Main config references external file via absolute path
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(
            &config_path,
            format!(
                "songs: songs\nsamples_file: {}\n",
                samples_path.to_str().unwrap()
            ),
        )
        .unwrap();

        let player = Player::deserialize(&config_path).unwrap();
        let sc = player.samples_config(&config_path).unwrap();
        assert!(sc.samples().contains_key("hat"));
    }

    #[test]
    fn test_serialize_deserialize_round_trip() {
        let yaml = r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: mock-device
      sample_rate: 48000
      track_mappings:
        click: [1]
        cue: [2]
    midi:
      device: mock-midi
      playback_delay: 500ms
    dmx:
      universes:
        - universe: 1
          name: main
    controllers:
      - kind: grpc
        port: 43234
      - kind: osc
  - audio:
      device: fallback
      track_mappings:
        drums: [1, 2]
"#;

        let player = player_from_yaml(yaml);

        // Serialize to YAML via util::to_yaml_string
        let serialized =
            crate::util::to_yaml_string(&player).expect("serialization should succeed");

        // Deserialize the serialized YAML back
        let mut temp = tempfile::NamedTempFile::with_suffix(".yaml").unwrap();
        temp.write_all(serialized.as_bytes()).unwrap();
        let round_tripped =
            Player::deserialize(temp.path()).expect("round-trip deserialization should succeed");

        // Compare by serializing both to JSON (deterministic field order)
        let json1 = serde_json::to_value(&player).unwrap();
        let json2 = serde_json::to_value(&round_tripped).unwrap();
        assert_eq!(json1, json2, "round-trip should preserve all config values");
    }
}