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
//! HTML parsing utilities for Last.fm pages.
//!
//! This module contains all the HTML parsing logic for extracting track, album,
//! and other data from Last.fm web pages. These functions are primarily pure
//! functions that take HTML documents and return structured data.

use crate::{Album, AlbumPage, Artist, ArtistPage, LastFmError, Result, Track, TrackPage};
use scraper::{Html, Selector};

/// Parser struct containing parsing methods for Last.fm HTML pages.
///
/// This struct holds the parsing logic that was previously embedded in the client.
/// It's designed to be stateless and focused purely on HTML parsing.
#[derive(Debug, Clone)]
pub struct LastFmParser;

impl LastFmParser {
    /// Create a new parser instance.
    pub fn new() -> Self {
        Self
    }

    /// Parse recent scrobbles from the user's library page
    /// This extracts real scrobble data with timestamps for editing
    pub fn parse_recent_scrobbles(&self, document: &Html) -> Result<Vec<Track>> {
        let mut tracks = Vec::new();

        // Recent scrobbles are typically in chartlist tables - there can be multiple
        let table_selector = Selector::parse("table.chartlist").unwrap();
        let row_selector = Selector::parse("tbody tr").unwrap();

        let tables: Vec<_> = document.select(&table_selector).collect();
        log::debug!("Found {} chartlist tables", tables.len());

        for table in tables {
            for row in table.select(&row_selector) {
                if let Ok(track) = self.parse_recent_scrobble_row(&row) {
                    tracks.push(track);
                }
            }
        }

        if tracks.is_empty() {
            log::debug!("No tracks found in recent scrobbles");
        }

        log::debug!("Parsed {} recent scrobbles", tracks.len());
        Ok(tracks)
    }

    /// Parse a single row from the recent scrobbles table
    fn parse_recent_scrobble_row(&self, row: &scraper::ElementRef) -> Result<Track> {
        // Extract track name
        let name_selector = Selector::parse(".chartlist-name a").unwrap();
        let name = row
            .select(&name_selector)
            .next()
            .ok_or(LastFmError::Parse("Missing track name".to_string()))?
            .text()
            .collect::<String>()
            .trim()
            .to_string();

        // Extract artist name
        let artist_selector = Selector::parse(".chartlist-artist a").unwrap();
        let artist = row
            .select(&artist_selector)
            .next()
            .ok_or(LastFmError::Parse("Missing artist name".to_string()))?
            .text()
            .collect::<String>()
            .trim()
            .to_string();

        // Extract timestamp from data attributes or hidden inputs
        let timestamp = self.extract_scrobble_timestamp(row);

        // Extract album from hidden inputs in edit form
        let album = self.extract_scrobble_album(row);

        // Extract album artist from hidden inputs in edit form
        let album_artist = self.extract_scrobble_album_artist(row);

        // For recent scrobbles, playcount is typically 1 since they're individual scrobbles
        let playcount = 1;

        Ok(Track {
            name,
            artist,
            playcount,
            timestamp,
            album,
            album_artist,
        })
    }

    /// Extract timestamp from scrobble row elements
    fn extract_scrobble_timestamp(&self, row: &scraper::ElementRef) -> Option<u64> {
        // Look for timestamp in various places:

        // 1. Check for data-timestamp attribute
        if let Some(timestamp_str) = row.value().attr("data-timestamp") {
            if let Ok(timestamp) = timestamp_str.parse::<u64>() {
                return Some(timestamp);
            }
        }

        // 2. Look for hidden timestamp input
        let timestamp_input_selector = Selector::parse("input[name='timestamp']").unwrap();
        if let Some(input) = row.select(&timestamp_input_selector).next() {
            if let Some(value) = input.value().attr("value") {
                if let Ok(timestamp) = value.parse::<u64>() {
                    return Some(timestamp);
                }
            }
        }

        // 3. Look for edit form with timestamp
        let edit_form_selector =
            Selector::parse("form[data-edit-scrobble] input[name='timestamp']").unwrap();
        if let Some(timestamp_input) = row.select(&edit_form_selector).next() {
            if let Some(value) = timestamp_input.value().attr("value") {
                if let Ok(timestamp) = value.parse::<u64>() {
                    return Some(timestamp);
                }
            }
        }

        // Removed time element parsing - testing if needed

        None
    }

    /// Extract album name from scrobble row elements
    fn extract_scrobble_album(&self, row: &scraper::ElementRef) -> Option<String> {
        // Look for album_name in hidden inputs within edit forms
        let album_input_selector =
            Selector::parse("form[data-edit-scrobble] input[name='album_name']").unwrap();

        if let Some(album_input) = row.select(&album_input_selector).next() {
            if let Some(album_name) = album_input.value().attr("value") {
                if !album_name.is_empty() {
                    return Some(album_name.to_string());
                }
            }
        }

        None
    }

    /// Extract album artist name from scrobble row elements
    fn extract_scrobble_album_artist(&self, row: &scraper::ElementRef) -> Option<String> {
        // Look for album_artist_name in hidden inputs within edit forms
        let album_artist_input_selector =
            Selector::parse("form[data-edit-scrobble] input[name='album_artist_name']").unwrap();

        if let Some(album_artist_input) = row.select(&album_artist_input_selector).next() {
            if let Some(album_artist_name) = album_artist_input.value().attr("value") {
                if !album_artist_name.is_empty() {
                    return Some(album_artist_name.to_string());
                }
            }
        }

        None
    }

    /// Parse a tracks page into a `TrackPage` structure
    pub fn parse_tracks_page(
        &self,
        document: &Html,
        page_number: u32,
        artist: &str,
        album: Option<&str>,
    ) -> Result<TrackPage> {
        let tracks = self.extract_tracks_from_document(document, artist, album)?;

        // Check for pagination
        let (has_next_page, total_pages) = self.parse_pagination(document, page_number)?;

        Ok(TrackPage {
            tracks,
            page_number,
            has_next_page,
            total_pages,
        })
    }

    /// Extract tracks from HTML document
    pub fn extract_tracks_from_document(
        &self,
        document: &Html,
        artist: &str,
        album: Option<&str>,
    ) -> Result<Vec<Track>> {
        let mut tracks = Vec::new();
        let mut seen_tracks = std::collections::HashSet::new();

        log::debug!("Starting track extraction for artist: {artist}, album: {album:?}");

        // JSON parsing removed - was not implemented and always failed

        // Parse track data from data-track-name attributes (AJAX response)
        let track_selector = Selector::parse("[data-track-name]").unwrap();
        let track_elements: Vec<_> = document.select(&track_selector).collect();
        log::debug!(
            "Found {} elements with data-track-name",
            track_elements.len()
        );

        for element in track_elements {
            let track_name = element.value().attr("data-track-name").unwrap_or("");
            if track_name.is_empty() {
                continue;
            }
            if seen_tracks.contains(track_name) {
                continue;
            }
            seen_tracks.insert(track_name.to_string());

            match self.find_playcount_for_track(document, track_name) {
                Ok(playcount) => {
                    let timestamp = self.find_timestamp_for_track(document, track_name);
                    let track = Track {
                        name: track_name.to_string(),
                        artist: artist.to_string(),
                        playcount,
                        timestamp,
                        album: album.map(|a| a.to_string()),
                        album_artist: None, // Not available in aggregate track listings
                    };
                    tracks.push(track);
                    log::debug!("Added track '{track_name}' with {playcount} plays");
                }
                Err(e) => {
                    log::debug!("FAILED to find playcount for track '{track_name}': {e}");
                }
            }
        }

        // Always try fallback parsing from chartlist tables to catch tracks without data-track-name
        let table_selector = Selector::parse("table.chartlist").unwrap();
        let tables: Vec<_> = document.select(&table_selector).collect();

        for table in tables {
            let row_selector = Selector::parse("tbody tr").unwrap();
            let rows: Vec<_> = table.select(&row_selector).collect();

            for row in rows.iter() {
                // Try to parse as track row
                if let Ok(mut track) = self.parse_track_row(row) {
                    track.artist = artist.to_string();
                    if let Some(album_name) = album {
                        track.album = Some(album_name.to_string());
                    }

                    // Only add if we don't already have this track
                    if !seen_tracks.contains(&track.name) {
                        seen_tracks.insert(track.name.clone());
                        tracks.push(track);
                    }
                }
            }
        }

        log::debug!("Successfully extracted {} unique tracks", tracks.len());
        Ok(tracks)
    }

    // Removed parse_tracks_from_rows - no longer needed

    /// Parse a single track row from chartlist table
    pub fn parse_track_row(&self, row: &scraper::ElementRef) -> Result<Track> {
        // Extract track name using shared method
        let name = self.extract_name_from_row(row, "track")?;

        // Parse play count using shared method
        let playcount = self.extract_playcount_from_row(row);

        let artist = "".to_string(); // Will be filled in by caller

        Ok(Track {
            name,
            artist,
            playcount,
            timestamp: None,    // Not available in table parsing mode
            album: None,        // Not available in table parsing mode
            album_artist: None, // Not available in table parsing mode
        })
    }

    /// Parse albums page into `AlbumPage` structure
    pub fn parse_albums_page(
        &self,
        document: &Html,
        page_number: u32,
        artist: &str,
    ) -> Result<AlbumPage> {
        let mut albums = Vec::new();

        // Try parsing album data from data attributes (AJAX response)
        let album_selector = Selector::parse("[data-album-name]").unwrap();
        let album_elements: Vec<_> = document.select(&album_selector).collect();

        if !album_elements.is_empty() {
            log::debug!(
                "Found {} album elements with data-album-name",
                album_elements.len()
            );

            // Use a set to track unique albums
            let mut seen_albums = std::collections::HashSet::new();

            for element in album_elements {
                let album_name = element.value().attr("data-album-name").unwrap_or("");
                if !album_name.is_empty() && !seen_albums.contains(album_name) {
                    seen_albums.insert(album_name.to_string());

                    if let Ok(playcount) = self.find_playcount_for_album(document, album_name) {
                        let timestamp = self.find_timestamp_for_album(document, album_name);
                        let album = Album {
                            name: album_name.to_string(),
                            artist: artist.to_string(),
                            playcount,
                            timestamp,
                        };
                        albums.push(album);
                    }
                }
            }
        } else {
            // Fall back to parsing album rows from chartlist tables
            albums = self.parse_albums_from_rows(document, artist)?;
        }

        let (has_next_page, total_pages) = self.parse_pagination(document, page_number)?;

        Ok(AlbumPage {
            albums,
            page_number,
            has_next_page,
            total_pages,
        })
    }

    /// Parse albums from chartlist table rows
    fn parse_albums_from_rows(&self, document: &Html, artist: &str) -> Result<Vec<Album>> {
        let mut albums = Vec::new();
        let table_selector = Selector::parse("table.chartlist").unwrap();
        let row_selector = Selector::parse("tbody tr").unwrap();

        for table in document.select(&table_selector) {
            for row in table.select(&row_selector) {
                if let Ok(mut album) = self.parse_album_row(&row) {
                    album.artist = artist.to_string();
                    albums.push(album);
                }
            }
        }
        Ok(albums)
    }

    /// Parse a single album row from chartlist table
    pub fn parse_album_row(&self, row: &scraper::ElementRef) -> Result<Album> {
        // Extract album name using shared method
        let name = self.extract_name_from_row(row, "album")?;

        // Parse play count using shared method
        let playcount = self.extract_playcount_from_row(row);

        let artist = "".to_string(); // Will be filled in by caller

        Ok(Album {
            name,
            artist,
            playcount,
            timestamp: None, // Not available in table parsing
        })
    }

    // === SEARCH RESULTS PARSING ===

    /// Parse track search results from AJAX response
    ///
    /// This parses the HTML returned by `/user/{username}/library/tracks/search?ajax=1&query={query}`
    /// which contains chartlist tables with track results.
    pub fn parse_track_search_results(&self, document: &Html) -> Result<Vec<Track>> {
        let mut tracks = Vec::new();

        // Search results use the same chartlist structure as library pages
        let table_selector = Selector::parse("table.chartlist").unwrap();
        let row_selector = Selector::parse("tbody tr").unwrap();

        let tables: Vec<_> = document.select(&table_selector).collect();
        log::debug!("Found {} chartlist tables in search results", tables.len());

        for table in tables {
            for row in table.select(&row_selector) {
                if let Ok(track) = self.parse_search_track_row(&row) {
                    tracks.push(track);
                }
            }
        }

        log::debug!("Parsed {} tracks from search results", tracks.len());
        Ok(tracks)
    }

    /// Parse album search results from AJAX response
    ///
    /// This parses the HTML returned by `/user/{username}/library/albums/search?ajax=1&query={query}`
    /// which contains chartlist tables with album results.
    pub fn parse_album_search_results(&self, document: &Html) -> Result<Vec<Album>> {
        let mut albums = Vec::new();

        // Search results use the same chartlist structure as library pages
        let table_selector = Selector::parse("table.chartlist").unwrap();
        let row_selector = Selector::parse("tbody tr").unwrap();

        let tables: Vec<_> = document.select(&table_selector).collect();
        log::debug!(
            "Found {} chartlist tables in album search results",
            tables.len()
        );

        for table in tables {
            for row in table.select(&row_selector) {
                if let Ok(album) = self.parse_search_album_row(&row) {
                    albums.push(album);
                }
            }
        }

        log::debug!("Parsed {} albums from search results", albums.len());
        Ok(albums)
    }

    /// Parse artist search results from AJAX response
    ///
    /// This parses the HTML returned by `/user/{username}/library/artists/search?ajax=1&query={query}`
    /// which contains chartlist tables with artist results.
    pub fn parse_artist_search_results(&self, document: &Html) -> Result<Vec<Artist>> {
        let mut artists = Vec::new();

        // Search results use the same chartlist structure as library pages
        let table_selector = Selector::parse("table.chartlist").unwrap();
        let row_selector = Selector::parse("tbody tr").unwrap();

        let tables: Vec<_> = document.select(&table_selector).collect();
        log::debug!(
            "Found {} chartlist tables in artist search results",
            tables.len()
        );

        for table in tables {
            for row in table.select(&row_selector) {
                if let Ok(artist) = self.parse_search_artist_row(&row) {
                    artists.push(artist);
                }
            }
        }

        log::debug!("Parsed {} artists from search results", artists.len());
        Ok(artists)
    }

    /// Parse a single artist row from search results
    fn parse_search_artist_row(&self, row: &scraper::ElementRef) -> Result<Artist> {
        // Extract artist name from the name column
        let name_selector = Selector::parse("td.chartlist-name a").unwrap();
        let name = row
            .select(&name_selector)
            .next()
            .ok_or(LastFmError::Parse(
                "Missing artist name in search results".to_string(),
            ))?
            .text()
            .collect::<String>()
            .trim()
            .to_string();

        // Extract playcount from the count bar
        let playcount = self.extract_playcount_from_row(row);

        Ok(Artist {
            name,
            playcount,
            timestamp: None, // Search results don't have timestamps
        })
    }

    /// Parse a single track row from search results
    fn parse_search_track_row(&self, row: &scraper::ElementRef) -> Result<Track> {
        // Extract track name using the standard chartlist structure
        let name = self.extract_name_from_row(row, "track")?;

        // Extract artist name from chartlist-artist column
        let artist_selector = Selector::parse(".chartlist-artist a").unwrap();
        let artist = row
            .select(&artist_selector)
            .next()
            .map(|el| el.text().collect::<String>().trim().to_string())
            .ok_or_else(|| {
                LastFmError::Parse("Missing artist name in search results".to_string())
            })?;

        // Extract playcount from the bar value
        let playcount = self.extract_playcount_from_row(row);

        // Search results typically don't have timestamps since they're aggregated
        let timestamp = None;

        // Try to extract album information if available in the search results
        let album = self.extract_album_from_search_row(row);
        let album_artist = self.extract_album_artist_from_search_row(row);

        Ok(Track {
            name,
            artist,
            playcount,
            timestamp,
            album,
            album_artist,
        })
    }

    /// Parse a single album row from search results
    fn parse_search_album_row(&self, row: &scraper::ElementRef) -> Result<Album> {
        // Extract album name using the standard chartlist structure
        let name = self.extract_name_from_row(row, "album")?;

        // Extract artist name from chartlist-artist column
        let artist_selector = Selector::parse(".chartlist-artist a").unwrap();
        let artist = row
            .select(&artist_selector)
            .next()
            .map(|el| el.text().collect::<String>().trim().to_string())
            .ok_or_else(|| {
                LastFmError::Parse("Missing artist name in album search results".to_string())
            })?;

        // Extract playcount from the bar value
        let playcount = self.extract_playcount_from_row(row);

        Ok(Album {
            name,
            artist,
            playcount,
            timestamp: None, // Search results don't have timestamps
        })
    }

    /// Extract album information from search track row
    fn extract_album_from_search_row(&self, row: &scraper::ElementRef) -> Option<String> {
        // Look for album information in hidden form inputs (similar to recent scrobbles)
        let album_input_selector = Selector::parse("input[name='album']").unwrap();
        if let Some(input) = row.select(&album_input_selector).next() {
            if let Some(value) = input.value().attr("value") {
                let album = value.trim().to_string();
                if !album.is_empty() {
                    return Some(album);
                }
            }
        }
        None
    }

    /// Extract album artist information from search track row
    fn extract_album_artist_from_search_row(&self, row: &scraper::ElementRef) -> Option<String> {
        // Look for album artist information in hidden form inputs
        let album_artist_input_selector = Selector::parse("input[name='album_artist']").unwrap();
        if let Some(input) = row.select(&album_artist_input_selector).next() {
            if let Some(value) = input.value().attr("value") {
                let album_artist = value.trim().to_string();
                if !album_artist.is_empty() {
                    return Some(album_artist);
                }
            }
        }
        None
    }

    // === SHARED PARSING UTILITIES ===

    /// Extract name from chartlist row (works for both tracks and albums)
    fn extract_name_from_row(&self, row: &scraper::ElementRef, item_type: &str) -> Result<String> {
        let name_selector = Selector::parse(".chartlist-name a").unwrap();
        let name = row
            .select(&name_selector)
            .next()
            .map(|el| el.text().collect::<String>().trim().to_string())
            .ok_or_else(|| LastFmError::Parse(format!("Missing {item_type} name")))?;
        Ok(name)
    }

    /// Extract playcount from chartlist row (works for both tracks and albums)
    fn extract_playcount_from_row(&self, row: &scraper::ElementRef) -> u32 {
        let playcount_selector = Selector::parse(".chartlist-count-bar-value").unwrap();
        let mut playcount = 1; // default fallback

        if let Some(element) = row.select(&playcount_selector).next() {
            let text = element.text().collect::<String>().trim().to_string();
            // Extract just the number part (before "scrobbles" if present)
            if let Some(number_part) = text.split_whitespace().next() {
                if let Ok(count) = number_part.parse::<u32>() {
                    playcount = count;
                }
            }
        }
        playcount
    }

    /// Parse pagination information from document
    pub fn parse_pagination(
        &self,
        document: &Html,
        _current_page: u32,
    ) -> Result<(bool, Option<u32>)> {
        // Different parts of Last.fm use slightly different pagination wrappers.
        // Prefer the more specific `.pagination-list` when present, otherwise fall back to `.pagination`.
        let pagination = [
            Selector::parse(".pagination-list").unwrap(),
            Selector::parse(".pagination").unwrap(),
        ]
        .into_iter()
        .find_map(|sel| document.select(&sel).next());

        if let Some(pagination) = pagination {
            // Try multiple possible selectors for next page link
            let next_selectors = [
                "a[aria-label=\"Next\"]",
                "a[aria-label=\"Next page\"]",
                "a[rel=\"next\"]",
                ".pagination-next a",
                "a:contains(\"Next\")",
                ".next a",
            ];

            let mut has_next = false;
            for selector_str in &next_selectors {
                if let Ok(selector) = Selector::parse(selector_str) {
                    if pagination.select(&selector).next().is_some() {
                        has_next = true;
                        break;
                    }
                }
            }

            // Try to extract total pages from pagination text
            let total_pages = self.extract_total_pages_from_pagination(&pagination);

            Ok((has_next, total_pages))
        } else {
            // No pagination found - single page
            Ok((false, Some(1)))
        }
    }

    /// Helper functions for pagination parsing
    fn extract_total_pages_from_pagination(&self, pagination: &scraper::ElementRef) -> Option<u32> {
        // Look for patterns like "Page 1 of 42"
        let text = pagination.text().collect::<String>();
        if let Some(of_pos) = text.find(" of ") {
            let after_of = &text[of_pos + 4..];
            if let Some(number_end) = after_of.find(|c: char| !c.is_ascii_digit()) {
                if let Ok(total) = after_of[..number_end].parse::<u32>() {
                    return Some(total);
                }
            } else if let Ok(total) = after_of.trim().parse::<u32>() {
                return Some(total);
            }
        }

        let extract_page_param = |href: &str| -> Option<u32> {
            let idx = href.find("page=")?;
            let after = &href[idx + "page=".len()..];
            let digits: String = after.chars().take_while(|c| c.is_ascii_digit()).collect();
            if digits.is_empty() {
                return None;
            }
            digits.parse::<u32>().ok()
        };

        // Fall back to extracting the maximum `page=` value found in pagination links.
        let link_selector = Selector::parse("a[href*=\"page=\"]").unwrap();
        let mut max_page = None::<u32>;
        for a in pagination.select(&link_selector) {
            if let Some(href) = a.value().attr("href") {
                if let Some(p) = extract_page_param(href) {
                    max_page = Some(max_page.map_or(p, |m| m.max(p)));
                }
            }

            let label = a.text().collect::<String>().trim().to_string();
            if !label.is_empty() && label.chars().all(|c| c.is_ascii_digit()) {
                if let Ok(p) = label.parse::<u32>() {
                    max_page = Some(max_page.map_or(p, |m| m.max(p)));
                }
            }
        }

        max_page
    }

    // === JSON PARSING METHODS ===
    // Removed unused JSON parsing method

    // === FIND HELPER METHODS ===

    pub fn find_timestamp_for_track(&self, _document: &Html, _track_name: &str) -> Option<u64> {
        // Implementation would search for timestamp data
        None
    }

    pub fn find_playcount_for_track(&self, document: &Html, track_name: &str) -> Result<u32> {
        // Look for chartlist-count-bar-value elements near the track
        let count_selector = Selector::parse(".chartlist-count-bar-value").unwrap();
        let link_selector = Selector::parse("a[href*=\"/music/\"]").unwrap();

        // Find all track links that match our track name
        for link in document.select(&link_selector) {
            let link_text = link.text().collect::<String>().trim().to_string();
            if link_text == track_name {
                if let Some(row) = self.find_ancestor_row(link) {
                    if let Some(count_element) = row.select(&count_selector).next() {
                        let text = count_element.text().collect::<String>().trim().to_string();
                        if let Some(number_part) = text.split_whitespace().next() {
                            if let Ok(count) = number_part.parse::<u32>() {
                                return Ok(count);
                            }
                        }
                    }
                }
            }
        }
        Err(LastFmError::Parse(format!(
            "Could not find playcount for track: {track_name}"
        )))
    }

    pub fn find_timestamp_for_album(&self, _document: &Html, _album_name: &str) -> Option<u64> {
        // Implementation would search for timestamp data
        None
    }

    pub fn find_playcount_for_album(&self, document: &Html, album_name: &str) -> Result<u32> {
        // Look for chartlist-count-bar-value elements near the album
        let count_selector = Selector::parse(".chartlist-count-bar-value").unwrap();
        let link_selector = Selector::parse("a[href*=\"/music/\"]").unwrap();

        // Find all album links that match our album name
        for link in document.select(&link_selector) {
            let link_text = link.text().collect::<String>().trim().to_string();
            if link_text == album_name {
                if let Some(row) = self.find_ancestor_row(link) {
                    if let Some(count_element) = row.select(&count_selector).next() {
                        let text = count_element.text().collect::<String>().trim().to_string();
                        if let Some(number_part) = text.split_whitespace().next() {
                            if let Ok(count) = number_part.parse::<u32>() {
                                return Ok(count);
                            }
                        }
                    }
                }
            }
        }
        Err(LastFmError::Parse(format!(
            "Could not find playcount for album: {album_name}"
        )))
    }

    pub fn find_ancestor_row<'a>(
        &self,
        element: scraper::ElementRef<'a>,
    ) -> Option<scraper::ElementRef<'a>> {
        let mut current = element;
        while let Some(parent) = current.parent() {
            if let Some(parent_elem) = scraper::ElementRef::wrap(parent) {
                if parent_elem.value().name() == "tr" {
                    return Some(parent_elem);
                }
                current = parent_elem;
            } else {
                break;
            }
        }
        None
    }

    /// Parse artists page from user's library
    pub fn parse_artists_page(&self, document: &Html, page_number: u32) -> Result<ArtistPage> {
        let mut artists = Vec::new();

        // Parse artists from chartlist table rows
        let table_selector = Selector::parse("table.chartlist").unwrap();
        let row_selector = Selector::parse("tr.js-link-block").unwrap();

        let tables: Vec<_> = document.select(&table_selector).collect();
        log::debug!("Found {} chartlist tables for artists", tables.len());

        for table in tables {
            for row in table.select(&row_selector) {
                if let Ok(artist) = self.parse_artist_row(&row) {
                    artists.push(artist);
                }
            }
        }

        log::debug!("Parsed {} artists from page {}", artists.len(), page_number);

        let (has_next_page, total_pages) = self.parse_pagination(document, page_number)?;

        Ok(ArtistPage {
            artists,
            page_number,
            has_next_page,
            total_pages,
        })
    }

    /// Parse a single artist row from the artist library table
    fn parse_artist_row(&self, row: &scraper::ElementRef) -> Result<Artist> {
        // Extract artist name from the name column
        let name_selector = Selector::parse("td.chartlist-name a").unwrap();
        let name = row
            .select(&name_selector)
            .next()
            .ok_or(LastFmError::Parse("Missing artist name".to_string()))?
            .text()
            .collect::<String>()
            .trim()
            .to_string();

        // Extract playcount from the count bar
        let count_selector = Selector::parse(".chartlist-count-bar").unwrap();
        let playcount = if let Some(count_element) = row.select(&count_selector).next() {
            let count_text = count_element.text().collect::<String>();
            self.extract_number_from_count_text(&count_text)
                .unwrap_or(0)
        } else {
            0
        };

        // Artists in library listings typically don't have individual timestamps
        let timestamp = None;

        Ok(Artist {
            name,
            playcount,
            timestamp,
        })
    }

    /// Extract numeric value from count text like "3,395 scrobbles"
    fn extract_number_from_count_text(&self, text: &str) -> Option<u32> {
        // Remove commas and extract the first numeric part
        let cleaned = text.replace(',', "");
        cleaned.split_whitespace().next()?.parse::<u32>().ok()
    }
}

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