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
// 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 std::error::Error;
use std::path::{Path, PathBuf};

use crate::config;

/// Resolves the config file path from a user-provided path string.
/// If it's a file or has a YAML extension, use it directly.
/// Otherwise treat it as a project directory and look for mtrack.yaml inside.
fn resolve_config_path(path: &str) -> PathBuf {
    let input = Path::new(path);
    if input.is_file() || input.extension().is_some_and(|e| e == "yaml" || e == "yml") {
        input.to_path_buf()
    } else {
        input.join("mtrack.yaml")
    }
}

/// A migration action to report to the user.
struct MigrationAction {
    category: &'static str,
    description: String,
}

/// Collected migration results that can be applied or reported.
struct MigrationPlan {
    actions: Vec<MigrationAction>,
    files_to_write: Vec<(PathBuf, String)>,
    files_to_copy: Vec<(PathBuf, PathBuf)>,
    dirs_to_create: Vec<PathBuf>,
    files_to_delete: Vec<PathBuf>,
    config_yaml: Option<String>,
    config_path: PathBuf,
    backup_path: PathBuf,
}

impl MigrationPlan {
    fn new(config_path: PathBuf) -> Self {
        let backup_path = config_path.with_extension("yaml.bak");
        Self {
            actions: Vec::new(),
            files_to_write: Vec::new(),
            files_to_copy: Vec::new(),
            dirs_to_create: Vec::new(),
            files_to_delete: Vec::new(),
            config_yaml: None,
            config_path,
            backup_path,
        }
    }

    fn add_action(&mut self, category: &'static str, description: String) {
        self.actions.push(MigrationAction {
            category,
            description,
        });
    }

    fn has_changes(&self) -> bool {
        !self.actions.is_empty()
    }

    fn print_report(&self, apply: bool) {
        if apply {
            println!("mtrack migrate [applied]\n");
        } else {
            println!("mtrack migrate [dry-run]\n");
        }

        let mut current_category = "";
        for action in &self.actions {
            if action.category != current_category {
                if !current_category.is_empty() {
                    println!();
                }
                println!("{}:", action.category);
                current_category = action.category;
            }
            println!("  [migrate] {}", action.description);
        }

        if !apply {
            println!("\nRun with --apply to execute these changes.");
        }
    }

    fn apply(&self) -> Result<(), Box<dyn Error>> {
        // Create directories.
        for dir in &self.dirs_to_create {
            std::fs::create_dir_all(dir)?;
        }

        // Write files.
        for (path, content) in &self.files_to_write {
            std::fs::write(path, content)?;
        }

        // Copy files.
        for (src, dst) in &self.files_to_copy {
            std::fs::copy(src, dst)?;
        }

        // Backup and rewrite config.
        if let Some(yaml) = &self.config_yaml {
            std::fs::copy(&self.config_path, &self.backup_path)?;
            std::fs::write(&self.config_path, yaml)?;
        }

        // Delete files (after successful copy).
        for path in &self.files_to_delete {
            std::fs::remove_file(path)?;
        }

        Ok(())
    }
}

/// Runs the migration process.
pub fn migrate(path: &str, apply: bool) -> Result<(), Box<dyn Error>> {
    let config_path = resolve_config_path(path);
    if !config_path.exists() {
        return Err(format!("Config file not found: {}", config_path.display()).into());
    }

    let config_dir = config_path.parent().unwrap_or(Path::new(".")).to_path_buf();

    // Deserialize raw (before normalize) to inspect inline fields.
    let raw_player = config::Player::deserialize_raw(&config_path)?;

    // Now deserialize with normalize to get the canonical form.
    let mut player = config::Player::deserialize(&config_path)?;

    let mut plan = MigrationPlan::new(config_path.clone());

    // Step C runs before A so fixture mutations are applied to profiles before
    // they are serialized and cleared by the profiles migration step.
    // Step C: Inline fixtures → venue file
    migrate_fixtures(&raw_player, &mut player, &config_dir, &mut plan);

    // Step A: Profiles → profiles_dir
    migrate_profiles(&raw_player, &mut player, &config_dir, &mut plan);

    // Step B: Playlist → playlists_dir
    migrate_playlist(
        &raw_player,
        &mut player,
        &config_dir,
        &config_path,
        &mut plan,
    )?;

    // Step D: Legacy fields → clear (implicit via normalize + step A)
    migrate_legacy_fields(&raw_player, &mut player, &mut plan);

    if !plan.has_changes() {
        println!("Nothing to migrate. Config is already using directory-based files.");
        return Ok(());
    }

    // Serialize the modified config.
    let yaml = crate::util::to_yaml_string(&player)?;
    plan.add_action(
        "Config",
        format!(
            "Backup {}{}",
            config_path.display(),
            plan.backup_path.display()
        ),
    );
    plan.add_action("Config", format!("Rewrite {}", config_path.display()));
    plan.config_yaml = Some(yaml);

    plan.print_report(apply);

    if apply {
        plan.apply()?;
    }

    Ok(())
}

/// Step A: Migrate inline profiles to profiles_dir.
fn migrate_profiles(
    raw: &config::Player,
    player: &mut config::Player,
    config_dir: &Path,
    plan: &mut MigrationPlan,
) {
    // Skip if profiles_dir is already set and there are no inline profiles.
    if raw.profiles_dir_raw().is_some() {
        return;
    }

    let profiles = match player.inline_profiles() {
        Some(profiles) if !profiles.is_empty() => profiles.to_vec(),
        _ => return,
    };

    let profiles_dir = config_dir.join("profiles");
    plan.dirs_to_create.push(profiles_dir.clone());

    for (i, profile) in profiles.iter().enumerate() {
        let filename = match profile.hostname() {
            Some(hostname) => format!("{}.yaml", hostname),
            None => format!("profile-{}.yaml", i + 1),
        };
        let profile_path = profiles_dir.join(&filename);

        let hostname_desc = match profile.hostname() {
            Some(h) => format!("hostname: {}", h),
            None => "no hostname".to_string(),
        };

        match crate::util::to_yaml_string(profile) {
            Ok(yaml) => {
                plan.add_action(
                    "Profiles",
                    format!("Write profiles/{} ({})", filename, hostname_desc),
                );
                plan.files_to_write.push((profile_path, yaml));
            }
            Err(e) => {
                eprintln!("Warning: failed to serialize profile {}: {}", filename, e);
            }
        }
    }

    plan.add_action("Profiles", "Set profiles_dir: profiles/".to_string());
    plan.add_action("Profiles", "Clear inline profiles".to_string());

    player.set_profiles_dir("profiles/".to_string());
    player.clear_inline_profiles();
}

/// Step B: Migrate legacy playlist to playlists_dir.
fn migrate_playlist(
    raw: &config::Player,
    player: &mut config::Player,
    config_dir: &Path,
    config_path: &Path,
    plan: &mut MigrationPlan,
) -> Result<(), Box<dyn Error>> {
    let playlist_value = match raw.playlist_raw() {
        Some(v) => v.to_string(),
        None => return Ok(()),
    };

    // Resolve the playlist file path.
    let playlist_path = if Path::new(&playlist_value).is_absolute() {
        PathBuf::from(&playlist_value)
    } else {
        let cfg_dir = config_path.parent().unwrap_or(Path::new("."));
        cfg_dir.join(&playlist_value)
    };

    let playlists_dir = config_dir.join("playlists");

    // Get just the filename from the playlist path.
    let filename = playlist_path
        .file_name()
        .map(|f| f.to_string_lossy().to_string())
        .unwrap_or_else(|| "playlist.yaml".to_string());

    let dest = playlists_dir.join(&filename);

    plan.dirs_to_create.push(playlists_dir);

    if playlist_path.exists() {
        plan.add_action(
            "Playlists",
            format!("Copy {} → playlists/{}", playlist_value, filename),
        );
        plan.files_to_copy.push((playlist_path.clone(), dest));
        plan.files_to_delete.push(playlist_path);
    } else {
        plan.add_action(
            "Playlists",
            format!(
                "Warning: playlist file {} not found, skipping copy",
                playlist_value
            ),
        );
    }

    if raw.profiles_dir_raw().is_none() || player.playlist_raw().is_some() {
        plan.add_action("Playlists", "Set playlists_dir: playlists/".to_string());
        plan.add_action("Playlists", "Clear playlist field".to_string());
    }

    player.set_playlists_dir_value("playlists/".to_string());
    player.clear_playlist();

    Ok(())
}

/// Step C: Migrate inline fixtures to a venue file.
fn migrate_fixtures(
    raw: &config::Player,
    player: &mut config::Player,
    config_dir: &Path,
    plan: &mut MigrationPlan,
) {
    // Check raw config for inline fixtures (they live in dmx.lighting.fixtures).
    // Check profiles first (modern config), then fall back to the raw top-level
    // dmx field (legacy config before normalize moves it into profiles).
    let fixtures = if let Some(lighting) = raw.lighting_from_profiles() {
        lighting.inline_fixtures_raw().cloned()
    } else {
        raw.dmx_raw()
            .and_then(|d| d.lighting())
            .and_then(|l| l.inline_fixtures_raw())
            .cloned()
    };

    let fixtures = match fixtures {
        Some(f) if !f.is_empty() => f,
        _ => return,
    };

    let venues_dir = config_dir.join("lighting").join("venues");
    let venue_path = venues_dir.join("inline_migrated.light");

    plan.dirs_to_create.push(venues_dir);

    // Generate venue DSL.
    let mut lines = vec![format!("venue \"inline_migrated\" {{")];
    let mut sorted_fixtures: Vec<_> = fixtures.iter().collect();
    sorted_fixtures.sort_by_key(|(name, _)| name.as_str());

    for (name, type_spec) in &sorted_fixtures {
        // type_spec is expected to be "Type @ universe:channel"
        lines.push(format!("  fixture \"{}\" {}", name, type_spec));
    }
    lines.push("}".to_string());
    let venue_content = lines.join("\n") + "\n";

    plan.add_action(
        "Lighting",
        format!(
            "Write lighting/venues/inline_migrated.light ({} fixtures)",
            fixtures.len()
        ),
    );
    plan.files_to_write.push((venue_path, venue_content));

    plan.add_action(
        "Lighting",
        "Set directories.venues: lighting/venues".to_string(),
    );
    plan.add_action("Lighting", "Clear inline fixtures".to_string());

    // Mutate the player config to set venues dir and clear fixtures.
    // We need to modify the lighting config on profiles (after normalize).
    if let Some(profiles) = player.profiles_mut() {
        for profile in profiles.iter_mut() {
            if let Some(dmx) = profile.dmx_mut() {
                if let Some(lighting) = dmx.lighting_mut() {
                    if lighting.directories().and_then(|d| d.venues()).is_none() {
                        lighting.set_venues_dir("lighting/venues".to_string());
                    }
                    lighting.clear_inline_fixtures();
                }
            }
        }
    }
    // Also clear on the raw dmx field (which will be serialized if profiles haven't been set up).
    if let Some(lighting) = player.lighting_mut() {
        if lighting.directories().and_then(|d| d.venues()).is_none() {
            lighting.set_venues_dir("lighting/venues".to_string());
        }
        lighting.clear_inline_fixtures();
    }
}

/// Step D: Clear legacy top-level fields (they've already been normalized into profiles).
fn migrate_legacy_fields(
    raw: &config::Player,
    player: &mut config::Player,
    plan: &mut MigrationPlan,
) {
    if !raw.has_legacy_fields() {
        return;
    }

    plan.add_action(
        "Legacy Fields",
        "Clear legacy top-level fields (audio, midi, dmx, trigger, track_mappings, controllers, sample_triggers)".to_string(),
    );
    player.clear_legacy_fields();
}

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

    /// Helper: create a temp dir with a config file and optional additional files.
    fn setup_migration(yaml: &str, extra_files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("mtrack.yaml");
        std::fs::write(&config_path, yaml).unwrap();
        for (name, content) in extra_files {
            let file_path = dir.path().join(name);
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            std::fs::write(&file_path, content).unwrap();
        }
        (dir, config_path)
    }

    #[test]
    fn test_migrate_profiles_to_dir() {
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: device-a
      track_mappings:
        drums: [1]
  - hostname: pi-b
    audio:
      device: device-b
      track_mappings:
        drums: [11]
  - audio:
      device: fallback
      track_mappings:
        drums: [1]
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Profile files should exist.
        assert!(dir.path().join("profiles/pi-a.yaml").exists());
        assert!(dir.path().join("profiles/pi-b.yaml").exists());
        assert!(dir.path().join("profiles/profile-3.yaml").exists());

        // Backup should exist.
        assert!(dir.path().join("mtrack.yaml.bak").exists());

        // Rewritten config should have profiles_dir set.
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(rewritten.contains("profiles_dir"));
    }

    #[test]
    fn test_migrate_playlist_to_dir() {
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
playlist: my_playlist.yaml
"#,
            &[("my_playlist.yaml", "- song1\n- song2\n")],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Playlist should be copied.
        assert!(dir.path().join("playlists/my_playlist.yaml").exists());
        let content =
            std::fs::read_to_string(dir.path().join("playlists/my_playlist.yaml")).unwrap();
        assert!(content.contains("song1"));

        // Original should be deleted.
        assert!(!dir.path().join("my_playlist.yaml").exists());

        // Config should have playlists_dir.
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(rewritten.contains("playlists_dir"));
        assert!(!rewritten.contains("playlist: my_playlist"));
    }

    #[test]
    fn test_migrate_inline_fixtures() {
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
    dmx:
      universes:
        - universe: 1
          name: main
      lighting:
        fixtures:
          par1: "GenericPar @ 1:1"
          mover1: "MovingHead @ 1:10"
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Venue file should exist.
        let venue_path = dir.path().join("lighting/venues/inline_migrated.light");
        assert!(venue_path.exists());

        let venue = std::fs::read_to_string(&venue_path).unwrap();
        assert!(venue.contains("venue \"inline_migrated\""));
        assert!(venue.contains("fixture \"mover1\" MovingHead @ 1:10"));
        assert!(venue.contains("fixture \"par1\" GenericPar @ 1:1"));
    }

    #[test]
    fn test_migrate_legacy_fields() {
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
midi:
  device: mock-midi
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Profile should be created from legacy fields.
        assert!(dir.path().join("profiles").exists());

        // A profile file should exist with the legacy config.
        let profile_files: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(profile_files.len(), 1);

        // The profile should contain the device from the legacy config.
        let profile_content = std::fs::read_to_string(profile_files[0].path()).unwrap();
        assert!(profile_content.contains("mock-device"));

        // Config should have profiles_dir and not contain legacy device values.
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(rewritten.contains("profiles_dir"));
        assert!(!rewritten.contains("mock-device"));
        assert!(!rewritten.contains("mock-midi"));
    }

    #[test]
    fn test_migrate_idempotent() {
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: device-a
      track_mappings:
        drums: [1]
"#,
            &[],
        );

        // First migration.
        migrate(dir.path().to_str().unwrap(), true).unwrap();

        let config_after_first = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();

        // Second migration should be a no-op.
        migrate(dir.path().to_str().unwrap(), true).unwrap();

        let config_after_second = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert_eq!(config_after_first, config_after_second);
    }

    #[test]
    fn test_migrate_dry_run_no_writes() {
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: device-a
      track_mappings:
        drums: [1]
"#,
            &[],
        );

        // Dry-run (default).
        migrate(dir.path().to_str().unwrap(), false).unwrap();

        // No profiles directory should be created.
        assert!(!dir.path().join("profiles").exists());

        // No backup file.
        assert!(!dir.path().join("mtrack.yaml.bak").exists());

        // Config should be unchanged.
        let config = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(config.contains("hostname: pi-a"));
    }

    #[test]
    fn test_migrate_nothing_to_do() {
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles_dir: profiles/
playlists_dir: playlists/
"#,
            &[],
        );

        // Create the required profiles dir (empty is ok).
        std::fs::create_dir_all(dir.path().join("profiles")).unwrap();

        // Should print nothing-to-do message and not error.
        migrate(dir.path().to_str().unwrap(), false).unwrap();

        // No backup created since nothing to do.
        assert!(!dir.path().join("mtrack.yaml.bak").exists());
    }

    #[test]
    fn test_migrate_backup_created() {
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
"#,
            &[],
        );

        let original = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Backup should contain the original config.
        let backup = std::fs::read_to_string(dir.path().join("mtrack.yaml.bak")).unwrap();
        assert_eq!(original, backup);
    }

    #[test]
    fn test_resolve_config_path_directory() {
        // When given a directory, appends mtrack.yaml.
        let path = resolve_config_path("/some/dir");
        assert_eq!(path, PathBuf::from("/some/dir/mtrack.yaml"));
    }

    #[test]
    fn test_resolve_config_path_yaml_file() {
        let path = resolve_config_path("/some/dir/custom.yaml");
        assert_eq!(path, PathBuf::from("/some/dir/custom.yaml"));
    }

    #[test]
    fn test_resolve_config_path_yml_file() {
        let path = resolve_config_path("/some/dir/config.yml");
        assert_eq!(path, PathBuf::from("/some/dir/config.yml"));
    }

    #[test]
    fn test_migrate_playlist_missing_file() {
        // Playlist field set but file doesn't exist — should still migrate config
        // but skip the copy.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
playlist: nonexistent.yaml
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // playlists dir created but no file inside.
        assert!(dir.path().join("playlists").exists());
        assert!(!dir.path().join("playlists/nonexistent.yaml").exists());

        // Config should still be updated.
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(rewritten.contains("playlists_dir"));
    }

    #[test]
    fn test_migrate_config_not_found() {
        let result = migrate("/nonexistent/path/to/project", false);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Config file not found"));
    }

    #[test]
    fn test_migrate_with_yaml_file_path() {
        // Pass a .yaml file path directly instead of a directory.
        let (dir, config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - hostname: test-host
    audio:
      device: device-x
      track_mappings:
        drums: [1]
"#,
            &[],
        );

        migrate(config_path.to_str().unwrap(), true).unwrap();

        assert!(dir.path().join("profiles/test-host.yaml").exists());
        assert!(dir.path().join("mtrack.yaml.bak").exists());
    }

    #[test]
    fn test_migrate_profiles_dir_already_set_skips() {
        // When profiles_dir is already set, profile migration is skipped entirely.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles_dir: profiles/
profiles:
  - hostname: pi-a
    audio:
      device: device-a
      track_mappings:
        drums: [1]
"#,
            &[],
        );

        // Create the profiles dir so deserialize works.
        std::fs::create_dir_all(dir.path().join("profiles")).unwrap();

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // No profile files should be written (profiles_dir already set).
        let entries: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(entries.len(), 0);
    }

    #[test]
    fn test_migrate_no_profiles_skips() {
        // Config with no profiles at all — profile step should be a no-op.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), false).unwrap();

        // No profiles directory created.
        assert!(!dir.path().join("profiles").exists());
        // No backup since nothing to migrate.
        assert!(!dir.path().join("mtrack.yaml.bak").exists());
    }

    #[test]
    fn test_migrate_legacy_fixtures_from_dmx() {
        // Fixtures on legacy top-level dmx field (not in profiles).
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
dmx:
  universes:
    - universe: 1
      name: main
  lighting:
    fixtures:
      wash1: "GenericWash @ 1:20"
      spot1: "Spot @ 1:30"
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Venue file should be created from legacy dmx fixtures.
        let venue_path = dir.path().join("lighting/venues/inline_migrated.light");
        assert!(venue_path.exists());

        let venue = std::fs::read_to_string(&venue_path).unwrap();
        assert!(venue.contains("fixture \"spot1\" Spot @ 1:30"));
        assert!(venue.contains("fixture \"wash1\" GenericWash @ 1:20"));
    }

    #[test]
    fn test_migrate_fixtures_existing_venues_dir_preserved() {
        // If lighting config already has a venues directory set, don't overwrite it.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
    dmx:
      universes:
        - universe: 1
          name: main
      lighting:
        fixtures:
          par1: "GenericPar @ 1:1"
        directories:
          venues: custom/venues
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Venue file should still be written to the default location.
        assert!(dir
            .path()
            .join("lighting/venues/inline_migrated.light")
            .exists());

        // The profile file should preserve the existing custom venues dir
        // (profiles are extracted to files, so the venues dir is in the profile).
        let profile_files: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(profile_files.len(), 1);
        let profile_content = std::fs::read_to_string(profile_files[0].path()).unwrap();
        assert!(
            profile_content.contains("custom/venues"),
            "profile should preserve existing venues dir, got:\n{}",
            profile_content
        );

        // Fixtures should be cleared from the profile.
        assert!(
            !profile_content.contains("GenericPar"),
            "fixtures should be cleared from profile"
        );
    }

    #[test]
    fn test_migrate_empty_fixtures_skips() {
        // Empty fixtures map — fixture step should be a no-op.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
    dmx:
      universes:
        - universe: 1
          name: main
      lighting:
        fixtures: {}
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // No venue file should be created.
        assert!(!dir.path().join("lighting/venues").exists());
    }

    #[test]
    fn test_migrate_all_steps_combined() {
        // Config with inline profiles, legacy playlist, inline fixtures, and legacy fields.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
playlist: setlist.yaml
audio:
  device: my-interface
track_mappings:
  click: [1]
  cue: [2]
midi:
  device: my-midi
dmx:
  universes:
    - universe: 1
      name: main
  lighting:
    fixtures:
      par1: "GenericPar @ 1:1"
"#,
            &[("setlist.yaml", "- song_a\n- song_b\n")],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Profiles extracted.
        assert!(dir.path().join("profiles").exists());
        let profile_files: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(profile_files.len(), 1);

        // Playlist copied.
        assert!(dir.path().join("playlists/setlist.yaml").exists());
        assert!(!dir.path().join("setlist.yaml").exists());

        // Venue file created.
        assert!(dir
            .path()
            .join("lighting/venues/inline_migrated.light")
            .exists());

        // Config rewritten with directory pointers.
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(rewritten.contains("profiles_dir"));
        assert!(rewritten.contains("playlists_dir"));

        // Legacy values should not appear.
        assert!(!rewritten.contains("my-interface"));
        assert!(!rewritten.contains("my-midi"));

        // Backup exists.
        assert!(dir.path().join("mtrack.yaml.bak").exists());
    }

    #[test]
    fn test_migrate_absolute_playlist_path() {
        let dir = tempfile::tempdir().unwrap();
        let playlist_dir = tempfile::tempdir().unwrap();
        let abs_playlist = playlist_dir.path().join("abs_playlist.yaml");
        std::fs::write(&abs_playlist, "- song_x\n").unwrap();

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

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Playlist copied using original filename.
        assert!(dir.path().join("playlists/abs_playlist.yaml").exists());
        let content =
            std::fs::read_to_string(dir.path().join("playlists/abs_playlist.yaml")).unwrap();
        assert!(content.contains("song_x"));

        // Original should be deleted.
        assert!(!abs_playlist.exists());
    }

    #[test]
    fn test_migrate_resolve_config_path_existing_file() {
        // When the path points to an actual file, resolve_config_path returns it directly.
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("custom.yaml");
        std::fs::write(&config_path, "songs: songs\n").unwrap();

        let resolved = resolve_config_path(config_path.to_str().unwrap());
        assert_eq!(resolved, config_path);
    }

    #[test]
    fn test_migrated_config_round_trips() {
        // After migration, the rewritten config should be loadable by Player::deserialize.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: device-a
      track_mappings:
        drums: [1]
        synth: [2]
    midi:
      device: midi-a
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // The migrated config with profiles_dir should deserialize successfully.
        let config_path = dir.path().join("mtrack.yaml");
        let player = config::Player::deserialize(&config_path).unwrap();

        // Should load profiles from the directory.
        let profiles = player.all_profiles();
        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].hostname(), Some("pi-a"));
        assert_eq!(
            profiles[0].audio_config().unwrap().audio().device(),
            "device-a"
        );
    }

    #[test]
    fn test_migrate_legacy_with_controllers() {
        // Legacy controller/controllers fields should be cleared.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
controllers:
  - kind: grpc
    port: 43234
  - kind: osc
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Profile should contain the controllers.
        let profile_files: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(profile_files.len(), 1);
        let profile_content = std::fs::read_to_string(profile_files[0].path()).unwrap();
        assert!(profile_content.contains("grpc"));

        // Config should not contain the legacy controller values.
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(!rewritten.contains("43234"));
    }

    #[test]
    fn test_migrate_legacy_with_trigger() {
        // Legacy trigger config should be normalized into profile and cleared.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
trigger:
  device: "UltraLite-mk5"
  inputs:
    - kind: audio
      channel: 1
      sample: "kick"
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Profile should contain trigger config.
        let profile_files: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(profile_files.len(), 1);
        let profile_content = std::fs::read_to_string(profile_files[0].path()).unwrap();
        assert!(profile_content.contains("UltraLite"));

        // Config should not contain legacy trigger values.
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(!rewritten.contains("UltraLite"));
    }

    #[test]
    fn test_migrate_legacy_sample_triggers() {
        // Legacy sample_triggers should be normalized and cleared.
        let (dir, _config_path) = setup_migration(
            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
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Profile should exist.
        assert!(dir.path().join("profiles").exists());

        // Config should not contain legacy sample_triggers values.
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(!rewritten.contains("note_on"));
    }

    #[test]
    fn test_migrate_playlist_only() {
        // Only playlist needs migration, no profiles or fixtures.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles_dir: profiles/
playlist: show.yaml
"#,
            &[("show.yaml", "- intro\n- outro\n")],
        );

        std::fs::create_dir_all(dir.path().join("profiles")).unwrap();

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Playlist migrated.
        assert!(dir.path().join("playlists/show.yaml").exists());
        assert!(!dir.path().join("show.yaml").exists());

        // No profiles directory changes (already set).
        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(rewritten.contains("playlists_dir"));
    }

    #[test]
    fn test_migrate_fixtures_only() {
        // Only fixtures need migration.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles_dir: profiles/
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
    dmx:
      universes:
        - universe: 1
          name: main
      lighting:
        fixtures:
          par1: "GenericPar @ 1:1"
"#,
            &[],
        );

        std::fs::create_dir_all(dir.path().join("profiles")).unwrap();
        std::fs::write(
            dir.path().join("profiles/host.yaml"),
            "audio:\n  device: device-a\n  track_mappings:\n    drums: [1]\ndmx:\n  universes:\n    - universe: 1\n      name: main\n  lighting:\n    fixtures:\n      par1: \"GenericPar @ 1:1\"\n",
        ).unwrap();

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Venue file created.
        assert!(dir
            .path()
            .join("lighting/venues/inline_migrated.light")
            .exists());
    }

    #[test]
    fn test_migrate_preserves_songs_path() {
        // After migration, the songs path should be preserved.
        let (dir, _config_path) = setup_migration(
            r#"
songs: my_songs
profiles:
  - hostname: pi-a
    audio:
      device: device-a
      track_mappings:
        drums: [1]
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(rewritten.contains("my_songs"));
    }

    #[test]
    fn test_migrate_preserves_non_migrated_fields() {
        // Non-migrated fields like active_playlist and samples should survive.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
active_playlist: all_songs
samples:
  kick:
    file: kick.wav
    output_channels: [1, 2]
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        let rewritten = std::fs::read_to_string(dir.path().join("mtrack.yaml")).unwrap();
        assert!(rewritten.contains("all_songs"));
        assert!(rewritten.contains("kick"));
    }

    #[test]
    fn test_migrate_multiple_profiles_naming() {
        // Verify the naming convention: hostname-based and index-based.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - hostname: stage-left
    audio:
      device: device-a
      track_mappings:
        drums: [1]
  - audio:
      device: fallback-1
      track_mappings:
        drums: [1]
  - audio:
      device: fallback-2
      track_mappings:
        drums: [2]
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        assert!(dir.path().join("profiles/stage-left.yaml").exists());
        assert!(dir.path().join("profiles/profile-2.yaml").exists());
        assert!(dir.path().join("profiles/profile-3.yaml").exists());
    }

    #[test]
    fn test_resolve_config_path_non_yaml_extension() {
        // A non-yaml extension on a non-existent path appends mtrack.yaml
        // (the path isn't a file, so is_file() is false, extension check fails).
        let path = resolve_config_path("/some/dir/config.toml");
        assert_eq!(path, PathBuf::from("/some/dir/config.toml/mtrack.yaml"));
    }

    #[test]
    fn test_resolve_config_path_existing_non_yaml_file() {
        // An existing file with a non-yaml extension is returned as-is
        // (is_file() short-circuits the extension check).
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("config.toml");
        std::fs::write(&file_path, "songs: songs\n").unwrap();

        let resolved = resolve_config_path(file_path.to_str().unwrap());
        assert_eq!(resolved, file_path);
    }

    #[test]
    fn test_migrate_invalid_yaml() {
        // Invalid YAML should return an error from deserialize_raw.
        let (dir, _config_path) = setup_migration("this is not valid yaml: [[[", &[]);

        let result = migrate(dir.path().to_str().unwrap(), false);
        assert!(result.is_err());
    }

    #[test]
    fn test_migrate_explicit_empty_profiles() {
        // `profiles: []` is a valid config with an explicit empty list.
        // Should be a no-op (no profiles to extract).
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles: []
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), false).unwrap();

        // No profiles directory should be created.
        assert!(!dir.path().join("profiles").exists());
    }

    #[test]
    fn test_migrate_legacy_audio_device_string() {
        // Legacy `audio_device: "..."` (bare string) triggers migration.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
audio_device: my-card
track_mappings:
  click: [1]
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Profile should be extracted.
        assert!(dir.path().join("profiles").exists());
        let profile_files: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(profile_files.len(), 1);
        let profile_content = std::fs::read_to_string(profile_files[0].path()).unwrap();
        assert!(profile_content.contains("my-card"));
    }

    #[test]
    fn test_migrate_legacy_midi_device_string() {
        // Legacy `midi_device: "..."` (bare string) triggers migration.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
midi_device: my-midi-port
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Profile should contain the midi device.
        let profile_files: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(profile_files.len(), 1);
        let profile_content = std::fs::read_to_string(profile_files[0].path()).unwrap();
        assert!(profile_content.contains("my-midi-port"));
    }

    #[test]
    fn test_migrate_lighting_without_fixtures_key() {
        // Profile with lighting section but no fixtures key at all — should skip.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
    dmx:
      universes:
        - universe: 1
          name: main
      lighting:
        current_venue: main_stage
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // No venue file should be created.
        assert!(!dir.path().join("lighting/venues").exists());
    }

    #[test]
    fn test_migrate_dmx_without_lighting() {
        // DMX configured but no lighting section at all.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
    dmx:
      universes:
        - universe: 1
          name: main
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // No venue file should be created.
        assert!(!dir.path().join("lighting/venues").exists());
    }

    #[test]
    fn test_migrate_multi_profile_fixtures_cleared() {
        // Multiple profiles both have inline fixtures — verify both get cleared.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: device-a
      track_mappings:
        drums: [1]
    dmx:
      universes:
        - universe: 1
          name: main
      lighting:
        fixtures:
          par1: "GenericPar @ 1:1"
  - hostname: pi-b
    audio:
      device: device-b
      track_mappings:
        drums: [11]
    dmx:
      universes:
        - universe: 2
          name: aux
      lighting:
        fixtures:
          mover1: "MovingHead @ 2:1"
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Venue file created.
        assert!(dir
            .path()
            .join("lighting/venues/inline_migrated.light")
            .exists());

        // Both profile files should have fixtures cleared.
        let pi_a = std::fs::read_to_string(dir.path().join("profiles/pi-a.yaml")).unwrap();
        assert!(
            !pi_a.contains("GenericPar"),
            "fixtures should be cleared from pi-a profile"
        );

        let pi_b = std::fs::read_to_string(dir.path().join("profiles/pi-b.yaml")).unwrap();
        assert!(
            !pi_b.contains("MovingHead"),
            "fixtures should be cleared from pi-b profile"
        );
    }

    #[test]
    fn test_migrate_legacy_dmx_without_lighting_section() {
        // Legacy top-level DMX with universes but no lighting — fixtures step
        // should be skipped, but legacy fields should still be cleared.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
audio:
  device: mock-device
track_mappings:
  click: [1]
dmx:
  universes:
    - universe: 1
      name: main
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // No venue file.
        assert!(!dir.path().join("lighting/venues").exists());

        // Profile should exist with DMX config.
        let profile_files: Vec<_> = std::fs::read_dir(dir.path().join("profiles"))
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(profile_files.len(), 1);
    }

    #[test]
    fn test_migrate_playlists_dir_already_set_skips_playlist() {
        // When playlists_dir is already set but playlist field is also set,
        // playlist should still be migrated.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles_dir: profiles/
playlists_dir: playlists/
playlist: legacy.yaml
"#,
            &[("legacy.yaml", "- song1\n"), ("playlists/.gitkeep", "")],
        );

        std::fs::create_dir_all(dir.path().join("profiles")).unwrap();

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // Playlist should be copied.
        assert!(dir.path().join("playlists/legacy.yaml").exists());
        // Original deleted.
        assert!(!dir.path().join("legacy.yaml").exists());
    }

    #[test]
    fn test_migrate_venue_dsl_sorted_output() {
        // Verify fixtures in the venue file are sorted alphabetically by name.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - audio:
      device: device-a
      track_mappings:
        drums: [1]
    dmx:
      universes:
        - universe: 1
          name: main
      lighting:
        fixtures:
          zebra: "Z @ 1:100"
          alpha: "A @ 1:1"
          middle: "M @ 1:50"
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        let venue =
            std::fs::read_to_string(dir.path().join("lighting/venues/inline_migrated.light"))
                .unwrap();

        // Verify sorted order: alpha < middle < zebra.
        let alpha_pos = venue.find("alpha").unwrap();
        let middle_pos = venue.find("middle").unwrap();
        let zebra_pos = venue.find("zebra").unwrap();
        assert!(alpha_pos < middle_pos);
        assert!(middle_pos < zebra_pos);
    }

    #[test]
    fn test_migrate_profile_content_valid_yaml() {
        // Extracted profile files should be valid YAML that can be deserialized.
        let (dir, _config_path) = setup_migration(
            r#"
songs: songs
profiles:
  - hostname: pi-a
    audio:
      device: device-a
      sample_rate: 48000
      track_mappings:
        drums: [1, 2]
        synth: [3, 4]
    midi:
      device: midi-a
    controllers:
      - kind: grpc
        port: 43234
"#,
            &[],
        );

        migrate(dir.path().to_str().unwrap(), true).unwrap();

        // The extracted profile should be valid YAML and round-trip as a Profile.
        let profile_path = dir.path().join("profiles/pi-a.yaml");
        let profile_yaml = std::fs::read_to_string(&profile_path).unwrap();
        assert!(profile_yaml.contains("pi-a"));
        assert!(profile_yaml.contains("device-a"));
        assert!(profile_yaml.contains("48000"));
        assert!(profile_yaml.contains("grpc"));
    }
}