cider-api 0.1.1

Async Rust client for the Cider music player REST API
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Types for the Cider REST API.
//!
//! This module contains all request and response types used by
//! [`CiderClient`](crate::CiderClient). Response types use `#[serde(default)]`
//! on fields that may be absent so deserialization succeeds even when the API
//! omits them (e.g. radio stations may omit `artist_name`).
//!
//! The response shapes match the [Cider RPC documentation](https://cider.sh/docs/client/rpc).

use serde::{Deserialize, Serialize};

// ─── Response wrapper ────────────────────────────────────────────────────────

/// Generic wrapper for Cider API JSON responses.
///
/// Most endpoints return `{ "status": "ok", ...fields }`. The inner payload is
/// flattened so its fields sit alongside `status`.
///
/// # Example (JSON)
///
/// ```json
/// { "status": "ok", "is_playing": true }
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct ApiResponse<T> {
    /// Status string, typically `"ok"`.
    pub status: String,

    /// Endpoint-specific payload, flattened into the same JSON object.
    #[serde(flatten)]
    pub data: T,
}

// ─── Common types ────────────────────────────────────────────────────────────

/// Artwork metadata for a track, album, or station.
///
/// The `url` field may contain `{w}` and `{h}` placeholders for the desired
/// image dimensions. Use [`Artwork::url_for_size`] to get a ready-to-use URL.
///
/// Color fields (`text_color1`–`text_color4`, `bg_color`) are hex color strings
/// present on certain container artwork (e.g. radio stations).
///
/// # Examples
///
/// ```
/// # use cider_api::Artwork;
/// let art = Artwork {
///     width: 600,
///     height: 600,
///     url: "https://example.com/img/{w}x{h}bb.jpg".into(),
///     ..Default::default()
/// };
/// assert_eq!(
///     art.url_for_size(300),
///     "https://example.com/img/300x300bb.jpg"
/// );
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Artwork {
    /// Image width in pixels.
    #[serde(default)]
    pub width: u32,

    /// Image height in pixels.
    #[serde(default)]
    pub height: u32,

    /// URL template — may contain `{w}` and `{h}` size placeholders.
    #[serde(default)]
    pub url: String,

    /// Primary text color (hex, e.g. `"eaccc1"`). Present on station artwork.
    #[serde(default)]
    pub text_color1: Option<String>,

    /// Secondary text color (hex). Present on station artwork.
    #[serde(default)]
    pub text_color2: Option<String>,

    /// Tertiary text color (hex). Present on station artwork.
    #[serde(default)]
    pub text_color3: Option<String>,

    /// Quaternary text color (hex). Present on station artwork.
    #[serde(default)]
    pub text_color4: Option<String>,

    /// Background color (hex, e.g. `"0c0e0d"`). Present on station artwork.
    #[serde(default)]
    pub bg_color: Option<String>,

    /// Whether the artwork uses the Display P3 color space.
    #[serde(default)]
    pub has_p3: Option<bool>,
}

impl Artwork {
    /// Return the artwork URL with `{w}` and `{h}` replaced by `size`.
    ///
    /// If the URL has no placeholders the original URL is returned unchanged.
    #[must_use]
    pub fn url_for_size(&self, size: u32) -> String {
        let s = size.to_string();
        self.url.replace("{w}", &s).replace("{h}", &s)
    }
}

/// Play parameters identifying a playable item.
///
/// Every playable track, album, or station carries an `id` (Apple Music
/// catalog ID) and a `kind` (e.g. `"song"`, `"album"`, `"radioStation"`).
///
/// # Examples
///
/// ```
/// # use cider_api::PlayParams;
/// let pp = PlayParams { id: "1719861213".into(), kind: "song".into() };
/// assert_eq!(pp.id, "1719861213");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlayParams {
    /// Apple Music catalog ID.
    pub id: String,

    /// Item kind — `"song"`, `"album"`, `"playlist"`, `"radioStation"`, etc.
    pub kind: String,
}

/// A track audio preview.
///
/// The `url` points to a short AAC preview clip hosted on Apple's CDN.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Preview {
    /// Direct URL to the preview audio file.
    pub url: String,
}

// ─── Now Playing ─────────────────────────────────────────────────────────────

/// Currently playing track information returned by `GET /now-playing`.
///
/// This is an Apple Music API–style resource enriched with live playback
/// state (`current_playback_time`, `remaining_time`, `shuffle_mode`, etc.).
///
/// All fields use `#[serde(default)]` so deserialization succeeds even when
/// the API omits fields (e.g. radio stations may lack `artist_name`).
///
/// # Examples
///
/// ```
/// # use cider_api::NowPlaying;
/// # fn example(track: &NowPlaying) {
/// println!("{} — {} ({})", track.name, track.artist_name, track.album_name);
/// println!("Position: {:.1}s / {}ms", track.current_playback_time, track.duration_in_millis);
/// if let Some(id) = track.song_id() {
///     println!("Song ID: {id}");
/// }
/// println!("Artwork: {}", track.artwork_url(600));
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(clippy::struct_excessive_bools)]
pub struct NowPlaying {
    /// Song name.
    #[serde(default)]
    pub name: String,

    /// Artist name.
    #[serde(default)]
    pub artist_name: String,

    /// Album name.
    #[serde(default)]
    pub album_name: String,

    /// Artwork information.
    #[serde(default)]
    pub artwork: Artwork,

    /// Total duration in milliseconds.
    #[serde(default)]
    pub duration_in_millis: u64,

    // ── Identifiers ──

    /// Play parameters containing the song ID and kind.
    #[serde(default)]
    pub play_params: Option<PlayParams>,

    /// Apple Music web URL for the track.
    #[serde(default)]
    pub url: Option<String>,

    /// International Standard Recording Code.
    #[serde(default)]
    pub isrc: Option<String>,

    // ── Playback state (injected by Cider, not in the Apple Music catalog) ──

    /// Current playback position in seconds.
    #[serde(default)]
    pub current_playback_time: f64,

    /// Remaining playback time in seconds.
    #[serde(default)]
    pub remaining_time: f64,

    /// Shuffle mode — `0` = off, `1` = on.
    #[serde(default)]
    pub shuffle_mode: u8,

    /// Repeat mode — `0` = off, `1` = repeat one, `2` = repeat all.
    #[serde(default)]
    pub repeat_mode: u8,

    /// Whether the track is in the user's favorites.
    #[serde(default)]
    pub in_favorites: bool,

    /// Whether the track is in the user's library.
    #[serde(default)]
    pub in_library: bool,

    // ── Catalog metadata ──

    /// Genre names (e.g. `["Electronic", "Music"]`).
    #[serde(default)]
    pub genre_names: Vec<String>,

    /// Track number on the album.
    #[serde(default)]
    pub track_number: u32,

    /// Disc number on the album.
    #[serde(default)]
    pub disc_number: u32,

    /// Release date as an ISO-8601 string (e.g. `"2016-05-27T12:00:00Z"`).
    #[serde(default)]
    pub release_date: Option<String>,

    /// Audio locale code (e.g. `"en-US"`).
    #[serde(default)]
    pub audio_locale: Option<String>,

    /// Composer / songwriter name.
    #[serde(default)]
    pub composer_name: Option<String>,

    /// Whether the track has lyrics.
    #[serde(default)]
    pub has_lyrics: bool,

    /// Whether the track has time-synced (karaoke-style) lyrics.
    #[serde(default)]
    pub has_time_synced_lyrics: bool,

    /// Whether vocal attenuation (sing-along mode) is available.
    #[serde(default)]
    pub is_vocal_attenuation_allowed: bool,

    /// Legacy flag — replaced by [`is_apple_digital_master`](Self::is_apple_digital_master).
    #[serde(default)]
    pub is_mastered_for_itunes: bool,

    /// Whether the track is an Apple Digital Master (high-resolution master).
    #[serde(default)]
    pub is_apple_digital_master: bool,

    /// Audio traits (e.g. `["atmos", "lossless", "lossy-stereo", "spatial"]`).
    #[serde(default)]
    pub audio_traits: Vec<String>,

    /// Audio preview URLs.
    #[serde(default)]
    pub previews: Vec<Preview>,
}

impl NowPlaying {
    /// Get the song ID from [`play_params`](Self::play_params), if present.
    #[must_use]
    pub fn song_id(&self) -> Option<&str> {
        self.play_params.as_ref().map(|p| p.id.as_str())
    }

    /// Get the current playback position in milliseconds.
    ///
    /// Negative `current_playback_time` values (possible at seek boundaries)
    /// are clamped to zero.
    #[must_use]
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    pub fn current_position_ms(&self) -> u64 {
        // max(0.0) guards against negative values; truncation is intentional.
        (self.current_playback_time.max(0.0) * 1000.0).round() as u64
    }

    /// Get the artwork URL at the specified square size (in pixels).
    ///
    /// Shorthand for `self.artwork.url_for_size(size)`.
    #[must_use]
    pub fn artwork_url(&self, size: u32) -> String {
        self.artwork.url_for_size(size)
    }
}

// ─── Queue types ─────────────────────────────────────────────────────────────

/// A single item in the Cider playback queue.
///
/// Returned as part of the array from `GET /queue`. The queue includes
/// history items, the currently playing track, and upcoming items. Use
/// [`QueueItem::is_current`] to identify the active track.
///
/// Most useful data lives in [`attributes`](Self::attributes). Top-level
/// fields like `asset_url`, `assets`, and `key_urls` are Apple Music
/// streaming internals.
///
/// # Examples
///
/// ```no_run
/// # use cider_api::{CiderClient, QueueItem};
/// # async fn example() -> Result<(), cider_api::CiderError> {
/// let queue = CiderClient::new().get_queue().await?;
///
/// // Find the currently playing item
/// if let Some(current) = queue.iter().find(|i| i.is_current()) {
///     if let Some(attrs) = &current.attributes {
///         println!("Now playing: {} — {}", attrs.name, attrs.artist_name);
///     }
/// }
///
/// // List upcoming tracks
/// let current_idx = queue.iter().position(|i| i.is_current()).unwrap_or(0);
/// for item in &queue[current_idx + 1..] {
///     if let Some(attrs) = &item.attributes {
///         println!("  Up next: {}", attrs.name);
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QueueItem {
    /// Apple Music catalog ID for this item.
    #[serde(default)]
    pub id: Option<String>,

    /// Item type (e.g. `"song"`).
    #[serde(default, rename = "type")]
    pub item_type: Option<String>,

    /// HLS streaming URL for the asset.
    #[serde(default, rename = "assetURL")]
    pub asset_url: Option<String>,

    /// HLS metadata (opaque object).
    #[serde(default)]
    pub hls_metadata: Option<serde_json::Value>,

    /// Audio flavor / codec descriptor (e.g. `"28:ctrp256"`).
    #[serde(default)]
    pub flavor: Option<String>,

    /// Track metadata attributes.
    #[serde(default)]
    pub attributes: Option<QueueItemAttributes>,

    /// Playback type identifier.
    #[serde(default)]
    pub playback_type: Option<u32>,

    /// The container this item was queued from (e.g. a station or playlist).
    #[serde(default, rename = "_container")]
    pub container: Option<QueueContainer>,

    /// Context information about how this item was queued.
    #[serde(default, rename = "_context")]
    pub context: Option<QueueContext>,

    /// Playback state — `current == Some(2)` means currently playing.
    #[serde(default, rename = "_state")]
    pub state: Option<QueueItemState>,

    /// Song ID (may differ from `id` for library vs. catalog tracks).
    #[serde(default, rename = "_songId")]
    pub song_id: Option<String>,

    /// Available audio assets with different codec flavors and metadata.
    #[serde(default)]
    pub assets: Option<Vec<serde_json::Value>>,

    /// DRM key URLs for HLS playback.
    #[serde(default, rename = "keyURLs")]
    pub key_urls: Option<KeyUrls>,
}

impl QueueItem {
    /// Returns `true` if this is the currently playing item.
    #[must_use]
    pub fn is_current(&self) -> bool {
        self.state
            .as_ref()
            .and_then(|s| s.current)
            .is_some_and(|c| c == 2)
    }
}

/// Track attributes within a [`QueueItem`].
///
/// Contains the same catalog metadata as [`NowPlaying`] plus
/// live playback state injected by Cider.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(clippy::struct_excessive_bools)]
pub struct QueueItemAttributes {
    /// Song name.
    #[serde(default)]
    pub name: String,

    /// Artist name.
    #[serde(default)]
    pub artist_name: String,

    /// Album name.
    #[serde(default)]
    pub album_name: String,

    /// Total duration in milliseconds.
    #[serde(default)]
    pub duration_in_millis: u64,

    // ── Identifiers ──

    /// Artwork information.
    #[serde(default)]
    pub artwork: Option<Artwork>,

    /// Play parameters containing the song ID and kind.
    #[serde(default)]
    pub play_params: Option<PlayParams>,

    /// Apple Music web URL for the track.
    #[serde(default)]
    pub url: Option<String>,

    /// International Standard Recording Code.
    #[serde(default)]
    pub isrc: Option<String>,

    // ── Catalog metadata ──

    /// Genre names.
    #[serde(default)]
    pub genre_names: Vec<String>,

    /// Track number on the album.
    #[serde(default)]
    pub track_number: u32,

    /// Disc number on the album.
    #[serde(default)]
    pub disc_number: u32,

    /// Release date as an ISO-8601 string.
    #[serde(default)]
    pub release_date: Option<String>,

    /// Audio locale code (e.g. `"en-US"`).
    #[serde(default)]
    pub audio_locale: Option<String>,

    /// Composer / songwriter name.
    #[serde(default)]
    pub composer_name: Option<String>,

    /// Whether the track has lyrics.
    #[serde(default)]
    pub has_lyrics: bool,

    /// Whether the track has time-synced lyrics.
    #[serde(default)]
    pub has_time_synced_lyrics: bool,

    /// Whether vocal attenuation is available.
    #[serde(default)]
    pub is_vocal_attenuation_allowed: bool,

    /// Legacy Mastered for iTunes flag.
    #[serde(default)]
    pub is_mastered_for_itunes: bool,

    /// Whether the track is an Apple Digital Master.
    #[serde(default)]
    pub is_apple_digital_master: bool,

    /// Audio traits (e.g. `["lossless", "lossy-stereo"]`).
    #[serde(default)]
    pub audio_traits: Vec<String>,

    /// Audio preview URLs.
    #[serde(default)]
    pub previews: Vec<Preview>,

    // ── Playback state (injected by Cider) ──

    /// Current playback position in seconds.
    #[serde(default)]
    pub current_playback_time: f64,

    /// Remaining playback time in seconds.
    #[serde(default)]
    pub remaining_time: f64,
}

/// Playback state of a [`QueueItem`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueItemState {
    /// `2` indicates this is the currently playing item.
    #[serde(default)]
    pub current: Option<u8>,
}

/// The container (playlist, station, album) a queue item was sourced from.
///
/// Container `attributes` vary by type and are exposed as raw JSON.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QueueContainer {
    /// Container ID (e.g. `"ra.cp-1055074639"`).
    #[serde(default)]
    pub id: Option<String>,

    /// Container type (e.g. `"stations"`, `"playlists"`, `"albums"`).
    #[serde(default, rename = "type")]
    pub container_type: Option<String>,

    /// Apple Music API href for the container.
    #[serde(default)]
    pub href: Option<String>,

    /// Display name / context label (e.g. `"now_playing"`).
    #[serde(default)]
    pub name: Option<String>,

    /// Container-specific attributes (varies by type).
    #[serde(default)]
    pub attributes: Option<serde_json::Value>,
}

/// Context metadata for a [`QueueItem`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QueueContext {
    /// Feature that queued this item (e.g. `"now_playing"`).
    #[serde(default)]
    pub feature_name: Option<String>,
}

/// DRM / streaming key URLs for HLS playback.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyUrls {
    /// URL for the HLS `FairPlay` certificate bundle.
    #[serde(default, rename = "hls-key-cert-url")]
    pub hls_key_cert_url: Option<String>,

    /// URL for the HLS `FairPlay` license server.
    #[serde(default, rename = "hls-key-server-url")]
    pub hls_key_server_url: Option<String>,

    /// URL for the Widevine certificate.
    #[serde(default, rename = "widevine-cert-url")]
    pub widevine_cert_url: Option<String>,
}

// ─── Endpoint-specific response payloads ─────────────────────────────────────

/// Payload for `GET /is-playing`.
#[derive(Debug, Clone, Deserialize)]
pub struct IsPlayingResponse {
    /// `true` if music is currently playing.
    pub is_playing: bool,
}

/// Payload for `GET /now-playing`.
#[derive(Debug, Clone, Deserialize)]
pub struct NowPlayingResponse {
    /// Currently playing track info.
    pub info: NowPlaying,
}

/// Payload for `GET /volume`.
#[derive(Debug, Clone, Deserialize)]
pub struct VolumeResponse {
    /// Current volume level (`0.0`–`1.0`).
    pub volume: f32,
}

/// Payload for `GET /repeat-mode`.
#[derive(Debug, Clone, Deserialize)]
pub struct RepeatModeResponse {
    /// `0` = off, `1` = repeat one, `2` = repeat all.
    pub value: u8,
}

/// Payload for `GET /shuffle-mode`.
#[derive(Debug, Clone, Deserialize)]
pub struct ShuffleModeResponse {
    /// `0` = off, `1` = on.
    pub value: u8,
}

/// Payload for `GET /autoplay`.
#[derive(Debug, Clone, Deserialize)]
pub struct AutoplayResponse {
    /// `true` = autoplay enabled.
    pub value: bool,
}

// ─── Request bodies ──────────────────────────────────────────────────────────

/// Request body for `POST /play-url`.
#[derive(Debug, Clone, Serialize)]
pub struct PlayUrlRequest {
    /// Apple Music URL to play (e.g. `"https://music.apple.com/…"`).
    pub url: String,
}

/// Request body for `POST /play-item` / `POST /play-next` / `POST /play-later`.
#[derive(Debug, Clone, Serialize)]
pub struct PlayItemRequest {
    /// Item type (e.g. `"songs"`, `"albums"`, `"playlists"`).
    #[serde(rename = "type")]
    pub item_type: String,

    /// Apple Music catalog ID (must be a string, not a number).
    pub id: String,
}

/// Request body for `POST /play-item-href`.
#[derive(Debug, Clone, Serialize)]
pub struct PlayItemHrefRequest {
    /// Apple Music API href (e.g. `"/v1/catalog/ca/songs/1719861213"`).
    pub href: String,
}

/// Request body for `POST /seek`.
#[derive(Debug, Clone, Serialize)]
pub struct SeekRequest {
    /// Target position in **seconds**.
    pub position: f64,
}

/// Request body for `POST /volume`.
#[derive(Debug, Clone, Serialize)]
pub struct VolumeRequest {
    /// Target volume (`0.0`–`1.0`).
    pub volume: f32,
}

/// Request body for `POST /set-rating`.
#[derive(Debug, Clone, Serialize)]
pub struct RatingRequest {
    /// `-1` = dislike, `0` = unset, `1` = like.
    pub rating: i8,
}

/// Request body for `POST /queue/move-to-position`.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QueueMoveRequest {
    /// Current 1-based index of the item to move.
    pub start_index: u32,

    /// Target 1-based index.
    pub destination_index: u32,

    /// If `true`, the response includes the updated queue.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_queue: Option<bool>,
}

/// Request body for `POST /queue/remove-by-index`.
#[derive(Debug, Clone, Serialize)]
pub struct QueueRemoveRequest {
    /// 1-based index of the item to remove.
    pub index: u32,
}

/// Request body for `POST /api/v1/amapi/run-v3`.
#[derive(Debug, Clone, Serialize)]
pub struct AmApiRequest {
    /// Apple Music API path (e.g. `"/v1/catalog/ca/search?term=…"`).
    pub path: String,
}

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

    // ── NowPlaying deserialization ──

    #[test]
    fn deserialize_now_playing_full() {
        let json = r#"{
            "name": "Never Be Like You",
            "artistName": "Flume",
            "albumName": "Skin",
            "artwork": {
                "width": 3000,
                "height": 3000,
                "url": "https://example.com/{w}x{h}bb.jpg"
            },
            "durationInMillis": 234000,
            "playParams": { "id": "1719861213", "kind": "song" },
            "url": "https://music.apple.com/ca/album/skin/1719860281",
            "isrc": "AUUM71600506",
            "currentPlaybackTime": 42.5,
            "remainingTime": 191.5,
            "shuffleMode": 1,
            "repeatMode": 0,
            "inFavorites": true,
            "inLibrary": true,
            "genreNames": ["Electronic", "Music"],
            "trackNumber": 3,
            "discNumber": 1,
            "releaseDate": "2016-05-27T12:00:00Z",
            "hasLyrics": true,
            "isAppleDigitalMaster": true,
            "audioTraits": ["lossless", "lossy-stereo"],
            "previews": [{"url": "https://audio-ssl.itunes.apple.com/preview.m4a"}]
        }"#;

        let track: NowPlaying = serde_json::from_str(json).unwrap();
        assert_eq!(track.name, "Never Be Like You");
        assert_eq!(track.artist_name, "Flume");
        assert_eq!(track.album_name, "Skin");
        assert_eq!(track.duration_in_millis, 234000);
        assert_eq!(track.song_id(), Some("1719861213"));
        assert!(track.in_favorites);
        assert!(track.in_library);
        assert_eq!(track.genre_names.len(), 2);
        assert_eq!(track.track_number, 3);
        assert!(track.has_lyrics);
        assert!(track.is_apple_digital_master);
        assert_eq!(track.previews.len(), 1);
    }

    #[test]
    fn deserialize_now_playing_minimal() {
        let json = r#"{"name": "Some Station"}"#;
        let track: NowPlaying = serde_json::from_str(json).unwrap();
        assert_eq!(track.name, "Some Station");
        assert_eq!(track.artist_name, "");
        assert_eq!(track.duration_in_millis, 0);
        assert!(track.song_id().is_none());
        assert!(!track.in_favorites);
        assert!(track.genre_names.is_empty());
    }

    #[test]
    fn deserialize_now_playing_empty_object() {
        let track: NowPlaying = serde_json::from_str("{}").unwrap();
        assert_eq!(track.name, "");
        assert!(track.play_params.is_none());
    }

    // ── Helper methods ──

    #[test]
    fn artwork_url_for_size_replaces_placeholders() {
        let art = Artwork {
            url: "https://example.com/{w}x{h}bb.jpg".into(),
            width: 3000,
            height: 3000,
            ..Default::default()
        };
        assert_eq!(art.url_for_size(300), "https://example.com/300x300bb.jpg");
    }

    #[test]
    fn artwork_url_for_size_no_placeholders() {
        let art = Artwork {
            url: "https://example.com/static.jpg".into(),
            ..Default::default()
        };
        assert_eq!(art.url_for_size(300), "https://example.com/static.jpg");
    }

    #[test]
    fn now_playing_current_position_ms() {
        let track: NowPlaying = serde_json::from_str(r#"{"currentPlaybackTime": 42.567}"#).unwrap();
        assert_eq!(track.current_position_ms(), 42567);
    }

    #[test]
    fn now_playing_current_position_ms_zero() {
        let track: NowPlaying = serde_json::from_str("{}").unwrap();
        assert_eq!(track.current_position_ms(), 0);
    }

    #[test]
    fn now_playing_current_position_ms_negative_clamped() {
        let track: NowPlaying = serde_json::from_str(r#"{"currentPlaybackTime": -0.5}"#).unwrap();
        assert_eq!(track.current_position_ms(), 0);
    }

    #[test]
    fn now_playing_artwork_url_delegates() {
        let track: NowPlaying = serde_json::from_str(
            r#"{"artwork": {"url": "https://example.com/{w}x{h}bb.jpg"}}"#,
        )
        .unwrap();
        assert_eq!(
            track.artwork_url(600),
            "https://example.com/600x600bb.jpg"
        );
    }

    #[test]
    fn queue_item_is_current_true() {
        let item: QueueItem =
            serde_json::from_str(r#"{"_state": {"current": 2}}"#).unwrap();
        assert!(item.is_current());
    }

    #[test]
    fn queue_item_is_current_false_when_not_2() {
        let item: QueueItem =
            serde_json::from_str(r#"{"_state": {"current": 1}}"#).unwrap();
        assert!(!item.is_current());
    }

    #[test]
    fn queue_item_is_current_false_when_no_state() {
        let item: QueueItem = serde_json::from_str("{}").unwrap();
        assert!(!item.is_current());
    }

    // ── Request body serialization ──

    #[test]
    fn play_item_request_renames_type() {
        let req = PlayItemRequest {
            item_type: "songs".into(),
            id: "123".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["type"], "songs");
        assert_eq!(json["id"], "123");
        assert!(json.get("item_type").is_none());
    }

    #[test]
    fn seek_request_serialization() {
        let req = SeekRequest { position: 30.5 };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert!((json["position"].as_f64().unwrap() - 30.5).abs() < 0.001);
    }

    #[test]
    fn volume_request_serialization() {
        let req = VolumeRequest { volume: 0.75 };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert!((json["volume"].as_f64().unwrap() - 0.75).abs() < 0.001);
    }

    #[test]
    fn rating_request_serialization() {
        let req = RatingRequest { rating: -1 };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["rating"], -1);
    }

    #[test]
    fn queue_move_request_omits_none_return_queue() {
        let req = QueueMoveRequest {
            start_index: 3,
            destination_index: 1,
            return_queue: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(!json.contains("returnQueue"));
        let val: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(val["startIndex"], 3);
        assert_eq!(val["destinationIndex"], 1);
    }

    #[test]
    fn queue_move_request_includes_return_queue_when_some() {
        let req = QueueMoveRequest {
            start_index: 1,
            destination_index: 5,
            return_queue: Some(true),
        };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["returnQueue"], true);
    }

    #[test]
    fn queue_remove_request_serialization() {
        let req = QueueRemoveRequest { index: 7 };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["index"], 7);
    }

    #[test]
    fn amapi_request_serialization() {
        let req = AmApiRequest {
            path: "/v1/catalog/us/search?term=flume".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["path"], "/v1/catalog/us/search?term=flume");
    }

    #[test]
    fn play_url_request_serialization() {
        let req = PlayUrlRequest {
            url: "https://music.apple.com/ca/album/skin/1719860281".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(
            json["url"],
            "https://music.apple.com/ca/album/skin/1719860281"
        );
    }

    #[test]
    fn play_item_href_request_serialization() {
        let req = PlayItemHrefRequest {
            href: "/v1/catalog/ca/songs/123".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["href"], "/v1/catalog/ca/songs/123");
    }

    // ── ApiResponse flatten deserialization ──

    #[test]
    fn api_response_is_playing() {
        let json = r#"{"status":"ok","is_playing":true}"#;
        let resp: ApiResponse<IsPlayingResponse> = serde_json::from_str(json).unwrap();
        assert_eq!(resp.status, "ok");
        assert!(resp.data.is_playing);
    }

    #[test]
    fn api_response_volume() {
        let json = r#"{"status":"ok","volume":0.65}"#;
        let resp: ApiResponse<VolumeResponse> = serde_json::from_str(json).unwrap();
        assert!((resp.data.volume - 0.65).abs() < 0.001);
    }

    #[test]
    fn api_response_repeat_mode() {
        let json = r#"{"status":"ok","value":2}"#;
        let resp: ApiResponse<RepeatModeResponse> = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data.value, 2);
    }

    #[test]
    fn api_response_shuffle_mode() {
        let json = r#"{"status":"ok","value":1}"#;
        let resp: ApiResponse<ShuffleModeResponse> = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data.value, 1);
    }

    #[test]
    fn api_response_autoplay() {
        let json = r#"{"status":"ok","value":true}"#;
        let resp: ApiResponse<AutoplayResponse> = serde_json::from_str(json).unwrap();
        assert!(resp.data.value);
    }

    #[test]
    fn api_response_now_playing() {
        let json = r#"{"status":"ok","info":{"name":"Test Track","artistName":"Artist"}}"#;
        let resp: ApiResponse<NowPlayingResponse> = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data.info.name, "Test Track");
        assert_eq!(resp.data.info.artist_name, "Artist");
    }

    // ── Queue item deserialization ──

    #[test]
    fn deserialize_queue_item_array() {
        let json = r#"[
            {"id": "123", "type": "song", "_state": {"current": 2}, "attributes": {"name": "Track 1", "artistName": "Artist"}},
            {"id": "456", "type": "song", "attributes": {"name": "Track 2", "artistName": "Artist"}}
        ]"#;
        let items: Vec<QueueItem> = serde_json::from_str(json).unwrap();
        assert_eq!(items.len(), 2);
        assert!(items[0].is_current());
        assert!(!items[1].is_current());
        assert_eq!(items[0].attributes.as_ref().unwrap().name, "Track 1");
    }
}