lastfm_edit/
client.rs

1use crate::parsing::LastFmParser;
2use crate::session::LastFmEditSession;
3use crate::{
4    AlbumPage, ArtistAlbumsIterator, ArtistTracksIterator, AsyncPaginatedIterator, EditResponse,
5    LastFmError, RecentTracksIterator, Result, ScrobbleEdit, Track, TrackPage,
6};
7use http_client::{HttpClient, Request, Response};
8use http_types::{Method, Url};
9use scraper::{Html, Selector};
10use std::collections::HashMap;
11use std::fs;
12use std::path::Path;
13use std::sync::{Arc, Mutex};
14
15/// Main client for interacting with Last.fm's web interface.
16///
17/// This client handles authentication, session management, and provides methods for
18/// browsing user libraries and editing scrobble data through web scraping.
19///
20/// # Examples
21///
22/// ```rust,no_run
23/// use lastfm_edit::{LastFmEditClient, Result};
24///
25/// #[tokio::main]
26/// async fn main() -> Result<()> {
27///     // Create client with any HTTP implementation
28///     let http_client = http_client::native::NativeClient::new();
29///     let mut client = LastFmEditClient::new(Box::new(http_client));
30///
31///     // Login to Last.fm
32///     client.login("username", "password").await?;
33///
34///     // Check if authenticated
35///     assert!(client.is_logged_in());
36///
37///     Ok(())
38/// }
39/// ```
40pub struct LastFmEditClient {
41    client: Box<dyn HttpClient + Send + Sync>,
42    session: Arc<Mutex<LastFmEditSession>>,
43    rate_limit_patterns: Vec<String>,
44    debug_save_responses: bool,
45    parser: LastFmParser,
46}
47
48impl LastFmEditClient {
49    /// Create a new [`LastFmEditClient`] with the default Last.fm URL.
50    ///
51    /// **Note:** This creates an unauthenticated client. You must call [`login`](Self::login)
52    /// or [`restore_session`](Self::restore_session) before using most functionality.
53    ///
54    /// # Arguments
55    ///
56    /// * `client` - Any HTTP client implementation that implements [`HttpClient`]
57    ///
58    /// # Examples
59    ///
60    /// ```rust,no_run
61    /// use lastfm_edit::{LastFmEditClient, Result};
62    ///
63    /// #[tokio::main]
64    /// async fn main() -> Result<()> {
65    ///     let http_client = http_client::native::NativeClient::new();
66    ///     let mut client = LastFmEditClient::new(Box::new(http_client));
67    ///     client.login("username", "password").await?;
68    ///     Ok(())
69    /// }
70    /// ```
71    pub fn new(client: Box<dyn HttpClient + Send + Sync>) -> Self {
72        Self::with_base_url(client, "https://www.last.fm".to_string())
73    }
74
75    /// Create a new [`LastFmEditClient`] with a custom base URL.
76    ///
77    /// **Note:** This creates an unauthenticated client. You must call [`login`](Self::login)
78    /// or [`restore_session`](Self::restore_session) before using most functionality.
79    ///
80    /// This is useful for testing or if Last.fm changes their domain.
81    ///
82    /// # Arguments
83    ///
84    /// * `client` - Any HTTP client implementation
85    /// * `base_url` - The base URL for Last.fm (e.g., <https://www.last.fm>)
86    pub fn with_base_url(client: Box<dyn HttpClient + Send + Sync>, base_url: String) -> Self {
87        Self::with_rate_limit_patterns(
88            client,
89            base_url,
90            vec![
91                "you've tried to log in too many times".to_string(),
92                "you're requesting too many pages".to_string(),
93                "slow down".to_string(),
94                "too fast".to_string(),
95                "rate limit".to_string(),
96                "throttled".to_string(),
97                "temporarily blocked".to_string(),
98                "temporarily restricted".to_string(),
99                "captcha".to_string(),
100                "verify you're human".to_string(),
101                "prove you're not a robot".to_string(),
102                "security check".to_string(),
103                "service temporarily unavailable".to_string(),
104                "quota exceeded".to_string(),
105                "limit exceeded".to_string(),
106                "daily limit".to_string(),
107            ],
108        )
109    }
110
111    /// Create a new [`LastFmEditClient`] with custom rate limit detection patterns.
112    ///
113    /// # Arguments
114    ///
115    /// * `client` - Any HTTP client implementation
116    /// * `base_url` - The base URL for Last.fm
117    /// * `rate_limit_patterns` - Text patterns that indicate rate limiting in responses
118    pub fn with_rate_limit_patterns(
119        client: Box<dyn HttpClient + Send + Sync>,
120        base_url: String,
121        rate_limit_patterns: Vec<String>,
122    ) -> Self {
123        Self {
124            client,
125            session: Arc::new(Mutex::new(LastFmEditSession::new(
126                String::new(),
127                Vec::new(),
128                None,
129                base_url,
130            ))),
131            rate_limit_patterns,
132            debug_save_responses: std::env::var("LASTFM_DEBUG_SAVE_RESPONSES").is_ok(),
133            parser: LastFmParser::new(),
134        }
135    }
136
137    /// Create a new authenticated [`LastFmEditClient`] by logging in with username and password.
138    ///
139    /// This is a convenience method that combines client creation and login into one step.
140    ///
141    /// # Arguments
142    ///
143    /// * `client` - Any HTTP client implementation
144    /// * `username` - Last.fm username or email
145    /// * `password` - Last.fm password
146    ///
147    /// # Returns
148    ///
149    /// Returns an authenticated client on success, or [`LastFmError::Auth`] on failure.
150    ///
151    /// # Examples
152    ///
153    /// ```rust,no_run
154    /// use lastfm_edit::{LastFmEditClient, Result};
155    ///
156    /// #[tokio::main]
157    /// async fn main() -> Result<()> {
158    ///     let client = LastFmEditClient::login_with_credentials(
159    ///         Box::new(http_client::native::NativeClient::new()),
160    ///         "username",
161    ///         "password"
162    ///     ).await?;
163    ///     assert!(client.is_logged_in());
164    ///     Ok(())
165    /// }
166    /// ```
167    pub async fn login_with_credentials(
168        client: Box<dyn HttpClient + Send + Sync>,
169        username: &str,
170        password: &str,
171    ) -> Result<Self> {
172        let new_client = Self::new(client);
173        new_client.login(username, password).await?;
174        Ok(new_client)
175    }
176
177    /// Create a new [`LastFmEditClient`] by restoring a previously saved session.
178    ///
179    /// This allows you to resume a Last.fm session without requiring the user to log in again.
180    ///
181    /// # Arguments
182    ///
183    /// * `client` - Any HTTP client implementation
184    /// * `session` - Previously saved [`LastFmEditSession`]
185    ///
186    /// # Returns
187    ///
188    /// Returns a client with the restored session.
189    ///
190    /// # Examples
191    ///
192    /// ```rust,no_run
193    /// use lastfm_edit::{LastFmEditClient, LastFmEditSession};
194    ///
195    /// fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
196    ///     // Assume we have a saved session
197    ///     let session_json = std::fs::read_to_string("session.json")?;
198    ///     let session = LastFmEditSession::from_json(&session_json)?;
199    ///
200    ///     let client = LastFmEditClient::from_session(
201    ///         Box::new(http_client::native::NativeClient::new()),
202    ///         session
203    ///     );
204    ///     assert!(client.is_logged_in());
205    ///     Ok(())
206    /// }
207    /// ```
208    pub fn from_session(
209        client: Box<dyn HttpClient + Send + Sync>,
210        session: LastFmEditSession,
211    ) -> Self {
212        Self {
213            client,
214            session: Arc::new(Mutex::new(session)),
215            rate_limit_patterns: vec![
216                "you've tried to log in too many times".to_string(),
217                "you're requesting too many pages".to_string(),
218                "slow down".to_string(),
219                "too fast".to_string(),
220                "rate limit".to_string(),
221                "throttled".to_string(),
222                "temporarily blocked".to_string(),
223                "temporarily restricted".to_string(),
224                "captcha".to_string(),
225                "verify you're human".to_string(),
226                "prove you're not a robot".to_string(),
227                "security check".to_string(),
228                "service temporarily unavailable".to_string(),
229                "quota exceeded".to_string(),
230                "limit exceeded".to_string(),
231                "daily limit".to_string(),
232            ],
233            debug_save_responses: std::env::var("LASTFM_DEBUG_SAVE_RESPONSES").is_ok(),
234            parser: LastFmParser::new(),
235        }
236    }
237
238    /// Extract the current session state for persistence.
239    ///
240    /// This allows you to save the authentication state and restore it later
241    /// without requiring the user to log in again.
242    ///
243    /// # Returns
244    ///
245    /// Returns a [`LastFmEditSession`] that can be serialized and saved.
246    ///
247    /// # Examples
248    ///
249    /// ```rust,no_run
250    /// use lastfm_edit::{LastFmEditClient, Result};
251    ///
252    /// #[tokio::main]
253    /// async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
254    ///     let mut client = LastFmEditClient::new(Box::new(http_client::native::NativeClient::new()));
255    ///     client.login("username", "password").await?;
256    ///
257    ///     // Save session for later use
258    ///     let session = client.get_session();
259    ///     let session_json = session.to_json()?;
260    ///     std::fs::write("session.json", session_json)?;
261    ///     Ok(())
262    /// }
263    /// ```
264    pub fn get_session(&self) -> LastFmEditSession {
265        self.session.lock().unwrap().clone()
266    }
267
268    /// Restore session state from a previously saved [`LastFmEditSession`].
269    ///
270    /// This allows you to restore authentication state without logging in again.
271    ///
272    /// # Arguments
273    ///
274    /// * `session` - Previously saved session state
275    ///
276    /// # Examples
277    ///
278    /// ```rust,no_run
279    /// use lastfm_edit::{LastFmEditClient, LastFmEditSession};
280    ///
281    /// fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
282    ///     let mut client = LastFmEditClient::new(Box::new(http_client::native::NativeClient::new()));
283    ///
284    ///     // Restore from saved session
285    ///     let session_json = std::fs::read_to_string("session.json")?;
286    ///     let session = LastFmEditSession::from_json(&session_json)?;
287    ///     client.restore_session(session);
288    ///
289    ///     assert!(client.is_logged_in());
290    ///     Ok(())
291    /// }
292    /// ```
293    pub fn restore_session(&self, session: LastFmEditSession) {
294        *self.session.lock().unwrap() = session;
295    }
296
297    /// Authenticate with Last.fm using username and password.
298    ///
299    /// This method:
300    /// 1. Fetches the login page to extract CSRF tokens
301    /// 2. Submits the login form with credentials
302    /// 3. Validates the authentication by checking for session cookies
303    /// 4. Stores session data for subsequent requests
304    ///
305    /// # Arguments
306    ///
307    /// * `username` - Last.fm username or email
308    /// * `password` - Last.fm password
309    ///
310    /// # Returns
311    ///
312    /// Returns [`Ok(())`] on successful authentication, or [`LastFmError::Auth`] on failure.
313    ///
314    /// # Examples
315    ///
316    /// ```rust,no_run
317    /// # use lastfm_edit::{LastFmEditClient, Result};
318    /// # tokio_test::block_on(async {
319    /// let mut client = LastFmEditClient::new(Box::new(http_client::native::NativeClient::new()));
320    /// client.login("username", "password").await?;
321    /// assert!(client.is_logged_in());
322    /// # Ok::<(), lastfm_edit::LastFmError>(())
323    /// # });
324    /// ```
325    pub async fn login(&self, username: &str, password: &str) -> Result<()> {
326        // Get login page to extract CSRF token
327        let login_url = {
328            let session = self.session.lock().unwrap();
329            format!("{}/login", session.base_url)
330        };
331        let mut response = self.get(&login_url).await?;
332
333        // Extract any initial cookies from the login page
334        self.extract_cookies(&response);
335
336        let html = response
337            .body_string()
338            .await
339            .map_err(|e| LastFmError::Http(e.to_string()))?;
340
341        // Parse HTML synchronously to avoid holding parser state across await boundaries
342        let (csrf_token, next_field) = self.extract_login_form_data(&html)?;
343
344        // Submit login form
345        let mut form_data = HashMap::new();
346        form_data.insert("csrfmiddlewaretoken", csrf_token.as_str());
347        form_data.insert("username_or_email", username);
348        form_data.insert("password", password);
349
350        // Add 'next' field if present
351        if let Some(ref next_value) = next_field {
352            form_data.insert("next", next_value);
353        }
354
355        let mut request = Request::new(Method::Post, login_url.parse::<Url>().unwrap());
356        let _ = request.insert_header("Referer", &login_url);
357        {
358            let session = self.session.lock().unwrap();
359            let _ = request.insert_header("Origin", &session.base_url);
360        }
361        let _ = request.insert_header("Content-Type", "application/x-www-form-urlencoded");
362        let _ = request.insert_header(
363            "User-Agent",
364            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
365        );
366        let _ = request.insert_header(
367            "Accept",
368            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
369        );
370        let _ = request.insert_header("Accept-Language", "en-US,en;q=0.9");
371        let _ = request.insert_header("Accept-Encoding", "gzip, deflate, br");
372        let _ = request.insert_header("DNT", "1");
373        let _ = request.insert_header("Connection", "keep-alive");
374        let _ = request.insert_header("Upgrade-Insecure-Requests", "1");
375        let _ = request.insert_header(
376            "sec-ch-ua",
377            "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
378        );
379        let _ = request.insert_header("sec-ch-ua-mobile", "?0");
380        let _ = request.insert_header("sec-ch-ua-platform", "\"Linux\"");
381        let _ = request.insert_header("Sec-Fetch-Dest", "document");
382        let _ = request.insert_header("Sec-Fetch-Mode", "navigate");
383        let _ = request.insert_header("Sec-Fetch-Site", "same-origin");
384        let _ = request.insert_header("Sec-Fetch-User", "?1");
385
386        // Add any cookies we already have
387        {
388            let session = self.session.lock().unwrap();
389            if !session.cookies.is_empty() {
390                let cookie_header = session.cookies.join("; ");
391                let _ = request.insert_header("Cookie", &cookie_header);
392            }
393        }
394
395        // Convert form data to URL-encoded string
396        let form_string: String = form_data
397            .iter()
398            .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
399            .collect::<Vec<_>>()
400            .join("&");
401
402        request.set_body(form_string);
403
404        let mut response = self
405            .client
406            .send(request)
407            .await
408            .map_err(|e| LastFmError::Http(e.to_string()))?;
409
410        // Extract session cookies from login response
411        self.extract_cookies(&response);
412
413        log::debug!("Login response status: {}", response.status());
414
415        // If we get a 403, it might be rate limiting or auth failure
416        if response.status() == 403 {
417            // Get the response body to check if it's rate limiting
418            let response_html = response
419                .body_string()
420                .await
421                .map_err(|e| LastFmError::Http(e.to_string()))?;
422
423            // Look for rate limit indicators in the response
424            if self.is_rate_limit_response(&response_html) {
425                log::debug!("403 response appears to be rate limiting");
426                return Err(LastFmError::RateLimit { retry_after: 60 });
427            }
428            log::debug!("403 response appears to be authentication failure");
429
430            // Continue with the normal auth failure handling using the response_html
431            let login_error = self.parse_login_error(&response_html);
432            return Err(LastFmError::Auth(login_error));
433        }
434
435        // Check if we got a new sessionid that looks like a real Last.fm session
436        let has_real_session = {
437            let session = self.session.lock().unwrap();
438            session
439                .cookies
440                .iter()
441                .any(|cookie| cookie.starts_with("sessionid=.") && cookie.len() > 50)
442        };
443
444        if has_real_session && (response.status() == 302 || response.status() == 200) {
445            // We got a real session ID, login was successful
446            {
447                let mut session = self.session.lock().unwrap();
448                session.username = username.to_string();
449                session.csrf_token = Some(csrf_token);
450            }
451            log::debug!("Login successful - authenticated session established");
452            return Ok(());
453        }
454
455        // At this point, we didn't get a 403, so read the response body for other cases
456        let response_html = response
457            .body_string()
458            .await
459            .map_err(|e| LastFmError::Http(e.to_string()))?;
460
461        // Check if we were redirected away from login page (success) by parsing synchronously
462        let has_login_form = self.check_for_login_form(&response_html);
463
464        if !has_login_form && response.status() == 200 {
465            {
466                let mut session = self.session.lock().unwrap();
467                session.username = username.to_string();
468                session.csrf_token = Some(csrf_token);
469            }
470            Ok(())
471        } else {
472            // Parse error messages synchronously
473            let error_msg = self.parse_login_error(&response_html);
474            Err(LastFmError::Auth(error_msg))
475        }
476    }
477
478    /// Get the currently authenticated username.
479    ///
480    /// Returns an empty string if not logged in.
481    pub fn username(&self) -> String {
482        self.session.lock().unwrap().username.clone()
483    }
484
485    /// Check if the client is currently authenticated.
486    ///
487    /// Returns `true` if [`login`](Self::login) was successful and session is active.
488    pub fn is_logged_in(&self) -> bool {
489        self.session.lock().unwrap().is_valid()
490    }
491
492    /// Create an iterator for browsing an artist's tracks from the user's library.
493    ///
494    /// # Arguments
495    ///
496    /// * `artist` - The artist name to browse
497    ///
498    /// # Returns
499    ///
500    /// Returns an [`ArtistTracksIterator`] that implements [`AsyncPaginatedIterator`].
501    pub fn artist_tracks<'a>(&'a self, artist: &str) -> ArtistTracksIterator<'a> {
502        ArtistTracksIterator::new(self, artist.to_string())
503    }
504
505    /// Create an iterator for browsing an artist's albums from the user's library.
506    ///
507    /// # Arguments
508    ///
509    /// * `artist` - The artist name to browse
510    ///
511    /// # Returns
512    ///
513    /// Returns an [`ArtistAlbumsIterator`] that implements [`AsyncPaginatedIterator`].
514    pub fn artist_albums<'a>(&'a self, artist: &str) -> ArtistAlbumsIterator<'a> {
515        ArtistAlbumsIterator::new(self, artist.to_string())
516    }
517
518    /// Create an iterator for browsing the user's recent tracks.
519    ///
520    /// This provides access to the user's recent listening history with timestamps,
521    /// which is useful for finding tracks to edit.
522    ///
523    /// # Returns
524    ///
525    /// Returns a [`RecentTracksIterator`] that implements [`AsyncPaginatedIterator`].
526    pub fn recent_tracks<'a>(&'a self) -> RecentTracksIterator<'a> {
527        RecentTracksIterator::new(self)
528    }
529
530    /// Create an iterator for recent tracks starting from a specific page.
531    ///
532    /// This allows resuming pagination from an arbitrary page, useful for
533    /// continuing from where a previous iteration left off.
534    ///
535    /// # Arguments
536    ///
537    /// * `starting_page` - The page number to start from (1-indexed, minimum 1)
538    ///
539    /// # Returns
540    ///
541    /// Returns a [`RecentTracksIterator`] that implements [`AsyncPaginatedIterator`].
542    ///
543    /// # Examples
544    ///
545    /// ```rust,no_run
546    /// # use lastfm_edit::{LastFmEditClient, AsyncPaginatedIterator};
547    /// # tokio_test::block_on(async {
548    /// let mut client = LastFmEditClient::new(Box::new(http_client::native::NativeClient::new()));
549    /// // client.login(...).await?;
550    ///
551    /// // Resume from page 10
552    /// let mut recent = client.recent_tracks_from_page(10);
553    /// let tracks = recent.take(50).await?;
554    /// # Ok::<(), Box<dyn std::error::Error>>(())
555    /// # });
556    /// ```
557    pub fn recent_tracks_from_page<'a>(&'a self, starting_page: u32) -> RecentTracksIterator<'a> {
558        RecentTracksIterator::with_starting_page(self, starting_page)
559    }
560
561    /// Fetch recent scrobbles from the user's listening history
562    /// This gives us real scrobble data with timestamps for editing
563    pub async fn get_recent_scrobbles(&self, page: u32) -> Result<Vec<Track>> {
564        let url = {
565            let session = self.session.lock().unwrap();
566            format!(
567                "{}/user/{}/library?page={}",
568                session.base_url, session.username, page
569            )
570        };
571
572        log::debug!("Fetching recent scrobbles page {page}");
573        let mut response = self.get(&url).await?;
574        let content = response
575            .body_string()
576            .await
577            .map_err(|e| LastFmError::Http(e.to_string()))?;
578
579        log::debug!(
580            "Recent scrobbles response: {} status, {} chars",
581            response.status(),
582            content.len()
583        );
584
585        let document = Html::parse_document(&content);
586        self.parser.parse_recent_scrobbles(&document)
587    }
588
589    /// Find the most recent scrobble for a specific track
590    /// This searches through recent listening history to find real scrobble data
591    pub async fn find_recent_scrobble_for_track(
592        &self,
593        track_name: &str,
594        artist_name: &str,
595        max_pages: u32,
596    ) -> Result<Option<Track>> {
597        log::debug!("Searching for recent scrobble: '{track_name}' by '{artist_name}'");
598
599        for page in 1..=max_pages {
600            let scrobbles = self.get_recent_scrobbles(page).await?;
601
602            for scrobble in scrobbles {
603                if scrobble.name == track_name && scrobble.artist == artist_name {
604                    log::debug!(
605                        "Found recent scrobble: '{}' with timestamp {:?}",
606                        scrobble.name,
607                        scrobble.timestamp
608                    );
609                    return Ok(Some(scrobble));
610                }
611            }
612
613            // Small delay between pages to be polite
614        }
615
616        log::debug!(
617            "No recent scrobble found for '{track_name}' by '{artist_name}' in {max_pages} pages"
618        );
619        Ok(None)
620    }
621
622    pub async fn edit_scrobble(&self, edit: &ScrobbleEdit) -> Result<EditResponse> {
623        self.edit_scrobble_with_retry(edit, 3).await
624    }
625
626    pub async fn edit_scrobble_with_retry(
627        &self,
628        edit: &ScrobbleEdit,
629        max_retries: u32,
630    ) -> Result<EditResponse> {
631        let mut retries = 0;
632
633        loop {
634            match self.edit_scrobble_impl(edit).await {
635                Ok(result) => return Ok(result),
636                Err(LastFmError::RateLimit { retry_after }) => {
637                    if retries >= max_retries {
638                        log::warn!("Max retries ({max_retries}) exceeded for edit operation");
639                        return Err(LastFmError::RateLimit { retry_after });
640                    }
641
642                    let delay = std::cmp::min(retry_after, 2_u64.pow(retries + 1) * 5);
643                    log::info!(
644                        "Edit rate limited. Waiting {} seconds before retry {} of {}",
645                        delay,
646                        retries + 1,
647                        max_retries
648                    );
649                    // Rate limit delay would go here
650                    retries += 1;
651                }
652                Err(other_error) => return Err(other_error),
653            }
654        }
655    }
656
657    async fn edit_scrobble_impl(&self, edit: &ScrobbleEdit) -> Result<EditResponse> {
658        if !self.is_logged_in() {
659            return Err(LastFmError::Auth(
660                "Must be logged in to edit scrobbles".to_string(),
661            ));
662        }
663
664        let edit_url = {
665            let session = self.session.lock().unwrap();
666            format!(
667                "{}/user/{}/library/edit?edited-variation=library-track-scrobble",
668                session.base_url, session.username
669            )
670        };
671
672        log::debug!("Getting fresh CSRF token for edit");
673
674        // First request: Get the edit form to extract fresh CSRF token
675        let form_html = self.get_edit_form_html(&edit_url).await?;
676
677        // Parse HTML to get fresh CSRF token - do parsing synchronously
678        let form_document = Html::parse_document(&form_html);
679        let fresh_csrf_token = self.extract_csrf_token(&form_document)?;
680
681        log::debug!("Submitting edit with fresh token");
682
683        let mut form_data = HashMap::new();
684
685        // Add fresh CSRF token (required)
686        form_data.insert("csrfmiddlewaretoken", fresh_csrf_token.as_str());
687
688        // Include ALL form fields as they were extracted from the track page
689        form_data.insert("track_name_original", &edit.track_name_original);
690        form_data.insert("track_name", &edit.track_name);
691        form_data.insert("artist_name_original", &edit.artist_name_original);
692        form_data.insert("artist_name", &edit.artist_name);
693        form_data.insert("album_name_original", &edit.album_name_original);
694        form_data.insert("album_name", &edit.album_name);
695        form_data.insert(
696            "album_artist_name_original",
697            &edit.album_artist_name_original,
698        );
699        form_data.insert("album_artist_name", &edit.album_artist_name);
700
701        // ALWAYS include timestamp - Last.fm requires it even with edit_all=true
702        let timestamp_str = edit.timestamp.to_string();
703        form_data.insert("timestamp", &timestamp_str);
704
705        // Edit flags
706        if edit.edit_all {
707            form_data.insert("edit_all", "1");
708        }
709        form_data.insert("submit", "edit-scrobble");
710        form_data.insert("ajax", "1");
711
712        log::debug!(
713            "Editing scrobble: '{}' -> '{}'",
714            edit.track_name_original,
715            edit.track_name
716        );
717        {
718            let session = self.session.lock().unwrap();
719            log::trace!("Session cookies count: {}", session.cookies.len());
720        }
721
722        let mut request = Request::new(Method::Post, edit_url.parse::<Url>().unwrap());
723
724        // Add comprehensive headers matching your browser request
725        let _ = request.insert_header("Accept", "*/*");
726        let _ = request.insert_header("Accept-Language", "en-US,en;q=0.9");
727        let _ = request.insert_header(
728            "Content-Type",
729            "application/x-www-form-urlencoded;charset=UTF-8",
730        );
731        let _ = request.insert_header("Priority", "u=1, i");
732        let _ = request.insert_header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36");
733        let _ = request.insert_header("X-Requested-With", "XMLHttpRequest");
734        let _ = request.insert_header("Sec-Fetch-Dest", "empty");
735        let _ = request.insert_header("Sec-Fetch-Mode", "cors");
736        let _ = request.insert_header("Sec-Fetch-Site", "same-origin");
737        let _ = request.insert_header(
738            "sec-ch-ua",
739            "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
740        );
741        let _ = request.insert_header("sec-ch-ua-mobile", "?0");
742        let _ = request.insert_header("sec-ch-ua-platform", "\"Linux\"");
743
744        // Add session cookies
745        {
746            let session = self.session.lock().unwrap();
747            if !session.cookies.is_empty() {
748                let cookie_header = session.cookies.join("; ");
749                let _ = request.insert_header("Cookie", &cookie_header);
750            }
751        }
752
753        // Add referer header - use the current artist being edited
754        {
755            let session = self.session.lock().unwrap();
756            let _ = request.insert_header(
757                "Referer",
758                format!("{}/user/{}/library", session.base_url, session.username),
759            );
760        }
761
762        // Convert form data to URL-encoded string
763        let form_string: String = form_data
764            .iter()
765            .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
766            .collect::<Vec<_>>()
767            .join("&");
768
769        request.set_body(form_string);
770
771        let mut response = self
772            .client
773            .send(request)
774            .await
775            .map_err(|e| LastFmError::Http(e.to_string()))?;
776
777        log::debug!("Edit response status: {}", response.status());
778
779        let response_text = response
780            .body_string()
781            .await
782            .map_err(|e| LastFmError::Http(e.to_string()))?;
783
784        // Parse the HTML response to check for actual success/failure
785        let document = Html::parse_document(&response_text);
786
787        // Check for success indicator
788        let success_selector = Selector::parse(".alert-success").unwrap();
789        let error_selector = Selector::parse(".alert-danger, .alert-error, .error").unwrap();
790
791        let has_success_alert = document.select(&success_selector).next().is_some();
792        let has_error_alert = document.select(&error_selector).next().is_some();
793
794        // Also check if we can see the edited track in the response
795        // The response contains the track data in a table format within a script template
796        let mut actual_track_name = None;
797        let mut actual_album_name = None;
798
799        // Try direct selectors first
800        let track_name_selector = Selector::parse("td.chartlist-name a").unwrap();
801        let album_name_selector = Selector::parse("td.chartlist-album a").unwrap();
802
803        if let Some(track_element) = document.select(&track_name_selector).next() {
804            actual_track_name = Some(track_element.text().collect::<String>().trim().to_string());
805        }
806
807        if let Some(album_element) = document.select(&album_name_selector).next() {
808            actual_album_name = Some(album_element.text().collect::<String>().trim().to_string());
809        }
810
811        // If not found, try extracting from the raw response text using generic patterns
812        if actual_track_name.is_none() || actual_album_name.is_none() {
813            // Look for track name in href="/music/{artist}/_/{track}"
814            // Use regex to find track URLs
815            let track_pattern = regex::Regex::new(r#"href="/music/[^"]+/_/([^"]+)""#).unwrap();
816            if let Some(captures) = track_pattern.captures(&response_text) {
817                if let Some(track_match) = captures.get(1) {
818                    let raw_track = track_match.as_str();
819                    // URL decode the track name
820                    let decoded_track = urlencoding::decode(raw_track)
821                        .unwrap_or_else(|_| raw_track.into())
822                        .replace("+", " ");
823                    actual_track_name = Some(decoded_track);
824                }
825            }
826
827            // Look for album name in href="/music/{artist}/{album}"
828            // Find album links that are not track links (don't contain /_/)
829            let album_pattern =
830                regex::Regex::new(r#"href="/music/[^"]+/([^"/_]+)"[^>]*>[^<]*</a>"#).unwrap();
831            if let Some(captures) = album_pattern.captures(&response_text) {
832                if let Some(album_match) = captures.get(1) {
833                    let raw_album = album_match.as_str();
834                    // URL decode the album name
835                    let decoded_album = urlencoding::decode(raw_album)
836                        .unwrap_or_else(|_| raw_album.into())
837                        .replace("+", " ");
838                    actual_album_name = Some(decoded_album);
839                }
840            }
841        }
842
843        log::debug!(
844            "Response analysis: success_alert={}, error_alert={}, track='{}', album='{}'",
845            has_success_alert,
846            has_error_alert,
847            actual_track_name.as_deref().unwrap_or("not found"),
848            actual_album_name.as_deref().unwrap_or("not found")
849        );
850
851        // Determine if edit was truly successful
852        let final_success = response.status().is_success() && has_success_alert && !has_error_alert;
853
854        // Create detailed message
855        let message = if has_error_alert {
856            // Extract error message
857            if let Some(error_element) = document.select(&error_selector).next() {
858                Some(format!(
859                    "Edit failed: {}",
860                    error_element.text().collect::<String>().trim()
861                ))
862            } else {
863                Some("Edit failed with unknown error".to_string())
864            }
865        } else if final_success {
866            Some(format!(
867                "Edit successful - Track: '{}', Album: '{}'",
868                actual_track_name.as_deref().unwrap_or("unknown"),
869                actual_album_name.as_deref().unwrap_or("unknown")
870            ))
871        } else {
872            Some(format!("Edit failed with status: {}", response.status()))
873        };
874
875        Ok(EditResponse {
876            success: final_success,
877            message,
878        })
879    }
880
881    /// Fetch raw HTML content for edit form page
882    /// This separates HTTP fetching from parsing to avoid Send/Sync issues
883    async fn get_edit_form_html(&self, edit_url: &str) -> Result<String> {
884        let mut form_response = self.get(edit_url).await?;
885        let form_html = form_response
886            .body_string()
887            .await
888            .map_err(|e| LastFmError::Http(e.to_string()))?;
889
890        log::debug!("Edit form response status: {}", form_response.status());
891        Ok(form_html)
892    }
893
894    /// Load prepopulated form values for editing a specific track
895    /// This extracts scrobble data directly from the track page forms
896    pub async fn load_edit_form_values(
897        &self,
898        track_name: &str,
899        artist_name: &str,
900    ) -> Result<crate::ScrobbleEdit> {
901        log::debug!("Loading edit form values for '{track_name}' by '{artist_name}'");
902
903        // Get the specific track page to find scrobble forms
904        // Add +noredirect to avoid redirects as per lastfm-bulk-edit approach
905        // Use the correct URL format with underscore: artist/_/track
906        let track_url = {
907            let session = self.session.lock().unwrap();
908            format!(
909                "{}/user/{}/library/music/+noredirect/{}/_/{}",
910                session.base_url,
911                session.username,
912                urlencoding::encode(artist_name),
913                urlencoding::encode(track_name)
914            )
915        };
916
917        log::debug!("Fetching track page: {track_url}");
918
919        let mut response = self.get(&track_url).await?;
920        let html = response
921            .body_string()
922            .await
923            .map_err(|e| crate::LastFmError::Http(e.to_string()))?;
924
925        let document = Html::parse_document(&html);
926
927        // Extract scrobble data directly from the track page forms
928        self.extract_scrobble_data_from_track_page(&document, track_name, artist_name)
929    }
930
931    /// Extract scrobble edit data directly from track page forms
932    /// Based on the approach used in lastfm-bulk-edit
933    fn extract_scrobble_data_from_track_page(
934        &self,
935        document: &Html,
936        expected_track: &str,
937        expected_artist: &str,
938    ) -> Result<crate::ScrobbleEdit> {
939        // Look for the chartlist table that contains scrobbles
940        let table_selector =
941            Selector::parse("table.chartlist:not(.chartlist__placeholder)").unwrap();
942        let table = document.select(&table_selector).next().ok_or_else(|| {
943            crate::LastFmError::Parse("No chartlist table found on track page".to_string())
944        })?;
945
946        // Look for table rows that contain scrobble edit forms
947        let row_selector = Selector::parse("tr").unwrap();
948        for row in table.select(&row_selector) {
949            // Check if this row has a count bar link (means it's an aggregation, not individual scrobbles)
950            let count_bar_link_selector = Selector::parse(".chartlist-count-bar-link").unwrap();
951            if row.select(&count_bar_link_selector).next().is_some() {
952                log::debug!("Found count bar link, skipping aggregated row");
953                continue;
954            }
955
956            // Look for scrobble edit form in this row
957            let form_selector = Selector::parse("form[data-edit-scrobble]").unwrap();
958            if let Some(form) = row.select(&form_selector).next() {
959                // Extract all form values directly
960                let extract_form_value = |name: &str| -> Option<String> {
961                    let selector = Selector::parse(&format!("input[name='{name}']")).unwrap();
962                    form.select(&selector)
963                        .next()
964                        .and_then(|input| input.value().attr("value"))
965                        .map(|s| s.to_string())
966                };
967
968                // Get the track and artist from this form
969                let form_track = extract_form_value("track_name").unwrap_or_default();
970                let form_artist = extract_form_value("artist_name").unwrap_or_default();
971                let form_album = extract_form_value("album_name").unwrap_or_default();
972                let form_album_artist =
973                    extract_form_value("album_artist_name").unwrap_or_else(|| form_artist.clone());
974                let form_timestamp = extract_form_value("timestamp").unwrap_or_default();
975
976                log::debug!(
977                    "Found scrobble form - Track: '{form_track}', Artist: '{form_artist}', Album: '{form_album}', Timestamp: {form_timestamp}"
978                );
979
980                // Check if this form matches the expected track and artist
981                if form_track == expected_track && form_artist == expected_artist {
982                    let timestamp = form_timestamp.parse::<u64>().map_err(|_| {
983                        crate::LastFmError::Parse("Invalid timestamp in form".to_string())
984                    })?;
985
986                    log::debug!(
987                        "✅ Found matching scrobble form for '{expected_track}' by '{expected_artist}'"
988                    );
989
990                    // Create ScrobbleEdit with the extracted values
991                    return Ok(crate::ScrobbleEdit::new(
992                        form_track.clone(),
993                        form_album.clone(),
994                        form_artist.clone(),
995                        form_album_artist.clone(),
996                        form_track,
997                        form_album,
998                        form_artist,
999                        form_album_artist,
1000                        timestamp,
1001                        true,
1002                    ));
1003                }
1004            }
1005        }
1006
1007        Err(crate::LastFmError::Parse(format!(
1008            "No scrobble form found for track '{expected_track}' by '{expected_artist}'"
1009        )))
1010    }
1011
1012    /// Get tracks from a specific album page
1013    /// This makes a single request to the album page and extracts track data
1014    pub async fn get_album_tracks(
1015        &self,
1016        album_name: &str,
1017        artist_name: &str,
1018    ) -> Result<Vec<Track>> {
1019        log::debug!("Getting tracks from album '{album_name}' by '{artist_name}'");
1020
1021        // Get the album page directly - this should contain track listings
1022        let album_url = {
1023            let session = self.session.lock().unwrap();
1024            format!(
1025                "{}/user/{}/library/music/{}/{}",
1026                session.base_url,
1027                session.username,
1028                urlencoding::encode(artist_name),
1029                urlencoding::encode(album_name)
1030            )
1031        };
1032
1033        log::debug!("Fetching album page: {album_url}");
1034
1035        let mut response = self.get(&album_url).await?;
1036        let html = response
1037            .body_string()
1038            .await
1039            .map_err(|e| LastFmError::Http(e.to_string()))?;
1040
1041        let document = Html::parse_document(&html);
1042
1043        // Use the shared track extraction function
1044        let tracks = self
1045            .parser
1046            .extract_tracks_from_document(&document, artist_name)?;
1047
1048        log::debug!(
1049            "Successfully parsed {} tracks from album page",
1050            tracks.len()
1051        );
1052        Ok(tracks)
1053    }
1054
1055    /// Edit album metadata by updating scrobbles with new album name
1056    /// This edits ALL tracks from the album that are found in recent scrobbles
1057    pub async fn edit_album(
1058        &self,
1059        old_album_name: &str,
1060        new_album_name: &str,
1061        artist_name: &str,
1062    ) -> Result<EditResponse> {
1063        log::debug!("Editing album '{old_album_name}' -> '{new_album_name}' by '{artist_name}'");
1064
1065        // Get all tracks from the album page
1066        let tracks = self.get_album_tracks(old_album_name, artist_name).await?;
1067
1068        if tracks.is_empty() {
1069            return Ok(EditResponse {
1070                success: false,
1071                message: Some(format!(
1072                    "No tracks found for album '{old_album_name}' by '{artist_name}'. Make sure the album name matches exactly."
1073                )),
1074            });
1075        }
1076
1077        log::info!(
1078            "Found {} tracks in album '{}'",
1079            tracks.len(),
1080            old_album_name
1081        );
1082
1083        let mut successful_edits = 0;
1084        let mut failed_edits = 0;
1085        let mut error_messages = Vec::new();
1086        let mut skipped_tracks = 0;
1087
1088        // For each track, try to load and edit it
1089        for (index, track) in tracks.iter().enumerate() {
1090            log::debug!(
1091                "Processing track {}/{}: '{}'",
1092                index + 1,
1093                tracks.len(),
1094                track.name
1095            );
1096
1097            match self.load_edit_form_values(&track.name, artist_name).await {
1098                Ok(mut edit_data) => {
1099                    // Update the album name
1100                    edit_data.album_name = new_album_name.to_string();
1101
1102                    // Perform the edit
1103                    match self.edit_scrobble(&edit_data).await {
1104                        Ok(response) => {
1105                            if response.success {
1106                                successful_edits += 1;
1107                                log::info!("✅ Successfully edited track '{}'", track.name);
1108                            } else {
1109                                failed_edits += 1;
1110                                let error_msg = format!(
1111                                    "Failed to edit track '{}': {}",
1112                                    track.name,
1113                                    response
1114                                        .message
1115                                        .unwrap_or_else(|| "Unknown error".to_string())
1116                                );
1117                                error_messages.push(error_msg);
1118                                log::debug!("❌ {}", error_messages.last().unwrap());
1119                            }
1120                        }
1121                        Err(e) => {
1122                            failed_edits += 1;
1123                            let error_msg = format!("Error editing track '{}': {}", track.name, e);
1124                            error_messages.push(error_msg);
1125                            log::info!("❌ {}", error_messages.last().unwrap());
1126                        }
1127                    }
1128                }
1129                Err(e) => {
1130                    skipped_tracks += 1;
1131                    log::debug!("Could not load edit form for track '{}': {e}", track.name);
1132                    // Continue to next track - some tracks might not be in recent scrobbles
1133                }
1134            }
1135
1136            // Add delay between edits to be respectful to the server
1137        }
1138
1139        let total_processed = successful_edits + failed_edits;
1140        let success = successful_edits > 0 && failed_edits == 0;
1141
1142        let message = if success {
1143            Some(format!(
1144                "Successfully renamed album '{old_album_name}' to '{new_album_name}' for all {successful_edits} editable tracks ({skipped_tracks} tracks were not in recent scrobbles)"
1145            ))
1146        } else if successful_edits > 0 {
1147            Some(format!(
1148                "Partially successful: {} of {} editable tracks renamed ({} skipped, {} failed). Errors: {}",
1149                successful_edits,
1150                total_processed,
1151                skipped_tracks,
1152                failed_edits,
1153                error_messages.join("; ")
1154            ))
1155        } else if total_processed == 0 {
1156            Some(format!(
1157                "No editable tracks found for album '{}' by '{}'. All {} tracks were skipped because they're not in recent scrobbles.",
1158                old_album_name, artist_name, tracks.len()
1159            ))
1160        } else {
1161            Some(format!(
1162                "Failed to rename any tracks. Errors: {}",
1163                error_messages.join("; ")
1164            ))
1165        };
1166
1167        Ok(EditResponse { success, message })
1168    }
1169
1170    /// Edit artist metadata by updating scrobbles with new artist name
1171    /// This edits ALL tracks from the artist that are found in recent scrobbles
1172    pub async fn edit_artist(
1173        &self,
1174        old_artist_name: &str,
1175        new_artist_name: &str,
1176    ) -> Result<EditResponse> {
1177        log::debug!("Editing artist '{old_artist_name}' -> '{new_artist_name}'");
1178
1179        // Get all tracks from the artist using the iterator
1180        let mut tracks = Vec::new();
1181        let mut iterator = self.artist_tracks(old_artist_name);
1182
1183        // Collect tracks (limit to reasonable number to avoid infinite processing)
1184        while tracks.len() < 200 {
1185            match iterator.next().await {
1186                Ok(Some(track)) => tracks.push(track),
1187                Ok(None) => break,
1188                Err(e) => {
1189                    log::warn!("Error fetching artist tracks: {e}");
1190                    break;
1191                }
1192            }
1193        }
1194
1195        if tracks.is_empty() {
1196            return Ok(EditResponse {
1197                success: false,
1198                message: Some(format!(
1199                    "No tracks found for artist '{old_artist_name}'. Make sure the artist name matches exactly."
1200                )),
1201            });
1202        }
1203
1204        log::info!(
1205            "Found {} tracks for artist '{}'",
1206            tracks.len(),
1207            old_artist_name
1208        );
1209
1210        let mut successful_edits = 0;
1211        let mut failed_edits = 0;
1212        let mut error_messages = Vec::new();
1213        let mut skipped_tracks = 0;
1214
1215        // For each track, try to load and edit it
1216        for (index, track) in tracks.iter().enumerate() {
1217            log::debug!(
1218                "Processing track {}/{}: '{}'",
1219                index + 1,
1220                tracks.len(),
1221                track.name
1222            );
1223
1224            match self
1225                .load_edit_form_values(&track.name, old_artist_name)
1226                .await
1227            {
1228                Ok(mut edit_data) => {
1229                    // Update the artist name and album artist name
1230                    edit_data.artist_name = new_artist_name.to_string();
1231                    edit_data.album_artist_name = new_artist_name.to_string();
1232
1233                    // Perform the edit
1234                    match self.edit_scrobble(&edit_data).await {
1235                        Ok(response) => {
1236                            if response.success {
1237                                successful_edits += 1;
1238                                log::info!("✅ Successfully edited track '{}'", track.name);
1239                            } else {
1240                                failed_edits += 1;
1241                                let error_msg = format!(
1242                                    "Failed to edit track '{}': {}",
1243                                    track.name,
1244                                    response
1245                                        .message
1246                                        .unwrap_or_else(|| "Unknown error".to_string())
1247                                );
1248                                error_messages.push(error_msg);
1249                                log::debug!("❌ {}", error_messages.last().unwrap());
1250                            }
1251                        }
1252                        Err(e) => {
1253                            failed_edits += 1;
1254                            let error_msg = format!("Error editing track '{}': {}", track.name, e);
1255                            error_messages.push(error_msg);
1256                            log::info!("❌ {}", error_messages.last().unwrap());
1257                        }
1258                    }
1259                }
1260                Err(e) => {
1261                    skipped_tracks += 1;
1262                    log::debug!("Could not load edit form for track '{}': {e}", track.name);
1263                    // Continue to next track - some tracks might not be in recent scrobbles
1264                }
1265            }
1266
1267            // Add delay between edits to be respectful to the server
1268        }
1269
1270        let total_processed = successful_edits + failed_edits;
1271        let success = successful_edits > 0 && failed_edits == 0;
1272
1273        let message = if success {
1274            Some(format!(
1275                "Successfully renamed artist '{old_artist_name}' to '{new_artist_name}' for all {successful_edits} editable tracks ({skipped_tracks} tracks were not in recent scrobbles)"
1276            ))
1277        } else if successful_edits > 0 {
1278            Some(format!(
1279                "Partially successful: {} of {} editable tracks renamed ({} skipped, {} failed). Errors: {}",
1280                successful_edits,
1281                total_processed,
1282                skipped_tracks,
1283                failed_edits,
1284                error_messages.join("; ")
1285            ))
1286        } else if total_processed == 0 {
1287            Some(format!(
1288                "No editable tracks found for artist '{}'. All {} tracks were skipped because they're not in recent scrobbles.",
1289                old_artist_name, tracks.len()
1290            ))
1291        } else {
1292            Some(format!(
1293                "Failed to rename any tracks. Errors: {}",
1294                error_messages.join("; ")
1295            ))
1296        };
1297
1298        Ok(EditResponse { success, message })
1299    }
1300
1301    /// Edit artist metadata for a specific track only
1302    /// This edits only the specified track if found in recent scrobbles
1303    pub async fn edit_artist_for_track(
1304        &self,
1305        track_name: &str,
1306        old_artist_name: &str,
1307        new_artist_name: &str,
1308    ) -> Result<EditResponse> {
1309        log::debug!("Editing artist for track '{track_name}' from '{old_artist_name}' -> '{new_artist_name}'");
1310
1311        match self.load_edit_form_values(track_name, old_artist_name).await {
1312            Ok(mut edit_data) => {
1313                // Update the artist name and album artist name
1314                edit_data.artist_name = new_artist_name.to_string();
1315                edit_data.album_artist_name = new_artist_name.to_string();
1316
1317                log::info!("Updating artist for track '{track_name}' from '{old_artist_name}' to '{new_artist_name}'");
1318
1319                // Perform the edit
1320                match self.edit_scrobble(&edit_data).await {
1321                    Ok(response) => {
1322                        if response.success {
1323                            Ok(EditResponse {
1324                                success: true,
1325                                message: Some(format!(
1326                                    "Successfully renamed artist for track '{track_name}' from '{old_artist_name}' to '{new_artist_name}'"
1327                                )),
1328                            })
1329                        } else {
1330                            Ok(EditResponse {
1331                                success: false,
1332                                message: Some(format!(
1333                                    "Failed to rename artist for track '{track_name}': {}",
1334                                    response.message.unwrap_or_else(|| "Unknown error".to_string())
1335                                )),
1336                            })
1337                        }
1338                    }
1339                    Err(e) => Ok(EditResponse {
1340                        success: false,
1341                        message: Some(format!("Error editing track '{track_name}': {e}")),
1342                    }),
1343                }
1344            }
1345            Err(e) => Ok(EditResponse {
1346                success: false,
1347                message: Some(format!(
1348                    "Could not load edit form for track '{track_name}' by '{old_artist_name}': {e}. The track may not be in your recent scrobbles."
1349                )),
1350            }),
1351        }
1352    }
1353
1354    /// Edit artist metadata for all tracks in a specific album
1355    /// This edits ALL tracks from the specified album that are found in recent scrobbles
1356    pub async fn edit_artist_for_album(
1357        &self,
1358        album_name: &str,
1359        old_artist_name: &str,
1360        new_artist_name: &str,
1361    ) -> Result<EditResponse> {
1362        log::debug!("Editing artist for album '{album_name}' from '{old_artist_name}' -> '{new_artist_name}'");
1363
1364        // Get all tracks from the album page
1365        let tracks = self.get_album_tracks(album_name, old_artist_name).await?;
1366
1367        if tracks.is_empty() {
1368            return Ok(EditResponse {
1369                success: false,
1370                message: Some(format!(
1371                    "No tracks found for album '{album_name}' by '{old_artist_name}'. Make sure the album name matches exactly."
1372                )),
1373            });
1374        }
1375
1376        log::info!(
1377            "Found {} tracks in album '{}' by '{}'",
1378            tracks.len(),
1379            album_name,
1380            old_artist_name
1381        );
1382
1383        let mut successful_edits = 0;
1384        let mut failed_edits = 0;
1385        let mut error_messages = Vec::new();
1386        let mut skipped_tracks = 0;
1387
1388        // For each track, try to load and edit it
1389        for (index, track) in tracks.iter().enumerate() {
1390            log::debug!(
1391                "Processing track {}/{}: '{}'",
1392                index + 1,
1393                tracks.len(),
1394                track.name
1395            );
1396
1397            match self
1398                .load_edit_form_values(&track.name, old_artist_name)
1399                .await
1400            {
1401                Ok(mut edit_data) => {
1402                    // Update the artist name and album artist name
1403                    edit_data.artist_name = new_artist_name.to_string();
1404                    edit_data.album_artist_name = new_artist_name.to_string();
1405
1406                    // Perform the edit
1407                    match self.edit_scrobble(&edit_data).await {
1408                        Ok(response) => {
1409                            if response.success {
1410                                successful_edits += 1;
1411                                log::info!("✅ Successfully edited track '{}'", track.name);
1412                            } else {
1413                                failed_edits += 1;
1414                                let error_msg = format!(
1415                                    "Failed to edit track '{}': {}",
1416                                    track.name,
1417                                    response
1418                                        .message
1419                                        .unwrap_or_else(|| "Unknown error".to_string())
1420                                );
1421                                error_messages.push(error_msg);
1422                                log::debug!("❌ {}", error_messages.last().unwrap());
1423                            }
1424                        }
1425                        Err(e) => {
1426                            failed_edits += 1;
1427                            let error_msg = format!("Error editing track '{}': {}", track.name, e);
1428                            error_messages.push(error_msg);
1429                            log::info!("❌ {}", error_messages.last().unwrap());
1430                        }
1431                    }
1432                }
1433                Err(e) => {
1434                    skipped_tracks += 1;
1435                    log::debug!("Could not load edit form for track '{}': {e}", track.name);
1436                    // Continue to next track - some tracks might not be in recent scrobbles
1437                }
1438            }
1439
1440            // Add delay between edits to be respectful to the server
1441        }
1442
1443        let total_processed = successful_edits + failed_edits;
1444        let success = successful_edits > 0 && failed_edits == 0;
1445
1446        let message = if success {
1447            Some(format!(
1448                "Successfully renamed artist for album '{album_name}' from '{old_artist_name}' to '{new_artist_name}' for all {successful_edits} editable tracks ({skipped_tracks} tracks were not in recent scrobbles)"
1449            ))
1450        } else if successful_edits > 0 {
1451            Some(format!(
1452                "Partially successful: {} of {} editable tracks renamed ({} skipped, {} failed). Errors: {}",
1453                successful_edits,
1454                total_processed,
1455                skipped_tracks,
1456                failed_edits,
1457                error_messages.join("; ")
1458            ))
1459        } else if total_processed == 0 {
1460            Some(format!(
1461                "No editable tracks found for album '{album_name}' by '{old_artist_name}'. All {} tracks were skipped because they're not in recent scrobbles.",
1462                tracks.len()
1463            ))
1464        } else {
1465            Some(format!(
1466                "Failed to rename any tracks. Errors: {}",
1467                error_messages.join("; ")
1468            ))
1469        };
1470
1471        Ok(EditResponse { success, message })
1472    }
1473
1474    pub async fn get_artist_tracks_page(&self, artist: &str, page: u32) -> Result<TrackPage> {
1475        // Use AJAX endpoint for page content
1476        let url = {
1477            let session = self.session.lock().unwrap();
1478            format!(
1479                "{}/user/{}/library/music/{}/+tracks?page={}&ajax=true",
1480                session.base_url,
1481                session.username,
1482                artist.replace(" ", "+"),
1483                page
1484            )
1485        };
1486
1487        log::debug!("Fetching tracks page {page} for artist: {artist}");
1488        let mut response = self.get(&url).await?;
1489        let content = response
1490            .body_string()
1491            .await
1492            .map_err(|e| LastFmError::Http(e.to_string()))?;
1493
1494        log::debug!(
1495            "AJAX response: {} status, {} chars",
1496            response.status(),
1497            content.len()
1498        );
1499
1500        // Check if we got JSON or HTML
1501        if content.trim_start().starts_with("{") || content.trim_start().starts_with("[") {
1502            log::debug!("Parsing JSON response from AJAX endpoint");
1503            self.parse_json_tracks_page(&content, page, artist)
1504        } else {
1505            log::debug!("Parsing HTML response from AJAX endpoint");
1506            let document = Html::parse_document(&content);
1507            self.parser.parse_tracks_page(&document, page, artist)
1508        }
1509    }
1510
1511    /// Parse JSON tracks page (delegates to parser)
1512    fn parse_json_tracks_page(
1513        &self,
1514        _json_content: &str,
1515        page_number: u32,
1516        _artist: &str,
1517    ) -> Result<TrackPage> {
1518        // JSON parsing not yet implemented - fallback to empty page
1519        log::debug!("JSON parsing not implemented, returning empty page");
1520        Ok(TrackPage {
1521            tracks: Vec::new(),
1522            page_number,
1523            has_next_page: false,
1524            total_pages: Some(1),
1525        })
1526    }
1527
1528    /// Extract tracks from HTML document (delegates to parser)
1529    pub fn extract_tracks_from_document(
1530        &self,
1531        document: &Html,
1532        artist: &str,
1533    ) -> Result<Vec<Track>> {
1534        self.parser.extract_tracks_from_document(document, artist)
1535    }
1536
1537    /// Parse tracks page (delegates to parser)
1538    pub fn parse_tracks_page(
1539        &self,
1540        document: &Html,
1541        page_number: u32,
1542        artist: &str,
1543    ) -> Result<TrackPage> {
1544        self.parser.parse_tracks_page(document, page_number, artist)
1545    }
1546
1547    /// Parse recent scrobbles from HTML document (for testing)
1548    pub fn parse_recent_scrobbles(&self, document: &Html) -> Result<Vec<Track>> {
1549        self.parser.parse_recent_scrobbles(document)
1550    }
1551
1552    fn extract_csrf_token(&self, document: &Html) -> Result<String> {
1553        let csrf_selector = Selector::parse("input[name=\"csrfmiddlewaretoken\"]").unwrap();
1554
1555        document
1556            .select(&csrf_selector)
1557            .next()
1558            .and_then(|input| input.value().attr("value"))
1559            .map(|token| token.to_string())
1560            .ok_or(LastFmError::CsrfNotFound)
1561    }
1562
1563    /// Extract login form data (CSRF token and next field) - synchronous parsing helper
1564    fn extract_login_form_data(&self, html: &str) -> Result<(String, Option<String>)> {
1565        let document = Html::parse_document(html);
1566
1567        let csrf_token = self.extract_csrf_token(&document)?;
1568
1569        // Check if there's a 'next' field in the form
1570        let next_selector = Selector::parse("input[name=\"next\"]").unwrap();
1571        let next_field = document
1572            .select(&next_selector)
1573            .next()
1574            .and_then(|input| input.value().attr("value"))
1575            .map(|s| s.to_string());
1576
1577        Ok((csrf_token, next_field))
1578    }
1579
1580    /// Parse login error messages from HTML - synchronous parsing helper
1581    fn parse_login_error(&self, html: &str) -> String {
1582        let document = Html::parse_document(html);
1583
1584        let error_selector = Selector::parse(".alert-danger, .form-error, .error-message").unwrap();
1585
1586        let mut error_messages = Vec::new();
1587        for error in document.select(&error_selector) {
1588            let error_text = error.text().collect::<String>().trim().to_string();
1589            if !error_text.is_empty() {
1590                error_messages.push(error_text);
1591            }
1592        }
1593
1594        if error_messages.is_empty() {
1595            "Login failed - please check your credentials".to_string()
1596        } else {
1597            format!("Login failed: {}", error_messages.join("; "))
1598        }
1599    }
1600
1601    /// Check if HTML contains a login form - synchronous parsing helper
1602    fn check_for_login_form(&self, html: &str) -> bool {
1603        let document = Html::parse_document(html);
1604        let login_form_selector =
1605            Selector::parse("form[action*=\"login\"], input[name=\"username_or_email\"]").unwrap();
1606        document.select(&login_form_selector).next().is_some()
1607    }
1608
1609    /// Make an HTTP GET request with authentication and retry logic
1610    pub async fn get(&self, url: &str) -> Result<Response> {
1611        self.get_with_retry(url, 3).await
1612    }
1613
1614    /// Make an HTTP GET request with retry logic for rate limits
1615    async fn get_with_retry(&self, url: &str, max_retries: u32) -> Result<Response> {
1616        let mut retries = 0;
1617
1618        loop {
1619            match self.get_with_redirects(url, 0).await {
1620                Ok(mut response) => {
1621                    // Extract body and save debug info if enabled
1622                    let body = self.extract_response_body(url, &mut response).await?;
1623
1624                    // Check for rate limit patterns in successful responses
1625                    if response.status().is_success() && self.is_rate_limit_response(&body) {
1626                        log::debug!("Response body contains rate limit patterns");
1627                        if retries < max_retries {
1628                            let delay = 60 + (retries as u64 * 30); // Exponential backoff
1629                            log::info!("Rate limit detected in response body, retrying in {delay}s (attempt {}/{max_retries})", retries + 1);
1630                            // Rate limit delay would go here
1631                            retries += 1;
1632                            continue;
1633                        }
1634                        return Err(crate::LastFmError::RateLimit { retry_after: 60 });
1635                    }
1636
1637                    // Recreate response with the body we extracted
1638                    let mut new_response = http_types::Response::new(response.status());
1639                    for (name, values) in response.iter() {
1640                        for value in values {
1641                            let _ = new_response.insert_header(name.clone(), value.clone());
1642                        }
1643                    }
1644                    new_response.set_body(body);
1645
1646                    return Ok(new_response);
1647                }
1648                Err(crate::LastFmError::RateLimit { retry_after }) => {
1649                    if retries < max_retries {
1650                        let delay = retry_after + (retries as u64 * 30); // Exponential backoff
1651                        log::info!(
1652                            "Rate limit detected, retrying in {delay}s (attempt {}/{max_retries})",
1653                            retries + 1
1654                        );
1655                        // Rate limit delay would go here
1656                        retries += 1;
1657                    } else {
1658                        return Err(crate::LastFmError::RateLimit { retry_after });
1659                    }
1660                }
1661                Err(e) => return Err(e),
1662            }
1663        }
1664    }
1665
1666    async fn get_with_redirects(&self, url: &str, redirect_count: u32) -> Result<Response> {
1667        if redirect_count > 5 {
1668            return Err(LastFmError::Http("Too many redirects".to_string()));
1669        }
1670
1671        let mut request = Request::new(Method::Get, url.parse::<Url>().unwrap());
1672        let _ = request.insert_header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36");
1673
1674        // Add session cookies for all authenticated requests
1675        {
1676            let session = self.session.lock().unwrap();
1677            if !session.cookies.is_empty() {
1678                let cookie_header = session.cookies.join("; ");
1679                let _ = request.insert_header("Cookie", &cookie_header);
1680            } else if url.contains("page=") {
1681                log::debug!("No cookies available for paginated request!");
1682            }
1683        }
1684
1685        // Add browser-like headers for all requests
1686        if url.contains("ajax=true") {
1687            // AJAX request headers
1688            let _ = request.insert_header("Accept", "*/*");
1689            let _ = request.insert_header("X-Requested-With", "XMLHttpRequest");
1690        } else {
1691            // Regular page request headers
1692            let _ = request.insert_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
1693        }
1694        let _ = request.insert_header("Accept-Language", "en-US,en;q=0.9");
1695        let _ = request.insert_header("Accept-Encoding", "gzip, deflate, br");
1696        let _ = request.insert_header("DNT", "1");
1697        let _ = request.insert_header("Connection", "keep-alive");
1698        let _ = request.insert_header("Upgrade-Insecure-Requests", "1");
1699
1700        // Add referer for paginated requests
1701        if url.contains("page=") {
1702            let base_url = url.split('?').next().unwrap_or(url);
1703            let _ = request.insert_header("Referer", base_url);
1704        }
1705
1706        let response = self
1707            .client
1708            .send(request)
1709            .await
1710            .map_err(|e| LastFmError::Http(e.to_string()))?;
1711
1712        // Extract any new cookies from the response
1713        self.extract_cookies(&response);
1714
1715        // Handle redirects manually
1716        if response.status() == 302 || response.status() == 301 {
1717            if let Some(location) = response.header("location") {
1718                if let Some(redirect_url) = location.get(0) {
1719                    let redirect_url_str = redirect_url.as_str();
1720                    if url.contains("page=") {
1721                        log::debug!("Following redirect from {url} to {redirect_url_str}");
1722
1723                        // Check if this is a redirect to login - authentication issue
1724                        if redirect_url_str.contains("/login") {
1725                            log::debug!("Redirect to login page - authentication failed for paginated request");
1726                            return Err(LastFmError::Auth(
1727                                "Session expired or invalid for paginated request".to_string(),
1728                            ));
1729                        }
1730                    }
1731
1732                    // Handle relative URLs
1733                    let full_redirect_url = if redirect_url_str.starts_with('/') {
1734                        let base_url = self.session.lock().unwrap().base_url.clone();
1735                        format!("{base_url}{redirect_url_str}")
1736                    } else if redirect_url_str.starts_with("http") {
1737                        redirect_url_str.to_string()
1738                    } else {
1739                        // Relative to current path
1740                        let base_url = url
1741                            .rsplit('/')
1742                            .skip(1)
1743                            .collect::<Vec<_>>()
1744                            .into_iter()
1745                            .rev()
1746                            .collect::<Vec<_>>()
1747                            .join("/");
1748                        format!("{base_url}/{redirect_url_str}")
1749                    };
1750
1751                    // Make a new request to the redirect URL
1752                    return Box::pin(
1753                        self.get_with_redirects(&full_redirect_url, redirect_count + 1),
1754                    )
1755                    .await;
1756                }
1757            }
1758        }
1759
1760        // Handle explicit rate limit responses
1761        if response.status() == 429 {
1762            let retry_after = response
1763                .header("retry-after")
1764                .and_then(|h| h.get(0))
1765                .and_then(|v| v.as_str().parse::<u64>().ok())
1766                .unwrap_or(60);
1767            return Err(LastFmError::RateLimit { retry_after });
1768        }
1769
1770        // Check for 403 responses that might be rate limits
1771        if response.status() == 403 {
1772            log::debug!("Got 403 response, checking if it's a rate limit");
1773            // For now, treat 403s from authenticated endpoints as potential rate limits
1774            {
1775                let session = self.session.lock().unwrap();
1776                if !session.cookies.is_empty() {
1777                    log::debug!("403 on authenticated request - likely rate limit");
1778                    return Err(LastFmError::RateLimit { retry_after: 60 });
1779                }
1780            }
1781        }
1782
1783        Ok(response)
1784    }
1785
1786    /// Check if a response body indicates rate limiting
1787    fn is_rate_limit_response(&self, response_body: &str) -> bool {
1788        let body_lower = response_body.to_lowercase();
1789
1790        // Check against configured rate limit patterns
1791        for pattern in &self.rate_limit_patterns {
1792            if body_lower.contains(&pattern.to_lowercase()) {
1793                return true;
1794            }
1795        }
1796
1797        false
1798    }
1799
1800    fn extract_cookies(&self, response: &Response) {
1801        // Extract Set-Cookie headers and store them (avoiding duplicates)
1802        if let Some(cookie_headers) = response.header("set-cookie") {
1803            let mut new_cookies = 0;
1804            for cookie_header in cookie_headers {
1805                let cookie_str = cookie_header.as_str();
1806                // Extract just the cookie name=value part (before any semicolon)
1807                if let Some(cookie_value) = cookie_str.split(';').next() {
1808                    let cookie_name = cookie_value.split('=').next().unwrap_or("");
1809
1810                    // Remove any existing cookie with the same name
1811                    {
1812                        let mut session = self.session.lock().unwrap();
1813                        session
1814                            .cookies
1815                            .retain(|existing| !existing.starts_with(&format!("{cookie_name}=")));
1816                        session.cookies.push(cookie_value.to_string());
1817                    }
1818                    new_cookies += 1;
1819                }
1820            }
1821            if new_cookies > 0 {
1822                {
1823                    let session = self.session.lock().unwrap();
1824                    log::trace!(
1825                        "Extracted {} new cookies, total: {}",
1826                        new_cookies,
1827                        session.cookies.len()
1828                    );
1829                    log::trace!("Updated cookies: {:?}", &session.cookies);
1830
1831                    // Check if sessionid changed
1832                    for cookie in &session.cookies {
1833                        if cookie.starts_with("sessionid=") {
1834                            log::trace!("Current sessionid: {}", &cookie[10..50.min(cookie.len())]);
1835                            break;
1836                        }
1837                    }
1838                }
1839            }
1840        }
1841    }
1842
1843    /// Extract response body, optionally saving debug info
1844    async fn extract_response_body(&self, url: &str, response: &mut Response) -> Result<String> {
1845        let body = response
1846            .body_string()
1847            .await
1848            .map_err(|e| LastFmError::Http(e.to_string()))?;
1849
1850        if self.debug_save_responses {
1851            self.save_debug_response(url, response.status().into(), &body);
1852        }
1853
1854        Ok(body)
1855    }
1856
1857    /// Save response to debug directory (optional debug feature)
1858    fn save_debug_response(&self, url: &str, status_code: u16, body: &str) {
1859        if let Err(e) = self.try_save_debug_response(url, status_code, body) {
1860            log::warn!("Failed to save debug response: {e}");
1861        }
1862    }
1863
1864    /// Internal debug response saving implementation
1865    fn try_save_debug_response(&self, url: &str, status_code: u16, body: &str) -> Result<()> {
1866        // Create debug directory if it doesn't exist
1867        let debug_dir = Path::new("debug_responses");
1868        if !debug_dir.exists() {
1869            fs::create_dir_all(debug_dir)
1870                .map_err(|e| LastFmError::Http(format!("Failed to create debug directory: {e}")))?;
1871        }
1872
1873        // Extract the path part of the URL (after base_url)
1874        let url_path = {
1875            let session = self.session.lock().unwrap();
1876            if url.starts_with(&session.base_url) {
1877                &url[session.base_url.len()..]
1878            } else {
1879                url
1880            }
1881        };
1882
1883        // Create safe filename from URL path and add timestamp
1884        let now = chrono::Utc::now();
1885        let timestamp = now.format("%Y%m%d_%H%M%S_%3f");
1886        let safe_path = url_path.replace(['/', '?', '&', '=', '%', '+'], "_");
1887
1888        let filename = format!("{timestamp}_{safe_path}_status{status_code}.html");
1889        let file_path = debug_dir.join(filename);
1890
1891        // Write response to file
1892        fs::write(&file_path, body)
1893            .map_err(|e| LastFmError::Http(format!("Failed to write debug file: {e}")))?;
1894
1895        log::debug!(
1896            "Saved HTTP response to {file_path:?} (status: {status_code}, url: {url_path})"
1897        );
1898
1899        Ok(())
1900    }
1901
1902    pub async fn get_artist_albums_page(&self, artist: &str, page: u32) -> Result<AlbumPage> {
1903        // Use AJAX endpoint for page content
1904        let url = {
1905            let session = self.session.lock().unwrap();
1906            format!(
1907                "{}/user/{}/library/music/{}/+albums?page={}&ajax=true",
1908                session.base_url,
1909                session.username,
1910                artist.replace(" ", "+"),
1911                page
1912            )
1913        };
1914
1915        log::debug!("Fetching albums page {page} for artist: {artist}");
1916        let mut response = self.get(&url).await?;
1917        let content = response
1918            .body_string()
1919            .await
1920            .map_err(|e| LastFmError::Http(e.to_string()))?;
1921
1922        log::debug!(
1923            "AJAX response: {} status, {} chars",
1924            response.status(),
1925            content.len()
1926        );
1927
1928        // Check if we got JSON or HTML
1929        if content.trim_start().starts_with("{") || content.trim_start().starts_with("[") {
1930            log::debug!("Parsing JSON response from AJAX endpoint");
1931            self.parse_json_albums_page(&content, page, artist)
1932        } else {
1933            log::debug!("Parsing HTML response from AJAX endpoint");
1934            let document = Html::parse_document(&content);
1935            self.parser.parse_albums_page(&document, page, artist)
1936        }
1937    }
1938
1939    fn parse_json_albums_page(
1940        &self,
1941        _json_content: &str,
1942        page_number: u32,
1943        _artist: &str,
1944    ) -> Result<AlbumPage> {
1945        // JSON parsing not yet implemented - fallback to empty page
1946        log::debug!("JSON parsing not implemented, returning empty page");
1947        Ok(AlbumPage {
1948            albums: Vec::new(),
1949            page_number,
1950            has_next_page: false,
1951            total_pages: Some(1),
1952        })
1953    }
1954}