bitrouter 1.0.0-alpha.5

BitRouter: an LLM API router. CLI + TUI + assembly library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
//! `bitrouter cloud …` — typed wrappers around every endpoint on
//! [`bitrouter_cloud_sdk::management::ManagementClient`].
//!
//! The subcommand tree is grouped by resource (`keys`, `usage`,
//! `billing`, `policy`, `budget`, `preset`, `byok`, `oauth-client`)
//! plus a top-level `whoami` that prints the local identity + the
//! configured cloud base URL. Every leaf accepts `--json` for raw
//! response output; the default is a compact human-readable form.
//!
//! Spec inputs that need a free-form JSON body (the generic
//! `policy create` / `policy update` and every `preset create` /
//! `preset update` clause) are read from a file path or `-` for stdin.
//!
//! All errors flow through one place ([`run`]); 403 responses whose
//! description matches the server's `missing required scope: <s>` shape
//! get a tailored re-login hint pointing the user at
//! `bitrouter auth login --scope "<existing scopes> <missing>"`.

use std::path::PathBuf;

use anyhow::Result;
use chrono::{DateTime, Utc};
use clap::{Subcommand, ValueEnum};

use bitrouter_cloud_sdk::auth::credentials::{CredentialsStore, default_credentials_path};
use bitrouter_cloud_sdk::management::types::{
    BudgetWindow as SdkBudgetWindow, ClientType as SdkClientType, PolicyKind as SdkPolicyKind,
};
use bitrouter_cloud_sdk::management::{
    Error as SdkError, ManagementClient, billing, budgets, byok, keys, oauth_clients, policies,
    presets, usage,
};

/// `bitrouter cloud …`. All variants land in [`run`].
#[derive(Debug, Subcommand)]
pub enum CloudAction {
    /// Print the cloud identity stored on this machine alongside the
    /// `/v1/*` base URL the CLI will target.
    Whoami,
    /// Manage `brk_` API keys on your account.
    Keys {
        #[command(subcommand)]
        action: KeysAction,
    },
    /// Read aggregate spend / token counts for your account.
    Usage(UsageArgs),
    /// Page through recent inference requests.
    Requests(RequestsArgs),
    /// Credit balance and Stripe checkout.
    Billing {
        #[command(subcommand)]
        action: BillingAction,
    },
    /// Generic CRUD over the typed policy registry.
    Policy {
        #[command(subcommand)]
        action: PolicyAction,
    },
    /// Typed wrapper over budget-kind policies.
    Budget {
        #[command(subcommand)]
        action: BudgetAction,
    },
    /// Typed wrapper over preset-kind policies.
    Preset {
        #[command(subcommand)]
        action: PresetAction,
    },
    /// Bring-your-own-key provider keys.
    Byok {
        #[command(subcommand)]
        action: ByokAction,
    },
    /// Registered OAuth clients on your account.
    #[command(name = "oauth-client")]
    OauthClient {
        #[command(subcommand)]
        action: OauthClientAction,
    },
}

// ===== Keys =====

#[derive(Debug, Subcommand)]
pub enum KeysAction {
    /// List API keys on your account.
    List(JsonFlag),
    /// Mint a new API key. The plaintext is printed once.
    Mint(MintKeyArgs),
    /// Revoke a key by id.
    Revoke(RevokeKeyArgs),
}

#[derive(Debug, clap::Args)]
pub struct MintKeyArgs {
    /// Operator-supplied display name.
    #[arg(long)]
    pub name: String,
    /// Wire-format scope tokens (repeat the flag, or pass a single
    /// space-delimited list). Must be a subset of your effective scopes.
    #[arg(long = "scope", value_name = "SCOPE")]
    pub scopes: Vec<String>,
    /// Optional expiry (RFC 3339, e.g. `2026-12-31T00:00:00Z`).
    #[arg(long)]
    pub expires_at: Option<DateTime<Utc>>,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct RevokeKeyArgs {
    /// The key id (e.g. `k_…`).
    pub id: String,
    #[command(flatten)]
    pub json: JsonFlag,
}

// ===== Usage / Requests =====

#[derive(Debug, clap::Args)]
pub struct UsageArgs {
    /// Lower bound (RFC 3339). Defaults to `to - 30 days`.
    #[arg(long)]
    pub from: Option<DateTime<Utc>>,
    /// Upper bound (RFC 3339). Defaults to now.
    #[arg(long)]
    pub to: Option<DateTime<Utc>>,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct RequestsArgs {
    /// Page size (server clamps to `[1, 100]`).
    #[arg(long)]
    pub limit: Option<u64>,
    /// Offset into the result set.
    #[arg(long)]
    pub offset: Option<u64>,
    #[command(flatten)]
    pub json: JsonFlag,
}

// ===== Billing =====

#[derive(Debug, Subcommand)]
pub enum BillingAction {
    /// Show the account's credit balance.
    Balance(JsonFlag),
    /// Start a Stripe checkout session for a credit top-up.
    /// Requires the `billing:write` scope.
    Checkout(CheckoutArgs),
}

#[derive(Debug, clap::Args)]
pub struct CheckoutArgs {
    /// Amount in USD cents.
    #[arg(long)]
    pub amount_cents: i64,
    #[command(flatten)]
    pub json: JsonFlag,
}

// ===== Policy =====

#[derive(Debug, Subcommand)]
pub enum PolicyAction {
    /// List policies on your account.
    List(PolicyListArgs),
    /// Fetch one policy.
    Get(IdArg),
    /// Create a policy. Spec body is read from `--spec <file|->`.
    Create(PolicyCreateArgs),
    /// Update a policy's name and / or spec.
    Update(PolicyUpdateArgs),
    /// Delete a policy.
    Delete(IdArg),
    /// Attach a policy to a principal.
    Bind(PolicyBindArgs),
    /// Detach one binding from a policy.
    Unbind(PolicyUnbindArgs),
    /// Park a policy — the engine skips it at request time.
    Disable(IdArg),
    /// Re-enable a previously disabled policy.
    Enable(IdArg),
    /// List the bindings of one policy.
    Bindings(IdArg),
    /// Preview the effective policy for a principal.
    Effective(EffectiveArgs),
    /// List every policy bound to a principal.
    #[command(name = "for-principal")]
    ForPrincipal(ForPrincipalArgs),
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum PolicyKindArg {
    Budget,
    RateLimit,
    Guardrail,
    Preset,
}

impl From<PolicyKindArg> for SdkPolicyKind {
    fn from(value: PolicyKindArg) -> Self {
        match value {
            PolicyKindArg::Budget => SdkPolicyKind::Budget,
            PolicyKindArg::RateLimit => SdkPolicyKind::RateLimit,
            PolicyKindArg::Guardrail => SdkPolicyKind::Guardrail,
            PolicyKindArg::Preset => SdkPolicyKind::Preset,
        }
    }
}

#[derive(Debug, clap::Args)]
pub struct PolicyListArgs {
    /// Narrow the list to one kind.
    #[arg(long)]
    pub kind: Option<PolicyKindArg>,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct PolicyCreateArgs {
    /// Operator-supplied display name.
    #[arg(long)]
    pub name: String,
    /// Kind discriminator — selects which shape `--spec` must take.
    #[arg(long)]
    pub kind: PolicyKindArg,
    /// Path to a JSON file containing the flat inner spec body, or
    /// `-` to read from stdin.
    #[arg(long)]
    pub spec: PathBuf,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct PolicyUpdateArgs {
    /// The policy id.
    pub id: String,
    /// New name. Omit to leave unchanged.
    #[arg(long)]
    pub name: Option<String>,
    /// New spec. Path to a JSON file or `-` for stdin. Omit to leave
    /// unchanged.
    #[arg(long)]
    pub spec: Option<PathBuf>,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct PolicyBindArgs {
    /// The policy id.
    pub id: String,
    /// Principal kind (`account`, `api_key`, `oauth_token`,
    /// `oauth_client`).
    #[arg(long)]
    pub principal_type: String,
    /// Principal id — interpretation depends on `--principal-type`.
    #[arg(long)]
    pub principal_id: String,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct PolicyUnbindArgs {
    /// The policy id.
    pub id: String,
    /// The binding id (from `cloud policy bindings <id>`).
    pub binding_id: String,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct EffectiveArgs {
    /// Principal kind (`account`, `api_key`, `oauth_token`,
    /// `oauth_client`).
    #[arg(long)]
    pub principal_type: String,
    /// Principal id.
    #[arg(long)]
    pub principal_id: String,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct ForPrincipalArgs {
    /// Principal kind.
    pub principal_type: String,
    /// Principal id.
    pub principal_id: String,
    #[command(flatten)]
    pub json: JsonFlag,
}

// ===== Budget =====

#[derive(Debug, Subcommand)]
pub enum BudgetAction {
    /// List every budget on the account.
    List(JsonFlag),
    /// Fetch one budget.
    Get(IdArg),
    /// Create a budget.
    Create(BudgetCreateArgs),
    /// Patch a budget's fields.
    Update(BudgetUpdateArgs),
    /// Remove a budget.
    Delete(IdArg),
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum BudgetWindowArg {
    Day,
    Month,
    Total,
}

impl From<BudgetWindowArg> for SdkBudgetWindow {
    fn from(value: BudgetWindowArg) -> Self {
        match value {
            BudgetWindowArg::Day => SdkBudgetWindow::Day,
            BudgetWindowArg::Month => SdkBudgetWindow::Month,
            BudgetWindowArg::Total => SdkBudgetWindow::Total,
        }
    }
}

#[derive(Debug, clap::Args)]
pub struct BudgetCreateArgs {
    /// Display name.
    #[arg(long)]
    pub name: String,
    /// Rolling-spend window.
    #[arg(long)]
    pub window: BudgetWindowArg,
    /// Spend cap in micro-USD (must be strictly positive).
    #[arg(long)]
    pub limit_micro_usd: i64,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct BudgetUpdateArgs {
    /// The budget id.
    pub id: String,
    /// New name.
    #[arg(long)]
    pub name: Option<String>,
    /// New window.
    #[arg(long)]
    pub window: Option<BudgetWindowArg>,
    /// New cap (must be strictly positive when supplied).
    #[arg(long)]
    pub limit_micro_usd: Option<i64>,
    #[command(flatten)]
    pub json: JsonFlag,
}

// ===== Preset =====

#[derive(Debug, Subcommand)]
pub enum PresetAction {
    /// List every preset on the account.
    List(JsonFlag),
    /// Fetch one preset.
    Get(IdArg),
    /// Create a preset. Each clause is supplied as a JSON file
    /// (or `-` for stdin).
    Create(PresetCreateArgs),
    /// Patch a preset's clauses. Use `--clear-*` to drop a clause.
    Update(PresetUpdateArgs),
    /// Remove a preset.
    Delete(IdArg),
}

#[derive(Debug, clap::Args)]
pub struct PresetCreateArgs {
    /// Display name.
    #[arg(long)]
    pub name: String,
    /// Optional guardrail clause (JSON file or `-`).
    #[arg(long)]
    pub guardrail: Option<PathBuf>,
    /// Optional budget clause.
    #[arg(long)]
    pub budget: Option<PathBuf>,
    /// Optional rate-limit clause.
    #[arg(long)]
    pub rate_limit: Option<PathBuf>,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct PresetUpdateArgs {
    /// The preset id.
    pub id: String,
    /// New name.
    #[arg(long)]
    pub name: Option<String>,
    /// Replace the guardrail clause (JSON file or `-`).
    #[arg(long)]
    pub guardrail: Option<PathBuf>,
    /// Replace the budget clause.
    #[arg(long)]
    pub budget: Option<PathBuf>,
    /// Replace the rate-limit clause.
    #[arg(long)]
    pub rate_limit: Option<PathBuf>,
    /// Drop the guardrail clause.
    #[arg(long)]
    pub clear_guardrail: bool,
    /// Drop the budget clause.
    #[arg(long)]
    pub clear_budget: bool,
    /// Drop the rate-limit clause.
    #[arg(long)]
    pub clear_rate_limit: bool,
    #[command(flatten)]
    pub json: JsonFlag,
}

// ===== BYOK =====

#[derive(Debug, Subcommand)]
pub enum ByokAction {
    /// List every BYOK row on the account.
    List(JsonFlag),
    /// Upsert a BYOK row. Ciphertext must be sealed by the caller
    /// against the cloud's current X25519 public key.
    Set(ByokSetArgs),
    /// Remove a BYOK row by provider id.
    Delete(ByokDeleteArgs),
}

#[derive(Debug, clap::Args)]
pub struct ByokSetArgs {
    /// Upstream provider id (e.g. `anthropic`).
    #[arg(long)]
    pub provider: String,
    /// Base64-encoded sealed-box ciphertext.
    #[arg(long)]
    pub ciphertext_b64: String,
    /// KEK id used to seal `--ciphertext-b64`. Must match the cloud's
    /// current `primary_kek_id`.
    #[arg(long)]
    pub kek_id: String,
    /// Operator-visible prefix of the underlying plaintext.
    #[arg(long)]
    pub key_prefix: String,
    /// Override API base for the provider.
    #[arg(long)]
    pub api_base: Option<String>,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct ByokDeleteArgs {
    /// Provider id (the row's `provider_name`).
    pub provider: String,
    #[command(flatten)]
    pub json: JsonFlag,
}

// ===== OAuth clients =====

#[derive(Debug, Subcommand)]
pub enum OauthClientAction {
    /// List every OAuth client on the account.
    List(JsonFlag),
    /// Register a new client.
    Register(OauthRegisterArgs),
    /// Patch one or more fields of an existing client.
    Update(OauthUpdateArgs),
    /// Remove a client.
    Delete(OauthDeleteArgs),
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ClientTypeArg {
    Confidential,
    Public,
}

impl From<ClientTypeArg> for SdkClientType {
    fn from(value: ClientTypeArg) -> Self {
        match value {
            ClientTypeArg::Confidential => SdkClientType::Confidential,
            ClientTypeArg::Public => SdkClientType::Public,
        }
    }
}

#[derive(Debug, clap::Args)]
pub struct OauthRegisterArgs {
    /// Display name.
    #[arg(long)]
    pub name: String,
    /// Client type.
    #[arg(long = "type")]
    pub client_type: ClientTypeArg,
    /// Redirect URI. Repeat for multiple values.
    #[arg(long = "redirect-uri")]
    pub redirect_uris: Vec<String>,
    /// Wire-format scope. Repeat for multiple values.
    #[arg(long = "scope", value_name = "SCOPE")]
    pub allowed_scopes: Vec<String>,
    /// Grant type — at least one of `authorization_code`,
    /// `refresh_token`, or the RFC 8628 URN.
    #[arg(long = "grant")]
    pub allowed_grant_types: Vec<String>,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct OauthUpdateArgs {
    /// The client id (the public `client_id`, not the row id).
    pub client_id: String,
    /// New display name.
    #[arg(long)]
    pub name: Option<String>,
    /// Replace the redirect-URI list. Repeat for multiple values.
    #[arg(long = "redirect-uri")]
    pub redirect_uris: Option<Vec<String>>,
    /// Replace the scope set.
    #[arg(long = "scope", value_name = "SCOPE")]
    pub allowed_scopes: Option<Vec<String>>,
    /// Replace the grant-type list.
    #[arg(long = "grant")]
    pub allowed_grant_types: Option<Vec<String>>,
    #[command(flatten)]
    pub json: JsonFlag,
}

#[derive(Debug, clap::Args)]
pub struct OauthDeleteArgs {
    /// The client id.
    pub client_id: String,
    #[command(flatten)]
    pub json: JsonFlag,
}

// ===== Shared little-arg structs =====

#[derive(Debug, clap::Args)]
pub struct IdArg {
    /// The resource id.
    pub id: String,
    #[command(flatten)]
    pub json: JsonFlag,
}

/// Shared `--json` switch. Flatten into every leaf so the user can
/// always opt out of the text formatter.
#[derive(Debug, Default, Clone, Copy, clap::Args)]
pub struct JsonFlag {
    /// Print the response as raw JSON instead of the human-readable
    /// summary.
    #[arg(long)]
    pub json: bool,
}

// =====================================================================
// Runner
// =====================================================================

/// Entry point dispatched by `apps/bitrouter/src/main.rs`.
pub async fn run(action: CloudAction) -> Result<()> {
    let result = run_inner(action).await;
    match result {
        Ok(()) => Ok(()),
        Err(err) => {
            print_error_hint(&err);
            Err(err.into())
        }
    }
}

async fn run_inner(action: CloudAction) -> std::result::Result<(), SdkError> {
    match action {
        CloudAction::Whoami => whoami().await,
        CloudAction::Keys { action } => run_keys(action).await,
        CloudAction::Usage(args) => run_usage(args).await,
        CloudAction::Requests(args) => run_requests(args).await,
        CloudAction::Billing { action } => run_billing(action).await,
        CloudAction::Policy { action } => run_policy(action).await,
        CloudAction::Budget { action } => run_budget(action).await,
        CloudAction::Preset { action } => run_preset(action).await,
        CloudAction::Byok { action } => run_byok(action).await,
        CloudAction::OauthClient { action } => run_oauth_client(action).await,
    }
}

fn client() -> std::result::Result<ManagementClient, SdkError> {
    ManagementClient::from_default_credentials()
}

async fn whoami() -> std::result::Result<(), SdkError> {
    // Doesn't hit the network — reads the local credentials file so
    // it works offline. Mirrors `bitrouter auth whoami` but adds the
    // base URL `bitrouter cloud …` will target.
    let client = client()?;
    println!("cloud base URL: {}", client.base_url());
    let store = CredentialsStore::default_path().map_err(SdkError::Auth)?;
    if let Some(creds) = store.current() {
        println!("scope:          {}", creds.scope);
        if let Some(sub) = creds.subject.as_deref() {
            println!("subject:        {sub}");
        }
        println!("credentials:    {}", store.path().display());
    } else {
        println!("(not signed in — run `bitrouter auth login`)");
    }
    Ok(())
}

// ----- Keys -----

async fn run_keys(action: KeysAction) -> std::result::Result<(), SdkError> {
    let client = client()?;
    match action {
        KeysAction::List(flag) => emit(flag.json, &client.list_keys().await?, format_keys_list),
        KeysAction::Mint(args) => {
            let body = keys::MintApiKeyRequest {
                display_name: args.name,
                scopes: split_scope_args(&args.scopes),
                expires_at: args.expires_at,
            };
            let resp = client.mint_key(&body).await?;
            emit(args.json.json, &resp, format_mint_key)
        }
        KeysAction::Revoke(args) => {
            let resp = client.revoke_key(&args.id).await?;
            emit(args.json.json, &resp, |r| format!("revoked: {}", r.revoked))
        }
    }
}

fn format_keys_list(resp: &keys::ApiKeyListResponse) -> String {
    if resp.data.is_empty() {
        return "no keys".to_owned();
    }
    let mut out = String::new();
    for k in &resp.data {
        out.push_str(&format!(
            "{:<24}  {:<24}  scopes=[{}]  prefix={}\n",
            k.id,
            k.display_name,
            k.scopes.join(", "),
            k.key_prefix,
        ));
    }
    out
}

fn format_mint_key(resp: &keys::MintApiKeyResponse) -> String {
    format!(
        "id:           {id}\nname:         {name}\nprefix:       {prefix}\nscopes:       [{scopes}]\ntoken:        {token}   (shown once — save it now)\n",
        id = resp.id,
        name = resp.display_name,
        prefix = resp.key_prefix,
        scopes = resp.scopes.join(", "),
        token = resp.token,
    )
}

// ----- Usage / requests -----

async fn run_usage(args: UsageArgs) -> std::result::Result<(), SdkError> {
    let client = client()?;
    let resp = client
        .usage_aggregate(&usage::UsageQuery {
            from: args.from,
            to: args.to,
        })
        .await?;
    emit(args.json.json, &resp, |r| {
        format!(
            "window:            {from} → {to}\nspend (micro-USD): {spend}\nprompt tokens:     {pt}\ncompletion tokens: {ct}\nrequests:          {rc}\n",
            from = r.from.to_rfc3339(),
            to = r.to.to_rfc3339(),
            spend = r.spend_micro_usd,
            pt = r.prompt_tokens,
            ct = r.completion_tokens,
            rc = r.request_count,
        )
    })
}

async fn run_requests(args: RequestsArgs) -> std::result::Result<(), SdkError> {
    let client = client()?;
    let resp = client
        .list_requests(&usage::RequestsQuery {
            limit: args.limit,
            offset: args.offset,
        })
        .await?;
    emit(args.json.json, &resp, format_requests)
}

fn format_requests(resp: &usage::RequestsResponse) -> String {
    if resp.data.is_empty() {
        return "no requests".to_owned();
    }
    let mut out = String::new();
    for r in &resp.data {
        out.push_str(&format!(
            "{}  {:<10}  {:<24}  {:>10} µUSD  prompt={:<6} completion={:<6}\n",
            r.created_at.to_rfc3339(),
            r.status,
            r.model_id.clone().unwrap_or_else(|| "—".into()),
            r.final_charge_micro_usd
                .map(|v| v.to_string())
                .unwrap_or_else(|| "—".into()),
            r.prompt_tokens,
            r.completion_tokens,
        ));
    }
    out.push_str(&format!("\nlimit={} offset={}\n", resp.limit, resp.offset));
    out
}

// ----- Billing -----

async fn run_billing(action: BillingAction) -> std::result::Result<(), SdkError> {
    let client = client()?;
    match action {
        BillingAction::Balance(flag) => {
            let resp = client.billing_balance().await?;
            emit(flag.json, &resp, |r| {
                format!(
                    "balance:    {} {} (micro-USD)\npending:    {} {}\navailable:  {} {}\n",
                    r.balance_micro_usd,
                    r.currency,
                    r.pending_debits_micro_usd,
                    r.currency,
                    r.available_micro_usd,
                    r.currency,
                )
            })
        }
        BillingAction::Checkout(args) => {
            let resp = client
                .create_checkout_session(&billing::CheckoutSessionRequest {
                    amount_cents: args.amount_cents,
                })
                .await?;
            emit(args.json.json, &resp, |r| {
                format!("session id: {}\ncheckout url: {}\n", r.id, r.url)
            })
        }
    }
}

// ----- Policy -----

async fn run_policy(action: PolicyAction) -> std::result::Result<(), SdkError> {
    let client = client()?;
    match action {
        PolicyAction::List(args) => {
            let resp = client
                .list_policies(&policies::ListPoliciesQuery {
                    kind: args.kind.map(Into::into),
                })
                .await?;
            emit(args.json.json, &resp, format_policy_list)
        }
        PolicyAction::Get(args) => {
            let resp = client.get_policy(&args.id).await?;
            emit(args.json.json, &resp, format_policy_one)
        }
        PolicyAction::Create(args) => {
            let spec = read_json_input(&args.spec)?;
            let resp = client
                .create_policy(&policies::CreatePolicyRequest {
                    name: args.name,
                    kind: args.kind.into(),
                    spec,
                })
                .await?;
            emit(args.json.json, &resp, format_policy_one)
        }
        PolicyAction::Update(args) => {
            let spec = match args.spec.as_ref() {
                Some(p) => Some(read_json_input(p)?),
                None => None,
            };
            let resp = client
                .update_policy(
                    &args.id,
                    &policies::UpdatePolicyRequest {
                        name: args.name,
                        spec,
                    },
                )
                .await?;
            emit(args.json.json, &resp, format_policy_one)
        }
        PolicyAction::Delete(args) => {
            let resp = client.delete_policy(&args.id).await?;
            emit(args.json.json, &resp, |r| {
                format!("deleted: {}\n", r.deleted)
            })
        }
        PolicyAction::Bind(args) => {
            let resp = client
                .bind_policy(
                    &args.id,
                    &policies::BindPolicyRequest {
                        principal_type: args.principal_type,
                        principal_id: args.principal_id,
                    },
                )
                .await?;
            emit(args.json.json, &resp, |r| {
                format!("binding id: {}\n", r.binding_id)
            })
        }
        PolicyAction::Unbind(args) => {
            let resp = client.unbind_policy(&args.id, &args.binding_id).await?;
            emit(args.json.json, &resp, |r| {
                format!("unbound: {}\n", r.unbound)
            })
        }
        PolicyAction::Disable(args) => {
            let resp = client.disable_policy(&args.id).await?;
            emit(args.json.json, &resp, |r| {
                format!("disabled: {}\n", r.disabled)
            })
        }
        PolicyAction::Enable(args) => {
            let resp = client.enable_policy(&args.id).await?;
            emit(args.json.json, &resp, |r| {
                format!("disabled: {}\n", r.disabled)
            })
        }
        PolicyAction::Bindings(args) => {
            let resp = client.list_policy_bindings(&args.id).await?;
            emit(args.json.json, &resp, format_binding_list)
        }
        PolicyAction::Effective(args) => {
            let resp = client
                .effective_policy(&policies::EffectivePolicyQuery {
                    principal_type: args.principal_type,
                    principal_id: args.principal_id,
                })
                .await?;
            emit(args.json.json, &resp, format_effective_policy)
        }
        PolicyAction::ForPrincipal(args) => {
            let resp = client
                .list_principal_policies(&args.principal_type, &args.principal_id)
                .await?;
            emit(args.json.json, &resp, format_policy_list)
        }
    }
}

fn format_policy_list(resp: &policies::PolicyListResponse) -> String {
    if resp.data.is_empty() {
        return "no policies".to_owned();
    }
    let mut out = String::new();
    for p in &resp.data {
        let disabled = if p.disabled_at.is_some() {
            " (disabled)"
        } else {
            ""
        };
        out.push_str(&format!(
            "{:<24}  {:<24}  kind={}{}\n",
            p.id,
            p.name,
            p.kind.as_str(),
            disabled,
        ));
    }
    out
}

fn format_policy_one(p: &policies::PolicyEnvelope) -> String {
    let mut out = format!(
        "id:    {}\nname:  {}\nkind:  {}\n",
        p.id,
        p.name,
        p.kind.as_str(),
    );
    if let Some(d) = p.disabled_at {
        out.push_str(&format!("disabled_at: {}\n", d.to_rfc3339()));
    }
    out.push_str(&format!(
        "spec:\n{}\n",
        serde_json::to_string_pretty(&p.spec).unwrap_or_else(|_| "{}".to_owned())
    ));
    out
}

fn format_binding_list(resp: &policies::BindingListResponse) -> String {
    if resp.data.is_empty() {
        return "no bindings".to_owned();
    }
    let mut out = String::new();
    for b in &resp.data {
        out.push_str(&format!(
            "{:<24}  policy={:<24}  principal={}:{}\n",
            b.id, b.policy_id, b.principal_type, b.principal_id,
        ));
    }
    out
}

fn format_effective_policy(p: &policies::EffectivePolicy) -> String {
    let mut out = String::new();
    out.push_str(&format!("budgets:    {} entries\n", p.budgets.len()));
    out.push_str(&format!("rate_limits: {} entries\n", p.rate_limits.len()));
    out.push_str(&format!(
        "guardrail:  {}\n",
        if p.guardrail.is_some() { "set" } else { "—" }
    ));
    if !p.budgets.is_empty() || !p.rate_limits.is_empty() || p.guardrail.is_some() {
        out.push_str("\nfull body:\n");
        if let Ok(pretty) = serde_json::to_string_pretty(p) {
            out.push_str(&pretty);
            out.push('\n');
        }
    }
    out
}

// ----- Budget -----

async fn run_budget(action: BudgetAction) -> std::result::Result<(), SdkError> {
    let client = client()?;
    match action {
        BudgetAction::List(flag) => {
            let resp = client.list_budgets().await?;
            emit(flag.json, &resp, format_budget_list)
        }
        BudgetAction::Get(args) => {
            let resp = client.get_budget(&args.id).await?;
            emit(args.json.json, &resp, format_budget_one)
        }
        BudgetAction::Create(args) => {
            let resp = client
                .create_budget(&budgets::CreateBudgetRequest {
                    name: args.name,
                    window: args.window.into(),
                    limit_micro_usd: args.limit_micro_usd,
                })
                .await?;
            emit(args.json.json, &resp, format_budget_one)
        }
        BudgetAction::Update(args) => {
            let resp = client
                .update_budget(
                    &args.id,
                    &budgets::UpdateBudgetRequest {
                        name: args.name,
                        window: args.window.map(Into::into),
                        limit_micro_usd: args.limit_micro_usd,
                    },
                )
                .await?;
            emit(args.json.json, &resp, format_budget_one)
        }
        BudgetAction::Delete(args) => {
            let resp = client.delete_budget(&args.id).await?;
            emit(args.json.json, &resp, |r| {
                format!("deleted: {}\n", r.deleted)
            })
        }
    }
}

fn format_budget_list(resp: &budgets::BudgetListResponse) -> String {
    if resp.data.is_empty() {
        return "no budgets".to_owned();
    }
    let mut out = String::new();
    for b in &resp.data {
        out.push_str(&format!(
            "{:<24}  {:<24}  window={:?}  limit={} µUSD{}\n",
            b.id,
            b.name,
            b.window,
            b.limit_micro_usd,
            if b.disabled_at.is_some() {
                " (disabled)"
            } else {
                ""
            },
        ));
    }
    out
}

fn format_budget_one(b: &budgets::BudgetEnvelope) -> String {
    let mut out = format!(
        "id:              {}\nname:            {}\nwindow:          {:?}\nlimit (µUSD):    {}\n",
        b.id, b.name, b.window, b.limit_micro_usd,
    );
    if let Some(d) = b.disabled_at {
        out.push_str(&format!("disabled_at:     {}\n", d.to_rfc3339()));
    }
    out
}

// ----- Preset -----

async fn run_preset(action: PresetAction) -> std::result::Result<(), SdkError> {
    let client = client()?;
    match action {
        PresetAction::List(flag) => {
            let resp = client.list_presets().await?;
            emit(flag.json, &resp, format_preset_list)
        }
        PresetAction::Get(args) => {
            let resp = client.get_preset(&args.id).await?;
            emit(args.json.json, &resp, format_preset_one)
        }
        PresetAction::Create(args) => {
            let body = presets::CreatePresetRequest {
                name: args.name,
                guardrail: opt_json_input(args.guardrail.as_ref())?,
                budget: opt_json_input(args.budget.as_ref())?,
                rate_limit: opt_json_input(args.rate_limit.as_ref())?,
            };
            let resp = client.create_preset(&body).await?;
            emit(args.json.json, &resp, format_preset_one)
        }
        PresetAction::Update(args) => {
            let body = presets::UpdatePresetRequest {
                name: args.name,
                guardrail: opt_json_input(args.guardrail.as_ref())?,
                budget: opt_json_input(args.budget.as_ref())?,
                rate_limit: opt_json_input(args.rate_limit.as_ref())?,
                clear_guardrail: args.clear_guardrail,
                clear_budget: args.clear_budget,
                clear_rate_limit: args.clear_rate_limit,
            };
            let resp = client.update_preset(&args.id, &body).await?;
            emit(args.json.json, &resp, format_preset_one)
        }
        PresetAction::Delete(args) => {
            let resp = client.delete_preset(&args.id).await?;
            emit(args.json.json, &resp, |r| {
                format!("deleted: {}\n", r.deleted)
            })
        }
    }
}

fn format_preset_list(resp: &presets::PresetListResponse) -> String {
    if resp.data.is_empty() {
        return "no presets".to_owned();
    }
    let mut out = String::new();
    for p in &resp.data {
        let clauses = [
            ("guardrail", p.guardrail.is_some()),
            ("budget", p.budget.is_some()),
            ("rate_limit", p.rate_limit.is_some()),
        ]
        .iter()
        .filter(|(_, set)| *set)
        .map(|(name, _)| *name)
        .collect::<Vec<_>>()
        .join(",");
        out.push_str(&format!(
            "{:<24}  {:<24}  clauses=[{}]{}\n",
            p.id,
            p.name,
            clauses,
            if p.disabled_at.is_some() {
                " (disabled)"
            } else {
                ""
            },
        ));
    }
    out
}

fn format_preset_one(p: &presets::PresetEnvelope) -> String {
    let mut out = format!("id:    {}\nname:  {}\n", p.id, p.name);
    if let Some(d) = p.disabled_at {
        out.push_str(&format!("disabled_at: {}\n", d.to_rfc3339()));
    }
    for (label, value) in [
        ("guardrail", &p.guardrail),
        ("budget", &p.budget),
        ("rate_limit", &p.rate_limit),
    ] {
        if let Some(v) = value {
            out.push_str(&format!(
                "{label}:\n{}\n",
                serde_json::to_string_pretty(v).unwrap_or_else(|_| "{}".to_owned())
            ));
        }
    }
    out
}

// ----- BYOK -----

async fn run_byok(action: ByokAction) -> std::result::Result<(), SdkError> {
    let client = client()?;
    match action {
        ByokAction::List(flag) => {
            let resp = client.list_byok_keys().await?;
            emit(flag.json, &resp, format_byok_list)
        }
        ByokAction::Set(args) => {
            let body = byok::UpsertByokKeyRequest {
                provider_name: args.provider,
                ciphertext_b64: args.ciphertext_b64,
                kek_id: args.kek_id,
                key_prefix: args.key_prefix,
                api_base: args.api_base,
            };
            let resp = client.upsert_byok_key(&body).await?;
            emit(args.json.json, &resp, |r| {
                format!(
                    "provider:  {}\nkek_id:    {}\nprefix:    {}\n",
                    r.provider_name, r.kek_id, r.key_prefix,
                )
            })
        }
        ByokAction::Delete(args) => {
            let resp = client.delete_byok_key(&args.provider).await?;
            emit(args.json.json, &resp, |r| {
                format!("deleted: {}\n", r.deleted)
            })
        }
    }
}

fn format_byok_list(resp: &byok::ByokKeyListResponse) -> String {
    if resp.data.is_empty() {
        return "no byok keys".to_owned();
    }
    let mut out = String::new();
    for k in &resp.data {
        out.push_str(&format!(
            "{:<20}  prefix={:<10}  kek={:<24}  last_used={}\n",
            k.provider_name,
            k.key_prefix,
            k.kek_id,
            k.last_used_at
                .map(|t| t.to_rfc3339())
                .unwrap_or_else(|| "—".into()),
        ));
    }
    out
}

// ----- OAuth clients -----

async fn run_oauth_client(action: OauthClientAction) -> std::result::Result<(), SdkError> {
    let client = client()?;
    match action {
        OauthClientAction::List(flag) => {
            let resp = client.list_oauth_clients().await?;
            emit(flag.json, &resp, format_oauth_client_list)
        }
        OauthClientAction::Register(args) => {
            let body = oauth_clients::RegisterOauthClientRequest {
                client_name: args.name,
                client_type: args.client_type.into(),
                redirect_uris: args.redirect_uris,
                allowed_scopes: args.allowed_scopes,
                allowed_grant_types: args.allowed_grant_types,
            };
            let resp = client.register_oauth_client(&body).await?;
            emit(args.json.json, &resp, format_oauth_client_register)
        }
        OauthClientAction::Update(args) => {
            let body = oauth_clients::UpdateOauthClientRequest {
                client_name: args.name,
                redirect_uris: args.redirect_uris,
                allowed_scopes: args.allowed_scopes,
                allowed_grant_types: args.allowed_grant_types,
            };
            let resp = client.update_oauth_client(&args.client_id, &body).await?;
            emit(args.json.json, &resp, format_oauth_client_envelope)
        }
        OauthClientAction::Delete(args) => {
            let resp = client.delete_oauth_client(&args.client_id).await?;
            emit(args.json.json, &resp, |r| {
                format!("deleted: {}\n", r.deleted)
            })
        }
    }
}

fn format_oauth_client_list(resp: &oauth_clients::OauthClientListResponse) -> String {
    if resp.data.is_empty() {
        return "no clients".to_owned();
    }
    let mut out = String::new();
    for c in &resp.data {
        out.push_str(&format!(
            "{:<24}  {:<24}  type={:?}  grants=[{}]  scopes=[{}]\n",
            c.client_id,
            c.client_name,
            c.client_type,
            c.allowed_grant_types.join(","),
            c.allowed_scopes.join(","),
        ));
    }
    out
}

fn format_oauth_client_envelope(c: &oauth_clients::OauthClientEnvelope) -> String {
    format!(
        "id:           {}\nclient_id:    {}\nname:         {}\ntype:         {:?}\nredirect_uris: {:?}\nscopes:       [{}]\ngrants:       [{}]\n",
        c.id,
        c.client_id,
        c.client_name,
        c.client_type,
        c.redirect_uris,
        c.allowed_scopes.join(", "),
        c.allowed_grant_types.join(", "),
    )
}

fn format_oauth_client_register(c: &oauth_clients::RegisterOauthClientResponse) -> String {
    let mut out = format!(
        "id:           {}\nclient_id:    {}\nname:         {}\ntype:         {:?}\nredirect_uris: {:?}\nscopes:       [{}]\ngrants:       [{}]\n",
        c.id,
        c.client_id,
        c.client_name,
        c.client_type,
        c.redirect_uris,
        c.allowed_scopes.join(", "),
        c.allowed_grant_types.join(", "),
    );
    if let Some(secret) = c.client_secret.as_deref() {
        out.push_str(&format!(
            "client_secret: {secret}   (shown once — save it now)\n"
        ));
    }
    out
}

// =====================================================================
// Output + error helpers
// =====================================================================

fn emit<T, F>(json: bool, value: &T, fmt: F) -> std::result::Result<(), SdkError>
where
    T: serde::Serialize,
    F: FnOnce(&T) -> String,
{
    if json {
        let pretty = serde_json::to_string_pretty(value)?;
        println!("{pretty}");
    } else {
        let text = fmt(value);
        if !text.is_empty() {
            // Trim a single trailing newline so we don't double-space
            // when the formatter already appended one.
            let trimmed = text.strip_suffix('\n').unwrap_or(&text);
            println!("{trimmed}");
        }
    }
    Ok(())
}

fn read_json_input(path: &std::path::Path) -> std::result::Result<serde_json::Value, SdkError> {
    use std::io::Read;
    let raw = if path == std::path::Path::new("-") {
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf).map_err(|e| {
            SdkError::Auth(anyhow::Error::new(e).context("reading JSON from stdin"))
        })?;
        buf
    } else {
        std::fs::read_to_string(path).map_err(|e| {
            SdkError::Auth(
                anyhow::Error::new(e).context(format!("reading JSON from {}", path.display())),
            )
        })?
    };
    serde_json::from_str::<serde_json::Value>(&raw).map_err(SdkError::from)
}

fn opt_json_input(
    path: Option<&PathBuf>,
) -> std::result::Result<Option<serde_json::Value>, SdkError> {
    match path {
        Some(p) => Ok(Some(read_json_input(p)?)),
        None => Ok(None),
    }
}

/// `--scope` accepts both repeated flags and a single space-delimited
/// list per flag — mirroring how the same value is handled by
/// `bitrouter auth login --scope`. Empty tokens are dropped.
fn split_scope_args(scopes: &[String]) -> Vec<String> {
    let mut out = Vec::new();
    for raw in scopes {
        for token in raw.split_whitespace() {
            if !token.is_empty() {
                out.push(token.to_owned());
            }
        }
    }
    out
}

fn print_error_hint(err: &SdkError) {
    match err {
        SdkError::NotSignedIn => {
            eprintln!();
            eprintln!("  Sign in first:");
            eprintln!("    bitrouter auth login");
        }
        SdkError::Forbidden {
            missing_scope: Some(scope),
            ..
        } => {
            eprintln!();
            eprintln!("  This command requires the scope: {scope}");
            if let Some(extended) = suggested_scope(scope) {
                eprintln!("  Re-run `bitrouter auth login --scope \"{extended}\"` to add it.");
            } else {
                eprintln!(
                    "  Re-run `bitrouter auth login --scope \"<your current scope> {scope}\"`."
                );
            }
        }
        _ => {}
    }
}

/// Best-effort: read the locally stored scope and append `missing` to
/// it, so the hint we print is copy-pasteable. Returns `None` when the
/// credentials file is unreadable.
fn suggested_scope(missing: &str) -> Option<String> {
    let path = default_credentials_path().ok()?;
    let store = CredentialsStore::load(&path).ok()?;
    let current = store.current()?.scope.clone();
    if current.split_whitespace().any(|s| s == missing) {
        // Already present — probably the server is rejecting something
        // we can't auto-fix. Don't suggest a duplicate.
        Some(current)
    } else {
        Some(format!("{current} {missing}"))
    }
}