koan-core 0.19.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
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
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};

use uuid::Uuid;

/// Stable identity for a queue entry. UUIDv7 — time-ordered, unique across duplicates.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct QueueItemId(pub Uuid);

impl QueueItemId {
    pub fn new() -> Self {
        Self(Uuid::now_v7())
    }
}

impl Default for QueueItemId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for QueueItemId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Short form for logs: first 8 hex chars.
        write!(f, "QId({})", &self.0.to_string()[..8])
    }
}

/// Playback state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PlaybackState {
    Stopped = 0,
    Playing = 1,
    Paused = 2,
}

impl PlaybackState {
    pub fn from_u8(v: u8) -> Self {
        match v {
            1 => Self::Playing,
            2 => Self::Paused,
            _ => Self::Stopped,
        }
    }
}

/// Audio format info for the currently playing track.
#[derive(Debug, Clone)]
pub struct TrackInfo {
    pub id: QueueItemId,
    pub path: PathBuf,
    pub codec: String,
    pub sample_rate: u32,
    pub bit_depth: u16,
    pub channels: u16,
    pub duration_ms: u64,
}

// --- Playlist data model (single source of truth) ---

/// Minimum bytes written before streaming playback can begin.
pub const STREAM_THRESHOLD: u64 = 256 * 1024; // 256 KB

/// Load state of a playlist item — tracks download lifecycle.
#[derive(Debug, Clone)]
pub enum LoadState {
    Pending,
    Downloading {
        downloaded: u64,
        total: u64,
        /// Shared counter updated atomically by the download thread after each chunk.
        bytes_written: Arc<AtomicU64>,
    },
    Ready,
    Failed(String),
}

/// Resolved playback source for a playlist item.
pub enum PlaybackSource {
    /// File fully downloaded — play from path.
    Ready(PathBuf),
    /// File being downloaded — enough data buffered to start streaming.
    Streaming {
        path: PathBuf,
        bytes_written: Arc<AtomicU64>,
        total: u64,
    },
}

/// A single item in the playlist. Replaces QueueEntry + QueueEntryMeta + pending entries
/// as the canonical data. Created once when tracks are added to the playlist.
#[derive(Debug, Clone)]
pub struct PlaylistItem {
    pub id: QueueItemId,
    /// Database track ID — set for tracks loaded from DB, used for downloads.
    pub db_id: Option<i64>,
    pub path: PathBuf,
    pub title: String,
    pub artist: String,
    pub album_artist: String,
    pub album: String,
    pub year: Option<String>,
    pub codec: Option<String>,
    pub track_number: Option<i64>,
    pub disc: Option<i64>,
    pub duration_ms: Option<u64>,
    pub load_state: LoadState,
}

/// The playlist — one flat array, one cursor. Everything else derived.
#[derive(Debug, Clone, Default)]
pub struct Playlist {
    pub items: Vec<PlaylistItem>,
    pub cursor: Option<QueueItemId>,
}

// --- UI view types (kept for TUI compat) ---

/// Status of a track in the queue — for UI display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueueEntryStatus {
    Queued,
    Playing,
    Played,
    Downloading,
    /// User double-clicked — this track is priority, will play when ready.
    PriorityPending,
    Failed,
}

/// A single entry in the UI-visible queue snapshot.
#[derive(Debug, Clone)]
pub struct QueueEntry {
    pub id: QueueItemId,
    /// Database track ID — set for tracks loaded from DB, used for downloads.
    pub db_id: Option<i64>,
    pub path: PathBuf,
    pub title: String,
    pub artist: String,
    pub album_artist: String,
    pub album: String,
    pub year: Option<String>,
    pub codec: Option<String>,
    pub track_number: Option<i64>,
    pub disc: Option<i64>,
    pub duration_ms: Option<u64>,
    pub status: QueueEntryStatus,
    pub download_progress: Option<(u64, u64)>,
}

/// Pre-built visible queue — single atomic snapshot for the UI.
#[derive(Debug, Clone, Default)]
pub struct VisibleQueueSnapshot {
    pub entries: Vec<QueueEntry>,
    pub finished_count: usize,
    pub has_playing: bool,
    pub queue_count: usize,
}

/// Shared player state — atomics for lock-free reads from UI thread.
///
/// The engine writes these, the UI reads them. No mutexes in the hot path.
#[derive(Debug)]
pub struct SharedPlayerState {
    state: AtomicU8,
    position_ms: AtomicU64,
    track_info: parking_lot::RwLock<Option<TrackInfo>>,

    /// THE playlist + cursor — one lock, one truth.
    playlist: parking_lot::RwLock<Playlist>,

    /// Bumped on every playlist mutation so UI can skip redundant redraws.
    playlist_version: AtomicU64,

    /// Playback generation — incremented each start_playback so stale decode
    /// thread callbacks can detect they're outdated and skip state mutations.
    playback_generation: AtomicU64,

    /// Set by external signals (e.g. souvlaki Quit event) to request clean shutdown.
    quit_requested: AtomicBool,

    /// Set when metadata has been refreshed (e.g. download completed while streaming).
    /// The UI loop checks this to force a souvlaki/cover-art update without a track change.
    metadata_refresh_pending: AtomicBool,

    /// Radio mode — automatically queue similar tracks when the queue runs low.
    /// Shared so GQL/MCP can toggle it without going through the TUI.
    radio_mode: AtomicBool,
}

impl SharedPlayerState {
    pub fn new() -> Arc<Self> {
        Arc::new(Self {
            state: AtomicU8::new(PlaybackState::Stopped as u8),
            position_ms: AtomicU64::new(0),
            track_info: parking_lot::RwLock::new(None),
            playlist: parking_lot::RwLock::new(Playlist::default()),
            playlist_version: AtomicU64::new(0),
            playback_generation: AtomicU64::new(0),
            quit_requested: AtomicBool::new(false),
            metadata_refresh_pending: AtomicBool::new(false),
            radio_mode: AtomicBool::new(false),
        })
    }

    // --- Playback state ---

    pub fn playback_state(&self) -> PlaybackState {
        PlaybackState::from_u8(self.state.load(Ordering::Acquire))
    }

    pub fn set_playback_state(&self, state: PlaybackState) {
        self.state.store(state as u8, Ordering::Release);
    }

    pub fn position_ms(&self) -> u64 {
        self.position_ms.load(Ordering::Acquire)
    }

    pub fn set_position_ms(&self, pos: u64) {
        self.position_ms.store(pos, Ordering::Release);
    }

    pub fn track_info(&self) -> Option<TrackInfo> {
        self.track_info.read().clone()
    }

    pub fn set_track_info(&self, info: Option<TrackInfo>) {
        *self.track_info.write() = info;
    }

    /// Download fraction (0.0..1.0) for the currently playing track, if streaming.
    /// Returns `None` for fully-downloaded or non-playing tracks.
    pub fn current_download_fraction(&self) -> Option<f64> {
        let track_info = self.track_info.read();
        let id = track_info.as_ref()?.id;
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .and_then(|item| match &item.load_state {
                LoadState::Downloading {
                    bytes_written,
                    total,
                    ..
                } => {
                    let written = bytes_written.load(Ordering::Acquire);
                    if *total > 0 {
                        Some((written as f64 / *total as f64).min(1.0))
                    } else {
                        None
                    }
                }
                _ => None,
            })
    }

    // --- Playback generation ---

    pub fn bump_generation(&self) -> u64 {
        self.playback_generation.fetch_add(1, Ordering::AcqRel) + 1
    }

    pub fn generation(&self) -> u64 {
        self.playback_generation.load(Ordering::Acquire)
    }

    // --- Quit ---

    pub fn request_quit(&self) {
        self.quit_requested.store(true, Ordering::Release);
    }

    pub fn quit_requested(&self) -> bool {
        self.quit_requested.load(Ordering::Acquire)
    }

    // --- Metadata refresh (progressive enhancement) ---

    /// Signal that metadata has been refreshed mid-stream (e.g. download completed).
    /// The UI loop calls `take_metadata_refresh()` to consume this flag and
    /// force a souvlaki/cover-art update without waiting for a track change.
    pub fn signal_metadata_refresh(&self) {
        self.metadata_refresh_pending.store(true, Ordering::Release);
    }

    /// Returns true and clears the flag if a metadata refresh is pending.
    pub fn take_metadata_refresh(&self) -> bool {
        self.metadata_refresh_pending
            .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
    }

    // --- Radio mode ---

    pub fn radio_mode(&self) -> bool {
        self.radio_mode.load(Ordering::Acquire)
    }

    pub fn set_radio_mode(&self, enabled: bool) {
        self.radio_mode.store(enabled, Ordering::Release);
    }

    // --- Playlist version ---

    pub fn playlist_version(&self) -> u64 {
        self.playlist_version.load(Ordering::Acquire)
    }

    fn bump_version(&self) {
        self.playlist_version.fetch_add(1, Ordering::AcqRel);
    }

    // --- Playlist mutations (called from player thread via commands) ---

    /// Append items to the playlist.
    pub fn add_items(&self, items: Vec<PlaylistItem>) {
        let mut pl = self.playlist.write();
        pl.items.extend(items);
        drop(pl);
        self.bump_version();
    }

    /// Insert items after a specific queue item.
    pub fn insert_items_after(&self, items: Vec<PlaylistItem>, after: QueueItemId) {
        let mut pl = self.playlist.write();
        let insert_at = match pl.items.iter().position(|item| item.id == after) {
            Some(pos) => pos + 1,
            None => pl.items.len(), // fallback: append
        };
        for (i, item) in items.into_iter().enumerate() {
            pl.items.insert(insert_at + i, item);
        }
        drop(pl);
        self.bump_version();
    }

    /// Update file paths for playlist items (after organize moves files).
    pub fn update_paths(&self, updates: &[(QueueItemId, PathBuf)]) {
        let mut pl = self.playlist.write();
        for (id, new_path) in updates {
            if let Some(item) = pl.items.iter_mut().find(|item| item.id == *id) {
                item.path = new_path.clone();
            }
        }
        drop(pl);
        self.bump_version();
    }

    /// Remove an item by ID.
    pub fn remove_item(&self, id: QueueItemId) {
        let mut pl = self.playlist.write();
        pl.items.retain(|item| item.id != id);
        // If cursor was on removed item, clear it (caller handles next_track).
        if pl.cursor == Some(id) {
            pl.cursor = None;
        }
        drop(pl);
        self.bump_version();
    }

    /// Move an item relative to another entry.
    pub fn move_item(&self, id: QueueItemId, target: QueueItemId, after: bool) {
        let mut pl = self.playlist.write();
        let Some(from) = pl.items.iter().position(|item| item.id == id) else {
            return;
        };
        let item = pl.items.remove(from);
        let Some(to) = pl.items.iter().position(|item| item.id == target) else {
            // Target gone — put it back.
            let pos = from.min(pl.items.len());
            pl.items.insert(pos, item);
            return;
        };
        let insert_at = if after { to + 1 } else { to };
        pl.items.insert(insert_at, item);
        drop(pl);
        self.bump_version();
    }

    /// Batch move: extract items by ID, reinsert them at `target` position.
    /// Preserves the relative order of the moved items.
    pub fn move_items(&self, ids: &[QueueItemId], target: QueueItemId, after: bool) {
        use std::collections::HashSet;
        let id_set: HashSet<QueueItemId> = ids.iter().copied().collect();

        let mut pl = self.playlist.write();

        // Partition: extract moved items, keep the rest.
        let mut remaining = Vec::with_capacity(pl.items.len());
        let mut moved = Vec::with_capacity(ids.len());
        for item in pl.items.drain(..) {
            if id_set.contains(&item.id) {
                moved.push(item);
            } else {
                remaining.push(item);
            }
        }

        // Find target in the remaining items.
        let insert_at = match remaining.iter().position(|item| item.id == target) {
            Some(pos) => {
                if after {
                    pos + 1
                } else {
                    pos
                }
            }
            None => remaining.len(),
        };

        // Splice moved items in at the target position.
        for (i, item) in moved.into_iter().enumerate() {
            remaining.insert(insert_at + i, item);
        }

        pl.items = remaining;
        drop(pl);
        self.bump_version();
    }

    /// Set the cursor (what's playing / should play).
    pub fn set_cursor(&self, id: Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        pl.cursor = id;
        drop(pl);
        self.bump_version();
    }

    /// Get the current cursor ID.
    pub fn cursor(&self) -> Option<QueueItemId> {
        self.playlist.read().cursor
    }

    /// Clear the entire playlist + cursor.
    pub fn clear_playlist(&self) {
        let mut pl = self.playlist.write();
        pl.items.clear();
        pl.cursor = None;
        drop(pl);
        self.bump_version();
    }

    // --- Called from decode thread (gapless) ---

    /// Advance cursor to the next Ready item. Returns (id, path) if found.
    /// Moves the cursor. Used for explicit next-track commands.
    pub fn advance_cursor(&self) -> Option<(QueueItemId, PathBuf)> {
        let mut pl = self.playlist.write();
        let cursor_pos = match pl.cursor {
            Some(cid) => pl.items.iter().position(|item| item.id == cid),
            None => None,
        };

        let start = match cursor_pos {
            Some(pos) => pos + 1,
            None => 0,
        };

        // Find next Ready item after cursor.
        for i in start..pl.items.len() {
            if matches!(pl.items[i].load_state, LoadState::Ready) {
                let item = &pl.items[i];
                let result = (item.id, item.path.clone());
                pl.cursor = Some(item.id);
                drop(pl);
                self.bump_version();
                return Some(result);
            }
        }
        None
    }

    /// Peek at the next Ready item after a given item ID WITHOUT moving the cursor.
    /// Used by the decode thread for gapless lookahead — the cursor is moved
    /// later by update_playback_state when playback actually reaches the track.
    pub fn peek_next_ready_after(&self, after_id: QueueItemId) -> Option<(QueueItemId, PathBuf)> {
        let pl = self.playlist.read();
        let pos = pl.items.iter().position(|item| item.id == after_id);

        let start = match pos {
            Some(p) => p + 1,
            None => 0,
        };

        for i in start..pl.items.len() {
            if matches!(pl.items[i].load_state, LoadState::Ready) {
                let item = &pl.items[i];
                return Some((item.id, item.path.clone()));
            }
        }
        None
    }

    /// Retreat cursor to the previous item. Returns (id, path) if found.
    /// For prev_track — goes to the item before cursor regardless of load state.
    pub fn retreat_cursor(&self) -> Option<(QueueItemId, PathBuf)> {
        let mut pl = self.playlist.write();
        let cursor_pos = match pl.cursor {
            Some(cid) => pl.items.iter().position(|item| item.id == cid),
            None => None,
        };

        let prev_pos = cursor_pos.and_then(|p| p.checked_sub(1));

        match prev_pos {
            Some(pos) => {
                let item = &pl.items[pos];
                let result = (item.id, item.path.clone());
                pl.cursor = Some(item.id);
                drop(pl);
                self.bump_version();
                Some(result)
            }
            None => None,
        }
    }

    // --- Called from resolve thread ---

    /// Update the load state of a playlist item. Safe — just a field update under lock.
    pub fn update_load_state(&self, id: QueueItemId, new_state: LoadState) {
        let mut pl = self.playlist.write();
        if let Some(item) = pl.items.iter_mut().find(|item| item.id == id) {
            item.load_state = new_state;
        }
        drop(pl);
        self.bump_version();
    }

    /// Update playlist item metadata after a full download completes.
    /// Used for progressive enhancement: streaming started with partial Symphonia tags,
    /// now the full file is available so we can refresh with complete lofty metadata.
    pub fn update_item_metadata(
        &self,
        id: QueueItemId,
        title: String,
        artist: String,
        album_artist: String,
        album: String,
        duration_ms: Option<u64>,
    ) {
        let mut pl = self.playlist.write();
        if let Some(item) = pl.items.iter_mut().find(|item| item.id == id) {
            item.title = title;
            item.artist = artist;
            item.album_artist = album_artist;
            item.album = album;
            if let Some(dur) = duration_ms {
                item.duration_ms = Some(dur);
            }
        }
        drop(pl);
        self.bump_version();
    }

    /// Get the playback source for an item if it's ready to play.
    /// Returns `None` if not enough data is available yet.
    pub fn item_playback_source(&self, id: QueueItemId) -> Option<PlaybackSource> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .and_then(|item| match &item.load_state {
                LoadState::Ready => Some(PlaybackSource::Ready(item.path.clone())),
                LoadState::Downloading {
                    total,
                    bytes_written,
                    ..
                } => {
                    let written = bytes_written.load(Ordering::Acquire);
                    if written >= STREAM_THRESHOLD {
                        Some(PlaybackSource::Streaming {
                            path: item.path.clone(),
                            bytes_written: bytes_written.clone(),
                            total: *total,
                        })
                    } else {
                        None
                    }
                }
                _ => None,
            })
    }

    /// Get the path of an item if it's Ready (legacy convenience — use item_playback_source for streaming).
    pub fn item_path_if_ready(&self, id: QueueItemId) -> Option<PathBuf> {
        let pl = self.playlist.read();
        pl.items.iter().find(|item| item.id == id).and_then(|item| {
            if matches!(item.load_state, LoadState::Ready) {
                Some(item.path.clone())
            } else {
                None
            }
        })
    }

    /// Check if the cursor is on the given item.
    pub fn is_cursor(&self, id: QueueItemId) -> bool {
        self.playlist.read().cursor == Some(id)
    }

    /// Get QueueItemIds of all playlist items sharing the same album as the given item.
    /// Matches on both album name and album artist to avoid false positives
    /// (e.g. two different "Greatest Hits" by different artists).
    pub fn same_album_item_ids(&self, id: QueueItemId) -> Vec<QueueItemId> {
        let pl = self.playlist.read();
        let Some(cursor) = pl.items.iter().find(|item| item.id == id) else {
            return vec![];
        };
        let album = cursor.album.clone();
        let album_artist = cursor.album_artist.clone();
        pl.items
            .iter()
            .filter(|item| {
                item.id != id && item.album == album && item.album_artist == album_artist
            })
            .map(|item| item.id)
            .collect()
    }

    /// Get all playlist items that are Pending and have a db_id.
    /// Returns `(db_id, QueueItemId)` pairs suitable for the download queue.
    pub fn pending_downloads(&self) -> Vec<(i64, QueueItemId)> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .filter(|item| matches!(item.load_state, LoadState::Pending))
            .filter_map(|item| item.db_id.map(|db_id| (db_id, item.id)))
            .collect()
    }

    /// Get the db_id for a specific playlist item.
    pub fn item_db_id(&self, id: QueueItemId) -> Option<i64> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .and_then(|item| item.db_id)
    }

    /// Get the load state of a specific playlist item.
    pub fn item_load_state(&self, id: QueueItemId) -> Option<LoadState> {
        let pl = self.playlist.read();
        pl.items
            .iter()
            .find(|item| item.id == id)
            .map(|item| item.load_state.clone())
    }

    // --- Snapshot helpers for undo ---

    /// Get the full playlist snapshot (items + cursor) for undo of ClearPlaylist.
    pub fn snapshot_playlist(&self) -> (Vec<PlaylistItem>, Option<QueueItemId>) {
        let pl = self.playlist.read();
        (pl.items.clone(), pl.cursor)
    }

    /// Get an item by ID (for undo of RemoveFromPlaylist).
    pub fn get_item(&self, id: QueueItemId) -> Option<PlaylistItem> {
        let pl = self.playlist.read();
        pl.items.iter().find(|item| item.id == id).cloned()
    }

    /// Get the ID of the item immediately before the given ID (None if first).
    pub fn item_before(&self, id: QueueItemId) -> Option<QueueItemId> {
        let pl = self.playlist.read();
        let pos = pl.items.iter().position(|item| item.id == id)?;
        if pos == 0 {
            None
        } else {
            Some(pl.items[pos - 1].id)
        }
    }

    /// For each ID, get the ID of the item before it (or None if first).
    /// Used to snapshot positions before a batch move for undo.
    pub fn items_before(&self, ids: &[QueueItemId]) -> Vec<(QueueItemId, Option<QueueItemId>)> {
        let pl = self.playlist.read();
        ids.iter()
            .filter_map(|&id| {
                let pos = pl.items.iter().position(|item| item.id == id)?;
                let before = if pos == 0 {
                    None
                } else {
                    Some(pl.items[pos - 1].id)
                };
                Some((id, before))
            })
            .collect()
    }

    /// Restore a full playlist from snapshot (for redo of ClearPlaylist undo).
    pub fn restore_playlist(&self, items: Vec<PlaylistItem>, cursor: Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        pl.items = items;
        pl.cursor = cursor;
        drop(pl);
        self.bump_version();
    }

    /// Remove multiple items by IDs.
    pub fn remove_items(&self, ids: &[QueueItemId]) {
        use std::collections::HashSet;
        let id_set: HashSet<QueueItemId> = ids.iter().copied().collect();
        let mut pl = self.playlist.write();
        pl.items.retain(|item| !id_set.contains(&item.id));
        if let Some(cursor) = pl.cursor
            && id_set.contains(&cursor)
        {
            pl.cursor = None;
        }
        drop(pl);
        self.bump_version();
    }

    /// Insert a single item after a given ID (or at front if None).
    pub fn insert_item_at(&self, item: PlaylistItem, after: Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        let insert_at = match after {
            Some(after_id) => {
                match pl.items.iter().position(|i| i.id == after_id) {
                    Some(pos) => pos + 1,
                    None => pl.items.len(), // fallback
                }
            }
            None => 0,
        };
        pl.items.insert(insert_at, item);
        drop(pl);
        self.bump_version();
    }

    /// Move a single item to after `after` (or to front if None).
    pub fn move_item_to(&self, id: QueueItemId, after: Option<QueueItemId>) {
        let mut pl = self.playlist.write();
        let Some(from) = pl.items.iter().position(|item| item.id == id) else {
            return;
        };
        let item = pl.items.remove(from);
        let insert_at = match after {
            Some(after_id) => match pl.items.iter().position(|i| i.id == after_id) {
                Some(pos) => pos + 1,
                None => pl.items.len(),
            },
            None => 0,
        };
        pl.items.insert(insert_at, item);
        drop(pl);
        self.bump_version();
    }

    /// Batch move: reposition each item to after its given predecessor.
    /// Processes in order so earlier insertions don't corrupt later positions.
    pub fn move_items_to(&self, entries: &[(QueueItemId, Option<QueueItemId>)]) {
        for &(id, after) in entries {
            self.move_item_to(id, after);
        }
    }

    // --- Called from UI thread (read lock) ---

    /// Derive the visible queue from the playlist + cursor. O(n).
    /// Called once per UI tick.
    pub fn derive_visible_queue(&self) -> VisibleQueueSnapshot {
        let pl = self.playlist.read();
        let track_info = self.track_info.read();

        let cursor_pos = match pl.cursor {
            Some(cid) => pl.items.iter().position(|item| item.id == cid),
            None => None,
        };

        let mut entries = Vec::with_capacity(pl.items.len());
        let mut finished_count = 0;
        let mut has_playing = false;
        let mut queue_count = 0;

        for (i, item) in pl.items.iter().enumerate() {
            let is_cursor = cursor_pos == Some(i);
            let is_before_cursor = cursor_pos.is_some_and(|cp| i < cp);

            // Derive download progress from load_state uniformly for all tracks.
            let dl_progress = match &item.load_state {
                LoadState::Downloading {
                    downloaded, total, ..
                } => Some((*downloaded, *total)),
                _ => None,
            };

            let status = if is_cursor {
                has_playing = true;
                match &item.load_state {
                    LoadState::Ready => QueueEntryStatus::Playing,
                    LoadState::Downloading { .. } => QueueEntryStatus::PriorityPending,
                    LoadState::Pending => QueueEntryStatus::PriorityPending,
                    LoadState::Failed(_) => QueueEntryStatus::Failed,
                }
            } else if is_before_cursor {
                finished_count += 1;
                match &item.load_state {
                    LoadState::Ready => QueueEntryStatus::Played,
                    LoadState::Downloading { .. } => QueueEntryStatus::Downloading,
                    LoadState::Pending => QueueEntryStatus::Downloading,
                    LoadState::Failed(_) => QueueEntryStatus::Failed,
                }
            } else {
                queue_count += 1;
                match &item.load_state {
                    LoadState::Ready => QueueEntryStatus::Queued,
                    LoadState::Downloading { .. } => QueueEntryStatus::Downloading,
                    LoadState::Pending => QueueEntryStatus::Downloading,
                    LoadState::Failed(_) => QueueEntryStatus::Failed,
                }
            };

            // Override duration from TrackInfo if we have it and this is playing.
            let duration_ms =
                if has_playing && status == QueueEntryStatus::Playing && item.duration_ms.is_none()
                {
                    track_info.as_ref().map(|ti| ti.duration_ms)
                } else {
                    item.duration_ms
                };

            entries.push(QueueEntry {
                id: item.id,
                db_id: item.db_id,
                path: item.path.clone(),
                title: item.title.clone(),
                artist: item.artist.clone(),
                album_artist: item.album_artist.clone(),
                album: item.album.clone(),
                year: item.year.clone(),
                codec: item.codec.clone(),
                track_number: item.track_number,
                disc: item.disc,
                duration_ms,
                status,
                download_progress: dl_progress,
            });
        }

        VisibleQueueSnapshot {
            entries,
            finished_count,
            has_playing,
            queue_count,
        }
    }
}

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

    // --- helpers ---

    fn make_item(title: &str, load_state: LoadState) -> PlaylistItem {
        PlaylistItem {
            id: QueueItemId::new(),
            db_id: None,
            path: PathBuf::from(format!("/music/{title}.flac")),
            title: title.to_string(),
            artist: "Artist".to_string(),
            album_artist: "Artist".to_string(),
            album: "Album".to_string(),
            year: None,
            codec: Some("FLAC".to_string()),
            track_number: None,
            disc: None,
            duration_ms: Some(200_000),
            load_state,
        }
    }

    fn ready_item(title: &str) -> PlaylistItem {
        make_item(title, LoadState::Ready)
    }

    fn pending_item(title: &str) -> PlaylistItem {
        make_item(title, LoadState::Pending)
    }

    // --- advance_cursor ---

    #[test]
    fn test_advance_cursor_skips_non_ready() {
        // playlist: Ready, Pending, Ready
        // advance from None should land on index 0 (first Ready).
        // advance again should skip Pending at index 1 and land on index 2.
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = pending_item("track-1");
        let item2 = ready_item("track-2");
        let id0 = item0.id;
        let id2 = item2.id;

        state.add_items(vec![item0, item1, item2]);

        // First advance — no cursor set yet, starts from beginning.
        let result = state.advance_cursor();
        assert!(result.is_some(), "expected to find first Ready item");
        assert_eq!(result.unwrap().0, id0, "should land on first Ready item");

        // Second advance — cursor is at index 0; Pending at index 1 must be skipped.
        let result = state.advance_cursor();
        assert!(
            result.is_some(),
            "expected to find next Ready item after skipping Pending"
        );
        assert_eq!(
            result.unwrap().0,
            id2,
            "should skip Pending and land on third item"
        );
    }

    #[test]
    fn test_advance_cursor_stops_at_end_of_playlist() {
        // With cursor already on the last Ready item, advance should return None.
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = ready_item("track-1");
        let id1 = item1.id;

        state.add_items(vec![item0, item1]);

        // Move cursor to last item.
        state.set_cursor(Some(id1));

        let result = state.advance_cursor();
        assert!(
            result.is_none(),
            "advance past last item should return None"
        );

        // Cursor should remain unchanged after a failed advance.
        assert_eq!(state.cursor(), Some(id1));
    }

    #[test]
    fn test_advance_cursor_with_no_ready_items_returns_none() {
        let state = SharedPlayerState::new();
        state.add_items(vec![pending_item("pending-0"), pending_item("pending-1")]);

        let result = state.advance_cursor();
        assert!(
            result.is_none(),
            "should return None when no Ready items exist"
        );
    }

    // --- retreat_cursor ---

    #[test]
    fn test_retreat_cursor_goes_to_previous_item() {
        let state = SharedPlayerState::new();
        let item0 = ready_item("track-0");
        let item1 = ready_item("track-1");
        let id0 = item0.id;
        let id1 = item1.id;

        state.add_items(vec![item0, item1]);
        state.set_cursor(Some(id1));

        let result = state.retreat_cursor();
        assert!(result.is_some(), "expected to retreat to previous item");
        assert_eq!(result.unwrap().0, id0, "should retreat to first item");
        assert_eq!(state.cursor(), Some(id0));
    }

    #[test]
    fn test_retreat_cursor_returns_none_when_at_first_item() {
        let state = SharedPlayerState::new();
        let item0 = ready_item("only-track");
        let id0 = item0.id;

        state.add_items(vec![item0]);
        state.set_cursor(Some(id0));

        let result = state.retreat_cursor();
        assert!(result.is_none(), "cannot retreat before the first item");
        // Cursor stays on the first item.
        assert_eq!(state.cursor(), Some(id0));
    }

    #[test]
    fn test_retreat_cursor_returns_none_when_cursor_is_unset() {
        let state = SharedPlayerState::new();
        state.add_items(vec![ready_item("track-0")]);

        let result = state.retreat_cursor();
        assert!(
            result.is_none(),
            "retreat with no cursor should return None"
        );
    }

    // --- derive_visible_queue ---

    #[test]
    fn test_derive_visible_queue_statuses() {
        // playlist: [played, playing, queued]
        let state = SharedPlayerState::new();
        let item0 = ready_item("played-track");
        let item1 = ready_item("playing-track");
        let item2 = ready_item("queued-track");
        let id1 = item1.id;

        state.add_items(vec![item0, item1, item2]);
        state.set_cursor(Some(id1));

        let snap = state.derive_visible_queue();

        assert_eq!(snap.entries.len(), 3);
        assert_eq!(snap.entries[0].status, QueueEntryStatus::Played);
        assert_eq!(snap.entries[1].status, QueueEntryStatus::Playing);
        assert_eq!(snap.entries[2].status, QueueEntryStatus::Queued);
        assert!(snap.has_playing);
        assert_eq!(snap.finished_count, 1);
        assert_eq!(snap.queue_count, 1);
    }

    #[test]
    fn test_derive_visible_queue_downloading_statuses() {
        // A Downloading item at cursor → PriorityPending; after cursor → Downloading.
        let state = SharedPlayerState::new();
        let bytes_cursor = Arc::new(AtomicU64::new(0));
        let bytes_queued = Arc::new(AtomicU64::new(0));
        let dl_cursor = make_item(
            "downloading-at-cursor",
            LoadState::Downloading {
                downloaded: 0,
                total: 1_000_000,
                bytes_written: bytes_cursor.clone(),
            },
        );
        let dl_queued = make_item(
            "downloading-queued",
            LoadState::Downloading {
                downloaded: 0,
                total: 500_000,
                bytes_written: bytes_queued.clone(),
            },
        );
        let id_cursor = dl_cursor.id;

        state.add_items(vec![dl_cursor, dl_queued]);
        state.set_cursor(Some(id_cursor));

        let snap = state.derive_visible_queue();

        assert_eq!(snap.entries[0].status, QueueEntryStatus::PriorityPending);
        assert_eq!(snap.entries[1].status, QueueEntryStatus::Downloading);
    }

    #[test]
    fn test_derive_visible_queue_no_cursor_all_queued() {
        let state = SharedPlayerState::new();
        state.add_items(vec![ready_item("a"), ready_item("b"), ready_item("c")]);

        let snap = state.derive_visible_queue();

        assert_eq!(snap.entries.len(), 3);
        for entry in &snap.entries {
            assert_eq!(entry.status, QueueEntryStatus::Queued);
        }
        assert!(!snap.has_playing);
        assert_eq!(snap.finished_count, 0);
        assert_eq!(snap.queue_count, 3);
    }

    // --- same_album_item_ids ---

    fn make_album_item(title: &str, album: &str, album_artist: &str) -> PlaylistItem {
        PlaylistItem {
            id: QueueItemId::new(),
            db_id: None,
            path: PathBuf::from(format!("/music/{title}.flac")),
            title: title.to_string(),
            artist: "Artist".to_string(),
            album_artist: album_artist.to_string(),
            album: album.to_string(),
            year: None,
            codec: Some("FLAC".to_string()),
            track_number: None,
            disc: None,
            duration_ms: Some(200_000),
            load_state: LoadState::Ready,
        }
    }

    #[test]
    fn test_same_album_item_ids_returns_album_mates() {
        let state = SharedPlayerState::new();
        let a1 = make_album_item("A1", "Album A", "Artist A");
        let a2 = make_album_item("A2", "Album A", "Artist A");
        let b1 = make_album_item("B1", "Album B", "Artist B");
        let a3 = make_album_item("A3", "Album A", "Artist A");

        let id_a1 = a1.id;
        let id_a2 = a2.id;
        let id_a3 = a3.id;

        state.add_items(vec![a1, a2, b1, a3]);

        let mates = state.same_album_item_ids(id_a1);
        assert_eq!(mates.len(), 2);
        assert!(mates.contains(&id_a2));
        assert!(mates.contains(&id_a3));
    }

    #[test]
    fn test_same_album_item_ids_distinguishes_album_artists() {
        // Two albums named the same but by different artists — should NOT match.
        let state = SharedPlayerState::new();
        let a1 = make_album_item("A1", "Greatest Hits", "Artist A");
        let b1 = make_album_item("B1", "Greatest Hits", "Artist B");

        let id_a1 = a1.id;

        state.add_items(vec![a1, b1]);

        let mates = state.same_album_item_ids(id_a1);
        assert!(mates.is_empty(), "different album_artist should not match");
    }

    #[test]
    fn test_same_album_item_ids_unknown_id_returns_empty() {
        let state = SharedPlayerState::new();
        state.add_items(vec![ready_item("track-0")]);

        let bogus = QueueItemId::new();
        let mates = state.same_album_item_ids(bogus);
        assert!(mates.is_empty());
    }

    // --- move_item_to ---

    #[test]
    fn test_move_item_to_reorders_playlist() {
        // Start: [A, B, C]. Move C to after A → [A, C, B].
        let state = SharedPlayerState::new();
        let item_a = ready_item("A");
        let item_b = ready_item("B");
        let item_c = ready_item("C");
        let id_a = item_a.id;
        let id_b = item_b.id;
        let id_c = item_c.id;

        state.add_items(vec![item_a, item_b, item_c]);
        state.move_item_to(id_c, Some(id_a));

        let (items, _) = state.snapshot_playlist();
        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
        assert_eq!(titles, vec!["A", "C", "B"]);
        assert_eq!(items[0].id, id_a);
        assert_eq!(items[1].id, id_c);
        assert_eq!(items[2].id, id_b);
    }

    #[test]
    fn test_move_item_to_front_when_after_is_none() {
        // Start: [A, B, C]. Move C to front (after=None) → [C, A, B].
        let state = SharedPlayerState::new();
        let item_a = ready_item("A");
        let item_b = ready_item("B");
        let item_c = ready_item("C");
        let id_c = item_c.id;

        state.add_items(vec![item_a, item_b, item_c]);
        state.move_item_to(id_c, None);

        let (items, _) = state.snapshot_playlist();
        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
        assert_eq!(titles, vec!["C", "A", "B"]);
    }

    // --- move_items (batch) ---

    #[test]
    fn test_move_items_batch_preserves_relative_order() {
        // Start: [A, B, C, D]. Move [A, C] after D → [B, D, A, C].
        let state = SharedPlayerState::new();
        let item_a = ready_item("A");
        let item_b = ready_item("B");
        let item_c = ready_item("C");
        let item_d = ready_item("D");
        let id_a = item_a.id;
        let id_b = item_b.id;
        let id_c = item_c.id;
        let id_d = item_d.id;

        state.add_items(vec![item_a, item_b, item_c, item_d]);
        state.move_items(&[id_a, id_c], id_d, true);

        let (items, _) = state.snapshot_playlist();
        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
        assert_eq!(titles, vec!["B", "D", "A", "C"]);
        assert_eq!(items[0].id, id_b);
        assert_eq!(items[1].id, id_d);
        assert_eq!(items[2].id, id_a);
        assert_eq!(items[3].id, id_c);
    }

    // --- pending_downloads ---

    #[test]
    fn test_pending_downloads_collects_pending_with_db_id() {
        let state = SharedPlayerState::new();
        let mut item_a = ready_item("local");
        item_a.db_id = None;

        let mut item_b = pending_item("remote-1");
        item_b.db_id = Some(10);
        let id_b = item_b.id;

        let mut item_c = ready_item("cached");
        item_c.db_id = Some(20);

        let mut item_d = pending_item("remote-2");
        item_d.db_id = Some(30);
        let id_d = item_d.id;

        // Pending without db_id — should NOT appear (no way to download).
        let item_e = pending_item("orphan");

        state.add_items(vec![item_a, item_b, item_c, item_d, item_e]);

        let pending = state.pending_downloads();
        assert_eq!(pending.len(), 2);
        assert_eq!(pending[0], (10, id_b));
        assert_eq!(pending[1], (30, id_d));
    }

    #[test]
    fn test_item_db_id_and_load_state() {
        let state = SharedPlayerState::new();
        let mut item = pending_item("track");
        item.db_id = Some(42);
        let id = item.id;
        state.add_items(vec![item]);

        assert_eq!(state.item_db_id(id), Some(42));
        assert!(matches!(
            state.item_load_state(id),
            Some(LoadState::Pending)
        ));

        state.update_load_state(id, LoadState::Ready);
        assert!(matches!(state.item_load_state(id), Some(LoadState::Ready)));
    }
}