lastfm-edit 6.0.1

Rust crate for programmatic access to Last.fm's scrobble editing functionality via web scraping
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
use crate::api::LastFmApiClient;
use crate::r#trait::LastFmBaseClient;
use crate::{Album, AlbumPage, Result, Track, TrackPage};

use async_trait::async_trait;

/// Async iterator trait for paginated Last.fm data.
///
/// This trait provides a common interface for iterating over paginated data from Last.fm,
/// such as tracks, albums, and recent scrobbles. All iterators implement efficient streaming
/// with automatic pagination and built-in rate limiting.
#[cfg_attr(feature = "mock", mockall::automock)]
#[async_trait(?Send)]
pub trait AsyncPaginatedIterator<T> {
    /// Fetch the next item from the iterator.
    ///
    /// This method automatically handles pagination, fetching new pages as needed.
    /// Returns `None` when there are no more items available.
    ///
    /// # Returns
    ///
    /// - `Ok(Some(item))` - Next item in the sequence
    /// - `Ok(None)` - No more items available
    /// - `Err(...)` - Network or parsing error occurred
    async fn next(&mut self) -> Result<Option<T>>;

    /// Collect all remaining items into a Vec.
    ///
    /// **Warning**: This method will fetch ALL remaining pages, which could be
    /// many thousands of items for large libraries. Use [`take`](Self::take) for
    /// safer bounded collection.
    async fn collect_all(&mut self) -> Result<Vec<T>> {
        let mut items = Vec::new();
        while let Some(item) = self.next().await? {
            items.push(item);
        }
        Ok(items)
    }

    /// Take up to n items from the iterator.
    ///
    /// This is the recommended way to collect a bounded number of items
    /// from potentially large datasets.
    ///
    /// # Arguments
    ///
    /// * `n` - Maximum number of items to collect
    async fn take(&mut self, n: usize) -> Result<Vec<T>> {
        let mut items = Vec::new();
        for _ in 0..n {
            match self.next().await? {
                Some(item) => items.push(item),
                None => break,
            }
        }
        Ok(items)
    }

    /// Get the current page number (0-indexed).
    ///
    /// Returns the page number of the most recently fetched page.
    fn current_page(&self) -> u32;

    /// Get the total number of pages, if known.
    ///
    /// Returns `Some(n)` if the total page count is known, `None` otherwise.
    /// This information may not be available until at least one page has been fetched.
    fn total_pages(&self) -> Option<u32> {
        None // Default implementation returns None
    }
}

/// Iterator for browsing an artist's tracks from a user's library.
///
/// This iterator provides access to all tracks by a specific artist
/// in the authenticated user's Last.fm library. Unlike the basic track listing,
/// this iterator fetches tracks by iterating through the artist's albums first,
/// which provides complete album information for each track.
///
/// The iterator loads albums and their tracks as needed and handles rate limiting
/// automatically to be respectful to Last.fm's servers.
pub struct ArtistTracksIterator<C: LastFmBaseClient> {
    client: C,
    artist: String,
    album_iterator: Option<ArtistAlbumsIterator<C>>,
    current_album_tracks: Option<AlbumTracksIterator<C>>,
    track_buffer: Vec<Track>,
    finished: bool,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient + Clone> AsyncPaginatedIterator<Track> for ArtistTracksIterator<C> {
    async fn next(&mut self) -> Result<Option<Track>> {
        // If we're finished, return None
        if self.finished {
            return Ok(None);
        }

        // If track buffer is empty, try to get more tracks
        while self.track_buffer.is_empty() {
            // If we don't have a current album tracks iterator, get the next album
            if self.current_album_tracks.is_none() {
                // Initialize album iterator if needed
                if self.album_iterator.is_none() {
                    self.album_iterator = Some(ArtistAlbumsIterator::new(
                        self.client.clone(),
                        self.artist.clone(),
                    ));
                }

                // Get next album
                if let Some(ref mut album_iter) = self.album_iterator {
                    if let Some(album) = album_iter.next().await? {
                        log::debug!(
                            "Processing album '{}' for artist '{}'",
                            album.name,
                            self.artist
                        );
                        // Create album tracks iterator for this album
                        self.current_album_tracks = Some(AlbumTracksIterator::new(
                            self.client.clone(),
                            album.name.clone(),
                            self.artist.clone(),
                        ));
                    } else {
                        // No more albums, we're done
                        log::debug!("No more albums for artist '{}'", self.artist);
                        self.finished = true;
                        return Ok(None);
                    }
                }
            }

            // Get tracks from current album
            if let Some(ref mut album_tracks) = self.current_album_tracks {
                if let Some(track) = album_tracks.next().await? {
                    self.track_buffer.push(track);
                } else {
                    // This album is exhausted, move to next album
                    log::debug!(
                        "Finished processing current album for artist '{}'",
                        self.artist
                    );
                    self.current_album_tracks = None;
                    // Continue the loop to try getting the next album
                }
            }
        }

        // Return the next track from our buffer
        Ok(self.track_buffer.pop())
    }

    fn current_page(&self) -> u32 {
        // Since we're iterating through albums, return the album iterator's current page
        if let Some(ref album_iter) = self.album_iterator {
            album_iter.current_page()
        } else {
            0
        }
    }

    fn total_pages(&self) -> Option<u32> {
        // Since we're iterating through albums, return the album iterator's total pages
        if let Some(ref album_iter) = self.album_iterator {
            album_iter.total_pages()
        } else {
            None
        }
    }
}

impl<C: LastFmBaseClient + Clone> ArtistTracksIterator<C> {
    /// Create a new artist tracks iterator.
    ///
    /// This is typically called via [`LastFmBaseClient::artist_tracks`](crate::LastFmBaseClient::artist_tracks).
    pub fn new(client: C, artist: String) -> Self {
        Self {
            client,
            artist,
            album_iterator: None,
            current_album_tracks: None,
            track_buffer: Vec::new(),
            finished: false,
        }
    }
}

/// Iterator for browsing an artist's tracks directly using the paginated artist tracks endpoint.
///
/// This iterator provides access to all tracks by a specific artist
/// in the authenticated user's Last.fm library by directly using the
/// `/user/{username}/library/music/{artist}/+tracks` endpoint with pagination.
/// This is more efficient than the album-based approach as it doesn't need to
/// iterate through albums first.
pub struct ArtistTracksDirectIterator<C: LastFmBaseClient> {
    client: C,
    artist: String,
    current_page: u32,
    has_more: bool,
    buffer: Vec<Track>,
    total_pages: Option<u32>,
    tracks_yielded: u32,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient> AsyncPaginatedIterator<Track> for ArtistTracksDirectIterator<C> {
    async fn next(&mut self) -> Result<Option<Track>> {
        // If buffer is empty, try to load next page
        if self.buffer.is_empty() {
            if let Some(page) = self.next_page().await? {
                self.buffer = page.tracks;
                self.buffer.reverse(); // Reverse so we can pop from end efficiently
            }
        }

        if let Some(track) = self.buffer.pop() {
            self.tracks_yielded += 1;
            Ok(Some(track))
        } else {
            Ok(None)
        }
    }

    fn current_page(&self) -> u32 {
        self.current_page.saturating_sub(1)
    }

    fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

impl<C: LastFmBaseClient> ArtistTracksDirectIterator<C> {
    /// Create a new direct artist tracks iterator.
    ///
    /// This is typically called via [`LastFmBaseClient::artist_tracks_direct`](crate::LastFmBaseClient::artist_tracks_direct).
    pub fn new(client: C, artist: String) -> Self {
        Self {
            client,
            artist,
            current_page: 1,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
            tracks_yielded: 0,
        }
    }

    /// Fetch the next page of tracks.
    ///
    /// This method handles pagination automatically and includes rate limiting.
    pub async fn next_page(&mut self) -> Result<Option<TrackPage>> {
        if !self.has_more {
            return Ok(None);
        }

        log::debug!(
            "Fetching page {} of {} tracks (yielded {} tracks so far)",
            self.current_page,
            self.artist,
            self.tracks_yielded
        );

        let page = self
            .client
            .get_artist_tracks_page(&self.artist, self.current_page)
            .await?;

        self.has_more = page.has_next_page;
        self.current_page += 1;
        self.total_pages = page.total_pages;

        Ok(Some(page))
    }

    /// Get the total number of pages, if known.
    ///
    /// Returns `None` until at least one page has been fetched.
    pub fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

/// Iterator for browsing an artist's albums from a user's library.
///
/// This iterator provides paginated access to all albums by a specific artist
/// in the authenticated user's Last.fm library, ordered by play count.
pub struct ArtistAlbumsIterator<C: LastFmBaseClient> {
    client: C,
    artist: String,
    current_page: u32,
    has_more: bool,
    buffer: Vec<Album>,
    total_pages: Option<u32>,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient> AsyncPaginatedIterator<Album> for ArtistAlbumsIterator<C> {
    async fn next(&mut self) -> Result<Option<Album>> {
        // If buffer is empty, try to load next page
        if self.buffer.is_empty() {
            if let Some(page) = self.next_page().await? {
                self.buffer = page.albums;
                self.buffer.reverse(); // Reverse so we can pop from end efficiently
            }
        }

        Ok(self.buffer.pop())
    }

    fn current_page(&self) -> u32 {
        self.current_page.saturating_sub(1)
    }

    fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

impl<C: LastFmBaseClient> ArtistAlbumsIterator<C> {
    /// Create a new artist albums iterator.
    ///
    /// This is typically called via [`LastFmBaseClient::artist_albums`](crate::LastFmBaseClient::artist_albums).
    pub fn new(client: C, artist: String) -> Self {
        Self {
            client,
            artist,
            current_page: 1,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Fetch the next page of albums.
    ///
    /// This method handles pagination automatically and includes rate limiting.
    pub async fn next_page(&mut self) -> Result<Option<AlbumPage>> {
        if !self.has_more {
            return Ok(None);
        }

        let page = self
            .client
            .get_artist_albums_page(&self.artist, self.current_page)
            .await?;

        self.has_more = page.has_next_page;
        self.current_page += 1;
        self.total_pages = page.total_pages;

        Ok(Some(page))
    }

    /// Get the total number of pages, if known.
    ///
    /// Returns `None` until at least one page has been fetched.
    pub fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

/// Iterator for browsing a user's recent tracks/scrobbles.
///
/// This iterator provides access to the user's recent listening history with timestamps,
/// which is essential for finding tracks that can be edited. It supports optional
/// timestamp-based filtering to avoid reprocessing old data.
pub struct RecentTracksIterator<C: LastFmBaseClient> {
    client: C,
    current_page: u32,
    has_more: bool,
    buffer: Vec<Track>,
    stop_at_timestamp: Option<u64>,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient> AsyncPaginatedIterator<Track> for RecentTracksIterator<C> {
    async fn next(&mut self) -> Result<Option<Track>> {
        // If buffer is empty, try to load next page
        if self.buffer.is_empty() {
            if !self.has_more {
                return Ok(None);
            }

            let page = self
                .client
                .get_recent_tracks_page(self.current_page)
                .await?;

            if page.tracks.is_empty() {
                self.has_more = false;
                return Ok(None);
            }

            self.has_more = page.has_next_page;

            // Check if we should stop based on timestamp
            if let Some(stop_timestamp) = self.stop_at_timestamp {
                let mut filtered_tracks = Vec::new();
                for track in page.tracks {
                    if let Some(track_timestamp) = track.timestamp {
                        if track_timestamp <= stop_timestamp {
                            self.has_more = false;
                            break;
                        }
                    }
                    filtered_tracks.push(track);
                }
                self.buffer = filtered_tracks;
            } else {
                self.buffer = page.tracks;
            }

            self.buffer.reverse(); // Reverse so we can pop from end efficiently
            self.current_page += 1;
        }

        Ok(self.buffer.pop())
    }

    fn current_page(&self) -> u32 {
        self.current_page.saturating_sub(1)
    }
}

impl<C: LastFmBaseClient> RecentTracksIterator<C> {
    /// Create a new recent tracks iterator starting from page 1.
    ///
    /// This is typically called via [`LastFmBaseClient::recent_tracks`](crate::LastFmBaseClient::recent_tracks).
    pub fn new(client: C) -> Self {
        Self::with_starting_page(client, 1)
    }

    /// Create a new recent tracks iterator starting from a specific page.
    ///
    /// This allows resuming pagination from an arbitrary page, useful for
    /// continuing from where a previous iteration left off.
    ///
    /// # Arguments
    ///
    /// * `client` - The LastFmBaseClient to use for API calls
    /// * `starting_page` - The page number to start from (1-indexed)
    pub fn with_starting_page(client: C, starting_page: u32) -> Self {
        let page = std::cmp::max(1, starting_page);
        Self {
            client,
            current_page: page,
            has_more: true,
            buffer: Vec::new(),
            stop_at_timestamp: None,
        }
    }

    /// Set a timestamp to stop iteration at.
    ///
    /// When this is set, the iterator will stop returning tracks once it encounters
    /// a track with a timestamp less than or equal to the specified value. This is
    /// useful for incremental processing to avoid reprocessing old data.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - Unix timestamp to stop at
    pub fn with_stop_timestamp(mut self, timestamp: u64) -> Self {
        self.stop_at_timestamp = Some(timestamp);
        self
    }
}

/// Iterator for browsing a user's recent tracks via the Last.fm JSON API.
///
/// This iterator uses the `user.getRecentTracks` API endpoint which supports
/// up to 200 items per page and is less aggressively rate-limited than web scraping.
/// It supports optional timestamp-based filtering identical to [`RecentTracksIterator`].
pub struct ApiRecentTracksIterator<C: LastFmApiClient> {
    client: C,
    current_page: u32,
    has_more: bool,
    buffer: Vec<Track>,
    stop_at_timestamp: Option<u64>,
    total_pages: Option<u32>,
}

#[async_trait(?Send)]
impl<C: LastFmApiClient> AsyncPaginatedIterator<Track> for ApiRecentTracksIterator<C> {
    async fn next(&mut self) -> Result<Option<Track>> {
        if self.buffer.is_empty() {
            if !self.has_more {
                return Ok(None);
            }

            let page = self
                .client
                .api_get_recent_tracks_page(self.current_page)
                .await?;

            if page.tracks.is_empty() {
                self.has_more = false;
                return Ok(None);
            }

            self.has_more = page.has_next_page;
            self.total_pages = page.total_pages;

            if let Some(stop_timestamp) = self.stop_at_timestamp {
                let mut filtered_tracks = Vec::new();
                for track in page.tracks {
                    if let Some(track_timestamp) = track.timestamp {
                        if track_timestamp <= stop_timestamp {
                            self.has_more = false;
                            break;
                        }
                    }
                    filtered_tracks.push(track);
                }
                self.buffer = filtered_tracks;
            } else {
                self.buffer = page.tracks;
            }

            self.buffer.reverse();
            self.current_page += 1;
        }

        Ok(self.buffer.pop())
    }

    fn current_page(&self) -> u32 {
        self.current_page.saturating_sub(1)
    }

    fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

impl<C: LastFmApiClient> ApiRecentTracksIterator<C> {
    pub fn new(client: C) -> Self {
        Self::with_starting_page(client, 1)
    }

    pub fn with_starting_page(client: C, starting_page: u32) -> Self {
        let page = std::cmp::max(1, starting_page);
        Self {
            client,
            current_page: page,
            has_more: true,
            buffer: Vec::new(),
            stop_at_timestamp: None,
            total_pages: None,
        }
    }

    pub fn with_stop_timestamp(mut self, timestamp: u64) -> Self {
        self.stop_at_timestamp = Some(timestamp);
        self
    }
}

/// Iterator for browsing tracks in a specific album from a user's library.
///
/// This iterator provides access to all tracks in a specific album by an artist
/// in the authenticated user's Last.fm library. Unlike paginated iterators,
/// this loads tracks once and iterates through them.
pub struct AlbumTracksIterator<C: LastFmBaseClient> {
    client: C,
    album_name: String,
    artist_name: String,
    tracks: Option<Vec<Track>>,
    index: usize,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient> AsyncPaginatedIterator<Track> for AlbumTracksIterator<C> {
    async fn next(&mut self) -> Result<Option<Track>> {
        // Load tracks if not already loaded
        if self.tracks.is_none() {
            // Use get_album_tracks_page instead of get_album_tracks to avoid infinite recursion
            let tracks_page = self
                .client
                .get_album_tracks_page(&self.album_name, &self.artist_name, 1)
                .await?;
            log::debug!(
                "Album '{}' by '{}' has {} tracks: {:?}",
                self.album_name,
                self.artist_name,
                tracks_page.tracks.len(),
                tracks_page
                    .tracks
                    .iter()
                    .map(|t| &t.name)
                    .collect::<Vec<_>>()
            );

            if tracks_page.tracks.is_empty() {
                log::warn!(
                    "🚨 ZERO TRACKS FOUND for album '{}' by '{}' - investigating...",
                    self.album_name,
                    self.artist_name
                );
                log::debug!("Full TrackPage for empty album: has_next_page={}, page_number={}, total_pages={:?}",
                           tracks_page.has_next_page, tracks_page.page_number, tracks_page.total_pages);
            }
            self.tracks = Some(tracks_page.tracks);
        }

        // Return next track
        if let Some(tracks) = &self.tracks {
            if self.index < tracks.len() {
                let track = tracks[self.index].clone();
                self.index += 1;
                Ok(Some(track))
            } else {
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }

    fn current_page(&self) -> u32 {
        // Album tracks don't have pages, so return 0
        0
    }
}

impl<C: LastFmBaseClient> AlbumTracksIterator<C> {
    /// Create a new album tracks iterator.
    ///
    /// This is typically called via [`LastFmBaseClient::album_tracks`](crate::LastFmBaseClient::album_tracks).
    pub fn new(client: C, album_name: String, artist_name: String) -> Self {
        Self {
            client,
            album_name,
            artist_name,
            tracks: None,
            index: 0,
        }
    }
}

/// Iterator for searching tracks in the user's library.
///
/// This iterator provides paginated access to tracks that match a search query
/// in the authenticated user's Last.fm library, using Last.fm's built-in search functionality.
pub struct SearchTracksIterator<C: LastFmBaseClient> {
    client: C,
    query: String,
    current_page: u32,
    has_more: bool,
    buffer: Vec<Track>,
    total_pages: Option<u32>,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient> AsyncPaginatedIterator<Track> for SearchTracksIterator<C> {
    async fn next(&mut self) -> Result<Option<Track>> {
        // If buffer is empty, try to load next page
        if self.buffer.is_empty() {
            if let Some(page) = self.next_page().await? {
                self.buffer = page.tracks;
                self.buffer.reverse(); // Reverse so we can pop from end efficiently
            }
        }

        Ok(self.buffer.pop())
    }

    fn current_page(&self) -> u32 {
        self.current_page.saturating_sub(1)
    }

    fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

impl<C: LastFmBaseClient> SearchTracksIterator<C> {
    /// Create a new search tracks iterator.
    ///
    /// This is typically called via [`LastFmBaseClient::search_tracks`](crate::LastFmBaseClient::search_tracks).
    pub fn new(client: C, query: String) -> Self {
        Self {
            client,
            query,
            current_page: 1,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Create a new search tracks iterator starting from a specific page.
    ///
    /// This is useful for implementing offset functionality efficiently by starting
    /// at the appropriate page rather than iterating through all previous pages.
    pub fn with_starting_page(client: C, query: String, starting_page: u32) -> Self {
        let page = std::cmp::max(1, starting_page);
        Self {
            client,
            query,
            current_page: page,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Fetch the next page of search results.
    ///
    /// This method handles pagination automatically and includes rate limiting
    /// to be respectful to Last.fm's servers.
    pub async fn next_page(&mut self) -> Result<Option<TrackPage>> {
        if !self.has_more {
            return Ok(None);
        }

        let page = self
            .client
            .search_tracks_page(&self.query, self.current_page)
            .await?;

        self.has_more = page.has_next_page;
        self.current_page += 1;
        self.total_pages = page.total_pages;

        Ok(Some(page))
    }

    /// Get the total number of pages, if known.
    ///
    /// Returns `None` until at least one page has been fetched.
    pub fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

/// Iterator for searching albums in the user's library.
///
/// This iterator provides paginated access to albums that match a search query
/// in the authenticated user's Last.fm library, using Last.fm's built-in search functionality.
///
/// # Examples
pub struct SearchAlbumsIterator<C: LastFmBaseClient> {
    client: C,
    query: String,
    current_page: u32,
    has_more: bool,
    buffer: Vec<Album>,
    total_pages: Option<u32>,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient> AsyncPaginatedIterator<Album> for SearchAlbumsIterator<C> {
    async fn next(&mut self) -> Result<Option<Album>> {
        // If buffer is empty, try to load next page
        if self.buffer.is_empty() {
            if let Some(page) = self.next_page().await? {
                self.buffer = page.albums;
                self.buffer.reverse(); // Reverse so we can pop from end efficiently
            }
        }

        Ok(self.buffer.pop())
    }

    fn current_page(&self) -> u32 {
        self.current_page.saturating_sub(1)
    }

    fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

impl<C: LastFmBaseClient> SearchAlbumsIterator<C> {
    /// Create a new search albums iterator.
    ///
    /// This is typically called via [`LastFmBaseClient::search_albums`](crate::LastFmBaseClient::search_albums).
    pub fn new(client: C, query: String) -> Self {
        Self {
            client,
            query,
            current_page: 1,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Create a new search albums iterator starting from a specific page.
    ///
    /// This is useful for implementing offset functionality efficiently by starting
    /// at the appropriate page rather than iterating through all previous pages.
    pub fn with_starting_page(client: C, query: String, starting_page: u32) -> Self {
        let page = std::cmp::max(1, starting_page);
        Self {
            client,
            query,
            current_page: page,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Fetch the next page of search results.
    ///
    /// This method handles pagination automatically and includes rate limiting
    /// to be respectful to Last.fm's servers.
    pub async fn next_page(&mut self) -> Result<Option<AlbumPage>> {
        if !self.has_more {
            return Ok(None);
        }

        let page = self
            .client
            .search_albums_page(&self.query, self.current_page)
            .await?;

        self.has_more = page.has_next_page;
        self.current_page += 1;
        self.total_pages = page.total_pages;

        Ok(Some(page))
    }

    /// Get the total number of pages, if known.
    ///
    /// Returns `None` until at least one page has been fetched.
    pub fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

/// Iterator for searching artists in the user's library.
///
/// This iterator provides paginated access to artists that match a search query
/// in the authenticated user's Last.fm library, using Last.fm's built-in search functionality.
pub struct SearchArtistsIterator<C: LastFmBaseClient> {
    client: C,
    query: String,
    current_page: u32,
    has_more: bool,
    buffer: Vec<crate::Artist>,
    total_pages: Option<u32>,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient> AsyncPaginatedIterator<crate::Artist> for SearchArtistsIterator<C> {
    async fn next(&mut self) -> Result<Option<crate::Artist>> {
        // If buffer is empty, try to load next page
        if self.buffer.is_empty() {
            if let Some(page) = self.next_page().await? {
                self.buffer = page.artists;
                self.buffer.reverse(); // Reverse so we can pop from end efficiently
            }
        }

        Ok(self.buffer.pop())
    }

    fn current_page(&self) -> u32 {
        self.current_page.saturating_sub(1)
    }

    fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

impl<C: LastFmBaseClient> SearchArtistsIterator<C> {
    /// Create a new search artists iterator.
    ///
    /// This is typically called via [`LastFmBaseClient::search_artists`](crate::LastFmBaseClient::search_artists).
    pub fn new(client: C, query: String) -> Self {
        Self {
            client,
            query,
            current_page: 1,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Create a new search artists iterator starting from a specific page.
    ///
    /// This is useful for implementing offset functionality efficiently by starting
    /// at the appropriate page rather than iterating through all previous pages.
    pub fn with_starting_page(client: C, query: String, starting_page: u32) -> Self {
        let page = std::cmp::max(1, starting_page);
        Self {
            client,
            query,
            current_page: page,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Fetch the next page of search results.
    ///
    /// This method handles pagination automatically and includes rate limiting
    /// to be respectful to Last.fm's servers.
    pub async fn next_page(&mut self) -> Result<Option<crate::ArtistPage>> {
        if !self.has_more {
            return Ok(None);
        }

        let page = self
            .client
            .search_artists_page(&self.query, self.current_page)
            .await?;

        self.has_more = page.has_next_page;
        self.current_page += 1;
        self.total_pages = page.total_pages;

        Ok(Some(page))
    }

    /// Get the total number of pages, if known.
    ///
    /// Returns `None` until at least one page has been fetched.
    pub fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

// =============================================================================
// ARTISTS ITERATOR
// =============================================================================

/// Iterator for browsing all artists in the user's library.
///
/// This iterator provides access to all artists in the authenticated user's Last.fm library,
/// sorted by play count (highest first). The iterator loads artists as needed and handles
/// rate limiting automatically to be respectful to Last.fm's servers.
pub struct ArtistsIterator<C: LastFmBaseClient> {
    client: C,
    current_page: u32,
    has_more: bool,
    buffer: Vec<crate::Artist>,
    total_pages: Option<u32>,
}

#[async_trait(?Send)]
impl<C: LastFmBaseClient> AsyncPaginatedIterator<crate::Artist> for ArtistsIterator<C> {
    async fn next(&mut self) -> Result<Option<crate::Artist>> {
        // If buffer is empty, try to load next page
        if self.buffer.is_empty() {
            if let Some(page) = self.next_page().await? {
                self.buffer = page.artists;
                self.buffer.reverse(); // Reverse so we can pop from end efficiently
            }
        }

        Ok(self.buffer.pop())
    }

    fn current_page(&self) -> u32 {
        self.current_page.saturating_sub(1)
    }

    fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}

impl<C: LastFmBaseClient> ArtistsIterator<C> {
    /// Create a new artists iterator.
    ///
    /// This iterator will start from page 1 and load all artists in the user's library.
    pub fn new(client: C) -> Self {
        Self {
            client,
            current_page: 1,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Create a new artists iterator starting from a specific page.
    ///
    /// This is useful for implementing offset functionality efficiently by starting
    /// at the appropriate page rather than iterating through all previous pages.
    pub fn with_starting_page(client: C, starting_page: u32) -> Self {
        let page = std::cmp::max(1, starting_page);
        Self {
            client,
            current_page: page,
            has_more: true,
            buffer: Vec::new(),
            total_pages: None,
        }
    }

    /// Fetch the next page of artists.
    ///
    /// This method handles pagination automatically and includes rate limiting
    /// to be respectful to Last.fm's servers.
    pub async fn next_page(&mut self) -> Result<Option<crate::ArtistPage>> {
        if !self.has_more {
            return Ok(None);
        }

        let page = self.client.get_artists_page(self.current_page).await?;

        self.has_more = page.has_next_page;
        self.current_page += 1;
        self.total_pages = page.total_pages;

        Ok(Some(page))
    }

    /// Get the total number of pages, if known.
    ///
    /// Returns `None` until at least one page has been fetched.
    pub fn total_pages(&self) -> Option<u32> {
        self.total_pages
    }
}