koan-core 0.20.4

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use rusqlite::params;

use crate::db::connection::{Database, DbError};
use crate::db::queries::{self, TrackRow};
use crate::format::{self, FormatError, MetadataProvider};

/// Ancillary file patterns we move alongside audio files.
const ANCILLARY_PATTERNS: &[&str] = &[
    "cover.jpg",
    "cover.png",
    "cover.webp",
    "folder.jpg",
    "folder.png",
    "front.jpg",
    "front.png",
];

const ANCILLARY_EXTENSIONS: &[&str] = &["cue", "log", "m3u", "m3u8"];

#[derive(Debug, thiserror::Error)]
pub enum OrganizeError {
    #[error("database error: {0}")]
    Db(#[from] DbError),
    #[error("sqlite error: {0}")]
    Sqlite(#[from] rusqlite::Error),
    #[error("format error: {0}")]
    Format(#[from] FormatError),
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("no tracks with local paths found")]
    NoLocalTracks,
    #[error("no organize batches to undo")]
    NothingToUndo,
}

#[derive(Debug)]
pub struct OrganizeResult {
    pub moves: Vec<FileMove>,
    pub errors: Vec<(PathBuf, String)>,
    pub skipped: usize,
}

#[derive(Debug)]
pub struct FileMove {
    pub track_id: i64,
    pub from: PathBuf,
    pub to: PathBuf,
    pub ancillary: Vec<(PathBuf, PathBuf)>,
}

/// Metadata provider backed by a HashMap, for evaluating format strings against track data.
struct TrackMetadata {
    fields: HashMap<String, String>,
}

impl TrackMetadata {
    fn from_track_row(track: &TrackRow, album_date: Option<&str>) -> Self {
        let mut fields = HashMap::new();
        // Sanitize all field values so they can't inject path separators or illegal chars.
        let s = sanitize_path_component;
        fields.insert("title".into(), s(&track.title));
        fields.insert("artist".into(), s(&track.artist_name));
        fields.insert("album artist".into(), s(&track.album_artist_name));
        fields.insert("album".into(), s(&track.album_title));
        if let Some(n) = track.track_number {
            fields.insert("tracknumber".into(), format!("{n:02}"));
        }
        if let Some(d) = track.disc {
            fields.insert("discnumber".into(), d.to_string());
        }
        if let Some(date) = album_date {
            // Date is safe (digits + hyphens) but sanitize anyway for consistency.
            fields.insert("date".into(), date.to_string());
        }
        if let Some(ref codec) = track.codec {
            fields.insert("codec".into(), codec.clone());
        }
        if let Some(ref genre) = track.genre {
            fields.insert("genre".into(), s(genre));
        }
        Self { fields }
    }

    /// Build metadata directly from file tags (no DB required).
    fn from_file_meta(meta: &queries::TrackMeta) -> Self {
        let mut fields = HashMap::new();
        let s = sanitize_path_component;
        fields.insert("title".into(), s(&meta.title));
        fields.insert("artist".into(), s(&meta.artist));
        fields.insert(
            "album artist".into(),
            s(meta.album_artist.as_deref().unwrap_or(&meta.artist)),
        );
        fields.insert("album".into(), s(&meta.album));
        if let Some(n) = meta.track_number {
            fields.insert("tracknumber".into(), format!("{n:02}"));
        }
        if let Some(d) = meta.disc {
            fields.insert("discnumber".into(), d.to_string());
        }
        if let Some(ref date) = meta.date {
            fields.insert("date".into(), date.clone());
        }
        if let Some(ref codec) = meta.codec {
            fields.insert("codec".into(), codec.clone());
        }
        if let Some(ref genre) = meta.genre {
            fields.insert("genre".into(), s(genre));
        }
        if let Some(ref label) = meta.label {
            fields.insert("label".into(), s(label));
        }
        Self { fields }
    }
}

impl MetadataProvider for TrackMetadata {
    fn get_field(&self, name: &str) -> Option<String> {
        self.fields.get(name).cloned()
    }
}

/// Replace characters that are illegal in file/directory names.
fn sanitize_path_component(s: &str) -> String {
    s.chars()
        .map(|c| match c {
            '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
            _ => c,
        })
        .collect::<String>()
        .trim()
        .to_string()
}

/// Sanitize each component of a relative path independently.
/// Rejects `..` and `.` components to prevent path traversal attacks
/// (e.g. malicious metadata containing `../../../../etc/passwd`).
fn sanitize_relative_path(rel: &str) -> PathBuf {
    let parts: Vec<&str> = if rel.contains('/') {
        rel.split('/')
    } else {
        rel.split(std::path::MAIN_SEPARATOR)
    }
    .collect();

    let mut result = PathBuf::new();
    for part in parts {
        let sanitized = sanitize_path_component(part);
        if sanitized.is_empty() || sanitized == "." || sanitized == ".." {
            continue;
        }
        result.push(sanitized);
    }
    result
}

/// Get the album date for a track via its album_id.
fn album_date_for_track(
    db: &Database,
    track: &TrackRow,
) -> Result<Option<String>, rusqlite::Error> {
    let Some(album_id) = track.album_id else {
        return Ok(None);
    };
    db.conn
        .query_row(
            "SELECT date FROM albums WHERE id = ?1",
            params![album_id],
            |row| row.get::<_, Option<String>>(0),
        )
        .or(Ok(None))
}

/// Find ancillary files in the same directory as a track.
fn find_ancillary_files(track_dir: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();
    let Ok(entries) = std::fs::read_dir(track_dir) else {
        return files;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default()
            .to_lowercase();

        // Check exact name matches.
        if ANCILLARY_PATTERNS.iter().any(|p| name == *p) {
            files.push(path);
            continue;
        }
        // Check extension matches.
        if let Some(ext) = path.extension().and_then(|e| e.to_str())
            && ANCILLARY_EXTENSIONS
                .iter()
                .any(|e| ext.eq_ignore_ascii_case(e))
        {
            files.push(path);
        }
    }
    files
}

/// Plan a single file move: format pattern, sanitize path, build dest, find ancillary files.
///
/// Returns `Ok(None)` when source == dest (skipped), `Ok(Some(FileMove))` for a planned move,
/// or `Err(String)` for errors that should be collected by the caller.
fn plan_single_move(
    source: &Path,
    track_id: i64,
    metadata: &TrackMetadata,
    pattern: &str,
    base_dir: &Path,
    planned_ancillary: &mut std::collections::HashSet<PathBuf>,
) -> Result<Option<FileMove>, String> {
    let relative = format::format(pattern, metadata).map_err(|e| format!("format error: {e}"))?;

    if relative.is_empty() {
        return Err("format string produced empty path".into());
    }

    let sanitized = sanitize_relative_path(&relative);

    if sanitized.as_os_str().is_empty() {
        return Err("format string produced empty path after sanitization".into());
    }

    // Preserve the original file extension.
    // Don't use with_extension() — it replaces after the LAST dot, which
    // destroys titles containing dots (e.g. "0111. Bicep - TANGZ II" → "0111.flac").
    let ext = source
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("flac");
    let mut dest = base_dir.join(sanitized);
    let stem = dest.as_os_str().to_os_string();
    dest = PathBuf::from(format!("{}.{}", stem.to_string_lossy(), ext));

    // Safety: verify dest stays under base_dir (defense-in-depth against path traversal).
    if !dest.starts_with(base_dir) {
        return Err(format!(
            "path traversal blocked: destination {} escapes base dir {}",
            dest.display(),
            base_dir.display()
        ));
    }

    if paths_equal(source, &dest) {
        return Ok(None);
    }

    // Plan ancillary moves — move files in source dir to dest dir.
    let source_dir = source.parent().unwrap_or(Path::new("."));
    let dest_dir = dest.parent().unwrap_or(Path::new("."));
    let mut ancillary = Vec::new();

    if source_dir != dest_dir {
        for anc_path in find_ancillary_files(source_dir) {
            if planned_ancillary.contains(&anc_path) {
                continue;
            }
            let Some(anc_name) = anc_path.file_name() else {
                continue;
            };
            let anc_dest = dest_dir.join(anc_name);
            planned_ancillary.insert(anc_path.clone());
            ancillary.push((anc_path, anc_dest));
        }
    }

    Ok(Some(FileMove {
        track_id,
        from: source.to_path_buf(),
        to: dest,
        ancillary,
    }))
}

/// Build the list of moves for all local tracks (or a filtered subset).
fn plan_moves(
    db: &Database,
    pattern: &str,
    base_dir: &Path,
    track_ids: Option<&[i64]>,
) -> Result<OrganizeResult, OrganizeError> {
    let tracks = match track_ids {
        Some(ids) => {
            let mut tracks = Vec::with_capacity(ids.len());
            for &id in ids {
                if let Some(row) = queries::get_track_row(&db.conn, id)? {
                    tracks.push(row);
                }
            }
            tracks
        }
        None => queries::all_tracks(&db.conn)?,
    };
    let mut moves = Vec::new();
    let mut errors = Vec::new();
    let mut skipped = 0;

    // Track which ancillary files we've already planned to move (dedup across tracks in same dir).
    let mut planned_ancillary: std::collections::HashSet<PathBuf> =
        std::collections::HashSet::new();

    for track in &tracks {
        let Some(ref path_str) = track.path else {
            continue; // remote-only, skip
        };

        let source = PathBuf::from(path_str);
        if !source.exists() {
            continue; // file gone, skip
        }

        let album_date = match album_date_for_track(db, track) {
            Ok(d) => d,
            Err(e) => {
                errors.push((source, format!("failed to get album date: {e}")));
                continue;
            }
        };

        let metadata = TrackMetadata::from_track_row(track, album_date.as_deref());

        match plan_single_move(
            &source,
            track.id,
            &metadata,
            pattern,
            base_dir,
            &mut planned_ancillary,
        ) {
            Ok(Some(file_move)) => moves.push(file_move),
            Ok(None) => skipped += 1,
            Err(msg) => errors.push((source, msg)),
        }
    }

    Ok(OrganizeResult {
        moves,
        errors,
        skipped,
    })
}

/// Build the list of moves from file paths directly (no DB required).
/// Reads metadata from tags in parallel (rayon), then plans moves serially
/// (ancillary dedup requires ordered processing).
fn plan_moves_from_paths(
    paths: &[PathBuf],
    pattern: &str,
    base_dir: &Path,
) -> Result<OrganizeResult, OrganizeError> {
    use rayon::prelude::*;

    // Phase 1: Read metadata in parallel — this is the expensive part (disk I/O + tag parsing).
    let meta_results: Vec<_> = paths
        .par_iter()
        .map(|source| {
            if !source.exists() {
                return (source.clone(), Err("file not found".to_string()));
            }
            match crate::index::metadata::read_metadata(source) {
                Ok(m) => (source.clone(), Ok(TrackMetadata::from_file_meta(&m))),
                Err(e) => (source.clone(), Err(format!("metadata error: {e}"))),
            }
        })
        .collect();

    // Phase 2: Plan moves serially (ancillary dedup needs ordered HashSet access).
    let mut moves = Vec::new();
    let mut errors = Vec::new();
    let mut skipped = 0;
    let mut planned_ancillary: std::collections::HashSet<PathBuf> =
        std::collections::HashSet::new();

    for (source, meta_result) in meta_results {
        let metadata = match meta_result {
            Ok(m) => m,
            Err(msg) => {
                errors.push((source, msg));
                continue;
            }
        };

        match plan_single_move(
            &source,
            0,
            &metadata,
            pattern,
            base_dir,
            &mut planned_ancillary,
        ) {
            Ok(Some(file_move)) => moves.push(file_move),
            Ok(None) => skipped += 1,
            Err(msg) => errors.push((source, msg)),
        }
    }

    Ok(OrganizeResult {
        moves,
        errors,
        skipped,
    })
}

/// Preview organize for file paths. Uses the DB for metadata when available
/// (instant), falls back to parallel disk reads for files not in the DB.
pub fn preview_for_paths(
    paths: &[PathBuf],
    pattern: &str,
    base_dir: Option<&Path>,
) -> Result<OrganizeResult, OrganizeError> {
    use rayon::prelude::*;

    let base = resolve_base_dir(base_dir)?;

    // Try to load metadata from the DB (single query, instant for 50k+ tracks).
    let db_cache: std::collections::HashMap<String, TrackRow> = Database::open_default()
        .ok()
        .and_then(|db| queries::all_tracks_by_path(&db.conn).ok())
        .unwrap_or_default();

    // Build album date cache from DB to avoid per-track queries.
    let album_dates: std::collections::HashMap<i64, Option<String>> = if !db_cache.is_empty() {
        let db = Database::open_default().ok();
        db.map(|db| {
            let mut dates = std::collections::HashMap::new();
            for track in db_cache.values() {
                if let Some(album_id) = track.album_id {
                    dates
                        .entry(album_id)
                        .or_insert_with(|| queries::album_date(&db.conn, album_id).ok().flatten());
                }
            }
            dates
        })
        .unwrap_or_default()
    } else {
        std::collections::HashMap::new()
    };

    // Phase 1: Resolve metadata — DB hits are instant, misses go to disk in parallel.
    let meta_results: Vec<_> = paths
        .par_iter()
        .map(|source| {
            let path_str = source.to_string_lossy();

            // Try DB first.
            if let Some(track) = db_cache.get(path_str.as_ref()) {
                let album_date = track
                    .album_id
                    .and_then(|aid| album_dates.get(&aid).and_then(|d| d.as_deref()));
                return (
                    source.clone(),
                    track.id,
                    Ok(TrackMetadata::from_track_row(track, album_date)),
                );
            }

            // Fallback: read from disk.
            if !source.exists() {
                return (source.clone(), 0, Err("file not found".to_string()));
            }
            match crate::index::metadata::read_metadata(source) {
                Ok(m) => (source.clone(), 0, Ok(TrackMetadata::from_file_meta(&m))),
                Err(e) => (source.clone(), 0, Err(format!("metadata error: {e}"))),
            }
        })
        .collect();

    // Phase 2: Plan moves serially (ancillary dedup needs ordered HashSet access).
    let mut moves = Vec::new();
    let mut errors = Vec::new();
    let mut skipped = 0;
    let mut planned_ancillary: std::collections::HashSet<PathBuf> =
        std::collections::HashSet::new();

    for (source, track_id, meta_result) in meta_results {
        let metadata = match meta_result {
            Ok(m) => m,
            Err(msg) => {
                errors.push((source, msg));
                continue;
            }
        };

        match plan_single_move(
            &source,
            track_id,
            &metadata,
            pattern,
            &base,
            &mut planned_ancillary,
        ) {
            Ok(Some(file_move)) => moves.push(file_move),
            Ok(None) => skipped += 1,
            Err(msg) => errors.push((source, msg)),
        }
    }

    Ok(OrganizeResult {
        moves,
        errors,
        skipped,
    })
}

/// Execute organize for file paths (no DB required — reads tags, moves files).
/// Does NOT log to organize_log or update DB paths (since tracks may not be in DB).
pub fn execute_for_paths(
    paths: &[PathBuf],
    pattern: &str,
    base_dir: Option<&Path>,
) -> Result<OrganizeResult, OrganizeError> {
    let base = resolve_base_dir(base_dir)?;
    let mut result = plan_moves_from_paths(paths, pattern, &base)?;

    if result.moves.is_empty() {
        return Ok(result);
    }

    let mut completed_moves = Vec::new();
    let mut new_errors = Vec::new();

    for file_move in result.moves.drain(..) {
        match execute_single_move_no_db(&file_move) {
            Ok(()) => match verify_move(&file_move) {
                Ok(()) => completed_moves.push(file_move),
                Err(msg) => new_errors.push((file_move.from, msg)),
            },
            Err(e) => {
                new_errors.push((file_move.from, e.to_string()));
            }
        }
    }

    result.moves = completed_moves;
    result.errors.extend(new_errors);
    Ok(result)
}

/// Verify a move actually happened — dest exists and source is gone.
fn verify_move(file_move: &FileMove) -> Result<(), String> {
    if !file_move.to.exists() {
        return Err(format!(
            "destination not found after move: {}",
            file_move.to.display()
        ));
    }
    if file_move.from.exists() && !paths_equal(&file_move.from, &file_move.to) {
        return Err(format!(
            "source still exists after move: {}",
            file_move.from.display()
        ));
    }
    Ok(())
}

/// Execute a single file move without DB logging (for non-library tracks).
fn execute_single_move_no_db(file_move: &FileMove) -> Result<(), OrganizeError> {
    if let Some(parent) = file_move.to.parent() {
        std::fs::create_dir_all(parent)?;
    }

    move_file(&file_move.from, &file_move.to)?;

    // Move ancillary files (best-effort).
    for (anc_from, anc_to) in &file_move.ancillary {
        if let Some(parent) = anc_to.parent() {
            std::fs::create_dir_all(parent).ok();
        }
        if let Err(e) = move_file(anc_from, anc_to) {
            log::warn!(
                "failed to move ancillary file {}: {}",
                anc_from.display(),
                e
            );
        }
    }

    if let Some(source_dir) = file_move.from.parent() {
        remove_empty_dirs(source_dir);
    }

    Ok(())
}

/// Preview what would happen without moving files.
pub fn preview(
    db: &Database,
    pattern: &str,
    base_dir: Option<&Path>,
) -> Result<OrganizeResult, OrganizeError> {
    let base = resolve_base_dir(base_dir)?;
    plan_moves(db, pattern, &base, None)
}

/// Execute the moves: rename files, update DB, log for undo.
pub fn execute(
    db: &Database,
    pattern: &str,
    base_dir: Option<&Path>,
) -> Result<OrganizeResult, OrganizeError> {
    let base = resolve_base_dir(base_dir)?;
    let mut result = plan_moves(db, pattern, &base, None)?;

    if result.moves.is_empty() {
        return Ok(result);
    }

    // Generate a batch ID from timestamp.
    let batch_id = chrono_batch_id();

    let mut completed_moves = Vec::new();
    let mut new_errors = Vec::new();

    for file_move in result.moves.drain(..) {
        match execute_single_move(db, &file_move, &batch_id) {
            Ok(()) => match verify_move(&file_move) {
                Ok(()) => completed_moves.push(file_move),
                Err(msg) => new_errors.push((file_move.from, msg)),
            },
            Err(e) => {
                new_errors.push((file_move.from, e.to_string()));
            }
        }
    }

    result.moves = completed_moves;
    result.errors.extend(new_errors);
    Ok(result)
}

/// Preview organize for a specific set of tracks.
pub fn preview_for_tracks(
    db: &Database,
    track_ids: &[i64],
    pattern: &str,
    base_dir: Option<&Path>,
) -> Result<OrganizeResult, OrganizeError> {
    let base = resolve_base_dir(base_dir)?;
    plan_moves(db, pattern, &base, Some(track_ids))
}

/// Execute organize for a specific set of tracks.
pub fn execute_for_tracks(
    db: &Database,
    track_ids: &[i64],
    pattern: &str,
    base_dir: Option<&Path>,
) -> Result<OrganizeResult, OrganizeError> {
    let base = resolve_base_dir(base_dir)?;
    let mut result = plan_moves(db, pattern, &base, Some(track_ids))?;

    if result.moves.is_empty() {
        return Ok(result);
    }

    let batch_id = chrono_batch_id();
    let mut completed_moves = Vec::new();
    let mut new_errors = Vec::new();

    for file_move in result.moves.drain(..) {
        match execute_single_move(db, &file_move, &batch_id) {
            Ok(()) => match verify_move(&file_move) {
                Ok(()) => completed_moves.push(file_move),
                Err(msg) => new_errors.push((file_move.from, msg)),
            },
            Err(e) => {
                new_errors.push((file_move.from, e.to_string()));
            }
        }
    }

    result.moves = completed_moves;
    result.errors.extend(new_errors);
    Ok(result)
}

/// Execute a single file move: create dirs, move file + ancillary, update DB, write log.
fn execute_single_move(
    db: &Database,
    file_move: &FileMove,
    batch_id: &str,
) -> Result<(), OrganizeError> {
    // Create destination directory.
    if let Some(parent) = file_move.to.parent() {
        std::fs::create_dir_all(parent)?;
    }

    // Move the audio file (falls back to copy+delete across filesystems).
    move_file(&file_move.from, &file_move.to)?;

    // Log the move.
    db.conn.execute(
        "INSERT INTO organize_log (batch_id, track_id, from_path, to_path) VALUES (?1, ?2, ?3, ?4)",
        params![
            batch_id,
            file_move.track_id,
            file_move.from.to_string_lossy().as_ref(),
            file_move.to.to_string_lossy().as_ref(),
        ],
    )?;

    // Update the track's path in the database.
    db.conn.execute(
        "UPDATE tracks SET path = ?1 WHERE id = ?2",
        params![file_move.to.to_string_lossy().as_ref(), file_move.track_id],
    )?;

    // Update scan_cache if it exists for the old path.
    db.conn.execute(
        "UPDATE scan_cache SET path = ?1 WHERE path = ?2",
        params![
            file_move.to.to_string_lossy().as_ref(),
            file_move.from.to_string_lossy().as_ref(),
        ],
    )?;

    // Move ancillary files.
    for (anc_from, anc_to) in &file_move.ancillary {
        if let Some(parent) = anc_to.parent() {
            std::fs::create_dir_all(parent)?;
        }
        // Best-effort — don't fail the whole move if ancillary fails.
        if move_file(anc_from, anc_to).is_ok() {
            db.conn.execute(
                "INSERT INTO organize_log (batch_id, track_id, from_path, to_path) VALUES (?1, NULL, ?2, ?3)",
                params![
                    batch_id,
                    anc_from.to_string_lossy().as_ref(),
                    anc_to.to_string_lossy().as_ref(),
                ],
            )?;
        }
    }

    // Try to remove empty source directories.
    if let Some(source_dir) = file_move.from.parent() {
        remove_empty_dirs(source_dir);
    }

    Ok(())
}

/// Undo the most recent organize batch.
pub fn undo(db: &Database) -> Result<usize, OrganizeError> {
    // Find the most recent batch.
    let batch_id: String = db
        .conn
        .query_row(
            "SELECT batch_id FROM organize_log ORDER BY created_at DESC LIMIT 1",
            [],
            |row| row.get(0),
        )
        .map_err(|_| OrganizeError::NothingToUndo)?;

    // Get all moves in this batch, in reverse order.
    let mut stmt = db.conn.prepare(
        "SELECT id, track_id, from_path, to_path FROM organize_log
         WHERE batch_id = ?1 ORDER BY id DESC",
    )?;

    let entries: Vec<(i64, Option<i64>, String, String)> = stmt
        .query_map(params![batch_id], |row| {
            Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
        })?
        .collect::<Result<Vec<_>, _>>()?;

    let mut count = 0;

    for (log_id, track_id, from_path, to_path) in &entries {
        let to = Path::new(to_path);
        let from = Path::new(from_path);

        if !to.exists() {
            // Already moved back or deleted — skip.
            db.conn
                .execute("DELETE FROM organize_log WHERE id = ?1", params![log_id])?;
            continue;
        }

        // Create original parent dir.
        if let Some(parent) = from.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Move back (falls back to copy+delete across filesystems).
        move_file(to, from)?;

        // Update track path in DB if this was a track (not ancillary).
        if let Some(tid) = track_id {
            db.conn.execute(
                "UPDATE tracks SET path = ?1 WHERE id = ?2",
                params![from_path, tid],
            )?;
            db.conn.execute(
                "UPDATE scan_cache SET path = ?1 WHERE path = ?2",
                params![from_path, to_path],
            )?;
        }

        // Remove empty dirs at the (now old) destination.
        if let Some(parent) = to.parent() {
            remove_empty_dirs(parent);
        }

        db.conn
            .execute("DELETE FROM organize_log WHERE id = ?1", params![log_id])?;

        count += 1;
    }

    Ok(count)
}

/// Walk up directories removing empty ones, stopping at first non-empty.
fn remove_empty_dirs(dir: &Path) {
    let mut current = dir.to_path_buf();
    loop {
        if std::fs::read_dir(&current)
            .map(|mut d| d.next().is_none())
            .unwrap_or(false)
        {
            if std::fs::remove_dir(&current).is_err() {
                break;
            }
            match current.parent() {
                Some(p) => current = p.to_path_buf(),
                None => break,
            }
        } else {
            break;
        }
    }
}

/// Move a file, falling back to copy+delete if rename fails (cross-device).
fn move_file(from: &Path, to: &Path) -> Result<(), OrganizeError> {
    match std::fs::rename(from, to) {
        Ok(()) => Ok(()),
        Err(e) if e.raw_os_error() == Some(18) => {
            // EXDEV (18): cross-device link — copy then delete original.
            std::fs::copy(from, to)?;
            std::fs::remove_file(from)?;
            Ok(())
        }
        Err(e) => Err(e.into()),
    }
}

/// Compare paths for equality, canonicalizing if possible (handles macOS case-insensitive FS).
fn paths_equal(a: &Path, b: &Path) -> bool {
    if a == b {
        return true;
    }
    // Try canonicalizing both — handles symlinks, case differences, etc.
    if let (Ok(ca), Ok(cb)) = (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
        return ca == cb;
    }
    false
}

fn resolve_base_dir(base_dir: Option<&Path>) -> Result<PathBuf, OrganizeError> {
    if let Some(dir) = base_dir {
        return Ok(dir.to_path_buf());
    }

    // Use first configured library folder.
    let config = crate::config::Config::load()
        .map_err(|e| OrganizeError::Io(std::io::Error::other(e.to_string())))?;

    config.library.folders.into_iter().next().ok_or_else(|| {
        OrganizeError::Io(std::io::Error::other(
            "no library folders configured; use --base-dir",
        ))
    })
}

fn chrono_batch_id() -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    format!("batch-{}", now.as_nanos())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::connection::Database;
    use crate::db::queries::TrackMeta;
    use crate::db::schema;

    fn test_db() -> Database {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        conn.pragma_update(None, "foreign_keys", "on").unwrap();
        schema::create_tables(&conn).unwrap();
        Database { conn }
    }

    fn sample_meta(title: &str, artist: &str, album: &str) -> TrackMeta {
        TrackMeta {
            title: title.into(),
            artist: artist.into(),
            album_artist: Some(artist.into()),
            album: album.into(),
            date: Some("1997-06-16".into()),
            disc: Some(1),
            track_number: Some(1),
            genre: Some("Rock".into()),
            label: None,
            duration_ms: Some(240_000),
            codec: Some("FLAC".into()),
            sample_rate: Some(44100),
            bit_depth: Some(16),
            channels: Some(2),
            bitrate: Some(1000),
            size_bytes: Some(30_000_000),
            mtime: Some(1700000000),
            path: None,
            source: "local".into(),
            remote_id: None,
            remote_url: None,
        }
    }

    #[test]
    fn track_metadata_provider_fields() {
        let track = TrackRow {
            id: 1,
            album_id: Some(1),
            artist_id: Some(1),
            artist_name: "Radiohead".into(),
            album_artist_name: "Radiohead".into(),
            album_title: "OK Computer".into(),
            disc: Some(1),
            track_number: Some(3),
            title: "Subterranean Homesick Alien".into(),
            duration_ms: Some(240_000),
            path: Some("/music/ok_computer/03.flac".into()),
            codec: Some("FLAC".into()),
            sample_rate: Some(44100),
            bit_depth: Some(16),
            channels: Some(2),
            bitrate: Some(1000),
            genre: Some("Alternative".into()),
            source: "local".into(),
            remote_id: None,
            cached_path: None,
        };

        let meta = TrackMetadata::from_track_row(&track, Some("1997-06-16"));
        assert_eq!(
            meta.get_field("title").as_deref(),
            Some("Subterranean Homesick Alien")
        );
        assert_eq!(meta.get_field("artist").as_deref(), Some("Radiohead"));
        assert_eq!(meta.get_field("album artist").as_deref(), Some("Radiohead"));
        assert_eq!(meta.get_field("album").as_deref(), Some("OK Computer"));
        assert_eq!(meta.get_field("tracknumber").as_deref(), Some("03"));
        assert_eq!(meta.get_field("discnumber").as_deref(), Some("1"));
        assert_eq!(meta.get_field("date").as_deref(), Some("1997-06-16"));
        assert_eq!(meta.get_field("codec").as_deref(), Some("FLAC"));
        assert_eq!(meta.get_field("genre").as_deref(), Some("Alternative"));
        assert_eq!(meta.get_field("nonexistent"), None);
    }

    #[test]
    fn sanitize_replaces_illegal_chars() {
        assert_eq!(sanitize_path_component("AC/DC"), "AC_DC");
        assert_eq!(sanitize_path_component("What?"), "What_");
        assert_eq!(sanitize_path_component("a:b*c"), "a_b_c");
        assert_eq!(sanitize_path_component("normal"), "normal");
    }

    #[test]
    fn sanitize_relative_path_splits() {
        let result = sanitize_relative_path("Artist/Album/Track");
        assert_eq!(result, PathBuf::from("Artist/Album/Track"));

        let result = sanitize_relative_path("Radiohead/(1997) OK Computer/01. Airbag");
        assert_eq!(
            result,
            PathBuf::from("Radiohead/(1997) OK Computer/01. Airbag")
        );
    }

    #[test]
    fn sanitize_relative_path_rejects_traversal() {
        // ".." components should be stripped to prevent path traversal.
        let result = sanitize_relative_path("../../../../etc/passwd");
        assert_eq!(result, PathBuf::from("etc/passwd"));

        let result = sanitize_relative_path("Artist/../../../outside");
        assert_eq!(result, PathBuf::from("Artist/outside"));

        // "." components should also be stripped.
        let result = sanitize_relative_path("./Artist/./Album");
        assert_eq!(result, PathBuf::from("Artist/Album"));

        // Normal paths remain unchanged.
        let result = sanitize_relative_path("Artist/Album/Track");
        assert_eq!(result, PathBuf::from("Artist/Album/Track"));
    }

    #[test]
    fn acdc_artist_name_sanitized() {
        // "AC/DC" should become "AC_DC" through field sanitization.
        let track = TrackRow {
            id: 1,
            album_id: Some(1),
            artist_id: Some(1),
            artist_name: "AC/DC".into(),
            album_artist_name: "AC/DC".into(),
            album_title: "Highway to Hell".into(),
            disc: Some(1),
            track_number: Some(1),
            title: "Highway to Hell".into(),
            duration_ms: None,
            path: Some("/music/test.flac".into()),
            codec: None,
            sample_rate: None,
            bit_depth: None,
            channels: None,
            bitrate: None,
            genre: None,
            source: "local".into(),
            remote_id: None,
            cached_path: None,
        };
        let meta = TrackMetadata::from_track_row(&track, Some("1979"));
        assert_eq!(meta.get_field("album artist").as_deref(), Some("AC_DC"));
        let result = format::format("%album artist%/%album%/%title%", &meta).unwrap();
        assert_eq!(result, "AC_DC/Highway to Hell/Highway to Hell");
    }

    #[test]
    fn format_string_evaluation() {
        let track = TrackRow {
            id: 1,
            album_id: Some(1),
            artist_id: Some(1),
            artist_name: "Radiohead".into(),
            album_artist_name: "Radiohead".into(),
            album_title: "OK Computer".into(),
            disc: Some(1),
            track_number: Some(1),
            title: "Airbag".into(),
            duration_ms: Some(240_000),
            path: Some("/music/test.flac".into()),
            codec: Some("FLAC".into()),
            sample_rate: Some(44100),
            bit_depth: Some(16),
            channels: Some(2),
            bitrate: Some(1000),
            genre: None,
            source: "local".into(),
            remote_id: None,
            cached_path: None,
        };

        let meta = TrackMetadata::from_track_row(&track, Some("1997-06-16"));
        let pattern =
            "%album artist%/['('$left(%date%,4)')' ]%album%/$num(%tracknumber%,2). %title%";
        let result = format::format(pattern, &meta).unwrap();
        assert_eq!(result, "Radiohead/(1997) OK Computer/01. Airbag");
    }

    #[test]
    fn preview_does_not_move_files() {
        let db = test_db();
        let tmp = std::env::temp_dir().join(format!("koan-organize-test-{}", std::process::id()));
        std::fs::create_dir_all(&tmp).unwrap();

        // Create a test file.
        let test_file = tmp.join("test.flac");
        std::fs::write(&test_file, b"fake audio data").unwrap();

        let mut meta = sample_meta("Airbag", "Radiohead", "OK Computer");
        meta.path = Some(test_file.to_string_lossy().into());
        queries::upsert_track(&db.conn, &meta).unwrap();

        let result = preview(&db, "%album artist%/%album%/%title%", Some(&tmp)).unwrap();
        // The file should still be at the original path.
        assert!(test_file.exists());
        assert!(!result.moves.is_empty());

        // Cleanup.
        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn execute_moves_files_and_undo_reverts() {
        let db = test_db();
        let tmp = std::env::temp_dir().join(format!("koan-organize-exec-{}", std::process::id()));
        let src_dir = tmp.join("src");
        std::fs::create_dir_all(&src_dir).unwrap();

        // Create test files.
        let test_file = src_dir.join("test.flac");
        std::fs::write(&test_file, b"fake audio data").unwrap();

        let mut meta = sample_meta("Airbag", "Radiohead", "OK Computer");
        meta.path = Some(test_file.to_string_lossy().into());
        queries::upsert_track(&db.conn, &meta).unwrap();

        // Execute.
        let result = execute(&db, "%album artist%/%album%/%title%", Some(&tmp)).unwrap();
        assert_eq!(result.moves.len(), 1);
        assert!(!test_file.exists()); // original gone
        let dest = &result.moves[0].to;
        assert!(dest.exists()); // new location exists

        // Undo.
        let undone = undo(&db).unwrap();
        assert_eq!(undone, 1);
        assert!(test_file.exists()); // back to original
        assert!(!dest.exists()); // new location gone

        // Cleanup.
        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn ancillary_file_detection() {
        let tmp = std::env::temp_dir().join(format!("koan-organize-anc-{}", std::process::id()));
        std::fs::create_dir_all(&tmp).unwrap();

        std::fs::write(tmp.join("cover.jpg"), b"img").unwrap();
        std::fs::write(tmp.join("cover.png"), b"img").unwrap();
        std::fs::write(tmp.join("album.cue"), b"cue").unwrap();
        std::fs::write(tmp.join("rip.log"), b"log").unwrap();
        std::fs::write(tmp.join("track.flac"), b"audio").unwrap(); // not ancillary

        let found = find_ancillary_files(&tmp);
        assert!(found.iter().any(|p| p.file_name().unwrap() == "cover.jpg"));
        assert!(found.iter().any(|p| p.file_name().unwrap() == "cover.png"));
        assert!(found.iter().any(|p| p.file_name().unwrap() == "album.cue"));
        assert!(found.iter().any(|p| p.file_name().unwrap() == "rip.log"));
        assert!(!found.iter().any(|p| p.file_name().unwrap() == "track.flac"));

        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn extension_not_clobbered_by_dots_in_title() {
        // Regression: with_extension() replaces after the LAST dot,
        // destroying titles with dots ("0111. Bicep - TANGZ II" → "0111.flac").
        let db = test_db();
        let tmp = std::env::temp_dir().join(format!("koan-organize-dots-{}", std::process::id()));
        let src_dir = tmp.join("src");
        std::fs::create_dir_all(&src_dir).unwrap();

        // Track with dots in title (A.L.O.E II) + tracknumber dot.
        let test_file = src_dir.join("CHROMA 011 A.L.O.E II.flac");
        std::fs::write(&test_file, b"fake").unwrap();

        let mut meta = sample_meta("CHROMA 011 A.L.O.E II", "Bicep", "CHROMA 000");
        meta.track_number = Some(10);
        meta.disc = Some(1);
        meta.date = Some("2025-11-21".into());
        meta.codec = Some("FLAC".into());
        meta.album_artist = Some("Bicep".into());
        meta.path = Some(test_file.to_string_lossy().into());
        queries::upsert_track(&db.conn, &meta).unwrap();

        let pattern = "%album artist%/['('$left(%date%,4)')' ]%album% '['%codec%']'/[$num(%discnumber%,2)][%tracknumber%. ][%artist% - ]%title%";
        let result = preview(&db, pattern, Some(&tmp)).unwrap();
        assert_eq!(result.moves.len(), 1);

        let dest_name = result.moves[0]
            .to
            .file_name()
            .unwrap()
            .to_string_lossy()
            .to_string();
        // Must preserve full title including dots — NOT truncated by set_extension.
        assert_eq!(dest_name, "0110. Bicep - CHROMA 011 A.L.O.E II.flac");

        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn extension_preserved_for_tracknumber_dot() {
        // "0111. Bicep - TANGZ II" must not become "0111.flac"
        let db = test_db();
        let tmp = std::env::temp_dir().join(format!("koan-organize-trkdot-{}", std::process::id()));
        let src_dir = tmp.join("src");
        std::fs::create_dir_all(&src_dir).unwrap();

        let test_file = src_dir.join("CHROMA 012 TANGZ II.flac");
        std::fs::write(&test_file, b"fake").unwrap();

        let mut meta = sample_meta("CHROMA 012 TANGZ II", "Bicep", "CHROMA 000");
        meta.track_number = Some(11);
        meta.disc = Some(1);
        meta.date = Some("2025-11-21".into());
        meta.codec = Some("FLAC".into());
        meta.album_artist = Some("Bicep".into());
        meta.path = Some(test_file.to_string_lossy().into());
        queries::upsert_track(&db.conn, &meta).unwrap();

        let pattern = "%album artist%/['('$left(%date%,4)')' ]%album% '['%codec%']'/[$num(%discnumber%,2)][%tracknumber%. ][%artist% - ]%title%";
        let result = preview(&db, pattern, Some(&tmp)).unwrap();
        assert_eq!(result.moves.len(), 1);

        let dest_name = result.moves[0]
            .to
            .file_name()
            .unwrap()
            .to_string_lossy()
            .to_string();
        assert_eq!(dest_name, "0111. Bicep - CHROMA 012 TANGZ II.flac");

        std::fs::remove_dir_all(&tmp).ok();
    }
}