lastfm-edit 6.0.1

Rust crate for programmatic access to Last.fm's scrobble editing functionality via web scraping
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
//! Data types for Last.fm music metadata and operations.
//!
//! This module contains all the core data structures used throughout the crate,
//! including track and album metadata, edit operations, error types, session state,
//! configuration, and event handling.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use thiserror::Error;
use tokio::sync::{broadcast, watch};

// ================================================================================================
// TRACK AND ALBUM METADATA
// ================================================================================================

/// Represents a music track with associated metadata.
///
/// This structure contains track information as parsed from Last.fm pages,
/// including play count and optional timestamp data for scrobbles.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Track {
    /// The track name/title
    pub name: String,
    /// The artist name
    pub artist: String,
    /// Number of times this track has been played/scrobbled
    pub playcount: u32,
    /// Unix timestamp of when this track was scrobbled (if available)
    ///
    /// This field is populated when tracks are retrieved from recent scrobbles
    /// or individual scrobble data, but may be `None` for aggregate track listings.
    pub timestamp: Option<u64>,
    /// The album name (if available)
    ///
    /// This field is populated when tracks are retrieved from recent scrobbles
    /// where album information is available in the edit forms. May be `None`
    /// for aggregate track listings or when album information is not available.
    pub album: Option<String>,
    /// The album artist name (if available and different from track artist)
    ///
    /// This field is populated when tracks are retrieved from recent scrobbles
    /// where album artist information is available. May be `None` for tracks
    /// where the album artist is the same as the track artist, or when this
    /// information is not available.
    pub album_artist: Option<String>,
}

impl fmt::Display for Track {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let album_part = if let Some(ref album) = self.album {
            format!(" [{album}]")
        } else {
            String::new()
        };
        write!(f, "{} - {}{}", self.artist, self.name, album_part)
    }
}

/// Represents a paginated collection of tracks.
///
/// This structure is returned by track listing methods and provides
/// information about the current page and pagination state.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct TrackPage {
    /// The tracks on this page
    pub tracks: Vec<Track>,
    /// Current page number (1-indexed)
    pub page_number: u32,
    /// Whether there are more pages available
    pub has_next_page: bool,
    /// Total number of pages, if known
    ///
    /// This may be `None` if the total page count cannot be determined
    /// from the Last.fm response.
    pub total_pages: Option<u32>,
}

/// Represents a music album with associated metadata.
///
/// This structure contains album information as parsed from Last.fm pages,
/// including play count and optional timestamp data for scrobbles.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Album {
    /// The album name/title
    pub name: String,
    /// The artist name
    pub artist: String,
    /// Number of times this album has been played/scrobbled
    pub playcount: u32,
    /// Unix timestamp of when this album was last scrobbled (if available)
    ///
    /// This field is populated when albums are retrieved from recent scrobbles
    /// or individual scrobble data, but may be `None` for aggregate album listings.
    pub timestamp: Option<u64>,
}

impl fmt::Display for Album {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} - {}", self.artist, self.name)
    }
}

/// Represents a paginated collection of albums.
///
/// This structure is returned by album listing methods and provides
/// information about the current page and pagination state.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct AlbumPage {
    /// The albums on this page
    pub albums: Vec<Album>,
    /// Current page number (1-indexed)
    pub page_number: u32,
    /// Whether there are more pages available
    pub has_next_page: bool,
    /// Total number of pages, if known
    ///
    /// This may be `None` if the total page count cannot be determined
    /// from the Last.fm response.
    pub total_pages: Option<u32>,
}

impl Album {
    /// Convert the Unix timestamp to a human-readable datetime.
    ///
    /// Returns `None` if no timestamp is available or if the timestamp is invalid.
    #[must_use]
    pub fn scrobbled_at(&self) -> Option<DateTime<Utc>> {
        self.timestamp
            .and_then(|ts| DateTime::from_timestamp(i64::try_from(ts).ok()?, 0))
    }
}

/// Represents a music artist with associated metadata.
///
/// This structure contains artist information as parsed from Last.fm pages,
/// including the total number of scrobbles for this artist.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Artist {
    /// The artist name
    pub name: String,
    /// Number of times this artist has been played/scrobbled
    pub playcount: u32,
    /// Unix timestamp of when this artist was last scrobbled (if available)
    ///
    /// This field is populated when artists are retrieved from recent scrobbles
    /// or individual scrobble data, but may be `None` for aggregate artist listings.
    pub timestamp: Option<u64>,
}

impl fmt::Display for Artist {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

/// Represents a paginated collection of artists.
///
/// This structure is returned by artist listing methods and provides
/// information about the current page and pagination state.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ArtistPage {
    /// The artists on this page
    pub artists: Vec<Artist>,
    /// Current page number (1-indexed)
    pub page_number: u32,
    /// Whether there are more pages available
    pub has_next_page: bool,
    /// Total number of pages, if known
    ///
    /// This may be `None` if the total page count cannot be determined
    /// from the Last.fm response.
    pub total_pages: Option<u32>,
}

impl Artist {
    /// Convert the Unix timestamp to a human-readable datetime.
    ///
    /// Returns `None` if no timestamp is available or if the timestamp is invalid.
    #[must_use]
    pub fn scrobbled_at(&self) -> Option<DateTime<Utc>> {
        self.timestamp
            .and_then(|ts| DateTime::from_timestamp(i64::try_from(ts).ok()?, 0))
    }
}

// ================================================================================================
// EDIT OPERATIONS
// ================================================================================================

/// Represents a scrobble edit operation.
///
/// This structure contains all the information needed to edit a specific scrobble
/// on Last.fm, including both the original and new metadata values.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ScrobbleEdit {
    /// Original track name as it appears in the scrobble (optional - if None, edits all tracks)
    pub track_name_original: Option<String>,
    /// Original album name as it appears in the scrobble (optional)
    pub album_name_original: Option<String>,
    /// Original artist name as it appears in the scrobble (required)
    pub artist_name_original: String,
    /// Original album artist name as it appears in the scrobble (optional)
    pub album_artist_name_original: Option<String>,

    /// New track name to set (optional - if None, keeps original track names)
    pub track_name: Option<String>,
    /// New album name to set (optional - if None, keeps original album names)
    pub album_name: Option<String>,
    /// New artist name to set
    pub artist_name: String,
    /// New album artist name to set (optional - if None, keeps original album artist names)
    pub album_artist_name: Option<String>,

    /// Unix timestamp of the scrobble to edit (optional)
    ///
    /// This identifies the specific scrobble instance to modify.
    /// If None, the client will attempt to find a representative timestamp.
    pub timestamp: Option<u64>,
    /// Whether to edit all instances or just this specific scrobble
    ///
    /// When `true`, Last.fm will update all scrobbles with matching metadata.
    /// When `false`, only this specific scrobble (identified by timestamp) is updated.
    pub edit_all: bool,
}

impl fmt::Display for ScrobbleEdit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut changes = Vec::new();

        // Check if artist is being changed
        if self.artist_name != self.artist_name_original {
            changes.push(format!(
                "Artist: {} → {}",
                self.artist_name_original, self.artist_name
            ));
        }

        // Check if track name is being changed
        if let Some(ref new_track) = self.track_name {
            if let Some(ref original_track) = self.track_name_original {
                if new_track != original_track {
                    changes.push(format!("Track: {original_track} → {new_track}"));
                }
            } else {
                changes.push(format!("Track: → {new_track}"));
            }
        }

        // Check if album name is being changed
        if let Some(ref new_album) = self.album_name {
            match &self.album_name_original {
                Some(ref original_album) if new_album != original_album => {
                    changes.push(format!("Album: {original_album} → {new_album}"));
                }
                None => {
                    changes.push(format!("Album: → {new_album}"));
                }
                _ => {} // No change
            }
        }

        // Check if album artist is being changed
        if let Some(ref new_album_artist) = self.album_artist_name {
            match &self.album_artist_name_original {
                Some(ref original_album_artist) if new_album_artist != original_album_artist => {
                    changes.push(format!(
                        "Album Artist: {original_album_artist} → {new_album_artist}"
                    ));
                }
                None => {
                    changes.push(format!("Album Artist: → {new_album_artist}"));
                }
                _ => {} // No change
            }
        }

        if changes.is_empty() {
            write!(f, "No changes")
        } else {
            let scope = if self.edit_all {
                " (all instances)"
            } else {
                ""
            };
            write!(f, "{}{}", changes.join(", "), scope)
        }
    }
}

/// Response from a single scrobble edit operation.
///
/// This structure contains the result of attempting to edit a specific scrobble instance,
/// including success status and any error messages.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SingleEditResponse {
    /// Whether this individual edit operation was successful
    pub success: bool,
    /// Optional message describing the result or any errors
    pub message: Option<String>,
    /// Information about which album variation was edited
    pub album_info: Option<String>,
    /// The exact scrobble edit that was performed
    pub exact_scrobble_edit: ExactScrobbleEdit,
}

/// Response from a scrobble edit operation that may affect multiple album variations.
///
/// When editing a track that appears on multiple albums, this response contains
/// the results of all individual edit operations performed.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EditResponse {
    /// Results of individual edit operations
    pub individual_results: Vec<SingleEditResponse>,
}

/// Internal representation of a scrobble edit with all fields fully specified.
///
/// This type is used internally by the client after enriching metadata from
/// Last.fm. Unlike `ScrobbleEdit`, all fields are required and non-optional,
/// ensuring we have complete information before performing edit operations.
///
/// This type represents a fully-specified scrobble edit where all fields are known.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ExactScrobbleEdit {
    /// Original track name as it appears in the scrobble
    pub track_name_original: String,
    /// Original album name as it appears in the scrobble
    pub album_name_original: String,
    /// Original artist name as it appears in the scrobble
    pub artist_name_original: String,
    /// Original album artist name as it appears in the scrobble
    pub album_artist_name_original: String,

    /// New track name to set
    pub track_name: String,
    /// New album name to set
    pub album_name: String,
    /// New artist name to set
    pub artist_name: String,
    /// New album artist name to set
    pub album_artist_name: String,

    /// Unix timestamp of the scrobble to edit
    pub timestamp: u64,
    /// Whether to edit all instances or just this specific scrobble
    pub edit_all: bool,
}

impl fmt::Display for ExactScrobbleEdit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut changes = Vec::new();

        // Check if artist is being changed
        if self.artist_name != self.artist_name_original {
            changes.push(format!(
                "Artist: {} → {}",
                self.artist_name_original, self.artist_name
            ));
        }

        // Check if track name is being changed
        if self.track_name != self.track_name_original {
            changes.push(format!(
                "Track: {} → {}",
                self.track_name_original, self.track_name
            ));
        }

        // Check if album name is being changed
        if self.album_name != self.album_name_original {
            changes.push(format!(
                "Album: {} → {}",
                self.album_name_original, self.album_name
            ));
        }

        // Check if album artist is being changed
        if self.album_artist_name != self.album_artist_name_original {
            changes.push(format!(
                "Album Artist: {} → {}",
                self.album_artist_name_original, self.album_artist_name
            ));
        }

        if changes.is_empty() {
            write!(f, "No changes")
        } else {
            let scope = if self.edit_all {
                " (all instances)"
            } else {
                ""
            };
            write!(f, "{}{}", changes.join(", "), scope)
        }
    }
}

impl ScrobbleEdit {
    /// Create a new [`ScrobbleEdit`] with all required fields.
    ///
    /// This is the most general constructor that allows setting all fields.
    /// For convenience, consider using [`from_track_info`](Self::from_track_info) instead.
    ///
    /// # Arguments
    ///
    /// * `track_name_original` - The current track name in the scrobble
    /// * `album_name_original` - The current album name in the scrobble
    /// * `artist_name_original` - The current artist name in the scrobble
    /// * `album_artist_name_original` - The current album artist name in the scrobble
    /// * `track_name` - The new track name to set
    /// * `album_name` - The new album name to set
    /// * `artist_name` - The new artist name to set
    /// * `album_artist_name` - The new album artist name to set
    /// * `timestamp` - Unix timestamp identifying the scrobble
    /// * `edit_all` - Whether to edit all matching scrobbles or just this one
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        track_name_original: Option<String>,
        album_name_original: Option<String>,
        artist_name_original: String,
        album_artist_name_original: Option<String>,
        track_name: Option<String>,
        album_name: Option<String>,
        artist_name: String,
        album_artist_name: Option<String>,
        timestamp: Option<u64>,
        edit_all: bool,
    ) -> Self {
        Self {
            track_name_original,
            album_name_original,
            artist_name_original,
            album_artist_name_original,
            track_name,
            album_name,
            artist_name,
            album_artist_name,
            timestamp,
            edit_all,
        }
    }

    /// Create an edit request from track information (convenience constructor).
    ///
    /// This constructor creates a [`ScrobbleEdit`] with the new values initially
    /// set to the same as the original values. Use the builder methods like
    /// [`with_track_name`](Self::with_track_name) to specify what should be changed.
    ///
    /// # Arguments
    ///
    /// * `original_track` - The current track name
    /// * `original_album` - The current album name
    /// * `original_artist` - The current artist name
    /// * `timestamp` - Unix timestamp identifying the scrobble
    pub fn from_track_info(
        original_track: &str,
        original_album: &str,
        original_artist: &str,
        timestamp: u64,
    ) -> Self {
        Self::new(
            Some(original_track.to_string()),
            Some(original_album.to_string()),
            original_artist.to_string(),
            Some(original_artist.to_string()), // album_artist defaults to artist
            Some(original_track.to_string()),
            Some(original_album.to_string()),
            original_artist.to_string(),
            Some(original_artist.to_string()), // album_artist defaults to artist
            Some(timestamp),
            true, // edit_all defaults to true
        )
    }

    /// Set the new track name.
    pub fn with_track_name(mut self, track_name: &str) -> Self {
        self.track_name = Some(track_name.to_string());
        self
    }

    /// Set the new album name.
    pub fn with_album_name(mut self, album_name: &str) -> Self {
        self.album_name = Some(album_name.to_string());
        self
    }

    /// Set the new artist name.
    ///
    /// This also sets the album artist name to the same value.
    pub fn with_artist_name(mut self, artist_name: &str) -> Self {
        self.artist_name = artist_name.to_string();
        self.album_artist_name = Some(artist_name.to_string());
        self
    }

    /// Set whether to edit all instances of this track.
    ///
    /// When `true`, Last.fm will update all scrobbles with the same metadata.
    /// When `false` (default), only the specific scrobble is updated.
    pub fn with_edit_all(mut self, edit_all: bool) -> Self {
        self.edit_all = edit_all;
        self
    }

    /// Create an edit request with minimal information, letting the client look up missing metadata.
    ///
    /// This constructor is useful when you only know some of the original metadata and want
    /// the client to automatically fill in missing information by looking up the scrobble.
    ///
    /// # Arguments
    ///
    /// * `track_name` - The new track name to set
    /// * `artist_name` - The new artist name to set
    /// * `album_name` - The new album name to set
    /// * `timestamp` - Unix timestamp identifying the scrobble
    pub fn with_minimal_info(
        track_name: &str,
        artist_name: &str,
        album_name: &str,
        timestamp: u64,
    ) -> Self {
        Self::new(
            Some(track_name.to_string()),
            Some(album_name.to_string()),
            artist_name.to_string(),
            Some(artist_name.to_string()),
            Some(track_name.to_string()),
            Some(album_name.to_string()),
            artist_name.to_string(),
            Some(artist_name.to_string()),
            Some(timestamp),
            true,
        )
    }
    /// Create an edit request with just track and artist information.
    ///
    /// This constructor is useful when you only know the track and artist names.
    /// The client will use these as both original and new values, and will
    /// attempt to find a representative timestamp and album information.
    ///
    /// # Arguments
    ///
    /// * `track_name` - The track name (used as both original and new)
    /// * `artist_name` - The artist name (used as both original and new)
    pub fn from_track_and_artist(track_name: &str, artist_name: &str) -> Self {
        Self::new(
            Some(track_name.to_string()),
            None, // Client will look up original album name
            artist_name.to_string(),
            None, // Client will look up original album artist name
            Some(track_name.to_string()),
            None, // Will be filled by client or kept as original
            artist_name.to_string(),
            Some(artist_name.to_string()), // album_artist defaults to artist
            None,                          // Client will find representative timestamp
            true,
        )
    }

    /// Create an edit request for all tracks by an artist.
    ///
    /// This constructor creates a [`ScrobbleEdit`] that will edit all tracks
    /// by the specified artist, changing the artist name to the new value.
    ///
    /// # Arguments
    ///
    /// * `old_artist_name` - The current artist name to change from
    /// * `new_artist_name` - The new artist name to change to
    pub fn for_artist(old_artist_name: &str, new_artist_name: &str) -> Self {
        Self::new(
            None, // No specific track - edit all tracks
            None, // No specific album - edit all albums
            old_artist_name.to_string(),
            None, // Client will look up original album artist name
            None, // No track name change - keep original track names
            None, // Keep original album names (they can vary)
            new_artist_name.to_string(),
            Some(new_artist_name.to_string()), // album_artist also changes for global renames
            None,                              // Client will find representative timestamp
            true,                              // Edit all instances by default for artist changes
        )
    }

    /// Create an edit request for all tracks in a specific album.
    ///
    /// This constructor creates a [`ScrobbleEdit`] that will edit all tracks
    /// in the specified album by the specified artist.
    ///
    /// # Arguments
    ///
    /// * `album_name` - The album name containing tracks to edit
    /// * `artist_name` - The artist name for the album
    /// * `new_artist_name` - The new artist name to change to
    pub fn for_album(album_name: &str, old_artist_name: &str, new_artist_name: &str) -> Self {
        Self::new(
            None, // No specific track - edit all tracks in album
            Some(album_name.to_string()),
            old_artist_name.to_string(),
            Some(old_artist_name.to_string()),
            None,                         // No track name change - keep original track names
            Some(album_name.to_string()), // Keep same album name
            new_artist_name.to_string(),
            None, // Keep original album_artist names (they can vary)
            None, // Client will find representative timestamp
            true, // Edit all instances by default for album changes
        )
    }
}

impl ExactScrobbleEdit {
    /// Create a new [`ExactScrobbleEdit`] with all fields specified.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        track_name_original: String,
        album_name_original: String,
        artist_name_original: String,
        album_artist_name_original: String,
        track_name: String,
        album_name: String,
        artist_name: String,
        album_artist_name: String,
        timestamp: u64,
        edit_all: bool,
    ) -> Self {
        Self {
            track_name_original,
            album_name_original,
            artist_name_original,
            album_artist_name_original,
            track_name,
            album_name,
            artist_name,
            album_artist_name,
            timestamp,
            edit_all,
        }
    }

    /// Build the form data for submitting this scrobble edit.
    ///
    /// This creates a HashMap containing all the form fields needed to submit
    /// the edit request to Last.fm, including the CSRF token and all metadata fields.
    pub fn build_form_data(&self, csrf_token: &str) -> HashMap<&str, String> {
        let mut form_data = HashMap::new();

        // Add fresh CSRF token (required)
        form_data.insert("csrfmiddlewaretoken", csrf_token.to_string());

        // Include ALL form fields (using ExactScrobbleEdit which has all required fields)
        form_data.insert("track_name_original", self.track_name_original.clone());
        form_data.insert("track_name", self.track_name.clone());
        form_data.insert("artist_name_original", self.artist_name_original.clone());
        form_data.insert("artist_name", self.artist_name.clone());
        form_data.insert("album_name_original", self.album_name_original.clone());
        form_data.insert("album_name", self.album_name.clone());
        form_data.insert(
            "album_artist_name_original",
            self.album_artist_name_original.clone(),
        );
        form_data.insert("album_artist_name", self.album_artist_name.clone());

        // Include timestamp (ExactScrobbleEdit always has a timestamp)
        form_data.insert("timestamp", self.timestamp.to_string());

        // Edit flags
        if self.edit_all {
            form_data.insert("edit_all", "1".to_string());
        }
        form_data.insert("submit", "edit-scrobble".to_string());
        form_data.insert("ajax", "1".to_string());

        form_data
    }

    /// Convert this exact edit back to a public ScrobbleEdit.
    ///
    /// This is useful when you need to expose the edit data through the public API.
    pub fn to_scrobble_edit(&self) -> ScrobbleEdit {
        ScrobbleEdit::new(
            Some(self.track_name_original.clone()),
            Some(self.album_name_original.clone()),
            self.artist_name_original.clone(),
            Some(self.album_artist_name_original.clone()),
            Some(self.track_name.clone()),
            Some(self.album_name.clone()),
            self.artist_name.clone(),
            Some(self.album_artist_name.clone()),
            Some(self.timestamp),
            self.edit_all,
        )
    }
}

impl EditResponse {
    /// Create a new EditResponse from a single result.
    pub fn single(
        success: bool,
        message: Option<String>,
        album_info: Option<String>,
        exact_scrobble_edit: ExactScrobbleEdit,
    ) -> Self {
        Self {
            individual_results: vec![SingleEditResponse {
                success,
                message,
                album_info,
                exact_scrobble_edit,
            }],
        }
    }

    /// Create a new EditResponse from multiple results.
    pub fn from_results(results: Vec<SingleEditResponse>) -> Self {
        Self {
            individual_results: results,
        }
    }

    /// Check if all individual edit operations were successful.
    pub fn all_successful(&self) -> bool {
        !self.individual_results.is_empty() && self.individual_results.iter().all(|r| r.success)
    }

    /// Check if any individual edit operations were successful.
    pub fn any_successful(&self) -> bool {
        self.individual_results.iter().any(|r| r.success)
    }

    /// Get the total number of edit operations performed.
    pub fn total_edits(&self) -> usize {
        self.individual_results.len()
    }

    /// Get the number of successful edit operations.
    pub fn successful_edits(&self) -> usize {
        self.individual_results.iter().filter(|r| r.success).count()
    }

    /// Get the number of failed edit operations.
    pub fn failed_edits(&self) -> usize {
        self.individual_results
            .iter()
            .filter(|r| !r.success)
            .count()
    }

    /// Generate a summary message describing the overall result.
    pub fn summary_message(&self) -> String {
        let total = self.total_edits();
        let successful = self.successful_edits();
        let failed = self.failed_edits();

        if total == 0 {
            return "No edit operations performed".to_string();
        }

        if successful == total {
            if total == 1 {
                "Edit completed successfully".to_string()
            } else {
                format!("All {total} edits completed successfully")
            }
        } else if successful == 0 {
            if total == 1 {
                "Edit failed".to_string()
            } else {
                format!("All {total} edits failed")
            }
        } else {
            format!("{successful} of {total} edits succeeded, {failed} failed")
        }
    }

    /// Get detailed messages from all edit operations.
    pub fn detailed_messages(&self) -> Vec<String> {
        self.individual_results
            .iter()
            .enumerate()
            .map(|(i, result)| {
                let album_info = result
                    .album_info
                    .as_deref()
                    .map(|info| format!(" ({info})"))
                    .unwrap_or_default();

                match &result.message {
                    Some(msg) => format!("{}: {}{}", i + 1, msg, album_info),
                    None => {
                        if result.success {
                            format!("{}: Success{}", i + 1, album_info)
                        } else {
                            format!("{}: Failed{}", i + 1, album_info)
                        }
                    }
                }
            })
            .collect()
    }

    /// Check if this response represents a single edit (for backward compatibility).
    pub fn is_single_edit(&self) -> bool {
        self.individual_results.len() == 1
    }

    /// Check if all edits succeeded (for backward compatibility).
    pub fn success(&self) -> bool {
        self.all_successful()
    }

    /// Get a single message for backward compatibility.
    /// Returns the summary message.
    pub fn message(&self) -> Option<String> {
        Some(self.summary_message())
    }
}

// ================================================================================================
// ERROR TYPES
// ================================================================================================

/// Error types for Last.fm operations.
///
/// This enum covers all possible errors that can occur when interacting with Last.fm,
/// including network issues, authentication failures, parsing errors, and rate limiting.
#[derive(Error, Debug)]
pub enum LastFmError {
    /// HTTP/network related errors.
    ///
    /// This includes connection failures, timeouts, DNS errors, and other
    /// low-level networking issues.
    #[error("HTTP error: {0}")]
    Http(String),

    /// Authentication failures.
    ///
    /// This occurs when login credentials are invalid, sessions expire,
    /// or authentication is required but not provided.
    ///
    /// # Common Causes
    /// - Invalid username/password
    /// - Expired session cookies
    /// - Account locked or suspended
    /// - Two-factor authentication required
    #[error("Authentication failed: {0}")]
    Auth(String),

    /// CSRF token not found in response.
    ///
    /// This typically indicates that Last.fm's page structure has changed
    /// or that the request was blocked.
    #[error("CSRF token not found")]
    CsrfNotFound,

    /// Failed to parse Last.fm's response.
    ///
    /// This can happen when Last.fm changes their HTML structure or
    /// returns unexpected data formats.
    #[error("Failed to parse response: {0}")]
    Parse(String),

    /// Rate limiting from Last.fm.
    ///
    /// Last.fm has rate limits to prevent abuse. When hit, the client
    /// should wait before making more requests.
    ///
    /// The `retry_after` field indicates how many seconds to wait before
    /// the next request attempt.
    #[error("Rate limited, retry after {retry_after} seconds")]
    RateLimit {
        /// Number of seconds to wait before retrying
        retry_after: u64,
    },

    /// Scrobble edit operation failed.
    ///
    /// This is returned when an edit request is properly formatted and sent,
    /// but Last.fm rejects it for business logic reasons.
    #[error("Edit failed: {0}")]
    EditFailed(String),

    /// File system I/O errors.
    ///
    /// This can occur when saving debug responses or other file operations.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

// ================================================================================================
// SESSION MANAGEMENT
// ================================================================================================

/// Serializable client session state that can be persisted and restored.
///
/// This contains all the authentication state needed to resume a Last.fm session
/// without requiring the user to log in again.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastFmEditSession {
    /// The authenticated username
    pub username: String,
    /// Session cookies required for authenticated requests
    pub cookies: Vec<String>,
    /// CSRF token for form submissions
    pub csrf_token: Option<String>,
    /// Base URL for the Last.fm instance
    pub base_url: String,
}

impl LastFmEditSession {
    /// Create a new client session with the provided state
    pub fn new(
        username: String,
        session_cookies: Vec<String>,
        csrf_token: Option<String>,
        base_url: String,
    ) -> Self {
        Self {
            username,
            cookies: session_cookies,
            csrf_token,
            base_url,
        }
    }

    /// Check if this session appears to be valid
    ///
    /// This performs basic validation but doesn't guarantee the session
    /// is still active on the server.
    pub fn is_valid(&self) -> bool {
        !self.username.is_empty()
            && !self.cookies.is_empty()
            && self.csrf_token.is_some()
            && self
                .cookies
                .iter()
                .any(|cookie| cookie.starts_with("sessionid=") && cookie.len() > 50)
    }

    /// Serialize session to JSON string
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Deserialize session from JSON string
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

// ================================================================================================
// CLIENT CONFIGURATION
// ================================================================================================

/// Configuration for rate limit detection behavior
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitConfig {
    /// Whether to detect rate limits by HTTP status codes (429, 403)
    pub detect_by_status: bool,
    /// Whether to detect rate limits by response body patterns
    pub detect_by_patterns: bool,
    /// Patterns to look for in response bodies (used when detect_by_patterns is true)
    pub patterns: Vec<String>,
    /// Additional custom patterns to look for in response bodies
    pub custom_patterns: Vec<String>,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            detect_by_status: true,
            detect_by_patterns: true,
            patterns: vec![
                "you've tried to log in too many times".to_string(),
                "you're requesting too many pages".to_string(),
                "slow down".to_string(),
                "too fast".to_string(),
                "rate limit".to_string(),
                "throttled".to_string(),
                "temporarily blocked".to_string(),
                "temporarily restricted".to_string(),
                "captcha".to_string(),
                "verify you're human".to_string(),
                "prove you're not a robot".to_string(),
                "security check".to_string(),
                "service temporarily unavailable".to_string(),
                "quota exceeded".to_string(),
                "limit exceeded".to_string(),
                "daily limit".to_string(),
            ],
            custom_patterns: vec![],
        }
    }
}

impl RateLimitConfig {
    /// Create config with all detection disabled
    pub fn disabled() -> Self {
        Self {
            detect_by_status: false,
            detect_by_patterns: false,
            patterns: vec![],
            custom_patterns: vec![],
        }
    }

    /// Create config with only status code detection
    pub fn status_only() -> Self {
        Self {
            detect_by_status: true,
            detect_by_patterns: false,
            patterns: vec![],
            custom_patterns: vec![],
        }
    }

    /// Create config with only default pattern detection
    pub fn patterns_only() -> Self {
        Self {
            detect_by_status: false,
            detect_by_patterns: true,
            ..Default::default()
        }
    }

    /// Create config with custom patterns only (no default patterns)
    pub fn custom_patterns_only(patterns: Vec<String>) -> Self {
        Self {
            detect_by_status: false,
            detect_by_patterns: false,
            patterns: vec![],
            custom_patterns: patterns,
        }
    }

    /// Create config with both default and custom patterns
    pub fn with_custom_patterns(mut self, patterns: Vec<String>) -> Self {
        self.custom_patterns = patterns;
        self
    }

    /// Create config with custom patterns (replaces built-in patterns)
    pub fn with_patterns(mut self, patterns: Vec<String>) -> Self {
        self.patterns = patterns;
        self
    }
}

/// Configuration for operational delays between requests
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationalDelayConfig {
    /// Optional delay before each GET request (in milliseconds).
    ///
    /// This is a pragmatic throttle to avoid triggering Last.fm's HTML page rate limits when
    /// scanning libraries (e.g. `.../library?page=N`).
    pub get_delay_ms: u64,
    /// Delay between multiple edit operations (in milliseconds)
    pub edit_delay_ms: u64,
    /// Delay between delete operations (in milliseconds)
    pub delete_delay_ms: u64,
}

impl Default for OperationalDelayConfig {
    fn default() -> Self {
        Self {
            get_delay_ms: 0,
            edit_delay_ms: 1000,   // 1 second
            delete_delay_ms: 1000, // 1 second
        }
    }
}

impl OperationalDelayConfig {
    /// Create config with no delays (useful for testing)
    pub fn no_delays() -> Self {
        Self {
            get_delay_ms: 0,
            edit_delay_ms: 0,
            delete_delay_ms: 0,
        }
    }

    /// Create config with custom delays
    pub fn with_delays(edit_delay_ms: u64, delete_delay_ms: u64) -> Self {
        Self {
            get_delay_ms: 0,
            edit_delay_ms,
            delete_delay_ms,
        }
    }

    /// Set GET request delay (in milliseconds).
    pub fn with_get_delay_ms(mut self, get_delay_ms: u64) -> Self {
        self.get_delay_ms = get_delay_ms;
        self
    }
}

/// Unified configuration for retry behavior and rate limiting
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ClientConfig {
    /// Retry configuration
    pub retry: RetryConfig,
    /// Rate limit detection configuration
    pub rate_limit: RateLimitConfig,
    /// Operational delay configuration
    pub operational_delays: OperationalDelayConfig,
    /// Last.fm API key for read-only API access (optional)
    pub api_key: Option<String>,
}

impl ClientConfig {
    /// Create a new config with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Create config with retries disabled
    pub fn with_retries_disabled() -> Self {
        Self {
            retry: RetryConfig::disabled(),
            ..Default::default()
        }
    }

    /// Create config with rate limit detection disabled
    pub fn with_rate_limiting_disabled() -> Self {
        Self {
            rate_limit: RateLimitConfig::disabled(),
            ..Default::default()
        }
    }

    /// Create config with both retries and rate limiting disabled
    pub fn minimal() -> Self {
        Self {
            retry: RetryConfig::disabled(),
            rate_limit: RateLimitConfig::disabled(),
            ..Default::default()
        }
    }

    /// Create config optimized for testing (rate limit detection enabled, retries enabled but no delays)
    pub fn for_testing() -> Self {
        Self {
            retry: RetryConfig {
                max_retries: 3,
                base_delay: 0, // No delay for fast tests
                max_delay: 0,  // No delay for fast tests
                enabled: true,
            },
            operational_delays: OperationalDelayConfig::no_delays(),
            ..Default::default()
        }
    }

    /// Set custom retry configuration
    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
        self.retry = retry_config;
        self
    }

    /// Set custom rate limit configuration
    pub fn with_rate_limit_config(mut self, rate_limit_config: RateLimitConfig) -> Self {
        self.rate_limit = rate_limit_config;
        self
    }

    /// Set custom operational delay configuration
    pub fn with_operational_delays(mut self, operational_delays: OperationalDelayConfig) -> Self {
        self.operational_delays = operational_delays;
        self
    }

    /// Set custom retry count
    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
        self.retry.max_retries = max_retries;
        self.retry.enabled = max_retries > 0;
        self
    }

    /// Set custom retry delays
    pub fn with_retry_delays(mut self, base_delay: u64, max_delay: u64) -> Self {
        self.retry.base_delay = base_delay;
        self.retry.max_delay = max_delay;
        self
    }

    /// Add custom rate limit patterns
    pub fn with_custom_rate_limit_patterns(mut self, patterns: Vec<String>) -> Self {
        self.rate_limit.custom_patterns = patterns;
        self
    }

    /// Enable/disable HTTP status code rate limit detection
    pub fn with_status_detection(mut self, enabled: bool) -> Self {
        self.rate_limit.detect_by_status = enabled;
        self
    }

    /// Enable/disable response pattern rate limit detection
    pub fn with_pattern_detection(mut self, enabled: bool) -> Self {
        self.rate_limit.detect_by_patterns = enabled;
        self
    }

    /// Set the Last.fm API key for read-only API access
    pub fn with_api_key(mut self, api_key: String) -> Self {
        self.api_key = Some(api_key);
        self
    }
}

/// Configuration for retry behavior
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RetryConfig {
    /// Maximum number of retry attempts (set to 0 to disable retries)
    pub max_retries: u32,
    /// Base delay for exponential backoff (in seconds)
    pub base_delay: u64,
    /// Maximum delay cap (in seconds)
    pub max_delay: u64,
    /// Whether retries are enabled at all
    pub enabled: bool,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_retries: 3,
            base_delay: 5,
            max_delay: 300, // 5 minutes
            enabled: true,
        }
    }
}

impl RetryConfig {
    /// Create a config with retries disabled
    pub fn disabled() -> Self {
        Self {
            max_retries: 0,
            base_delay: 5,
            max_delay: 300,
            enabled: false,
        }
    }

    /// Create a config with custom retry count
    pub fn with_retries(max_retries: u32) -> Self {
        Self {
            max_retries,
            enabled: max_retries > 0,
            ..Default::default()
        }
    }

    /// Create a config with custom delays
    pub fn with_delays(base_delay: u64, max_delay: u64) -> Self {
        Self {
            base_delay,
            max_delay,
            ..Default::default()
        }
    }

    /// Create a config that retries indefinitely on `RateLimit` errors.
    ///
    /// This is intended for long-running background workflows that prefer
    /// forward progress over failing fast (e.g. scanners/scrubbers).
    ///
    /// Cancellation is still honored by `retry_with_backoff_cancelable` when a
    /// `cancel_rx` is provided.
    pub fn unbounded() -> Self {
        Self {
            max_retries: u32::MAX,
            enabled: true,
            ..Default::default()
        }
    }
}

/// Result of a retry operation with context
#[derive(Debug)]
pub struct RetryResult<T> {
    /// The successful result
    pub result: T,
    /// Number of retry attempts made
    pub attempts_made: u32,
    /// Total time spent retrying (in seconds)
    pub total_retry_time: u64,
}

// ================================================================================================
// EVENT SYSTEM
// ================================================================================================

/// Request information for client events
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RequestInfo {
    /// The HTTP method (GET, POST, etc.)
    pub method: String,
    /// The full URI being requested
    pub uri: String,
    /// Query parameters as key-value pairs
    pub query_params: Vec<(String, String)>,
    /// Path without query parameters
    pub path: String,
}

impl RequestInfo {
    /// Create RequestInfo from a URL string and method
    pub fn from_url_and_method(url: &str, method: &str) -> Self {
        // Parse URL manually to avoid adding dependencies
        let (path, query_params) = if let Some(query_start) = url.find('?') {
            let path = url[..query_start].to_string();
            let query_string = &url[query_start + 1..];

            let query_params: Vec<(String, String)> = query_string
                .split('&')
                .filter_map(|pair| {
                    if let Some(eq_pos) = pair.find('=') {
                        let key = &pair[..eq_pos];
                        let value = &pair[eq_pos + 1..];
                        Some((key.to_string(), value.to_string()))
                    } else if !pair.is_empty() {
                        Some((pair.to_string(), String::new()))
                    } else {
                        None
                    }
                })
                .collect();

            (path, query_params)
        } else {
            (url.to_string(), Vec::new())
        };

        // Extract just the path part if it's a full URL
        let path = if path.starts_with("http://") || path.starts_with("https://") {
            if let Some(third_slash) = path[8..].find('/') {
                path[8 + third_slash..].to_string()
            } else {
                "/".to_string()
            }
        } else {
            path
        };

        Self {
            method: method.to_string(),
            uri: url.to_string(),
            query_params,
            path,
        }
    }

    /// Get a short description of the request for logging
    pub fn short_description(&self) -> String {
        let mut desc = format!("{} {}", self.method, self.path);
        if !self.query_params.is_empty() {
            let params: Vec<String> = self
                .query_params
                .iter()
                .map(|(k, v)| format!("{k}={v}"))
                .collect();
            if params.len() <= 2 {
                desc.push_str(&format!("?{}", params.join("&")));
            } else {
                desc.push_str(&format!("?{}...", params[0]));
            }
        }
        desc
    }
}

/// Type of rate limiting detected
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RateLimitType {
    /// HTTP 429 Too Many Requests
    Http429,
    /// HTTP 403 Forbidden (likely rate limiting)
    Http403,
    /// Rate limit patterns detected in response body
    ResponsePattern,
}

/// Reason why the client is intentionally delaying.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DelayReason {
    /// Exponential backoff / retry delay (typically after rate limiting).
    RetryBackoff,
    /// Intentional pacing between multiple edit operations.
    OperationalEditDelay,
    /// Intentional pacing between multiple delete operations.
    OperationalDeleteDelay,
}

/// Event type to describe internal HTTP client activity
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ClientEvent {
    /// Request started
    RequestStarted {
        /// Request details
        request: RequestInfo,
    },
    /// Request completed successfully
    RequestCompleted {
        /// Request details
        request: RequestInfo,
        /// HTTP status code
        status_code: u16,
        /// Duration of the request in milliseconds
        duration_ms: u64,
    },
    /// Rate limiting detected with backoff duration in seconds
    RateLimited {
        /// Duration to wait in seconds
        delay_seconds: u64,
        /// Request that triggered the rate limit (if available)
        request: Option<RequestInfo>,
        /// Type of rate limiting detected
        rate_limit_type: RateLimitType,
        /// Timestamp when the rate limit was detected (seconds since Unix epoch)
        rate_limit_timestamp: u64,
    },
    /// Rate limiting period has ended and normal operation resumed
    RateLimitEnded {
        /// Request that successfully completed after rate limiting
        request: RequestInfo,
        /// Type of rate limiting that ended
        rate_limit_type: RateLimitType,
        /// Total duration the rate limiting was active in seconds
        total_rate_limit_duration_seconds: u64,
    },
    /// Client is intentionally delaying before continuing.
    ///
    /// This is used to surface internal sleeps (backoff, pacing) to callers so that UIs/CLIs
    /// can display clear "waiting" state rather than appearing stuck.
    Delaying {
        /// Duration to wait in milliseconds.
        delay_ms: u64,
        /// Why we're delaying.
        reason: DelayReason,
        /// Optional request context associated with this delay.
        request: Option<RequestInfo>,
        /// Timestamp when the delay started (seconds since Unix epoch).
        delay_timestamp: u64,
    },
    /// Scrobble edit attempt completed
    EditAttempted {
        /// The exact scrobble edit that was attempted
        edit: ExactScrobbleEdit,
        /// Whether the edit was successful
        success: bool,
        /// Optional error message if the edit failed
        error_message: Option<String>,
        /// Duration of the edit operation in milliseconds
        duration_ms: u64,
    },
}

/// Type alias for the broadcast receiver
pub type ClientEventReceiver = broadcast::Receiver<ClientEvent>;

/// Type alias for the watch receiver
pub type ClientEventWatcher = watch::Receiver<Option<ClientEvent>>;

/// Shared event broadcasting state that persists across client clones
#[derive(Clone)]
pub struct SharedEventBroadcaster {
    event_tx: broadcast::Sender<ClientEvent>,
    last_event_tx: watch::Sender<Option<ClientEvent>>,
}

impl SharedEventBroadcaster {
    /// Create a new shared event broadcaster
    pub fn new() -> Self {
        let (event_tx, _) = broadcast::channel(100);
        let (last_event_tx, _) = watch::channel(None);

        Self {
            event_tx,
            last_event_tx,
        }
    }

    /// Broadcast an event to all subscribers
    pub fn broadcast_event(&self, event: ClientEvent) {
        let _ = self.event_tx.send(event.clone());
        let _ = self.last_event_tx.send(Some(event));
    }

    /// Subscribe to events
    pub fn subscribe(&self) -> ClientEventReceiver {
        self.event_tx.subscribe()
    }

    /// Get the latest event
    pub fn latest_event(&self) -> Option<ClientEvent> {
        self.last_event_tx.borrow().clone()
    }
}

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

impl std::fmt::Debug for SharedEventBroadcaster {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SharedEventBroadcaster")
            .field("subscribers", &self.event_tx.receiver_count())
            .finish()
    }
}

// ================================================================================================
// TESTS
// ================================================================================================

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

    #[test]
    fn test_session_validity() {
        let valid_session = LastFmEditSession::new(
            "testuser".to_string(),
            vec!["sessionid=.eJy1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".to_string()],
            Some("csrf_token_123".to_string()),
            "https://www.last.fm".to_string(),
        );
        assert!(valid_session.is_valid());

        let invalid_session = LastFmEditSession::new(
            "".to_string(),
            vec![],
            None,
            "https://www.last.fm".to_string(),
        );
        assert!(!invalid_session.is_valid());
    }

    #[test]
    fn test_session_serialization() {
        let session = LastFmEditSession::new(
            "testuser".to_string(),
            vec![
                "sessionid=.test123".to_string(),
                "csrftoken=abc".to_string(),
            ],
            Some("csrf_token_123".to_string()),
            "https://www.last.fm".to_string(),
        );

        let json = session.to_json().unwrap();
        let restored_session = LastFmEditSession::from_json(&json).unwrap();

        assert_eq!(session.username, restored_session.username);
        assert_eq!(session.cookies, restored_session.cookies);
        assert_eq!(session.csrf_token, restored_session.csrf_token);
        assert_eq!(session.base_url, restored_session.base_url);
    }
}