typecast-rust 0.3.9

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
//! Typecast API client
//!
//! This module contains the main client for interacting with the Typecast API.

use crate::composer::SpeechComposer;
use crate::errors::{Result, TypecastError};
use crate::models::{
    Age, AudioFormat, CustomVoice, ErrorResponse, Gender, GenerateToFileRequest, RecommendedVoice,
    SubscriptionResponse, TTSModel, TTSRequest, TTSRequestStream, TTSResponse, UseCase, VoiceV2,
    VoicesV2Filter, CLONING_MAX_FILE_SIZE, NAME_MAX_LENGTH, NAME_MIN_LENGTH,
};
use bytes::Bytes;
use futures_util::stream::{Stream, StreamExt};
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE, USER_AGENT};
use serde::Serialize;
use std::env;
use std::fs;
use std::path::Path;
use std::pin::Pin;
use std::time::Duration;

/// Boxed asynchronous stream of audio chunks returned by the streaming TTS endpoint.
pub type AudioByteStream = Pin<Box<dyn Stream<Item = Result<Bytes>> + Send>>;

/// Convert a [`TTSModel`] into the wire format string used in query parameters.
fn model_query_value(model: TTSModel) -> &'static str {
    match model {
        TTSModel::SsfmV30 => "ssfm-v30",
        TTSModel::SsfmV21 => "ssfm-v21",
    }
}

/// Convert a [`Gender`] into the wire format string used in query parameters.
fn gender_query_value(gender: Gender) -> &'static str {
    match gender {
        Gender::Male => "male",
        Gender::Female => "female",
    }
}

/// Convert an [`Age`] into the wire format string used in query parameters.
fn age_query_value(age: Age) -> &'static str {
    match age {
        Age::Child => "child",
        Age::Teenager => "teenager",
        Age::YoungAdult => "young_adult",
        Age::MiddleAge => "middle_age",
        Age::Elder => "elder",
    }
}

/// Convert a [`UseCase`] into the wire format string used in query parameters.
fn use_case_query_value(use_case: UseCase) -> &'static str {
    match use_case {
        UseCase::Announcer => "Announcer",
        UseCase::Anime => "Anime",
        UseCase::Audiobook => "Audiobook",
        UseCase::Conversational => "Conversational",
        UseCase::Documentary => "Documentary",
        UseCase::ELearning => "E-learning",
        UseCase::Rapper => "Rapper",
        UseCase::Game => "Game",
        UseCase::TikTokReels => "Tiktok/Reels",
        UseCase::News => "News",
        UseCase::Podcast => "Podcast",
        UseCase::Voicemail => "Voicemail",
        UseCase::Ads => "Ads",
    }
}

fn infer_audio_format_from_path(path: &Path) -> Option<AudioFormat> {
    match path.extension().and_then(|extension| extension.to_str()) {
        Some(extension) if extension.eq_ignore_ascii_case("mp3") => Some(AudioFormat::Mp3),
        Some(extension) if extension.eq_ignore_ascii_case("wav") => Some(AudioFormat::Wav),
        _ => None,
    }
}

/// Default API base URL
pub const DEFAULT_BASE_URL: &str = "https://api.typecast.ai";

/// Default request timeout in seconds
pub const DEFAULT_TIMEOUT_SECS: u64 = 60;

/// Configuration for the Typecast client
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// API key for authentication. Optional when using a proxy base URL.
    pub api_key: String,
    /// Base URL for the API (defaults to <https://api.typecast.ai>)
    pub base_url: String,
    /// Request timeout duration
    pub timeout: Duration,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            api_key: env::var("TYPECAST_API_KEY").unwrap_or_default(),
            base_url: env::var("TYPECAST_API_HOST")
                .unwrap_or_else(|_| DEFAULT_BASE_URL.to_string()),
            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
        }
    }
}

impl ClientConfig {
    /// Create a new configuration with an API key
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            ..Default::default()
        }
    }

    /// Set a custom base URL
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Set a custom timeout
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }
}

/// The main Typecast API client
#[derive(Debug, Clone)]
pub struct TypecastClient {
    client: reqwest::Client,
    base_url: String,
    api_key: String,
}

impl TypecastClient {
    /// Create a new TypecastClient with the given configuration
    pub fn new(config: ClientConfig) -> Result<Self> {
        let api_key = config.api_key.trim().to_string();
        let base_url = config.base_url.trim().trim_end_matches('/').to_string();
        if api_key.is_empty() && is_default_base_url(&base_url) {
            return Err(TypecastError::Unauthorized {
                detail: "API key is required for the default Typecast API host".to_string(),
            });
        }

        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
        headers.insert(
            USER_AGENT,
            HeaderValue::from_str(&build_user_agent(&base_url, config.timeout))
                .expect("SDK-generated User-Agent is valid ASCII"),
        );
        if !api_key.is_empty() {
            headers.insert(
                "X-API-KEY",
                HeaderValue::from_str(&api_key).map_err(|_| TypecastError::BadRequest {
                    detail: "Invalid API key format".to_string(),
                })?,
            );
        }

        // `reqwest::Client::builder().build()` only fails if TLS init fails,
        // which is not something we can usefully recover from at this layer.
        let client = reqwest::Client::builder()
            .default_headers(headers)
            .timeout(config.timeout)
            .build()
            .expect("reqwest client builder should not fail");

        Ok(Self {
            client,
            base_url,
            api_key,
        })
    }

    /// Create a new TypecastClient from environment variables
    ///
    /// Reads TYPECAST_API_KEY and optionally TYPECAST_API_HOST
    pub fn from_env() -> Result<Self> {
        Self::new(ClientConfig::default())
    }

    /// Create a new TypecastClient with just an API key
    pub fn with_api_key(api_key: impl Into<String>) -> Result<Self> {
        Self::new(ClientConfig::new(api_key))
    }

    /// Get the base URL
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Get the API key (masked)
    pub fn api_key_masked(&self) -> String {
        if self.api_key.len() > 8 {
            format!(
                "{}...{}",
                &self.api_key[..4],
                &self.api_key[self.api_key.len() - 4..]
            )
        } else {
            "****".to_string()
        }
    }

    /// Create a builder for composed speech with multiple speech segments and pauses.
    pub fn compose_speech(&self) -> SpeechComposer<'_> {
        SpeechComposer::new(self)
    }

    fn with_auth_header(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        if self.api_key.is_empty() {
            request
        } else {
            request.header("X-API-KEY", &self.api_key)
        }
    }

    /// Build a URL with optional query parameters.
    ///
    /// Callers must pass `None` when there are no query parameters; passing
    /// `Some(vec![])` is not supported and will produce a trailing `?`.
    fn build_url(&self, path: &str, params: Option<Vec<(&str, String)>>) -> String {
        let base = format!("{}{}", self.base_url, path);
        match params {
            Some(params) => {
                let query: Vec<String> = params
                    .into_iter()
                    .map(|(k, v)| format!("{}={}", k, urlencoding::encode(&v)))
                    .collect();
                format!("{}?{}", base, query.join("&"))
            }
            None => base,
        }
    }

    /// Handle an error response
    async fn handle_error_response(&self, response: reqwest::Response) -> TypecastError {
        let status_code = response.status().as_u16();
        let error_response: Option<ErrorResponse> = response.json().await.ok();
        TypecastError::from_response(status_code, error_response)
    }

    /// Convert text to speech
    ///
    /// # Arguments
    ///
    /// * `request` - The TTS request containing text, voice_id, model, and optional settings
    ///
    /// # Returns
    ///
    /// Returns a `TTSResponse` containing the audio data, duration, and format
    ///
    /// # Example
    ///
    /// ```no_run
    /// use typecast_rust::{TypecastClient, TTSRequest, TTSModel, ClientConfig};
    ///
    /// # async fn example() -> typecast_rust::Result<()> {
    /// let client = TypecastClient::from_env()?;
    /// let request = TTSRequest::new(
    ///     "tc_60e5426de8b95f1d3000d7b5",
    ///     "Hello, world!",
    ///     TTSModel::SsfmV30,
    /// );
    /// let response = client.text_to_speech(&request).await?;
    /// println!("Audio duration: {} seconds", response.duration);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn text_to_speech(&self, request: &TTSRequest) -> Result<TTSResponse> {
        let url = self.build_url("/v1/text-to-speech", None);

        let response = self.client.post(&url).json(request).send().await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        // Parse content type for format
        let content_type = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("audio/wav");

        let format = if content_type.contains("mp3") || content_type.contains("mpeg") {
            AudioFormat::Mp3
        } else {
            AudioFormat::Wav
        };

        // Parse duration from header
        let duration = response
            .headers()
            .get("X-Audio-Duration")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<f64>().ok())
            .unwrap_or(0.0);

        let audio_data = response.bytes().await?.to_vec();

        Ok(TTSResponse {
            audio_data,
            duration,
            format,
        })
    }

    pub(crate) async fn compose_text_to_speech(
        &self,
        request: &impl Serialize,
    ) -> Result<TTSResponse> {
        let url = self.build_url("/v1/text-to-speech/compose", None);
        let response = self.client.post(&url).json(request).send().await?;
        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }
        let format = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .filter(|v| {
                let normalized = v.to_ascii_lowercase();
                normalized.contains("mp3") || normalized.contains("mpeg")
            })
            .map(|_| AudioFormat::Mp3)
            .unwrap_or(AudioFormat::Wav);
        let duration = response
            .headers()
            .get("X-Audio-Duration")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<f64>().ok())
            .unwrap_or(0.0);
        Ok(TTSResponse {
            audio_data: response.bytes().await?.to_vec(),
            duration,
            format,
        })
    }

    /// Convert text to speech and write the audio bytes to a file.
    ///
    /// If `request.output.audio_format` is omitted, the format is inferred from
    /// a `.mp3` or `.wav` file extension.
    pub async fn generate_to_file(
        &self,
        path: impl AsRef<Path>,
        request: GenerateToFileRequest,
    ) -> Result<TTSResponse> {
        let path_ref = path.as_ref();
        let mut tts_request = request.into_tts_request();
        let inferred = infer_audio_format_from_path(path_ref);
        match tts_request.output.as_mut() {
            Some(output) => {
                if output.audio_format.is_none() {
                    output.audio_format = inferred;
                }
            }
            None => {
                if let Some(format) = inferred {
                    tts_request.output = Some(crate::models::Output::new().audio_format(format));
                }
            }
        }

        let response = self.text_to_speech(&tts_request).await?;
        fs::write(path_ref, &response.audio_data)
            .map_err(|e| TypecastError::IoError(e.to_string()))?;
        Ok(response)
    }

    /// Convert text to speech as a streaming response
    ///
    /// Returns a stream of audio byte chunks. For `wav` output the first chunk
    /// contains the WAV header followed by PCM samples; for `mp3` output each
    /// chunk is independently decodable.
    ///
    /// # Arguments
    ///
    /// * `request` - The streaming TTS request
    ///
    /// # Returns
    ///
    /// A pinned boxed [`Stream`] yielding [`Result<Bytes>`] chunks.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use futures_util::StreamExt;
    /// use typecast_rust::{TypecastClient, TTSRequestStream, TTSModel};
    ///
    /// # async fn example() -> typecast_rust::Result<()> {
    /// let client = TypecastClient::from_env()?;
    /// let request = TTSRequestStream::new(
    ///     "tc_60e5426de8b95f1d3000d7b5",
    ///     "Hello, world!",
    ///     TTSModel::SsfmV30,
    /// );
    /// let mut stream = client.text_to_speech_stream(&request).await?;
    /// while let Some(chunk) = stream.next().await {
    ///     let bytes = chunk?;
    ///     // write bytes to file or audio sink
    ///     let _ = bytes;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn text_to_speech_stream(
        &self,
        request: &TTSRequestStream,
    ) -> Result<AudioByteStream> {
        let url = self.build_url("/v1/text-to-speech/stream", None);

        let response = self.client.post(&url).json(request).send().await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let stream = response
            .bytes_stream()
            .map(|item| item.map_err(TypecastError::from));
        Ok(Box::pin(stream))
    }

    /// Get voices with enhanced metadata (V2 API)
    ///
    /// # Arguments
    ///
    /// * `filter` - Optional filter for voices (model, gender, age, use_cases)
    ///
    /// # Returns
    ///
    /// Returns a list of `VoiceV2` with enhanced metadata
    ///
    /// # Example
    ///
    /// ```no_run
    /// use typecast_rust::{TypecastClient, VoicesV2Filter, TTSModel, Gender, ClientConfig};
    ///
    /// # async fn example() -> typecast_rust::Result<()> {
    /// let client = TypecastClient::from_env()?;
    ///
    /// // Get all voices
    /// let voices = client.get_voices_v2(None).await?;
    ///
    /// // Get filtered voices
    /// let filter = VoicesV2Filter::new()
    ///     .model(TTSModel::SsfmV30)
    ///     .gender(Gender::Female);
    /// let filtered_voices = client.get_voices_v2(Some(filter)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_voices_v2(&self, filter: Option<VoicesV2Filter>) -> Result<Vec<VoiceV2>> {
        let mut params = Vec::new();

        if let Some(f) = filter {
            if let Some(model) = f.model {
                params.push(("model", model_query_value(model).to_string()));
            }
            if let Some(gender) = f.gender {
                params.push(("gender", gender_query_value(gender).to_string()));
            }
            if let Some(age) = f.age {
                params.push(("age", age_query_value(age).to_string()));
            }
            if let Some(use_cases) = f.use_cases {
                params.push(("use_cases", use_case_query_value(use_cases).to_string()));
            }
        }

        let url = self.build_url(
            "/v2/voices",
            if params.is_empty() {
                None
            } else {
                Some(params)
            },
        );

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let voices: Vec<VoiceV2> = response.json().await?;
        Ok(voices)
    }

    /// Get a specific voice by ID with enhanced metadata (V2 API)
    ///
    /// # Arguments
    ///
    /// * `voice_id` - The voice ID (e.g., 'tc_60e5426de8b95f1d3000d7b5')
    ///
    /// # Returns
    ///
    /// Returns a `VoiceV2` with enhanced metadata
    ///
    /// # Example
    ///
    /// ```no_run
    /// use typecast_rust::{TypecastClient, ClientConfig};
    ///
    /// # async fn example() -> typecast_rust::Result<()> {
    /// let client = TypecastClient::from_env()?;
    /// let voice = client.get_voice_v2("tc_60e5426de8b95f1d3000d7b5").await?;
    /// println!("Voice: {} ({})", voice.voice_name, voice.voice_id);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_voice_v2(&self, voice_id: &str) -> Result<VoiceV2> {
        let url = self.build_url(&format!("/v2/voices/{}", voice_id), None);

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let voice: VoiceV2 = response.json().await?;
        Ok(voice)
    }

    /// Recommend voices from a text description.
    ///
    /// Results only contain `voice_id`, `voice_name`, and `score`. Use
    /// `get_voice_v2` or `get_voices_v2` when you need detailed metadata for
    /// the returned voice IDs.
    pub async fn recommend_voices(
        &self,
        query: &str,
        count: Option<u8>,
    ) -> Result<Vec<RecommendedVoice>> {
        let count = count.unwrap_or(5);
        if !(1..=10).contains(&count) {
            return Err(TypecastError::ValidationError {
                detail: "count must be between 1 and 10".to_string(),
            });
        }

        let url = self.build_url(
            "/v1/voices/recommendations",
            Some(vec![
                ("query", query.to_string()),
                ("count", count.to_string()),
            ]),
        );

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let voices: Vec<RecommendedVoice> = response.json().await?;
        Ok(voices)
    }

    /// Convert text to speech with word- and/or character-level timestamps.
    ///
    /// # Arguments
    ///
    /// * `request` - The TTS request with timestamps parameters.
    /// * `granularity` - Optional granularity: `None` (both), `"word"`, or `"char"`.
    ///
    /// # Returns
    ///
    /// A [`crate::timestamps::TTSWithTimestampsResponse`] containing the Base64-encoded audio
    /// and alignment segment arrays.  Use the response's `.to_srt()` / `.to_vtt()` methods to
    /// generate subtitle files.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use typecast_rust::{TypecastClient, TTSModel};
    /// use typecast_rust::timestamps::TTSRequestWithTimestamps;
    ///
    /// # async fn example() -> typecast_rust::Result<()> {
    /// let client = TypecastClient::from_env()?;
    /// let request = TTSRequestWithTimestamps::new(
    ///     "tc_60e5426de8b95f1d3000d7b5",
    ///     "Hello, world!",
    ///     TTSModel::SsfmV30,
    /// );
    /// let response = client.text_to_speech_with_timestamps(&request, None).await?;
    /// let srt = response.to_srt()?;
    /// println!("{}", srt);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn text_to_speech_with_timestamps(
        &self,
        request: &crate::timestamps::TTSRequestWithTimestamps,
        granularity: Option<&str>,
    ) -> Result<crate::timestamps::TTSWithTimestampsResponse> {
        if let Some(g) = granularity {
            if g != "word" && g != "char" {
                return Err(TypecastError::ValidationError {
                    detail: format!(
                        "granularity must be None, \"word\", or \"char\"; got {:?}",
                        g
                    ),
                });
            }
        }

        let url = match granularity {
            Some(g) => self.build_url(
                "/v1/text-to-speech/with-timestamps",
                Some(vec![("granularity", g.to_string())]),
            ),
            None => self.build_url("/v1/text-to-speech/with-timestamps", None),
        };

        let response = self.client.post(&url).json(request).send().await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let parsed: crate::timestamps::TTSWithTimestampsResponse = response
            .json()
            .await
            .map_err(|e| TypecastError::DecodeError(e.to_string()))?;
        Ok(parsed)
    }

    /// Get the authenticated user's subscription
    ///
    /// # Returns
    ///
    /// Returns a `SubscriptionResponse` containing the user's plan, credits,
    /// and usage limits.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use typecast_rust::TypecastClient;
    ///
    /// # async fn example() -> typecast_rust::Result<()> {
    /// let client = TypecastClient::from_env()?;
    /// let subscription = client.get_my_subscription().await?;
    /// println!("Plan: {:?}", subscription.plan);
    /// println!(
    ///     "Credits: {}/{}",
    ///     subscription.credits.used_credits, subscription.credits.plan_credits
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_my_subscription(&self) -> Result<SubscriptionResponse> {
        let url = self.build_url("/v1/users/me/subscription", None);

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let subscription: SubscriptionResponse = response.json().await?;
        Ok(subscription)
    }

    /// Clone a voice from an audio recording.
    ///
    /// Uploads the audio file as `multipart/form-data` to `POST /v1/voices/clone`
    /// and returns a [`CustomVoice`] representing the newly created voice.
    ///
    /// # Arguments
    ///
    /// * `audio` - Raw audio bytes (WAV or MP3). Must not exceed 25 MB.
    /// * `filename` - File name used in the multipart part (e.g. `"sample.wav"`).
    ///   The extension determines the MIME type sent to the API.
    /// * `name` - Display name for the custom voice (1–30 characters).
    /// * `model` - TTS model to use for cloning (e.g. `"ssfm-v30"`).
    ///
    /// # Errors
    ///
    /// Returns [`TypecastError::ValidationError`] if `name` is outside 1–30 characters
    /// or if `audio` exceeds the 25 MB limit before any network call is made.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use typecast_rust::TypecastClient;
    ///
    /// # async fn example() -> typecast_rust::Result<()> {
    /// let client = TypecastClient::from_env()?;
    /// let audio = std::fs::read("sample.wav").unwrap();
    /// let voice = client.clone_voice(audio, "sample.wav", "My Voice", "ssfm-v30").await?;
    /// println!("Cloned voice ID: {}", voice.voice_id);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn clone_voice(
        &self,
        audio: Vec<u8>,
        filename: &str,
        name: &str,
        model: &str,
    ) -> Result<CustomVoice> {
        let name_len = name.chars().count();
        if !(NAME_MIN_LENGTH..=NAME_MAX_LENGTH).contains(&name_len) {
            return Err(TypecastError::ValidationError {
                detail: format!(
                    "name must be {}-{} characters; got {}",
                    NAME_MIN_LENGTH, NAME_MAX_LENGTH, name_len
                ),
            });
        }
        if audio.len() > CLONING_MAX_FILE_SIZE {
            return Err(TypecastError::ValidationError {
                detail: format!("audio file exceeds 25MB limit; got {} bytes", audio.len()),
            });
        }

        let mime = guess_audio_mime(filename);
        let part = reqwest::multipart::Part::bytes(audio)
            .file_name(filename.to_string())
            .mime_str(mime)
            .expect("guess_audio_mime only returns valid MIME constants");
        let form = reqwest::multipart::Form::new()
            .text("name", name.to_string())
            .text("model", model.to_string())
            .part("file", part);

        let url = self.build_url("/v1/voices/clone", None);
        let response = self
            .with_auth_header(self.client.post(&url))
            .multipart(form)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        let voice: CustomVoice = response.json().await?;
        Ok(voice)
    }

    /// Delete a custom (cloned) voice by its ID.
    ///
    /// Sends `DELETE /v1/voices/{voice_id}`. A 204 No Content response is
    /// treated as success; any other non-2xx status is mapped to a
    /// [`TypecastError`].
    ///
    /// # Arguments
    ///
    /// * `voice_id` - The voice ID returned by [`TypecastClient::clone_voice`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use typecast_rust::TypecastClient;
    ///
    /// # async fn example() -> typecast_rust::Result<()> {
    /// let client = TypecastClient::from_env()?;
    /// client.delete_voice("cv_abc123").await?;
    /// println!("Voice deleted.");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn delete_voice(&self, voice_id: &str) -> Result<()> {
        let url = self.build_url(&format!("/v1/voices/{}", voice_id), None);
        let response = self
            .with_auth_header(self.client.delete(&url))
            .send()
            .await?;

        let status = response.status();
        if !status.is_success() {
            return Err(self.handle_error_response(response).await);
        }
        Ok(())
    }
}

fn build_user_agent(base_url: &str, timeout: Duration) -> String {
    let base = if is_default_base_url(base_url) {
        "default"
    } else {
        "custom"
    };
    let timeout_value = if timeout == Duration::from_secs(DEFAULT_TIMEOUT_SECS) {
        "default".to_string()
    } else {
        format!("{}ms", timeout.as_millis())
    };
    format!(
        "typecast-rust/{} Rust/{} reqwest (base={}; timeout={}; os={}; arch={}; sdk_env=rust; platform=server)",
        env!("CARGO_PKG_VERSION"),
        rust_version(),
        base,
        timeout_value,
        os_name(),
        arch_name()
    )
}

fn rust_version() -> &'static str {
    "unknown"
}

fn os_name() -> &'static str {
    normalize_os_name(env::consts::OS)
}

fn normalize_os_name(os: &str) -> &'static str {
    match os {
        "macos" => "macos",
        "windows" => "windows",
        "linux" => "linux",
        "ios" => "ios",
        "android" => "android",
        _ => "unknown",
    }
}

fn arch_name() -> &'static str {
    normalize_arch_name(env::consts::ARCH)
}

fn normalize_arch_name(arch: &str) -> &'static str {
    match arch {
        "x86_64" => "x64",
        "aarch64" => "arm64",
        "x86" => "x86",
        "arm" => "arm",
        _ => "unknown",
    }
}

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

    #[test]
    fn user_agent_includes_sdk_metadata_and_base_timeout_context() {
        let default_user_agent =
            build_user_agent(DEFAULT_BASE_URL, Duration::from_secs(DEFAULT_TIMEOUT_SECS));
        assert!(default_user_agent.starts_with("typecast-rust/"));
        assert!(default_user_agent.contains("base=default"));
        assert!(default_user_agent.contains("timeout=default"));
        assert!(default_user_agent.contains("sdk_env=rust; platform=server"));

        let custom_user_agent = build_user_agent("https://proxy.example", Duration::from_secs(5));
        assert!(custom_user_agent.contains("base=custom"));
        assert!(custom_user_agent.contains("timeout=5000ms"));
    }

    #[test]
    fn platform_metadata_normalizes_known_and_unknown_values() {
        assert_eq!(normalize_os_name("macos"), "macos");
        assert_eq!(normalize_os_name("windows"), "windows");
        assert_eq!(normalize_os_name("linux"), "linux");
        assert_eq!(normalize_os_name("ios"), "ios");
        assert_eq!(normalize_os_name("android"), "android");
        assert_eq!(normalize_os_name("solaris"), "unknown");

        assert_eq!(normalize_arch_name("x86_64"), "x64");
        assert_eq!(normalize_arch_name("aarch64"), "arm64");
        assert_eq!(normalize_arch_name("x86"), "x86");
        assert_eq!(normalize_arch_name("arm"), "arm");
        assert_eq!(normalize_arch_name("mips"), "unknown");
    }
}

/// Infer an audio MIME type from a filename extension.
///
/// Defaults to `application/octet-stream` for unrecognised extensions.
fn guess_audio_mime(filename: &str) -> &'static str {
    let lower = filename.to_lowercase();
    if lower.ends_with(".wav") {
        "audio/wav"
    } else if lower.ends_with(".mp3") {
        "audio/mpeg"
    } else if lower.ends_with(".ogg") {
        "audio/ogg"
    } else if lower.ends_with(".flac") {
        "audio/flac"
    } else if lower.ends_with(".m4a") {
        "audio/mp4"
    } else {
        "application/octet-stream"
    }
}

fn is_default_base_url(base_url: &str) -> bool {
    base_url.eq_ignore_ascii_case(DEFAULT_BASE_URL)
}

/// URL encoding helper
mod urlencoding {
    pub fn encode(s: &str) -> String {
        url_encode(s)
    }

    fn url_encode(s: &str) -> String {
        let mut result = String::new();
        for c in s.chars() {
            match c {
                'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' | '~' => {
                    result.push(c);
                }
                _ => {
                    for b in c.to_string().as_bytes() {
                        result.push_str(&format!("%{:02X}", b));
                    }
                }
            }
        }
        result
    }
}