vta-service 0.5.1

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
// CLI-only modules (not part of the library)
mod acl_cli;
mod bootstrap_cli;
mod did_key;
#[cfg(feature = "setup")]
mod did_webvh;
mod import_did;
mod keys_cli;
#[cfg(feature = "setup")]
mod setup;
#[cfg(feature = "webvh")]
mod webvh_cli;

// Re-export library modules for use by CLI commands
use vta_service::*;

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64;
use clap::{Parser, Subcommand};
use config::AppConfig;
use ed25519_dalek::SigningKey;
use ed25519_dalek_bip32::{DerivationPath, ExtendedSigningKey};
use keys::seed_store::create_seed_store;
use keys::seeds::load_seed_bytes;
use multibase::Base;
use std::path::PathBuf;
use std::sync::Arc;

// There must be a valid mix of transports for the VTA Service
// The following checks if a valid set of features is enabled at compile time and produces a
// helpful error message if not.
#[cfg(not(any(feature = "rest", feature = "didcomm")))]
compile_error!("At least one of 'rest' or 'didcomm' must be enabled.");

#[derive(Parser)]
#[command(name = "vta", about = "Verifiable Trust Agent", version)]
struct Cli {
    /// Path to the configuration file
    #[arg(short, long, global = true)]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Run the setup wizard.
    ///
    /// Without arguments, prompts interactively. With `--from <file>`, reads
    /// a TOML setup-inputs file and runs end-to-end without prompts —
    /// suitable for CI, immutable images, or any unattended provisioning.
    /// See `vta_service::setup::WizardInputs` for the schema.
    Setup {
        /// Path to a TOML setup-inputs file. When set, setup runs
        /// non-interactively. The file format mirrors the on-disk
        /// `config.toml` plus a few one-shot fields (`admin_did`,
        /// `data_dir_exists`, etc.) that the interactive wizard normally
        /// collects via prompts.
        #[arg(long)]
        from: Option<PathBuf>,
    },
    /// Bootstrap the first admin and seal the VTA against offline CLI modifications.
    ///
    /// This is a ONE-TIME operation. After sealing, all CLI commands that modify
    /// state (ACL, keys, import, export) are disabled. Management is only possible
    /// via the authenticated REST API or DIDComm.
    BootstrapAdmin {
        /// DID to grant super admin access (must be a DID you control)
        #[arg(long)]
        did: String,
        /// Human-readable label for the admin ACL entry
        #[arg(long)]
        label: Option<String>,
    },
    /// Unseal the VTA — re-enables offline CLI commands (emergency recovery).
    ///
    /// Requires proof of super admin key ownership via challenge-response:
    /// the VTA generates a random challenge, you sign it with your admin
    /// private key using `pnm auth sign-challenge`, and paste the signature.
    Unseal,
    /// Export admin DID and credential (blocked when sealed)
    ExportAdmin,
    /// Show VTA status and statistics
    Status,
    /// Inspect the configuration file (offline, no server required).
    Config {
        #[command(subcommand)]
        command: ConfigCommands,
    },
    /// Create a did:key in a context (offline, no server required)
    CreateDidKey {
        /// Target context ID
        #[arg(long)]
        context: String,
        /// Also create an ACL entry with Admin role for the new DID
        #[arg(long)]
        admin: bool,
        /// Human-readable label for the key record and ACL entry
        #[arg(long)]
        label: Option<String>,
    },
    /// Create a did:webvh DID for a context (interactive wizard, no server required)
    CreateDidWebvh {
        /// Target context ID
        #[arg(long)]
        context: String,
        /// Human-readable label prefix for key records (default: context id)
        #[arg(long)]
        label: Option<String>,
    },
    /// Import an external DID and create an ACL entry (offline, no server required)
    ImportDid {
        /// The DID to import
        #[arg(long)]
        did: String,
        /// Role to assign (admin, initiator, application, reader)
        #[arg(long)]
        role: Option<String>,
        /// Human-readable label for the ACL entry
        #[arg(long)]
        label: Option<String>,
        /// Restrict to specific context(s); omit for unrestricted access
        #[arg(long)]
        context: Vec<String>,
    },
    /// Manage Access Control List entries (offline, no server required)
    Acl {
        #[command(subcommand)]
        command: AclCommands,
    },
    /// Manage keys (offline, no server required)
    Keys {
        #[command(subcommand)]
        command: KeyCliCommands,
    },
    /// Manage application contexts (offline, no server required)
    ///
    /// Mirrors `pnm contexts` so cold-start / air-gapped operators
    /// have an identical CLI surface (list/get/create/update/delete)
    /// against the local keystore. The historical `vta context`
    /// (singular) form is retained as a hidden alias for scripts
    /// already in production.
    #[command(alias = "context")]
    Contexts {
        #[command(subcommand)]
        command: ContextCommands,
    },
    /// Manage WebVH servers and DIDs (offline, no server required)
    #[cfg(feature = "webvh")]
    Webvh {
        #[command(subcommand)]
        command: WebvhCommands,
    },
    /// Sealed-transfer bootstrap — seal payloads for offline consumer
    /// provisioning (mediators, webvh servers, and other complex clients).
    Bootstrap {
        #[command(subcommand)]
        command: BootstrapCommands,
    },
}

#[derive(Subcommand)]
enum BootstrapCommands {
    /// Generate a fresh BootstrapRequest (consumer side).
    ///
    /// Mints an ephemeral Ed25519 keypair, persists the seed under
    /// `<seed-dir>/bootstrap-secrets/<bundle_id>.key`, and writes the
    /// `BootstrapRequest` JSON. Hand the JSON to the VTA operator; they
    /// return an armored sealed bundle which `vta bootstrap open` decrypts
    /// using the persisted seed.
    ///
    /// Used in cold-start scenarios where `pnm bootstrap request` isn't
    /// available — same wire format, different binary.
    Request {
        /// Output path for the BootstrapRequest JSON.
        #[arg(long)]
        out: PathBuf,
        /// Optional human-readable label echoed back in the request.
        #[arg(long)]
        label: Option<String>,
        /// Override the default seed cache directory
        /// (`~/.config/vta/bootstrap-secrets/`). Useful in CI or sealed
        /// images where `$HOME` isn't writable.
        #[arg(long)]
        seed_dir: Option<PathBuf>,
    },
    /// Open an armored sealed bundle returned by the producer (consumer side).
    ///
    /// Looks up the seed by `bundle_id` under `<seed-dir>/bootstrap-secrets/`,
    /// derives the X25519 HPKE secret, decrypts, and prints the payload.
    /// Counterpart to `vta bootstrap request`.
    ///
    /// When `--expect-vta-did` is set and the payload is a
    /// `TemplateBootstrap`, the VTA-issued authorization VC is verified
    /// end-to-end: the pinned DID is cross-checked against the bundle's
    /// `vta_trust.vta_did` and against `credentialSubject.adminOf.vta`,
    /// the issuer's pubkey is extracted from the bundled DID document's
    /// verificationMethod array, and the Data Integrity proof is
    /// verified. The DidSigned producer assertion (when present) is
    /// verified against the same key. Without this flag the opener
    /// trusts only the OOB SHA-256 digest; the printed payload is
    /// labelled "unverified trust bundle" so it's obvious.
    Open {
        /// Path to the armored sealed bundle.
        #[arg(long)]
        bundle: PathBuf,
        /// Expected SHA-256 digest, communicated by the producer
        /// out-of-band. Required unless `--no-verify-digest` is set.
        #[arg(long)]
        expect_digest: Option<String>,
        /// Skip out-of-band digest verification. Prints a warning;
        /// intended for testing only.
        #[arg(long, default_value_t = false)]
        no_verify_digest: bool,
        /// Pin the VTA DID out-of-band. When supplied and the payload is
        /// a `TemplateBootstrap`, the VC + producer assertion are
        /// verified end-to-end against this DID; mismatches are
        /// rejected (no silent fallback). Without this flag,
        /// verification is digest-only.
        #[arg(long)]
        expect_vta_did: Option<String>,
        /// Override the default seed cache directory
        /// (`~/.config/vta/bootstrap-secrets/`). Must match the value
        /// passed to `vta bootstrap request`.
        #[arg(long)]
        seed_dir: Option<PathBuf>,
    },
    /// Seal a payload for a consumer's BootstrapRequest (offline / Mode C).
    ///
    /// Reads the consumer's request (containing their ephemeral X25519 pubkey
    /// and a nonce), seals the supplied payload to that pubkey using HPKE,
    /// and writes an armored bundle. Prints the canonical SHA-256 digest the
    /// operator must communicate to the consumer out-of-band so they can
    /// pass it to `vta bootstrap open --expect-digest` (or
    /// `pnm bootstrap open` if the consumer has pnm installed).
    ///
    /// Producer authenticity in this mode is `PinnedOnly`: the consumer
    /// trusts the producer pubkey embedded in the bundle because they
    /// pinned it out-of-band.
    Seal {
        /// Path to the consumer's BootstrapRequest JSON.
        #[arg(long)]
        request: PathBuf,
        /// Path to a JSON file containing a SealedPayloadV1.
        #[arg(long)]
        payload: PathBuf,
        /// Output path for the armored bundle.
        #[arg(long)]
        out: PathBuf,
    },
    /// Generate a VP-framed BootstrapRequest for the provision-integration
    /// flow (consumer side).
    ///
    /// Mints an ephemeral Ed25519 keypair, persists the seed under
    /// `<seed-dir>/bootstrap-secrets/<bundle_id>.key`, and writes a signed
    /// VP (VC Data Model 2.0 `VerifiablePresentation` + `BootstrapRequest`
    /// types) carrying a `TemplateBootstrap` ask naming the target
    /// template and variables. Hand the JSON to the VTA operator; they
    /// return an armored sealed bundle which `vta bootstrap open`
    /// decrypts using the persisted seed.
    ///
    /// Used by integration operators (mediator, webvh-control, webvh-daemon,
    /// webvh-server, etc.) to request enrollment from a VTA that may not
    /// yet be network-reachable. See
    /// `docs/03-integrating/provision-integration.md` for the end-to-end
    /// flow.
    ProvisionRequest {
        /// DID template name the VTA should render (e.g.
        /// `didcomm-mediator`, `webvh-control`, `webvh-daemon`,
        /// `webvh-server`, or an operator-uploaded custom template).
        #[arg(long)]
        template: String,
        /// Template variable, repeat for each binding. Format `KEY=VALUE`.
        /// Values are parsed as JSON when the value starts with `{`, `[`,
        /// `"`, digit, `true`, `false`, or `null`; otherwise treated as a
        /// string.
        #[arg(long = "var", value_name = "KEY=VALUE")]
        vars: Vec<String>,
        /// Hint the target VTA context. The VTA operator may override
        /// but if they do and the hint disagrees, the request is
        /// rejected rather than silently normalised.
        #[arg(long)]
        context_hint: Option<String>,
        /// Opt into long-term admin-DID rollover: the VTA mints a
        /// fresh admin DID under its own key custody (default template
        /// `vta-admin`) and binds authorization to that DID instead
        /// of the ephemeral `client_did`. Recommended for any
        /// integration that stays up long-term.
        #[arg(long)]
        admin_template: Option<String>,
        /// Freshness window in hours for the VP's `validUntil`.
        /// Default 168 (7 days) — setup-file shuffling between hosts
        /// is slow.
        #[arg(long, value_name = "HOURS", default_value_t = 168.0)]
        validity_hours: f64,
        /// Free-form human label echoed back in audit logs.
        #[arg(long)]
        label: Option<String>,
        /// Override the default seed cache directory
        /// (`~/.config/vta/bootstrap-secrets/`). Must match the
        /// `--seed-dir` passed to `vta bootstrap open` on the same host.
        #[arg(long)]
        seed_dir: Option<PathBuf>,
        /// Output path for the signed BootstrapRequest JSON.
        #[arg(long)]
        out: PathBuf,
    },
    /// Provision a template-driven integration (mediator, webvh-host,
    /// future kinds) for a consumer's VP-framed BootstrapRequest.
    ///
    /// Mints integration key material, renders the named DID template,
    /// creates an admin ACL entry for the consumer's `client_did`,
    /// issues a VTA-signed authorization VC, and seals everything to
    /// the consumer's X25519 pubkey (derived from `client_did`).
    ///
    /// See `docs/03-integrating/provision-integration.md` for the full flow.
    #[cfg(feature = "webvh")]
    ProvisionIntegration {
        /// Path to the consumer's VP-framed BootstrapRequest JSON
        /// (`pnm bootstrap request --out …`).
        #[arg(long)]
        request: PathBuf,
        /// VTA context the integration will live in. Must be an
        /// existing context the operator is admin of (or pass
        /// `--create-context` to create it inline). If the request
        /// carries a `contextHint`, this flag must either match it or
        /// be omitted.
        #[arg(long)]
        context: Option<String>,
        /// Create the target context if it does not already exist.
        /// Idempotent — silently succeeds if the context exists. The
        /// context is created with `name = <id>`; rename later via the
        /// REST API if needed. Without this flag, a missing context
        /// fails with operator-remediation guidance.
        #[arg(long)]
        create_context: bool,
        /// Producer assertion mode on the returned sealed bundle.
        /// `did-signed` (default) signs with the VTA's `{vta_did}#key-0`.
        /// `pinned-only` is a dev/test escape hatch — no in-band
        /// signature, digest-pinning only.
        #[arg(long, default_value = "did-signed")]
        assertion: crate::bootstrap_cli::AssertionModeFlag,
        /// Override for the VC's `validUntil` window, in hours. Default
        /// is 1h. Fractional hours accepted (e.g. `0.25` for 15min).
        #[arg(long, value_name = "HOURS")]
        vc_validity_hours: Option<f64>,
        /// Output path for the armored bundle.
        #[arg(long)]
        out: PathBuf,
    },
}

#[derive(Subcommand)]
enum KeyCliCommands {
    /// List keys
    List {
        /// Filter by context ID
        #[arg(long)]
        context: Option<String>,
        /// Filter by status (active or revoked)
        #[arg(long)]
        status: Option<String>,
    },
    /// Export secret key material for one or more keys
    Secrets {
        /// Key IDs to export (omit to export all active keys in --context)
        key_ids: Vec<String>,
        /// Export all active keys in this context
        #[arg(long)]
        context: Option<String>,
    },
    /// List seed generations and their status
    Seeds,
    /// Rotate to a new master seed (retires the current seed)
    RotateSeed {
        /// BIP-39 mnemonic for the new seed (generates random if omitted)
        #[arg(long)]
        mnemonic: Option<String>,
    },
    /// Export all active keys in a context as a sealed DidSecrets bundle.
    ///
    /// Reads the local keystore directly — no running VTA or network
    /// required. Mirrors `pnm keys bundle` but works in cold-start /
    /// air-gapped environments where PNM cannot reach the VTA.
    Bundle {
        /// Context ID whose active keys should be exported.
        #[arg(long)]
        context: String,
        /// Path to the consumer's BootstrapRequest JSON (v1). Mutually
        /// exclusive with `--recipient-did` / `--recipient-nonce`.
        #[arg(long, conflicts_with_all = ["recipient_did", "recipient_nonce"])]
        recipient: Option<PathBuf>,
        /// Inline consumer DID (`did:key:z6Mk...`). Requires `--recipient-nonce`.
        #[arg(long, requires = "recipient_nonce")]
        recipient_did: Option<String>,
        /// Inline consumer nonce (32 hex chars == 16 bytes). Requires
        /// `--recipient-did`.
        #[arg(long, requires = "recipient_did")]
        recipient_nonce: Option<String>,
        /// Output path for the armored sealed bundle. If omitted, the
        /// armor is written to stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum ContextCommands {
    /// List all application contexts.
    List,
    /// Get a context by ID.
    Get {
        /// Context ID.
        id: String,
    },
    /// Create an application context (offline, no running VTA required).
    ///
    /// Allocates the next BIP-32 context index and writes the context
    /// record. Mirrors the online `POST /contexts` endpoint (and
    /// `pnm contexts create`) for cold-start / air-gapped operators
    /// who need to provision a context before standing the service up.
    ///
    /// Without `--admin-did` no keys, ACL entries, or DID are minted —
    /// pair with `vta bootstrap provision-integration` (or run it with
    /// `--create-context`) to populate the context. Supplying
    /// `--admin-did` writes an admin ACL entry scoped to the new
    /// context atomically with the context record, mirroring the
    /// `pnm contexts create --admin-did` shorthand.
    Create {
        /// Context ID (slug). Lowercase alphanumeric + hyphens, ≤64
        /// chars, no leading/trailing hyphen.
        #[arg(long)]
        id: String,
        /// Human-readable name. Defaults to the id when omitted.
        #[arg(long)]
        name: Option<String>,
        /// Free-form description.
        #[arg(long)]
        description: Option<String>,
        /// DID to grant admin access to (must start with `did:`). When
        /// set, atomically creates an ACL entry with role=admin scoped
        /// to this context.
        #[arg(long)]
        admin_did: Option<String>,
        /// Human-readable label for the admin ACL entry.
        #[arg(long)]
        admin_label: Option<String>,
        /// Setup-ACL expiry — accepts `N[s|m|h|d|w]` (e.g. `24h`, `7d`).
        /// When set, the admin ACL entry auto-expires via the server's
        /// ACL sweeper. Without this flag the entry is permanent.
        /// Requires `--admin-did`.
        #[arg(long, requires = "admin_did")]
        admin_expires: Option<String>,
    },
    /// Update an existing context.
    Update {
        /// Context ID.
        id: String,
        /// New name.
        #[arg(long)]
        name: Option<String>,
        /// Set the DID for this context.
        #[arg(long)]
        did: Option<String>,
        /// New description.
        #[arg(long)]
        description: Option<String>,
    },
    /// Delete a context and all associated resources (keys, ACL
    /// entries, DID records, scoped templates).
    Delete {
        /// Context ID.
        id: String,
        /// Skip confirmation and delete immediately.
        #[arg(long, short)]
        force: bool,
    },
    /// Export an existing context — its admin credential + all DID
    /// keys (signing + KA + any pre-rotation) + DID document + log —
    /// as a sealed ContextProvision bundle for a new/backup admin to
    /// import.
    ///
    /// Reads the local keystore directly — no running VTA or network
    /// required. Mirrors `pnm context reprovision` but works in
    /// cold-start / air-gapped environments where PNM cannot reach the
    /// VTA.
    ///
    /// The bundle always contains every key tied to the context's DID
    /// document (operational keys are auto-included). `--admin-key`
    /// separately names the existing Ed25519 seed that becomes the
    /// **admin credential** — the `did:key` the mediator operator uses
    /// to authenticate back to the VTA for ACL-gated operations.
    /// When omitted, a fresh admin key is minted in the context and
    /// the derived `did:key` is granted admin access automatically.
    Reprovision {
        /// Context ID to export.
        #[arg(long)]
        id: String,
        /// Existing Ed25519 key whose seed backs the exported admin
        /// credential. When omitted, a fresh admin key is minted in
        /// the context. Kept as `--key` for backward compatibility.
        #[arg(long = "admin-key", alias = "key")]
        admin_key: Option<String>,
        /// Label applied to the freshly-minted admin key when
        /// `--admin-key` is omitted. Defaults to
        /// `"admin-reprovision"`.
        #[arg(long)]
        admin_label: Option<String>,
        /// Path to the consumer's BootstrapRequest JSON (v1). Mutually
        /// exclusive with `--recipient-did` / `--recipient-nonce`.
        #[arg(long, conflicts_with_all = ["recipient_did", "recipient_nonce"])]
        recipient: Option<PathBuf>,
        /// Inline consumer DID (`did:key:z6Mk...`). Requires `--recipient-nonce`.
        #[arg(long, requires = "recipient_nonce")]
        recipient_did: Option<String>,
        /// Inline consumer nonce (32 hex chars == 16 bytes). Requires
        /// `--recipient-did`.
        #[arg(long, requires = "recipient_did")]
        recipient_nonce: Option<String>,
        /// Output path for the armored sealed bundle. If omitted, the
        /// armor is written to stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
}

#[cfg(feature = "webvh")]
#[derive(Subcommand)]
enum WebvhCommands {
    /// Add a WebVH server
    AddServer {
        /// Server identifier
        #[arg(long)]
        id: String,
        /// Server DID (must resolve to a DID document with a WebVHHostingService endpoint)
        #[arg(long)]
        did: String,
        /// Human-readable label
        #[arg(long)]
        label: Option<String>,
    },
    /// List configured WebVH servers
    ListServers,
    /// Update a WebVH server
    UpdateServer {
        /// Server identifier to update
        id: String,
        /// New label (empty string to clear)
        #[arg(long)]
        label: Option<String>,
    },
    /// Remove a WebVH server
    RemoveServer {
        /// Server identifier to remove
        id: String,
    },
    /// Create a did:webvh DID and publish to a WebVH server
    CreateDid {
        /// Target context ID
        #[arg(long)]
        context: String,
        /// WebVH server ID
        #[arg(long)]
        server: String,
        /// Optional path on the server (server allocates if omitted)
        #[arg(long)]
        path: Option<String>,
        /// Human-readable label for the DID and key records
        #[arg(long)]
        label: Option<String>,
        /// Make the DID portable (default: true)
        #[arg(long, default_value_t = true)]
        portable: bool,
        /// Add mediator DIDComm service endpoint
        #[arg(long)]
        mediator_service: bool,
        /// Additional services as JSON array
        #[arg(long)]
        services: Option<String>,
        /// Number of pre-rotation keys to generate
        #[arg(long)]
        pre_rotation: Option<u32>,
        /// Print the generated mnemonic to stderr. **Off by default** —
        /// printing puts the master seed in shell history, terminal
        /// scrollback, CI log collectors, and tmux/screen buffers. The
        /// mnemonic is also persisted via the configured seed-store; if
        /// you need it for paper backup, run `vta export-mnemonic`
        /// instead so it goes through the time-bounded export guard.
        #[arg(long)]
        print_mnemonic: bool,
    },
    /// List WebVH DIDs
    ListDids {
        /// Filter by context ID
        #[arg(long)]
        context: Option<String>,
        /// Filter by server ID
        #[arg(long)]
        server: Option<String>,
    },
    /// Delete a WebVH DID
    DeleteDid {
        /// The DID to delete
        did: String,
    },
    /// Print the raw `did.jsonl` log for a webvh DID the VTA knows.
    ///
    /// Snapshot from provisioning time — use this for audit or
    /// republication fallback, not as a live resolver (the integration
    /// itself becomes the live source once it publishes).
    DidLog {
        /// The DID to retrieve the log for.
        did: String,
        /// Optional output file. Stdout if omitted.
        #[arg(long)]
        out: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum ConfigCommands {
    /// Print the VTA's identity and service settings.
    ///
    /// Output matches what `pnm setup` asks for (VTA DID, public URL,
    /// mediator) plus the config/data paths. No network calls; the data
    /// store is not opened, so this works while the VTA is running.
    Show,
}

#[derive(Subcommand)]
enum AclCommands {
    /// List all ACL entries
    List {
        /// Filter by context
        #[arg(long)]
        context: Option<String>,
        /// Filter by role (admin, initiator, application, reader)
        #[arg(long)]
        role: Option<String>,
    },
    /// Show details of a single ACL entry
    Get {
        /// The DID to look up
        did: String,
    },
    /// Update an existing ACL entry
    Update {
        /// The DID to update
        did: String,
        /// New role (admin, initiator, application, reader)
        #[arg(long)]
        role: Option<String>,
        /// New label (empty string to clear)
        #[arg(long)]
        label: Option<String>,
        /// New context list (comma-separated; omit flag to keep unchanged)
        #[arg(long, value_delimiter = ',')]
        contexts: Option<Vec<String>>,
    },
    /// Delete an ACL entry
    Delete {
        /// The DID to delete
        did: String,
        /// Skip confirmation prompt
        #[arg(short, long)]
        yes: bool,
    },
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();

    #[cfg(feature = "keyring")]
    if let Err(e) = vta_sdk::keyring_init::install_default_store() {
        eprintln!("warning: OS keyring unavailable: {e}");
    }

    print_banner();

    match cli.command {
        Some(Commands::Setup { from }) => {
            #[cfg(feature = "setup")]
            {
                let result = match from {
                    Some(path) => setup::run_setup_from_file(path).await,
                    None => setup::run_setup_wizard(cli.config).await,
                };
                if let Err(e) = result {
                    eprintln!("Setup failed: {e}");
                    std::process::exit(1);
                }
            }
            #[cfg(not(feature = "setup"))]
            {
                let _ = from;
                eprintln!("Setup wizard not available (compiled without 'setup' feature)");
                std::process::exit(1);
            }
        }
        Some(Commands::BootstrapAdmin { did, label }) => {
            if let Err(e) = run_bootstrap_admin(cli.config, did, label).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Unseal) => {
            let config = match AppConfig::load(cli.config) {
                Ok(c) => c,
                Err(e) => {
                    eprintln!("Error: {e}");
                    std::process::exit(1);
                }
            };
            let store = store::Store::open(&config.store).expect("failed to open store");
            if let Err(e) = seal::run_unseal_challenge(&store).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::ExportAdmin) => {
            // SEALED CHECK: export-admin leaks private keys
            check_seal(&cli.config).await;
            if let Err(e) = export_admin(cli.config).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Status) => {
            if let Ok(config) = AppConfig::load(cli.config.clone()) {
                init_tracing(&config);
            }
            if let Err(e) = status::run_status(cli.config).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Config { command }) => {
            let result = match command {
                ConfigCommands::Show => run_config_show(cli.config),
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::CreateDidKey {
            context,
            admin,
            label,
        }) => {
            // SEALED CHECK: creates keys and optionally admin ACL entries
            check_seal(&cli.config).await;
            let args = did_key::CreateDidKeyArgs {
                config_path: cli.config,
                context,
                admin,
                label,
            };
            if let Err(e) = did_key::run_create_did_key(args).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::CreateDidWebvh { context, label }) => {
            // SEALED CHECK: creates keys and DIDs
            check_seal(&cli.config).await;
            #[cfg(feature = "setup")]
            {
                let args = did_webvh::CreateDidWebvhArgs {
                    config_path: cli.config,
                    context,
                    label,
                };
                if let Err(e) = did_webvh::run_create_did_webvh(args).await {
                    eprintln!("Error: {e}");
                    std::process::exit(1);
                }
            }
            #[cfg(not(feature = "setup"))]
            {
                let _ = (context, label);
                eprintln!("create-did-webvh is not available (compiled without 'setup' feature)");
                std::process::exit(1);
            }
        }
        Some(Commands::ImportDid {
            did,
            role,
            label,
            context,
        }) => {
            // SEALED CHECK: imports DIDs with arbitrary roles
            check_seal(&cli.config).await;
            let args = import_did::ImportDidArgs {
                config_path: cli.config,
                did,
                role,
                label,
                context,
            };
            if let Err(e) = import_did::run_import_did(args).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Keys { command }) => {
            // SEALED CHECK: secrets export and seed rotation
            match &command {
                KeyCliCommands::List { .. } | KeyCliCommands::Seeds => {}
                KeyCliCommands::Secrets { .. }
                | KeyCliCommands::RotateSeed { .. }
                | KeyCliCommands::Bundle { .. } => {
                    check_seal(&cli.config).await;
                }
            }
            let result = match command {
                KeyCliCommands::List { context, status } => {
                    keys_cli::run_keys_list(cli.config, context, status).await
                }
                KeyCliCommands::Secrets { key_ids, context } => {
                    keys_cli::run_keys_secrets(cli.config, key_ids, context).await
                }
                KeyCliCommands::Seeds => keys_cli::run_keys_seeds_list(cli.config).await,
                KeyCliCommands::RotateSeed { mnemonic } => {
                    keys_cli::run_rotate_seed(cli.config, mnemonic).await
                }
                KeyCliCommands::Bundle {
                    context,
                    recipient,
                    recipient_did,
                    recipient_nonce,
                    out,
                } => {
                    bootstrap_cli::run_keys_bundle(
                        cli.config,
                        context,
                        recipient,
                        recipient_did,
                        recipient_nonce,
                        out,
                    )
                    .await
                }
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Contexts { command }) => {
            // SEALED CHECK: only commands that mutate state need the
            // unsealed-store guard. List/Get are read-only.
            match &command {
                ContextCommands::List | ContextCommands::Get { .. } => {}
                ContextCommands::Create { .. }
                | ContextCommands::Update { .. }
                | ContextCommands::Delete { .. }
                | ContextCommands::Reprovision { .. } => {
                    check_seal(&cli.config).await;
                }
            }
            let result = match command {
                ContextCommands::List => bootstrap_cli::run_context_list(cli.config).await,
                ContextCommands::Get { id } => bootstrap_cli::run_context_get(cli.config, id).await,
                ContextCommands::Create {
                    id,
                    name,
                    description,
                    admin_did,
                    admin_label,
                    admin_expires,
                } => {
                    bootstrap_cli::run_context_create(
                        cli.config,
                        id,
                        name,
                        description,
                        admin_did,
                        admin_label,
                        admin_expires,
                    )
                    .await
                }
                ContextCommands::Update {
                    id,
                    name,
                    did,
                    description,
                } => {
                    bootstrap_cli::run_context_update(cli.config, id, name, did, description).await
                }
                ContextCommands::Delete { id, force } => {
                    bootstrap_cli::run_context_delete(cli.config, id, force).await
                }
                ContextCommands::Reprovision {
                    id,
                    admin_key,
                    admin_label,
                    recipient,
                    recipient_did,
                    recipient_nonce,
                    out,
                } => {
                    bootstrap_cli::run_context_reprovision(
                        cli.config,
                        id,
                        admin_key,
                        admin_label,
                        recipient,
                        recipient_did,
                        recipient_nonce,
                        out,
                    )
                    .await
                }
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Acl { command }) => {
            // SEALED CHECK: update and delete modify ACL
            match &command {
                AclCommands::List { .. } | AclCommands::Get { .. } => {}
                AclCommands::Update { .. } | AclCommands::Delete { .. } => {
                    check_seal(&cli.config).await;
                }
            }
            let result = match command {
                AclCommands::List { context, role } => {
                    acl_cli::run_acl_list(cli.config, context, role).await
                }
                AclCommands::Get { did } => acl_cli::run_acl_get(cli.config, did).await,
                AclCommands::Update {
                    did,
                    role,
                    label,
                    contexts,
                } => acl_cli::run_acl_update(cli.config, did, role, label, contexts).await,
                AclCommands::Delete { did, yes } => {
                    acl_cli::run_acl_delete(cli.config, did, yes).await
                }
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        #[cfg(feature = "webvh")]
        Some(Commands::Webvh { command }) => {
            // SEALED CHECK: webvh commands modify servers and DIDs
            match &command {
                WebvhCommands::ListServers
                | WebvhCommands::ListDids { .. }
                | WebvhCommands::DidLog { .. } => {}
                _ => check_seal(&cli.config).await,
            }
            let result = match command {
                WebvhCommands::AddServer { id, did, label } => {
                    webvh_cli::run_add_server(cli.config, id, did, label).await
                }
                WebvhCommands::ListServers => webvh_cli::run_list_servers(cli.config).await,
                WebvhCommands::UpdateServer { id, label } => {
                    webvh_cli::run_update_server(cli.config, id, label).await
                }
                WebvhCommands::RemoveServer { id } => {
                    webvh_cli::run_remove_server(cli.config, id).await
                }
                WebvhCommands::CreateDid {
                    context,
                    server,
                    path,
                    label,
                    portable,
                    mediator_service,
                    services,
                    pre_rotation,
                    print_mnemonic,
                } => {
                    webvh_cli::run_create_did(
                        cli.config,
                        context,
                        server,
                        path,
                        label,
                        portable,
                        mediator_service,
                        services,
                        pre_rotation,
                        print_mnemonic,
                    )
                    .await
                }
                WebvhCommands::ListDids { context, server } => {
                    webvh_cli::run_list_dids(cli.config, context, server).await
                }
                WebvhCommands::DeleteDid { did } => {
                    webvh_cli::run_delete_did(cli.config, did).await
                }
                WebvhCommands::DidLog { did, out } => {
                    webvh_cli::run_did_log(cli.config, did, out).await
                }
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Some(Commands::Bootstrap { command }) => {
            let result = match command {
                BootstrapCommands::Seal {
                    request,
                    payload,
                    out,
                } => bootstrap_cli::run_seal(cli.config.clone(), request, payload, out).await,
                BootstrapCommands::Request {
                    out,
                    label,
                    seed_dir,
                } => bootstrap_cli::run_request(out, label, seed_dir).await,
                BootstrapCommands::Open {
                    bundle,
                    expect_digest,
                    no_verify_digest,
                    expect_vta_did,
                    seed_dir,
                } => {
                    bootstrap_cli::run_open(
                        bundle,
                        expect_digest,
                        no_verify_digest,
                        expect_vta_did,
                        seed_dir,
                    )
                    .await
                }
                BootstrapCommands::ProvisionRequest {
                    template,
                    vars,
                    context_hint,
                    admin_template,
                    validity_hours,
                    label,
                    seed_dir,
                    out,
                } => {
                    bootstrap_cli::run_provision_request(
                        template,
                        vars,
                        context_hint,
                        admin_template,
                        validity_hours,
                        label,
                        seed_dir,
                        out,
                    )
                    .await
                }
                #[cfg(feature = "webvh")]
                BootstrapCommands::ProvisionIntegration {
                    request,
                    context,
                    create_context,
                    assertion,
                    vc_validity_hours,
                    out,
                } => {
                    bootstrap_cli::run_provision_integration(
                        cli.config.clone(),
                        request,
                        context,
                        create_context,
                        assertion,
                        vc_validity_hours,
                        out,
                    )
                    .await
                }
            };
            if let Err(e) = result {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        None => {
            let config = match AppConfig::load(cli.config) {
                Ok(config) => config,
                Err(e) => {
                    eprintln!("Error: {e}");
                    eprintln!();
                    eprintln!("To set up a new VTA instance, run:");
                    eprintln!("  vta setup");
                    eprintln!();
                    eprintln!("Or specify a config file:");
                    eprintln!("  vta --config <path>");
                    std::process::exit(1);
                }
            };

            init_tracing(&config);

            let store = store::Store::open(&config.store).expect("failed to open store");
            let seed_store: Arc<dyn keys::seed_store::SeedStore> =
                Arc::from(create_seed_store(&config).expect("failed to create seed store"));

            if let Err(e) = server::run(
                config, store, seed_store, None, // no storage encryption (non-TEE mode)
                None, // no TEE context (use vta-enclave for TEE mode)
            )
            .await
            {
                tracing::error!("server error: {e}");
                std::process::exit(1);
            }
        }
    }
}

fn print_banner() {
    let cyan = "\x1b[36m";
    let magenta = "\x1b[35m";
    let yellow = "\x1b[33m";
    let dim = "\x1b[2m";
    let reset = "\x1b[0m";

    eprintln!(
        r#"
{cyan} ██╗   ██╗{magenta}████████╗{yellow} █████╗{reset}
{cyan} ██║   ██║{magenta}╚══██╔══╝{yellow}██╔══██╗{reset}
{cyan} ██║   ██║{magenta}   ██║   {yellow}███████║{reset}
{cyan} ╚██╗ ██╔╝{magenta}   ██║   {yellow}██╔══██║{reset}
{cyan}  ╚████╔╝ {magenta}   ██║   {yellow}██║  ██║{reset}
{cyan}   ╚═══╝  {magenta}   ╚═╝   {yellow}╚═╝  ╚═╝{reset}
{dim}  Verifiable Trust Agent v{version}{reset}
"#,
        version = env!("CARGO_PKG_VERSION"),
    );
}

/// Check if the VTA is sealed; exit with an error if so.
/// Called before any CLI command that modifies state.
async fn check_seal(config_path: &Option<PathBuf>) {
    let config = match AppConfig::load(config_path.clone()) {
        Ok(c) => c,
        Err(_) => return, // Config not loadable — let the actual command handle it
    };
    let store = match store::Store::open(&config.store) {
        Ok(s) => s,
        Err(_) => return, // Store not openable — let the actual command handle it
    };
    if let Err(e) = seal::require_unsealed(&store).await {
        eprintln!("Error: {e}");
        std::process::exit(1);
    }
}

/// Bootstrap the first super admin and seal the VTA.
async fn run_bootstrap_admin(
    config_path: Option<PathBuf>,
    did: String,
    label: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = store::Store::open(&config.store)?;
    let acl_ks = store.keyspace("acl")?;

    // Check if already sealed
    if let Some(existing) = seal::get_seal(&acl_ks).await? {
        eprintln!(
            "VTA is already sealed (by {} on {}).",
            existing.sealed_by,
            existing
                .sealed_at
                .with_timezone(&chrono::Local)
                .format("%Y-%m-%d %H:%M:%S %:z")
        );
        eprintln!("Cannot bootstrap again. Manage admins via the REST API or DIDComm.");
        std::process::exit(1);
    }

    // Check no existing super admins
    let entries = acl::list_acl_entries(&acl_ks).await?;
    let existing_super_admins: Vec<_> = entries
        .iter()
        .filter(|e| e.role == acl::Role::Admin && e.allowed_contexts.is_empty())
        .collect();

    if !existing_super_admins.is_empty() {
        eprintln!(
            "WARNING: {} existing super admin(s) found:",
            existing_super_admins.len()
        );
        for admin in &existing_super_admins {
            eprintln!(
                "  - {} ({})",
                admin.did,
                admin.label.as_deref().unwrap_or("no label")
            );
        }
        eprintln!();
        eprintln!("Proceeding will add another super admin and seal the VTA.");
        eprintln!("Press Ctrl+C to cancel, or Enter to continue...");
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf)?;
    }

    // Create the super admin ACL entry
    let entry = acl::AclEntry {
        did: did.clone(),
        role: acl::Role::Admin,
        label,
        allowed_contexts: vec![], // Empty = super admin
        created_at: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        created_by: "cli:bootstrap-admin".into(),
        expires_at: None,
    };
    acl::store_acl_entry(&acl_ks, &entry).await?;

    // Seal the VTA
    let seal_record = seal::seal(&acl_ks, &did).await?;

    store.persist().await?;

    eprintln!();
    eprintln!("=== VTA Bootstrapped and Sealed ===");
    eprintln!();
    eprintln!("  Admin DID: {}", did);
    eprintln!(
        "  Sealed at: {}",
        seal_record
            .sealed_at
            .with_timezone(&chrono::Local)
            .format("%Y-%m-%d %H:%M:%S %:z")
    );
    eprintln!();
    eprintln!("  The VTA is now sealed. Offline CLI commands that modify state are disabled.");
    eprintln!("  All management must go through the authenticated REST API or DIDComm.");
    eprintln!();
    eprintln!("  To start the VTA server:");
    eprintln!("    vta --config config.toml");
    eprintln!();

    Ok(())
}

// init_tracing is now in vta_service::init_tracing (lib.rs)

/// Print the VTA's identity and service settings from `config.toml`.
///
/// Explicitly does NOT open the data store, so it works while the VTA
/// process is running. Also doesn't resolve DIDs or touch the network —
/// this is the quick, safe "what did setup write?" command.
fn run_config_show(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;

    const BOLD: &str = "\x1b[1m";
    const CYAN: &str = "\x1b[36m";
    const DIM: &str = "\x1b[2m";
    const RESET: &str = "\x1b[0m";

    fn line(label: &str, value: Option<&str>) {
        match value {
            Some(v) if !v.is_empty() => {
                println!("  {CYAN}{:<13}{RESET} {v}", label);
            }
            _ => {
                println!("  {CYAN}{:<13}{RESET} {DIM}(not set){RESET}", label);
            }
        }
    }

    println!();
    println!("{BOLD}VTA configuration{RESET}");
    println!();
    line("Name", config.vta_name.as_deref());
    line("VTA DID", config.vta_did.as_deref());
    line("Public URL", config.public_url.as_deref());

    let mut svc_list = Vec::new();
    if config.services.rest {
        svc_list.push("REST");
    }
    if config.services.didcomm {
        svc_list.push("DIDComm");
    }
    let svc_display = if svc_list.is_empty() {
        "(none)".to_string()
    } else {
        svc_list.join(", ")
    };
    line("Services", Some(&svc_display));
    line(
        "Listen",
        Some(&format!("{}:{}", config.server.host, config.server.port)),
    );

    if let Some(msg) = &config.messaging {
        line("Mediator DID", Some(&msg.mediator_did));
        if !msg.mediator_url.is_empty() {
            line("Mediator URL", Some(&msg.mediator_url));
        }
    } else {
        line("Mediator DID", None);
    }

    line(
        "Config file",
        Some(&config.config_path.display().to_string()),
    );
    line(
        "Data store",
        Some(&config.store.data_dir.display().to_string()),
    );
    println!();
    Ok(())
}

async fn export_admin(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    let config = AppConfig::load(config_path)?;
    let store = store::Store::open(&config.store)?;
    let acl_ks = store.keyspace("acl")?;
    let keys_ks = store.keyspace("keys")?;
    let seed_store = create_seed_store(&config)?;

    let vta_did = config.vta_did.as_deref().unwrap_or("(not set)");

    // Find admin ACL entries
    let entries = acl::list_acl_entries(&acl_ks).await?;
    let admins: Vec<_> = entries
        .iter()
        .filter(|e| e.role == acl::Role::Admin)
        .collect();

    if admins.is_empty() {
        eprintln!("No admin entries found in ACL.");
        return Ok(());
    }

    eprintln!("VTA DID: {vta_did}");
    if let Some(msg) = &config.messaging {
        eprintln!("Mediator DID: {}", msg.mediator_did);
    }
    eprintln!();

    for admin in &admins {
        eprintln!("Admin DID: {}", admin.did);
        if let Some(label) = &admin.label {
            eprintln!("  Label: {label}");
        }

        // For did:key admins, reconstruct the credential
        if admin.did.starts_with("did:key:") {
            match reconstruct_credential(&*seed_store, &admin.did, vta_did, &keys_ks).await {
                Ok(credential) => {
                    eprintln!();
                    eprintln!("  Credential:");
                    eprintln!("  {credential}");
                }
                Err(e) => {
                    eprintln!("  Could not reconstruct credential: {e}");
                }
            }
        }
        eprintln!();
    }

    Ok(())
}

/// Re-derive the admin private key from BIP-32 seed and build the credential bundle.
async fn reconstruct_credential(
    seed_store: &dyn keys::seed_store::SeedStore,
    admin_did: &str,
    vta_did: &str,
    keys_ks: &store::KeyspaceHandle,
) -> Result<String, Box<dyn std::error::Error>> {
    // The did:key fragment is {did}#{multibase_pubkey}
    let multibase_pubkey = admin_did.strip_prefix("did:key:").unwrap();
    let key_id = format!("{admin_did}#{multibase_pubkey}");

    // Look up the key record to get the derivation path
    let record: keys::KeyRecord = keys_ks
        .get(keys::store_key(&key_id))
        .await?
        .ok_or("admin key record not found in store")?;

    // Load seed for this key's generation
    let seed = load_seed_bytes(keys_ks, seed_store, record.seed_id).await?;

    // Re-derive the private key
    let root = ExtendedSigningKey::from_seed(&seed)
        .map_err(|e| format!("failed to create BIP-32 root key: {e}"))?;
    let derivation_path: DerivationPath = record
        .derivation_path
        .parse()
        .map_err(|e| format!("invalid derivation path: {e}"))?;
    let derived = root
        .derive(&derivation_path)
        .map_err(|e| format!("key derivation failed: {e}"))?;

    let signing_key = SigningKey::from_bytes(derived.signing_key.as_bytes());
    let private_key_multibase = multibase::encode(Base::Base58Btc, signing_key.as_bytes());

    let bundle = serde_json::json!({
        "did": admin_did,
        "privateKeyMultibase": private_key_multibase,
        "vtaDid": vta_did,
    });
    let bundle_json = serde_json::to_string(&bundle)?;
    Ok(BASE64.encode(bundle_json.as_bytes()))
}