typecast-rust 0.2.0

Official Rust SDK for Typecast Text-to-Speech 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
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
//! Unit tests for the Typecast Rust SDK.
//!
//! These tests use `mockito` to spin up an in-process HTTP server for every
//! test, so they never touch the real Typecast API and never require an API
//! key. They are designed to give 100% line, function, and region coverage of
//! the SDK source files.

use futures_util::StreamExt;
use mockito::Server;
use std::time::Duration;
use typecast_rust::{
    Age, AudioFormat, ClientConfig, Credits, EmotionPreset, ErrorResponse, Gender, Limits,
    ModelInfo, Output, OutputStream, PlanTier, PresetPrompt, Prompt, SmartPrompt,
    SubscriptionResponse, TTSModel, TTSPrompt, TTSRequest, TTSRequestStream, TypecastClient,
    TypecastError, UseCase, VoiceV2, VoicesV2Filter, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_SECS,
};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn make_client(server: &Server) -> TypecastClient {
    let config = ClientConfig::new("test-api-key")
        .base_url(server.url())
        .timeout(Duration::from_secs(5));
    TypecastClient::new(config).expect("client builds")
}

// ---------------------------------------------------------------------------
// errors.rs
// ---------------------------------------------------------------------------

#[test]
fn error_from_response_maps_all_known_status_codes() {
    let detail_resp = || {
        Some(ErrorResponse {
            detail: "boom".to_string(),
        })
    };

    let cases = [
        (400u16, "BadRequest"),
        (401, "Unauthorized"),
        (402, "PaymentRequired"),
        (403, "Forbidden"),
        (404, "NotFound"),
        (422, "ValidationError"),
        (429, "RateLimited"),
        (500, "ServerError"),
        (503, "ServerError"),
        (599, "ServerError"),
        (418, "Unknown"),
    ];

    for (code, name) in cases {
        let err = TypecastError::from_response(code, detail_resp());
        let variant_name = match err {
            TypecastError::BadRequest { .. } => "BadRequest",
            TypecastError::Unauthorized { .. } => "Unauthorized",
            TypecastError::PaymentRequired { .. } => "PaymentRequired",
            TypecastError::Forbidden { .. } => "Forbidden",
            TypecastError::NotFound { .. } => "NotFound",
            TypecastError::ValidationError { .. } => "ValidationError",
            TypecastError::RateLimited { .. } => "RateLimited",
            TypecastError::ServerError { .. } => "ServerError",
            TypecastError::Unknown { .. } => "Unknown",
            _ => "Other",
        };
        assert_eq!(variant_name, name, "for status {code}");
    }
}

#[test]
fn error_from_response_uses_default_detail_when_missing() {
    let err = TypecastError::from_response(400, None);
    match err {
        TypecastError::BadRequest { detail } => assert_eq!(detail, "Unknown error"),
        other => panic!("unexpected variant: {other:?}"),
    }
}

#[test]
fn error_predicate_methods_cover_every_variant() {
    let bad = TypecastError::BadRequest {
        detail: "x".into(),
    };
    let unauth = TypecastError::Unauthorized {
        detail: "x".into(),
    };
    let pay = TypecastError::PaymentRequired {
        detail: "x".into(),
    };
    let forbid = TypecastError::Forbidden {
        detail: "x".into(),
    };
    let nf = TypecastError::NotFound {
        detail: "x".into(),
    };
    let val = TypecastError::ValidationError {
        detail: "x".into(),
    };
    let rate = TypecastError::RateLimited {
        detail: "x".into(),
    };
    let server = TypecastError::ServerError {
        detail: "x".into(),
    };
    let unknown = TypecastError::Unknown {
        status_code: 418,
        detail: "x".into(),
    };

    assert!(bad.is_bad_request());
    assert!(!bad.is_unauthorized());
    assert!(unauth.is_unauthorized());
    assert!(pay.is_payment_required());
    assert!(forbid.is_forbidden());
    assert!(nf.is_not_found());
    assert!(val.is_validation_error());
    assert!(rate.is_rate_limited());
    assert!(server.is_server_error());

    assert_eq!(bad.status_code(), Some(400));
    assert_eq!(unauth.status_code(), Some(401));
    assert_eq!(pay.status_code(), Some(402));
    assert_eq!(forbid.status_code(), Some(403));
    assert_eq!(nf.status_code(), Some(404));
    assert_eq!(val.status_code(), Some(422));
    assert_eq!(rate.status_code(), Some(429));
    assert_eq!(server.status_code(), Some(500));
    assert_eq!(unknown.status_code(), Some(418));

    // Display impls (covers `#[error("...")]` formatters)
    assert!(bad.to_string().contains("Bad Request"));
    assert!(unauth.to_string().contains("Unauthorized"));
    assert!(pay.to_string().contains("Payment Required"));
    assert!(forbid.to_string().contains("Forbidden"));
    assert!(nf.to_string().contains("Not Found"));
    assert!(val.to_string().contains("Validation Error"));
    assert!(rate.to_string().contains("Too Many Requests"));
    assert!(server.to_string().contains("Internal Server Error"));
    assert!(unknown.to_string().contains("418"));
}

#[test]
fn error_status_code_is_none_for_transport_errors() {
    // serde_json::Error -> JsonError via From
    let json_err: serde_json::Error = serde_json::from_str::<i32>("not a number").unwrap_err();
    let err: TypecastError = json_err.into();
    assert!(matches!(err, TypecastError::JsonError(_)));
    assert_eq!(err.status_code(), None);
    assert!(err.to_string().contains("JSON error"));
    assert!(!err.is_bad_request());
    assert!(!err.is_unauthorized());
    assert!(!err.is_payment_required());
    assert!(!err.is_forbidden());
    assert!(!err.is_not_found());
    assert!(!err.is_validation_error());
    assert!(!err.is_rate_limited());
    assert!(!err.is_server_error());
}

#[tokio::test]
async fn error_status_code_is_none_for_http_errors() {
    // Build a client with a 1ms timeout pointed at a server that never replies
    // to force a reqwest::Error -> HttpError conversion.
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v2/voices")
        .with_status(200)
        .with_body("[]")
        // Long delay forces timeout.
        .with_chunked_body(|w| {
            std::thread::sleep(std::time::Duration::from_millis(500));
            w.write_all(b"[]")
        })
        .create_async()
        .await;

    let config = ClientConfig::new("k")
        .base_url(server.url())
        .timeout(Duration::from_millis(20));
    let client = TypecastClient::new(config).unwrap();
    let err = client.get_voices_v2(None).await.unwrap_err();
    assert!(matches!(err, TypecastError::HttpError(_)));
    assert_eq!(err.status_code(), None);
    assert!(err.to_string().contains("HTTP error"));
}

// ---------------------------------------------------------------------------
// models.rs
// ---------------------------------------------------------------------------

#[test]
fn defaults_for_enums_and_structs() {
    assert_eq!(TTSModel::default(), TTSModel::SsfmV30);
    assert_eq!(EmotionPreset::default(), EmotionPreset::Normal);
    assert_eq!(AudioFormat::default(), AudioFormat::Wav);

    let out = Output::default();
    assert!(out.volume.is_none());
    assert!(out.target_lufs.is_none());
    assert!(out.audio_pitch.is_none());
    assert!(out.audio_tempo.is_none());
    assert!(out.audio_format.is_none());

    let p = Prompt::default();
    assert!(p.emotion_preset.is_none());
    assert!(p.emotion_intensity.is_none());

    let pp = PresetPrompt::default();
    assert_eq!(pp.emotion_type, "preset");

    let sp = SmartPrompt::default();
    assert_eq!(sp.emotion_type, "smart");

    let f = VoicesV2Filter::default();
    assert!(f.model.is_none());
}

#[test]
fn output_builder_clamps_values() {
    let out = Output::new()
        .volume(500)
        .audio_pitch(20)
        .audio_tempo(5.0)
        .audio_format(AudioFormat::Mp3);
    assert_eq!(out.volume, Some(200));
    assert_eq!(out.audio_pitch, Some(12));
    assert_eq!(out.audio_tempo, Some(2.0));
    assert_eq!(out.audio_format, Some(AudioFormat::Mp3));

    let out2 = Output::new()
        .volume(-10)
        .audio_pitch(-100)
        .audio_tempo(0.1)
        .target_lufs(-200.0);
    assert_eq!(out2.volume, Some(0));
    assert_eq!(out2.audio_pitch, Some(-12));
    assert_eq!(out2.audio_tempo, Some(0.5));
    assert_eq!(out2.target_lufs, Some(-70.0));

    let out3 = Output::new().target_lufs(50.0);
    assert_eq!(out3.target_lufs, Some(0.0));
}

#[test]
fn prompt_builders_clamp_intensity() {
    let p = Prompt::new()
        .emotion_preset(EmotionPreset::Happy)
        .emotion_intensity(5.0);
    assert_eq!(p.emotion_preset, Some(EmotionPreset::Happy));
    assert_eq!(p.emotion_intensity, Some(2.0));

    let p2 = Prompt::new().emotion_intensity(-1.0);
    assert_eq!(p2.emotion_intensity, Some(0.0));

    let pp = PresetPrompt::new()
        .emotion_preset(EmotionPreset::Sad)
        .emotion_intensity(10.0);
    assert_eq!(pp.emotion_preset, Some(EmotionPreset::Sad));
    assert_eq!(pp.emotion_intensity, Some(2.0));

    let sp = SmartPrompt::new()
        .previous_text("before")
        .next_text("after");
    assert_eq!(sp.previous_text.as_deref(), Some("before"));
    assert_eq!(sp.next_text.as_deref(), Some("after"));
}

#[test]
fn tts_prompt_from_conversions() {
    let basic: TTSPrompt = Prompt::new().into();
    let preset: TTSPrompt = PresetPrompt::new().into();
    let smart: TTSPrompt = SmartPrompt::new().into();
    assert!(matches!(basic, TTSPrompt::Basic(_)));
    assert!(matches!(preset, TTSPrompt::Preset(_)));
    assert!(matches!(smart, TTSPrompt::Smart(_)));
}

#[test]
fn tts_request_builder_sets_all_fields() {
    let req = TTSRequest::new("tc_voice", "hello", TTSModel::SsfmV21)
        .language("eng")
        .prompt(Prompt::new().emotion_preset(EmotionPreset::Angry))
        .output(Output::new().volume(100))
        .seed(7);
    assert_eq!(req.voice_id, "tc_voice");
    assert_eq!(req.text, "hello");
    assert_eq!(req.model, TTSModel::SsfmV21);
    assert_eq!(req.language.as_deref(), Some("eng"));
    assert!(req.prompt.is_some());
    assert!(req.output.is_some());
    assert_eq!(req.seed, Some(7));
}

#[test]
fn output_stream_builder_clamps_values() {
    let out = OutputStream::default();
    assert!(out.audio_pitch.is_none());
    assert!(out.audio_tempo.is_none());
    assert!(out.audio_format.is_none());

    let out = OutputStream::new()
        .audio_pitch(20)
        .audio_tempo(5.0)
        .audio_format(AudioFormat::Mp3);
    assert_eq!(out.audio_pitch, Some(12));
    assert_eq!(out.audio_tempo, Some(2.0));
    assert_eq!(out.audio_format, Some(AudioFormat::Mp3));

    let out2 = OutputStream::new().audio_pitch(-100).audio_tempo(0.1);
    assert_eq!(out2.audio_pitch, Some(-12));
    assert_eq!(out2.audio_tempo, Some(0.5));

    // Cover Debug + Clone
    let _ = format!("{out2:?}");
    let _ = out2.clone();

    // Ensure volume / target_lufs are NOT serialized for OutputStream.
    let json = serde_json::to_string(&OutputStream::new().audio_format(AudioFormat::Wav)).unwrap();
    assert!(!json.contains("volume"));
    assert!(!json.contains("target_lufs"));
}

#[test]
fn tts_request_stream_builder_sets_all_fields() {
    let req = TTSRequestStream::new("tc_voice", "hello", TTSModel::SsfmV21)
        .language("eng")
        .prompt(Prompt::new().emotion_preset(EmotionPreset::Angry))
        .output(OutputStream::new().audio_format(AudioFormat::Mp3))
        .seed(7);
    assert_eq!(req.voice_id, "tc_voice");
    assert_eq!(req.text, "hello");
    assert_eq!(req.model, TTSModel::SsfmV21);
    assert_eq!(req.language.as_deref(), Some("eng"));
    assert!(req.prompt.is_some());
    assert!(req.output.is_some());
    assert_eq!(req.seed, Some(7));

    // Cover Debug + Clone
    let _ = format!("{req:?}");
    let _ = req.clone();

    // Default-only request (no optional builders) to cover the unset branches.
    let bare = TTSRequestStream::new("tc_x", "hi", TTSModel::SsfmV30);
    assert!(bare.language.is_none());
    assert!(bare.prompt.is_none());
    assert!(bare.output.is_none());
    assert!(bare.seed.is_none());
}

#[test]
fn voices_v2_filter_builder_sets_all_fields() {
    let f = VoicesV2Filter::new()
        .model(TTSModel::SsfmV30)
        .gender(Gender::Female)
        .age(Age::YoungAdult)
        .use_cases(UseCase::Audiobook);
    assert_eq!(f.model, Some(TTSModel::SsfmV30));
    assert_eq!(f.gender, Some(Gender::Female));
    assert_eq!(f.age, Some(Age::YoungAdult));
    assert!(f.use_cases.is_some());
}

#[test]
fn enums_serialize_with_expected_strings() {
    // Cover serde rename / rename_all branches.
    assert_eq!(
        serde_json::to_string(&TTSModel::SsfmV30).unwrap(),
        "\"ssfm-v30\""
    );
    assert_eq!(
        serde_json::to_string(&TTSModel::SsfmV21).unwrap(),
        "\"ssfm-v21\""
    );

    for emo in [
        EmotionPreset::Normal,
        EmotionPreset::Happy,
        EmotionPreset::Sad,
        EmotionPreset::Angry,
        EmotionPreset::Whisper,
        EmotionPreset::ToneUp,
        EmotionPreset::ToneDown,
    ] {
        let _ = serde_json::to_string(&emo).unwrap();
    }

    for fmt in [AudioFormat::Wav, AudioFormat::Mp3] {
        let _ = serde_json::to_string(&fmt).unwrap();
    }

    for g in [Gender::Male, Gender::Female] {
        let _ = serde_json::to_string(&g).unwrap();
    }

    for a in [
        Age::Child,
        Age::Teenager,
        Age::YoungAdult,
        Age::MiddleAge,
        Age::Elder,
    ] {
        let _ = serde_json::to_string(&a).unwrap();
    }

    for uc in [
        UseCase::Announcer,
        UseCase::Anime,
        UseCase::Audiobook,
        UseCase::Conversational,
        UseCase::Documentary,
        UseCase::ELearning,
        UseCase::Rapper,
        UseCase::Game,
        UseCase::TikTokReels,
        UseCase::News,
        UseCase::Podcast,
        UseCase::Voicemail,
        UseCase::Ads,
    ] {
        let _ = serde_json::to_string(&uc).unwrap();
    }

    let mi = ModelInfo {
        version: TTSModel::SsfmV30,
        emotions: vec!["happy".into()],
    };
    let _ = serde_json::to_string(&mi).unwrap();

    let voice = VoiceV2 {
        voice_id: "tc_x".into(),
        voice_name: "name".into(),
        models: vec![mi],
        gender: Some(Gender::Male),
        age: Some(Age::Elder),
        use_cases: Some(vec!["news".into()]),
    };
    let _ = serde_json::to_string(&voice).unwrap();

    // Cover Clone/Debug for ErrorResponse and TTSRequest.
    let er = ErrorResponse {
        detail: "x".into(),
    };
    let _ = format!("{er:?}");
    let _ = er.clone();
}

// ---------------------------------------------------------------------------
// client.rs - construction and accessors
// ---------------------------------------------------------------------------

#[test]
fn client_config_default_reads_env_or_default() {
    // Don't set env to anything specific - just exercise the path.
    let cfg = ClientConfig::default();
    // Either env-driven or fallback default; we only assert it parses.
    assert!(!cfg.base_url.is_empty());
    assert_eq!(cfg.timeout, Duration::from_secs(DEFAULT_TIMEOUT_SECS));
}

#[test]
fn client_config_new_and_builders() {
    let cfg = ClientConfig::new("k")
        .base_url("http://example.com")
        .timeout(Duration::from_secs(10));
    assert_eq!(cfg.api_key, "k");
    assert_eq!(cfg.base_url, "http://example.com");
    assert_eq!(cfg.timeout, Duration::from_secs(10));
    let _ = format!("{cfg:?}"); // Debug
    let _ = cfg.clone();
}

#[test]
fn client_with_api_key_and_accessors() {
    let client = TypecastClient::with_api_key("abcdefghij").unwrap();
    assert_eq!(client.api_key_masked(), "abcd...ghij");
    let _ = client.base_url();
    let _ = format!("{client:?}");
    let _ = client.clone();
}

#[test]
fn client_api_key_masked_short_key() {
    let client = TypecastClient::with_api_key("short").unwrap();
    assert_eq!(client.api_key_masked(), "****");
}

#[test]
fn client_new_rejects_invalid_api_key_header() {
    // Newline characters are not valid in HTTP header values.
    let result = TypecastClient::with_api_key("bad\nkey");
    let err = result.unwrap_err();
    assert!(err.is_bad_request());
    assert!(err.to_string().contains("Invalid API key format"));
}

#[test]
fn client_from_env_uses_default_config() {
    // Even with no env, default api key may be empty - just validate it parses
    // when we set a value. We rely on the existing value (or empty) being a
    // valid header string; empty string is acceptable for HeaderValue.
    let prev = std::env::var("TYPECAST_API_KEY").ok();
    std::env::set_var("TYPECAST_API_KEY", "env-key");
    let client = TypecastClient::from_env().expect("from_env should succeed");
    assert!(client.base_url().starts_with("http"));
    // Restore
    match prev {
        Some(v) => std::env::set_var("TYPECAST_API_KEY", v),
        None => std::env::remove_var("TYPECAST_API_KEY"),
    }

    // Sanity-check that DEFAULT_BASE_URL is the public re-export.
    assert!(DEFAULT_BASE_URL.starts_with("http"));
}

// ---------------------------------------------------------------------------
// client.rs - text_to_speech
// ---------------------------------------------------------------------------

#[tokio::test]
async fn text_to_speech_returns_wav_with_duration_header() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/v1/text-to-speech")
        .with_status(200)
        .with_header("content-type", "audio/wav")
        .with_header("X-Audio-Duration", "1.25")
        .with_body(b"RIFFwavfakebody")
        .create_async()
        .await;

    let client = make_client(&server);
    let req = TTSRequest::new("tc_x", "hello", TTSModel::SsfmV30);
    let resp = client.text_to_speech(&req).await.unwrap();
    assert_eq!(resp.format, AudioFormat::Wav);
    assert!((resp.duration - 1.25).abs() < f64::EPSILON);
    assert_eq!(&resp.audio_data[..4], b"RIFF");
    let _ = format!("{resp:?}");
    let _ = resp.clone();
}

#[tokio::test]
async fn text_to_speech_returns_mp3_when_content_type_says_mp3() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/v1/text-to-speech")
        .with_status(200)
        .with_header("content-type", "audio/mp3")
        .with_body(b"mp3data")
        .create_async()
        .await;

    let client = make_client(&server);
    let req = TTSRequest::new("tc_x", "hi", TTSModel::SsfmV30);
    let resp = client.text_to_speech(&req).await.unwrap();
    assert_eq!(resp.format, AudioFormat::Mp3);
    assert_eq!(resp.duration, 0.0);
}

#[tokio::test]
async fn text_to_speech_returns_mp3_for_audio_mpeg() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/v1/text-to-speech")
        .with_status(200)
        .with_header("content-type", "audio/mpeg")
        .with_body(b"mpegdata")
        .create_async()
        .await;

    let client = make_client(&server);
    let req = TTSRequest::new("tc_x", "hi", TTSModel::SsfmV30)
        .language("eng")
        .prompt(SmartPrompt::new().previous_text("a"))
        .output(Output::new().audio_format(AudioFormat::Mp3))
        .seed(11);
    let resp = client.text_to_speech(&req).await.unwrap();
    assert_eq!(resp.format, AudioFormat::Mp3);
}

#[tokio::test]
async fn text_to_speech_propagates_api_errors() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/v1/text-to-speech")
        .with_status(401)
        .with_header("content-type", "application/json")
        .with_body(r#"{"detail":"bad key"}"#)
        .create_async()
        .await;

    let client = make_client(&server);
    let req = TTSRequest::new("tc_x", "hi", TTSModel::SsfmV30);
    let err = client.text_to_speech(&req).await.unwrap_err();
    assert!(err.is_unauthorized());
}

#[tokio::test]
async fn text_to_speech_handles_error_with_unparseable_body() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/v1/text-to-speech")
        .with_status(500)
        .with_header("content-type", "text/plain")
        .with_body("internal boom")
        .create_async()
        .await;

    let client = make_client(&server);
    let req = TTSRequest::new("tc_x", "hi", TTSModel::SsfmV30);
    let err = client.text_to_speech(&req).await.unwrap_err();
    assert!(err.is_server_error());
}

// ---------------------------------------------------------------------------
// client.rs - text_to_speech_stream
// ---------------------------------------------------------------------------

#[tokio::test]
async fn text_to_speech_stream_returns_chunked_bytes() {
    let mut server = Server::new_async().await;
    let body = b"RIFFwavfakebodychunk1chunk2";
    let _m = server
        .mock("POST", "/v1/text-to-speech/stream")
        .with_status(200)
        .with_header("content-type", "audio/wav")
        .with_body(body)
        .create_async()
        .await;

    let client = make_client(&server);
    let req = TTSRequestStream::new("tc_x", "hello", TTSModel::SsfmV30)
        .output(OutputStream::new().audio_format(AudioFormat::Wav));
    let mut stream = client.text_to_speech_stream(&req).await.unwrap();

    let mut collected: Vec<u8> = Vec::new();
    let mut chunk_count: usize = 0;
    while let Some(chunk) = stream.next().await {
        let bytes = chunk.unwrap();
        collected.extend_from_slice(&bytes);
        chunk_count += 1;
    }
    assert_eq!(collected, body);
    assert!(chunk_count >= 1, "expected at least one chunk from stream");
}

#[tokio::test]
async fn text_to_speech_stream_maps_all_error_statuses() {
    let cases: &[(u16, fn(&TypecastError) -> bool)] = &[
        (400, TypecastError::is_bad_request),
        (401, TypecastError::is_unauthorized),
        (402, TypecastError::is_payment_required),
        (404, TypecastError::is_not_found),
        (422, TypecastError::is_validation_error),
        (429, TypecastError::is_rate_limited),
        (500, TypecastError::is_server_error),
    ];

    for (status, predicate) in cases {
        let mut server = Server::new_async().await;
        let _m = server
            .mock("POST", "/v1/text-to-speech/stream")
            .with_status(*status as usize)
            .with_header("content-type", "application/json")
            .with_body(r#"{"detail":"nope"}"#)
            .create_async()
            .await;

        let client = make_client(&server);
        let req = TTSRequestStream::new("tc_x", "hi", TTSModel::SsfmV30);
        let err = match client.text_to_speech_stream(&req).await {
            Ok(_) => panic!("expected error for status {status}"),
            Err(e) => e,
        };
        assert!(predicate(&err), "status {status} did not map correctly");
    }
}

#[tokio::test]
async fn text_to_speech_stream_handles_error_with_unparseable_body() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/v1/text-to-speech/stream")
        .with_status(500)
        .with_header("content-type", "text/plain")
        .with_body("internal boom")
        .create_async()
        .await;

    let client = make_client(&server);
    let req = TTSRequestStream::new("tc_x", "hi", TTSModel::SsfmV30);
    let err = match client.text_to_speech_stream(&req).await {
        Ok(_) => panic!("expected server error"),
        Err(e) => e,
    };
    assert!(err.is_server_error());
}

#[tokio::test]
async fn text_to_speech_stream_chunk_error_when_connection_drops() {
    // Mock a 200 OK that closes the connection mid-body so consuming the
    // stream yields a chunk-level transport error mapped through `From`.
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/v1/text-to-speech/stream")
        .with_status(200)
        .with_header("content-type", "audio/wav")
        .with_header("content-length", "1024")
        .with_body(b"truncated")
        .create_async()
        .await;

    let client = make_client(&server);
    let req = TTSRequestStream::new("tc_x", "hi", TTSModel::SsfmV30);

    // The truncated body may surface either as an error from the initial
    // `send().await` (caught by `?` and mapped via `From<reqwest::Error>`),
    // or as a per-chunk error when the stream is consumed. Both paths must
    // resolve to a transport HttpError.
    let mut saw_error = false;
    match client.text_to_speech_stream(&req).await {
        Err(e) => {
            assert!(matches!(e, TypecastError::HttpError(_)));
            saw_error = true;
        }
        Ok(mut stream) => {
            while let Some(item) = stream.next().await {
                if let Err(e) = item {
                    assert!(matches!(e, TypecastError::HttpError(_)));
                    saw_error = true;
                    break;
                }
            }
        }
    }
    assert!(saw_error, "expected a transport error from truncated body");
}

// ---------------------------------------------------------------------------
// client.rs - get_voices_v2
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_voices_v2_no_filter_returns_list() {
    let mut server = Server::new_async().await;
    let body = r#"[{
        "voice_id":"tc_a",
        "voice_name":"Alice",
        "models":[{"version":"ssfm-v30","emotions":["normal"]}],
        "gender":"female",
        "age":"young_adult",
        "use_cases":["news"]
    }]"#;
    let _m = server
        .mock("GET", "/v2/voices")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(body)
        .create_async()
        .await;

    let client = make_client(&server);
    let voices = client.get_voices_v2(None).await.unwrap();
    assert_eq!(voices.len(), 1);
    assert_eq!(voices[0].voice_id, "tc_a");
}

#[tokio::test]
async fn get_voices_v2_with_full_filter_appends_query_params() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v2/voices")
        .match_query(mockito::Matcher::AllOf(vec![
            mockito::Matcher::UrlEncoded("model".into(), "ssfm-v30".into()),
            mockito::Matcher::UrlEncoded("gender".into(), "male".into()),
            mockito::Matcher::UrlEncoded("age".into(), "elder".into()),
        ]))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body("[]")
        .create_async()
        .await;

    let client = make_client(&server);
    let filter = VoicesV2Filter::new()
        .model(TTSModel::SsfmV30)
        .gender(Gender::Male)
        .age(Age::Elder)
        .use_cases(UseCase::News);
    let voices = client.get_voices_v2(Some(filter)).await.unwrap();
    assert!(voices.is_empty());
}

#[tokio::test]
async fn get_voices_v2_propagates_api_errors() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v2/voices")
        .with_status(429)
        .with_header("content-type", "application/json")
        .with_body(r#"{"detail":"slow down"}"#)
        .create_async()
        .await;

    let client = make_client(&server);
    let err = client.get_voices_v2(None).await.unwrap_err();
    assert!(err.is_rate_limited());
}

// ---------------------------------------------------------------------------
// client.rs - get_voice_v2
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_voice_v2_returns_voice() {
    let mut server = Server::new_async().await;
    let body = r#"{
        "voice_id":"tc_a",
        "voice_name":"Alice",
        "models":[{"version":"ssfm-v21","emotions":[]}]
    }"#;
    let _m = server
        .mock("GET", "/v2/voices/tc_a")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(body)
        .create_async()
        .await;

    let client = make_client(&server);
    let voice = client.get_voice_v2("tc_a").await.unwrap();
    assert_eq!(voice.voice_id, "tc_a");
}

#[tokio::test]
async fn get_voice_v2_propagates_404() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v2/voices/missing")
        .with_status(404)
        .with_header("content-type", "application/json")
        .with_body(r#"{"detail":"not found"}"#)
        .create_async()
        .await;

    let client = make_client(&server);
    let err = client.get_voice_v2("missing").await.unwrap_err();
    assert!(err.is_not_found());
}

// ---------------------------------------------------------------------------
// client.rs - urlencoding helper
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_voices_v2_filter_covers_every_enum_variant() {
    // Each filter call must hit a fresh mock; use a regex matcher that
    // accepts any query string so we can iterate through every enum value
    // and exercise every helper match arm.
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", mockito::Matcher::Regex("^/v2/voices".into()))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body("[]")
        .expect_at_least(1)
        .create_async()
        .await;

    let client = make_client(&server);

    // Models
    for model in [TTSModel::SsfmV30, TTSModel::SsfmV21] {
        let f = VoicesV2Filter::new().model(model);
        client.get_voices_v2(Some(f)).await.unwrap();
    }
    // Genders
    for g in [Gender::Male, Gender::Female] {
        let f = VoicesV2Filter::new().gender(g);
        client.get_voices_v2(Some(f)).await.unwrap();
    }
    // Ages
    for a in [
        Age::Child,
        Age::Teenager,
        Age::YoungAdult,
        Age::MiddleAge,
        Age::Elder,
    ] {
        let f = VoicesV2Filter::new().age(a);
        client.get_voices_v2(Some(f)).await.unwrap();
    }
    // Use cases
    for uc in [
        UseCase::Announcer,
        UseCase::Anime,
        UseCase::Audiobook,
        UseCase::Conversational,
        UseCase::Documentary,
        UseCase::ELearning,
        UseCase::Rapper,
        UseCase::Game,
        UseCase::TikTokReels,
        UseCase::News,
        UseCase::Podcast,
        UseCase::Voicemail,
        UseCase::Ads,
    ] {
        let f = VoicesV2Filter::new().use_cases(uc);
        client.get_voices_v2(Some(f)).await.unwrap();
    }
}

/// Bind a TCP listener and immediately drop it to obtain a port that is
/// almost certainly free. Connecting to it will produce a connection-refused
/// error, which lets us hit `.send().await?` failure paths.
fn dead_base_url() -> String {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    drop(listener);
    format!("http://{}", addr)
}

#[tokio::test]
async fn text_to_speech_send_error_when_connection_refused() {
    let config = ClientConfig::new("k")
        .base_url(dead_base_url())
        .timeout(Duration::from_secs(2));
    let client = TypecastClient::new(config).unwrap();
    let req = TTSRequest::new("tc_x", "hi", TTSModel::SsfmV30);
    let err = client.text_to_speech(&req).await.unwrap_err();
    assert!(matches!(err, TypecastError::HttpError(_)));
}

#[tokio::test]
async fn get_voices_v2_send_error_when_connection_refused() {
    let config = ClientConfig::new("k")
        .base_url(dead_base_url())
        .timeout(Duration::from_secs(2));
    let client = TypecastClient::new(config).unwrap();
    let err = client.get_voices_v2(None).await.unwrap_err();
    assert!(matches!(err, TypecastError::HttpError(_)));
}

#[tokio::test]
async fn get_voice_v2_send_error_when_connection_refused() {
    let config = ClientConfig::new("k")
        .base_url(dead_base_url())
        .timeout(Duration::from_secs(2));
    let client = TypecastClient::new(config).unwrap();
    let err = client.get_voice_v2("tc_a").await.unwrap_err();
    assert!(matches!(err, TypecastError::HttpError(_)));
}

#[tokio::test]
async fn text_to_speech_send_error_on_timeout() {
    // Force a transport-level error from `.send().await?` by giving the
    // client a sub-millisecond timeout against a server that delays.
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/v1/text-to-speech")
        .with_status(200)
        .with_chunked_body(|w| {
            std::thread::sleep(Duration::from_millis(500));
            w.write_all(b"x")
        })
        .create_async()
        .await;

    let config = ClientConfig::new("k")
        .base_url(server.url())
        .timeout(Duration::from_millis(20));
    let client = TypecastClient::new(config).unwrap();
    let req = TTSRequest::new("tc_x", "hi", TTSModel::SsfmV30);
    let err = client.text_to_speech(&req).await.unwrap_err();
    assert!(matches!(err, TypecastError::HttpError(_)));
}

#[tokio::test]
async fn get_voice_v2_send_error_on_timeout() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v2/voices/tc_a")
        .with_status(200)
        .with_chunked_body(|w| {
            std::thread::sleep(Duration::from_millis(500));
            w.write_all(b"{}")
        })
        .create_async()
        .await;

    let config = ClientConfig::new("k")
        .base_url(server.url())
        .timeout(Duration::from_millis(20));
    let client = TypecastClient::new(config).unwrap();
    let err = client.get_voice_v2("tc_a").await.unwrap_err();
    assert!(matches!(err, TypecastError::HttpError(_)));
}

#[tokio::test]
async fn get_voice_v2_propagates_invalid_json_body() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v2/voices/tc_a")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body("not json at all")
        .create_async()
        .await;

    let client = make_client(&server);
    let err = client.get_voice_v2("tc_a").await.unwrap_err();
    // reqwest converts JSON parse failures into reqwest::Error.
    assert!(matches!(err, TypecastError::HttpError(_)));
}

// ---------------------------------------------------------------------------
// client.rs - get_my_subscription
// ---------------------------------------------------------------------------

#[tokio::test]
async fn get_my_subscription_returns_subscription() {
    let mut server = Server::new_async().await;
    let body = r#"{
        "plan":"plus",
        "credits":{"plan_credits":10000,"used_credits":2500},
        "limits":{"concurrency_limit":8}
    }"#;
    let _m = server
        .mock("GET", "/v1/users/me/subscription")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(body)
        .create_async()
        .await;

    let client = make_client(&server);
    let sub = client.get_my_subscription().await.unwrap();
    assert_eq!(sub.plan, PlanTier::Plus);
    assert_eq!(sub.credits.plan_credits, 10000);
    assert_eq!(sub.credits.used_credits, 2500);
    assert_eq!(sub.limits.concurrency_limit, 8);

    // Cover Debug/Clone/PartialEq for the new types.
    let _ = format!("{sub:?}");
    let cloned = sub.clone();
    assert_eq!(sub, cloned);
}

#[tokio::test]
async fn get_my_subscription_propagates_unauthorized() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v1/users/me/subscription")
        .with_status(401)
        .with_header("content-type", "application/json")
        .with_body(r#"{"detail":"bad key"}"#)
        .create_async()
        .await;

    let client = make_client(&server);
    let err = client.get_my_subscription().await.unwrap_err();
    assert!(err.is_unauthorized());
}

#[tokio::test]
async fn get_my_subscription_propagates_rate_limited() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v1/users/me/subscription")
        .with_status(429)
        .with_header("content-type", "application/json")
        .with_body(r#"{"detail":"slow down"}"#)
        .create_async()
        .await;

    let client = make_client(&server);
    let err = client.get_my_subscription().await.unwrap_err();
    assert!(err.is_rate_limited());
}

#[tokio::test]
async fn get_my_subscription_propagates_server_error() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v1/users/me/subscription")
        .with_status(500)
        .with_header("content-type", "application/json")
        .with_body(r#"{"detail":"boom"}"#)
        .create_async()
        .await;

    let client = make_client(&server);
    let err = client.get_my_subscription().await.unwrap_err();
    assert!(err.is_server_error());
}

#[tokio::test]
async fn get_my_subscription_propagates_invalid_json_body() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v1/users/me/subscription")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body("not json at all")
        .create_async()
        .await;

    let client = make_client(&server);
    let err = client.get_my_subscription().await.unwrap_err();
    assert!(matches!(err, TypecastError::HttpError(_)));
}

#[tokio::test]
async fn get_my_subscription_send_error_when_connection_refused() {
    let config = ClientConfig::new("k")
        .base_url(dead_base_url())
        .timeout(Duration::from_secs(2));
    let client = TypecastClient::new(config).unwrap();
    let err = client.get_my_subscription().await.unwrap_err();
    assert!(matches!(err, TypecastError::HttpError(_)));
}

#[test]
fn plan_tier_serializes_with_lowercase() {
    assert_eq!(serde_json::to_string(&PlanTier::Free).unwrap(), "\"free\"");
    assert_eq!(serde_json::to_string(&PlanTier::Lite).unwrap(), "\"lite\"");
    assert_eq!(serde_json::to_string(&PlanTier::Plus).unwrap(), "\"plus\"");
    assert_eq!(
        serde_json::to_string(&PlanTier::Custom).unwrap(),
        "\"custom\""
    );

    // Round-trip through Credits/Limits to cover their derives.
    let credits = Credits {
        plan_credits: 1,
        used_credits: 0,
    };
    let limits = Limits {
        concurrency_limit: 2,
    };
    let sub = SubscriptionResponse {
        plan: PlanTier::Free,
        credits: credits.clone(),
        limits: limits.clone(),
    };
    let json = serde_json::to_string(&sub).unwrap();
    let parsed: SubscriptionResponse = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed, sub);
    let _ = format!("{credits:?}{limits:?}");
}

#[tokio::test]
async fn url_encoding_handles_special_characters_in_filter_values() {
    // Force the urlencoding helper's escape branch by going through a filter
    // value that contains characters outside the unreserved set. We can't pass
    // arbitrary strings to filters, but the helper is exercised by the
    // `use_cases=Tiktok/Reels` value (slash needs encoding) below.
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/v2/voices")
        .match_query(mockito::Matcher::Regex("use_cases=Tiktok%2FReels".into()))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body("[]")
        .create_async()
        .await;

    let client = make_client(&server);
    let filter = VoicesV2Filter::new().use_cases(UseCase::TikTokReels);
    let voices = client.get_voices_v2(Some(filter)).await.unwrap();
    assert!(voices.is_empty());
}