edge-completions 0.4.0

Typed Rust SDK and CLI for OpenAI-compatible chat completions through Cloudflare
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
use std::{fmt, future::Future, net::IpAddr, pin::Pin, str::FromStr, time::Duration};

use reqwest::{Url, header};
use serde::Deserialize;
use url::Host;

use crate::{
    ChatCompletion, ChatRequest, Error, InvalidConfiguration, ProviderErrorCode, ProviderFailure,
};

const DEFAULT_BASE_URL: &str = "https://api.cloudflare.com/client/v4/";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_RESPONSE_SIZE_LIMIT: usize = 4 * 1024 * 1024;
const GATEWAY_ID_HEADER: &str = "cf-aig-gateway-id";
const LEGACY_KIMI_API_TOKEN_ENV: &str = "KIMI3_ON_CLOUDFLARE_API_KEY";

/// Environment variable read by [`Client::from_env`] for the Cloudflare account ID.
pub const ACCOUNT_ID_ENV: &str = "CLOUDFLARE_ACCOUNT_ID";

/// Environment variable read by [`Client::from_env`] for the Cloudflare API token.
pub const API_TOKEN_ENV: &str = "CLOUDFLARE_API_TOKEN";

/// Provider-independent capability boundary for chat-completion adapters.
///
/// Generic application code can depend on this trait and substitute a test
/// implementation without depending on HTTP or Cloudflare configuration. The
/// returned future is statically dispatched, requires no boxed allocation for
/// trait dispatch, and is safe to move between executor threads.
///
/// Use [`DynChatCompletions`] only when runtime type erasure is required.
///
/// ```
/// use edge_completions::{
///     ChatCompletion, ChatCompletions, ChatRequest, Error,
/// };
///
/// struct Unavailable;
///
/// impl ChatCompletions for Unavailable {
///     async fn complete<'a>(
///         &'a self,
///         _request: &'a ChatRequest,
///     ) -> Result<ChatCompletion, Error> {
///         Err(Error::MissingChoice)
///     }
/// }
///
/// fn require_send<T: Send>(_: T) {}
///
/// let request = ChatRequest::kimi_k3_builder()
///     .message(edge_completions::ChatMessage::user("hello"))
///     .build();
/// require_send(Unavailable.complete(&request));
/// ```
pub trait ChatCompletions: Send + Sync {
    /// Executes one typed chat-completion request.
    ///
    /// # Errors
    ///
    /// Returns a typed [`Error`] when local configuration, transport, provider
    /// status, response bounds, response decoding, or required response content
    /// prevents completion. Implementations must not expose credentials or raw
    /// provider bodies through the error.
    ///
    /// # Cancellation
    ///
    /// Dropping the returned future cancels the operation. Implementations must
    /// not detach background work that survives the future unless that behavior
    /// is separately documented and supervised.
    fn complete<'a>(
        &'a self,
        request: &'a ChatRequest,
    ) -> impl Future<Output = Result<ChatCompletion, Error>> + Send + 'a;
}

/// Boxed future returned by [`DynChatCompletions`].
///
/// This type makes the allocation required for dynamic async dispatch explicit.
///
/// ```
/// use edge_completions::BoxChatFuture;
///
/// fn require_send<T: Send>(_: &T) {}
///
/// let future: BoxChatFuture<'static> =
///     Box::pin(async { Err(edge_completions::Error::MissingChoice) });
/// require_send(&future);
/// ```
pub type BoxChatFuture<'a> =
    Pin<Box<dyn Future<Output = Result<ChatCompletion, Error>> + Send + 'a>>;

/// Object-safe adapter for runtime-selected chat-completion implementations.
///
/// Prefer [`ChatCompletions`] with generic dispatch. This boundary performs one
/// future allocation per call in exchange for supporting values such as
/// `Arc<dyn DynChatCompletions>`.
///
/// ```
/// use edge_completions::{
///     ChatCompletion, ChatCompletions, ChatMessage, ChatRequest,
///     DynChatCompletions, Error,
/// };
///
/// struct Unavailable;
///
/// impl ChatCompletions for Unavailable {
///     async fn complete<'a>(
///         &'a self,
///         _request: &'a ChatRequest,
///     ) -> Result<ChatCompletion, Error> {
///         Err(Error::MissingChoice)
///     }
/// }
///
/// let service: &dyn DynChatCompletions = &Unavailable;
/// let request = ChatRequest::kimi_k3_builder()
///     .message(ChatMessage::user("hello"))
///     .build();
/// let _future = service.complete_boxed(&request);
/// ```
pub trait DynChatCompletions: Send + Sync {
    /// Executes one typed request through an object-safe boxed future.
    ///
    /// Dropping the returned future cancels the in-flight operation. The SDK
    /// does not leave a background task running.
    ///
    /// # Errors
    ///
    /// Returns the same typed [`Error`] contract as
    /// [`ChatCompletions::complete`].
    fn complete_boxed<'a>(&'a self, request: &'a ChatRequest) -> BoxChatFuture<'a>;
}

impl<T> DynChatCompletions for T
where
    T: ChatCompletions,
{
    fn complete_boxed<'a>(&'a self, request: &'a ChatRequest) -> BoxChatFuture<'a> {
        Box::pin(self.complete(request))
    }
}

/// A validated Cloudflare account identifier.
///
/// ```
/// use edge_completions::AccountId;
///
/// let account = AccountId::new("account-123")?;
/// assert_eq!(account.as_str(), "account-123");
/// # Ok::<(), edge_completions::InvalidConfiguration>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AccountId(String);

impl AccountId {
    /// Validates and constructs an account identifier.
    ///
    /// Leading and trailing whitespace is removed before storage.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidConfiguration::EmptyAccountId`] when the trimmed value
    /// is empty.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidConfiguration> {
        let value = value.into();
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Err(InvalidConfiguration::EmptyAccountId);
        }
        Ok(Self(trimmed.to_owned()))
    }

    /// Returns the validated identifier.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for AccountId {
    type Err = InvalidConfiguration;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for AccountId {
    type Error = InvalidConfiguration;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// A validated API token whose debug output is always redacted.
///
/// ```
/// use edge_completions::ApiToken;
///
/// let token = ApiToken::new("secret-value")?;
/// assert_eq!(format!("{token:?}"), "ApiToken([REDACTED])");
/// # Ok::<(), edge_completions::InvalidConfiguration>(())
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct ApiToken(String);

impl ApiToken {
    /// Validates and constructs an API token.
    ///
    /// The original token bytes are retained for authentication, while
    /// [`Debug`](std::fmt::Debug) always emits a redacted value.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidConfiguration::EmptyApiToken`] when the value contains
    /// only whitespace.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidConfiguration> {
        let value = value.into();
        if value.trim().is_empty() {
            return Err(InvalidConfiguration::EmptyApiToken);
        }
        Ok(Self(value))
    }
}

impl fmt::Debug for ApiToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("ApiToken([REDACTED])")
    }
}

impl FromStr for ApiToken {
    type Err = InvalidConfiguration;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for ApiToken {
    type Error = InvalidConfiguration;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// A validated API base URL.
///
/// HTTPS is required except for loopback hosts, which are permitted so callers
/// can run local contract tests without sending credentials over a network.
///
/// ```
/// use edge_completions::ApiBaseUrl;
///
/// let base = ApiBaseUrl::new("https://api.cloudflare.com/client/v4/")?;
/// assert_eq!(base.as_url().scheme(), "https");
/// # Ok::<(), edge_completions::InvalidConfiguration>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiBaseUrl(Url);

impl ApiBaseUrl {
    /// Parses and validates a provider API base URL.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidConfiguration::InvalidBaseUrl`] when the value is not a
    /// hierarchical URL with a host, contains embedded credentials, or includes
    /// a query or fragment. Returns [`InvalidConfiguration::InsecureBaseUrl`]
    /// when a non-loopback URL does not use HTTPS.
    pub fn new(value: impl AsRef<str>) -> Result<Self, InvalidConfiguration> {
        let url =
            Url::parse(value.as_ref()).map_err(|source| InvalidConfiguration::InvalidBaseUrl {
                reason: source.to_string(),
            })?;

        if url.cannot_be_a_base() || url.host().is_none() {
            return Err(InvalidConfiguration::InvalidBaseUrl {
                reason: "URL must be hierarchical and include a host".to_owned(),
            });
        }
        if !url.username().is_empty() || url.password().is_some() {
            return Err(InvalidConfiguration::InvalidBaseUrl {
                reason: "embedded credentials are not allowed".to_owned(),
            });
        }
        if url.query().is_some() || url.fragment().is_some() {
            return Err(InvalidConfiguration::InvalidBaseUrl {
                reason: "query strings and fragments are not allowed".to_owned(),
            });
        }
        if url.scheme() != "https" && !(url.scheme() == "http" && is_loopback(&url)) {
            return Err(InvalidConfiguration::InsecureBaseUrl);
        }

        Ok(Self(url))
    }

    /// Returns the validated URL.
    #[must_use]
    pub fn as_url(&self) -> &Url {
        &self.0
    }
}

impl FromStr for ApiBaseUrl {
    type Err = InvalidConfiguration;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for ApiBaseUrl {
    type Error = InvalidConfiguration;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// A validated request timeout.
///
/// ```
/// use std::time::Duration;
/// use edge_completions::RequestTimeout;
///
/// let timeout = RequestTimeout::new(Duration::from_secs(15))?;
/// assert_eq!(timeout.duration(), Duration::from_secs(15));
/// # Ok::<(), edge_completions::InvalidConfiguration>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RequestTimeout(Duration);

impl RequestTimeout {
    /// Creates a non-zero request timeout.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidConfiguration::ZeroTimeout`] when `value` is zero.
    pub fn new(value: Duration) -> Result<Self, InvalidConfiguration> {
        if value.is_zero() {
            return Err(InvalidConfiguration::ZeroTimeout);
        }
        Ok(Self(value))
    }

    /// Returns the timeout duration.
    #[must_use]
    pub fn duration(self) -> Duration {
        self.0
    }
}

impl Default for RequestTimeout {
    fn default() -> Self {
        Self(DEFAULT_TIMEOUT)
    }
}

/// A validated maximum response-body size.
///
/// ```
/// use edge_completions::ResponseSizeLimit;
///
/// let limit = ResponseSizeLimit::new(1_048_576)?;
/// assert_eq!(limit.bytes(), 1_048_576);
/// # Ok::<(), edge_completions::InvalidConfiguration>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResponseSizeLimit(usize);

impl ResponseSizeLimit {
    /// Creates a non-zero response-body byte limit.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidConfiguration::ZeroResponseSizeLimit`] when `bytes` is
    /// zero.
    pub fn new(bytes: usize) -> Result<Self, InvalidConfiguration> {
        if bytes == 0 {
            return Err(InvalidConfiguration::ZeroResponseSizeLimit);
        }
        Ok(Self(bytes))
    }

    /// Returns the maximum accepted number of bytes.
    #[must_use]
    pub fn bytes(self) -> usize {
        self.0
    }
}

impl Default for ResponseSizeLimit {
    fn default() -> Self {
        Self(DEFAULT_RESPONSE_SIZE_LIMIT)
    }
}

/// A validated value for Cloudflare's optional `cf-aig-gateway-id` header.
///
/// ```
/// use edge_completions::GatewayId;
///
/// let gateway = GatewayId::new("production-gateway")?;
/// assert_eq!(gateway.as_str(), "production-gateway");
/// # Ok::<(), edge_completions::InvalidConfiguration>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GatewayId(String);

impl GatewayId {
    /// Validates and constructs an AI Gateway identifier.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidConfiguration::InvalidGatewayId`] when the value is
    /// empty or cannot be represented safely as an HTTP header value.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidConfiguration> {
        let value = value.into();
        if value.trim().is_empty() || header::HeaderValue::from_str(&value).is_err() {
            return Err(InvalidConfiguration::InvalidGatewayId);
        }
        Ok(Self(value))
    }

    /// Returns the validated header value.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for GatewayId {
    type Err = InvalidConfiguration;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for GatewayId {
    type Error = InvalidConfiguration;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// HTTP implementation of the typed chat-completion capability.
///
/// Construct a client from validated credentials without performing a network
/// request:
///
/// ```
/// use edge_completions::{AccountId, ApiToken, Client};
///
/// let client = Client::new(
///     AccountId::new("account-123")?,
///     ApiToken::new("test-token")?,
/// );
/// assert!(client.is_ok());
/// # Ok::<(), edge_completions::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct Client {
    http: reqwest::Client,
    endpoint: Url,
    api_token: ApiToken,
    gateway_id: Option<GatewayId>,
    timeout: RequestTimeout,
    response_size_limit: ResponseSizeLimit,
}

impl Client {
    /// Creates a client from `CLOUDFLARE_ACCOUNT_ID` and
    /// `CLOUDFLARE_API_TOKEN`.
    ///
    /// `KIMI3_ON_CLOUDFLARE_API_KEY` is accepted only as a compatibility
    /// fallback when `CLOUDFLARE_API_TOKEN` is absent.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidConfiguration`] when a credential is missing or
    /// invalid, and [`Error::Transport`] when the HTTP client cannot be built.
    pub fn from_env() -> Result<Self, Error> {
        Self::builder_from_env()?.build()
    }

    /// Starts a client builder from environment-provided credentials.
    ///
    /// This is the environment-based counterpart to [`Client::builder`]. It
    /// lets applications retain the standard credential lookup while
    /// configuring transport policy or AI Gateway routing before building the
    /// client.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidConfiguration`] when a required credential is
    /// missing or violates its typed invariant.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use edge_completions::{Client, GatewayId};
    ///
    /// # fn configured_client() -> Result<Client, edge_completions::Error> {
    /// let client = Client::builder_from_env()?
    ///     .gateway_id(GatewayId::new("production-gateway")?)
    ///     .build()?;
    /// # Ok(client)
    /// # }
    /// ```
    pub fn builder_from_env() -> Result<ClientBuilder, Error> {
        Self::builder_from_env_with(|name| std::env::var(name))
    }

    /// Creates a client from validated credentials using default transport settings.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidConfiguration`] if the default API endpoint
    /// cannot satisfy the base-URL contract, or [`Error::Transport`] if the HTTP
    /// client cannot be initialized.
    pub fn new(account_id: AccountId, api_token: ApiToken) -> Result<Self, Error> {
        Self::builder(account_id, api_token).build()
    }

    /// Starts a client builder from validated credentials.
    #[must_use]
    pub fn builder(account_id: AccountId, api_token: ApiToken) -> ClientBuilder {
        ClientBuilder::new(account_id, api_token)
    }

    /// Executes one typed chat-completion request.
    ///
    /// This method performs no automatic retry, does not spawn a task, and
    /// never executes proposed tools. The caller owns retry policy,
    /// authorization, concurrency, and side effects.
    ///
    /// Dropping the returned future cancels the HTTP exchange and discards any
    /// partial response. No SDK-owned task survives cancellation.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Timeout`] when the configured whole-request deadline
    /// elapses, [`Error::Transport`] for another incomplete HTTP exchange,
    /// [`Error::ResponseTooLarge`] when the configured body limit is exceeded,
    /// [`Error::Provider`] for a non-success status, or
    /// [`Error::InvalidResponse`] when a successful body violates the supported
    /// response contract.
    pub async fn chat(&self, request: &ChatRequest) -> Result<ChatCompletion, Error> {
        let mut call = self
            .http
            .post(self.endpoint.clone())
            .bearer_auth(&self.api_token.0)
            .json(request);

        if let Some(gateway_id) = &self.gateway_id {
            call = call.header(GATEWAY_ID_HEADER, gateway_id.as_str());
        }

        let response = call
            .send()
            .await
            .map_err(|source| map_request_error(source, self.timeout))?;
        let status = response.status();
        let body = read_bounded_body(response, self.response_size_limit, self.timeout).await?;

        if !status.is_success() {
            return Err(Error::Provider {
                status,
                failure: provider_failure(&body),
            });
        }

        serde_json::from_slice(&body).map_err(|source| Error::InvalidResponse { source })
    }

    fn builder_from_env_with(
        read: impl Fn(&str) -> Result<String, std::env::VarError>,
    ) -> Result<ClientBuilder, Error> {
        let account_id =
            read(ACCOUNT_ID_ENV).map_err(|_| InvalidConfiguration::MissingEnvironmentVariable {
                name: ACCOUNT_ID_ENV,
            })?;
        let api_token = match read(API_TOKEN_ENV) {
            Ok(value) => value,
            Err(_) => read(LEGACY_KIMI_API_TOKEN_ENV).map_err(|_| {
                InvalidConfiguration::MissingEnvironmentVariable {
                    name: API_TOKEN_ENV,
                }
            })?,
        };
        Ok(Self::builder(
            AccountId::new(account_id)?,
            ApiToken::new(api_token)?,
        ))
    }
}

impl ChatCompletions for Client {
    async fn complete<'a>(&'a self, request: &'a ChatRequest) -> Result<ChatCompletion, Error> {
        self.chat(request).await
    }
}

/// Builder for transport policy and optional Cloudflare AI Gateway routing.
///
/// ```
/// use std::time::Duration;
/// use edge_completions::{AccountId, ApiToken, Client, RequestTimeout};
///
/// let client = Client::builder(
///     AccountId::new("account-123")?,
///     ApiToken::new("test-token")?,
/// )
/// .timeout(RequestTimeout::new(Duration::from_secs(15))?)
/// .build();
/// assert!(client.is_ok());
/// # Ok::<(), edge_completions::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct ClientBuilder {
    account_id: AccountId,
    api_token: ApiToken,
    base_url: Option<ApiBaseUrl>,
    timeout: RequestTimeout,
    gateway_id: Option<GatewayId>,
    response_size_limit: ResponseSizeLimit,
}

impl ClientBuilder {
    fn new(account_id: AccountId, api_token: ApiToken) -> Self {
        Self {
            account_id,
            api_token,
            base_url: None,
            timeout: RequestTimeout::default(),
            gateway_id: None,
            response_size_limit: ResponseSizeLimit::default(),
        }
    }

    /// Overrides the API base URL.
    #[must_use]
    pub fn base_url(mut self, base_url: ApiBaseUrl) -> Self {
        self.base_url = Some(base_url);
        self
    }

    /// Overrides the default 60-second request timeout.
    #[must_use]
    pub fn timeout(mut self, timeout: RequestTimeout) -> Self {
        self.timeout = timeout;
        self
    }

    /// Adds Cloudflare's optional AI Gateway routing header.
    #[must_use]
    pub fn gateway_id(mut self, gateway_id: GatewayId) -> Self {
        self.gateway_id = Some(gateway_id);
        self
    }

    /// Overrides the default four-megabyte response-body limit.
    #[must_use]
    pub fn response_size_limit(mut self, limit: ResponseSizeLimit) -> Self {
        self.response_size_limit = limit;
        self
    }

    /// Validates transport configuration and creates the client.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidConfiguration`] if the selected API base cannot
    /// form the chat-completions endpoint, or [`Error::Transport`] if the HTTP
    /// client cannot be initialized.
    pub fn build(self) -> Result<Client, Error> {
        let base_url = match self.base_url {
            Some(base_url) => base_url,
            None => ApiBaseUrl::new(DEFAULT_BASE_URL)?,
        };
        let mut endpoint = base_url.0;
        endpoint
            .path_segments_mut()
            .map_err(|_| InvalidConfiguration::InvalidBaseUrl {
                reason: "URL cannot be used as a hierarchical API base".to_owned(),
            })?
            .pop_if_empty()
            .extend([
                "accounts",
                self.account_id.as_str(),
                "ai",
                "v1",
                "chat",
                "completions",
            ]);

        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::ACCEPT,
            header::HeaderValue::from_static("application/json"),
        );
        headers.insert(
            header::USER_AGENT,
            header::HeaderValue::from_static(concat!(
                "edge-completions/",
                env!("CARGO_PKG_VERSION")
            )),
        );
        let http = reqwest::Client::builder()
            .timeout(self.timeout.duration())
            .retry(reqwest::retry::never())
            .default_headers(headers)
            .build()
            .map_err(|source| Error::Transport { source })?;

        Ok(Client {
            http,
            endpoint,
            api_token: self.api_token,
            gateway_id: self.gateway_id,
            timeout: self.timeout,
            response_size_limit: self.response_size_limit,
        })
    }
}

async fn read_bounded_body(
    mut response: reqwest::Response,
    limit: ResponseSizeLimit,
    timeout: RequestTimeout,
) -> Result<Vec<u8>, Error> {
    let limit_bytes = limit.bytes();
    if response
        .content_length()
        .is_some_and(|length| length > limit_bytes as u64)
    {
        return Err(Error::ResponseTooLarge { limit_bytes });
    }

    let declared_capacity = match response
        .content_length()
        .and_then(|length| usize::try_from(length).ok())
    {
        Some(length) => length.min(limit_bytes),
        None => 0,
    };
    let mut body = Vec::with_capacity(declared_capacity);
    while let Some(chunk) = response
        .chunk()
        .await
        .map_err(|source| map_request_error(source, timeout))?
    {
        if body.len().saturating_add(chunk.len()) > limit_bytes {
            return Err(Error::ResponseTooLarge { limit_bytes });
        }
        body.extend_from_slice(&chunk);
    }
    Ok(body)
}

fn map_request_error(source: reqwest::Error, timeout: RequestTimeout) -> Error {
    if source.is_timeout() {
        Error::Timeout {
            duration: timeout.duration(),
            source,
        }
    } else {
        Error::Transport { source }
    }
}

fn is_loopback(url: &Url) -> bool {
    match url.host() {
        Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
        Some(Host::Ipv4(address)) => IpAddr::V4(address).is_loopback(),
        Some(Host::Ipv6(address)) => IpAddr::V6(address).is_loopback(),
        None => false,
    }
}

#[derive(Deserialize)]
struct OpenAiErrorEnvelope {
    error: OpenAiError,
}

#[derive(Deserialize)]
struct OpenAiError {
    message: String,
}

#[derive(Deserialize)]
struct CloudflareErrorEnvelope {
    errors: Vec<CloudflareApiError>,
}

#[derive(Deserialize)]
struct CloudflareApiError {
    code: u64,
    message: String,
}

fn provider_failure(body: &[u8]) -> ProviderFailure {
    if let Ok(envelope) = serde_json::from_slice::<CloudflareErrorEnvelope>(body) {
        if let Some(error) = envelope.errors.into_iter().next() {
            return ProviderFailure::Coded {
                code: ProviderErrorCode::new(error.code),
                message: bounded_message(error.message),
            };
        }
    }
    match serde_json::from_slice::<OpenAiErrorEnvelope>(body) {
        Ok(envelope) => ProviderFailure::Message {
            message: bounded_message(envelope.error.message),
        },
        Err(_) => ProviderFailure::Unrecognized,
    }
}

fn bounded_message(message: String) -> String {
    message.chars().take(1_000).collect()
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, env::VarError};

    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{body_json, header, method, path},
    };

    use super::*;
    use crate::ChatMessage;

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    fn credentials() -> Result<(AccountId, ApiToken), InvalidConfiguration> {
        Ok((AccountId::new("account-1")?, ApiToken::new("secret-token")?))
    }

    #[test]
    fn creates_client_from_named_environment_variables() -> TestResult {
        let values = HashMap::from([
            (ACCOUNT_ID_ENV, "account-1"),
            (API_TOKEN_ENV, "super-secret"),
        ]);
        let client = Client::builder_from_env_with(|name| {
            values
                .get(name)
                .map(ToString::to_string)
                .ok_or(VarError::NotPresent)
        })?
        .build()?;

        assert!(!format!("{client:?}").contains("super-secret"));
        assert_eq!(
            client.endpoint.as_str(),
            "https://api.cloudflare.com/client/v4/accounts/account-1/ai/v1/chat/completions"
        );
        Ok(())
    }

    #[test]
    fn reports_the_missing_environment_variable_by_name() -> TestResult {
        let error = match Client::builder_from_env_with(|_| Err(VarError::NotPresent)) {
            Err(error) => error,
            Ok(_) => return Err("client creation unexpectedly succeeded".into()),
        };

        assert_eq!(
            error.to_string(),
            "required environment variable CLOUDFLARE_ACCOUNT_ID is missing or is not valid Unicode"
        );
        Ok(())
    }

    #[test]
    fn reports_a_missing_api_token_without_reading_or_displaying_it() -> TestResult {
        let result = Client::builder_from_env_with(|name| match name {
            ACCOUNT_ID_ENV => Ok("account-1".to_owned()),
            _ => Err(VarError::NotPresent),
        });
        let error = match result {
            Err(error) => error,
            Ok(_) => return Err("client creation unexpectedly succeeded".into()),
        };

        assert_eq!(
            error.to_string(),
            "required environment variable CLOUDFLARE_API_TOKEN is missing or is not valid Unicode"
        );
        Ok(())
    }

    #[test]
    fn supports_the_original_kimi_token_variable_as_a_compatibility_fallback() -> TestResult {
        let values = HashMap::from([
            (ACCOUNT_ID_ENV, "account-1"),
            (LEGACY_KIMI_API_TOKEN_ENV, "legacy-secret"),
        ]);
        let client = Client::builder_from_env_with(|name| {
            values
                .get(name)
                .map(ToString::to_string)
                .ok_or(VarError::NotPresent)
        })?
        .build()?;

        assert!(!format!("{client:?}").contains("legacy-secret"));
        Ok(())
    }

    #[test]
    fn rejects_non_loopback_plain_http_base_urls() {
        assert!(matches!(
            ApiBaseUrl::new("http://example.com/client/v4/"),
            Err(InvalidConfiguration::InsecureBaseUrl)
        ));
    }

    #[tokio::test]
    async fn sends_request_and_decodes_tool_call() -> TestResult {
        let server = MockServer::start().await;
        let request = ChatRequest::kimi_k3(vec![ChatMessage::user("weather?")])?;
        Mock::given(method("POST"))
            .and(path("/accounts/account-1/ai/v1/chat/completions"))
            .and(header("authorization", "Bearer secret-token"))
            .and(header(
                "user-agent",
                concat!("edge-completions/", env!("CARGO_PKG_VERSION")),
            ))
            .and(body_json(json!({"model":"moonshotai/kimi-k3","messages":[{"role":"user","content":"weather?"}]})))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "id":"chatcmpl-1","object":"chat.completion","created":1,"model":"moonshotai/kimi-k3",
                "choices":[{"index":0,"message":{"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"}}]},"finish_reason":"tool_calls"}],
                "usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}
            })))
            .mount(&server)
            .await;

        let (account_id, token) = credentials()?;
        let client = Client::builder(account_id, token)
            .base_url(ApiBaseUrl::new(format!("{}/", server.uri()))?)
            .build()?;
        let response = client.chat(&request).await?;
        let choice = response.first_choice()?;
        let call = choice
            .message()
            .tool_calls()
            .first()
            .ok_or("response did not contain the expected tool call")?;

        assert_eq!(
            choice.finish_reason(),
            Some(&crate::FinishReason::ToolCalls)
        );
        assert_eq!(call.name(), "get_weather");
        Ok(())
    }

    #[tokio::test]
    async fn maps_provider_error_without_exposing_token() -> TestResult {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(
                ResponseTemplate::new(401)
                    .set_body_json(json!({"error":{"message":"invalid token"}})),
            )
            .mount(&server)
            .await;
        let client = Client::builder(AccountId::new("account-1")?, ApiToken::new("super-secret")?)
            .base_url(ApiBaseUrl::new(format!("{}/", server.uri()))?)
            .build()?;
        let request = ChatRequest::kimi_k3(vec![ChatMessage::user("hi")])?;

        let error = match client.chat(&request).await {
            Err(error) => error,
            Ok(_) => return Err("request unexpectedly succeeded".into()),
        };
        assert_eq!(
            error.to_string(),
            "provider returned HTTP 401 Unauthorized: invalid token"
        );
        assert!(!format!("{client:?}").contains("super-secret"));
        Ok(())
    }

    #[tokio::test]
    async fn maps_cloudflare_error_envelope_without_exposing_raw_json() -> TestResult {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(402).set_body_json(json!({
                "errors": [{
                    "message": "Insufficient balance; add money to your gateway or use BYOK",
                    "code": 2021
                }],
                "success": false,
                "result": {},
                "messages": []
            })))
            .mount(&server)
            .await;
        let client = Client::builder(AccountId::new("account-1")?, ApiToken::new("super-secret")?)
            .base_url(ApiBaseUrl::new(format!("{}/", server.uri()))?)
            .build()?;
        let request = ChatRequest::kimi_k3(vec![ChatMessage::user("hi")])?;

        let error = match client.chat(&request).await {
            Err(error) => error,
            Ok(_) => return Err("request unexpectedly succeeded".into()),
        };
        assert_eq!(
            error.to_string(),
            "provider returned HTTP 402 Payment Required: Insufficient balance; add money to your gateway or use BYOK (provider code 2021)"
        );
        assert!(!error.to_string().contains("\"errors\""));
        Ok(())
    }

    #[tokio::test]
    async fn rejects_a_response_body_larger_than_the_configured_limit() -> TestResult {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(200).set_body_string("x".repeat(65)))
            .mount(&server)
            .await;
        let (account_id, token) = credentials()?;
        let client = Client::builder(account_id, token)
            .base_url(ApiBaseUrl::new(format!("{}/", server.uri()))?)
            .response_size_limit(ResponseSizeLimit::new(64)?)
            .build()?;
        let request = ChatRequest::kimi_k3(vec![ChatMessage::user("hi")])?;

        assert!(matches!(
            client.chat(&request).await,
            Err(Error::ResponseTooLarge { limit_bytes: 64 })
        ));
        Ok(())
    }
}