confluence-cli 0.1.35

A CLI for reading, searching, syncing, and automating Confluence
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
use serde_json::{Value, json};
use std::any::TypeId;

fn arg_to_json(arg: &clap::Arg) -> Value {
    let mut obj = serde_json::Map::new();

    let id = arg.get_id().as_str();
    let name = if arg.is_positional() {
        id.to_string()
    } else {
        arg.get_long()
            .map(|l| format!("--{l}"))
            .unwrap_or_else(|| id.to_string())
    };
    obj.insert("name".into(), json!(name));

    let value_type = arg.get_value_parser().type_id();
    let is_bool = !arg.get_action().takes_values() || value_type == TypeId::of::<bool>();
    if is_bool {
        obj.insert("type".into(), json!("boolean"));
    } else if value_type == TypeId::of::<usize>()
        || value_type == TypeId::of::<u64>()
        || value_type == TypeId::of::<u32>()
        || value_type == TypeId::of::<i64>()
    {
        obj.insert("type".into(), json!("integer"));
    } else {
        let possible: Vec<String> = arg
            .get_possible_values()
            .iter()
            .map(|v| v.get_name().to_string())
            .collect();
        if !possible.is_empty() {
            obj.insert("type".into(), json!("string"));
            obj.insert("enum".into(), json!(possible));
        } else {
            obj.insert("type".into(), json!("string"));
        }
    }

    if let Some(help) = arg.get_help().map(|h| h.to_string()) {
        obj.insert("description".into(), json!(help));
    }

    if arg.is_required_set() {
        obj.insert("required".into(), json!(true));
    } else if arg.is_positional() {
        obj.insert("required".into(), json!(arg.is_required_set()));
    }

    if let Some(default) = arg.get_default_values().first() {
        obj.insert("default".into(), json!(default.to_string_lossy()));
    }

    Value::Object(obj)
}

fn is_mutating(path: &str) -> bool {
    if path.starts_with("pull ") || path == "attachment download" {
        return true;
    }
    let mutating_verbs = [
        "create", "update", "delete", "move", "add", "upload", "set", "apply", "pull", "remove",
        "login", "logout", "migrate", "use", "init",
    ];
    let last_word = path.rsplit_once(' ').map(|(_, w)| w).unwrap_or(path);
    mutating_verbs.contains(&last_word)
}

fn effect_kind(path: &str) -> &'static str {
    if !is_mutating(path) {
        "read_only"
    } else if is_idempotent(path) {
        "idempotent"
    } else {
        "non_idempotent"
    }
}

fn is_destructive(path: &str) -> bool {
    matches!(
        path,
        "auth logout"
            | "profile remove"
            | "page delete"
            | "blog delete"
            | "attachment delete"
            | "label remove"
            | "comment delete"
            | "property delete"
    )
}

fn is_idempotent(path: &str) -> bool {
    !is_mutating(path)
        || matches!(
            path,
            "profile use" | "label add" | "label remove" | "property delete"
        )
}

fn output_fields_for(path: &str) -> Vec<Value> {
    let content_fields = || {
        vec![
            json!({"name": "id", "type": "string"}),
            json!({"name": "kind", "type": "string"}),
            json!({"name": "space_id", "type": "string", "nullable": true}),
            json!({"name": "space_key", "type": "string", "nullable": true}),
            json!({"name": "title", "type": "string"}),
            json!({"name": "status", "type": "string"}),
            json!({"name": "version", "type": "integer", "nullable": true}),
            json!({"name": "parent_id", "type": "string", "nullable": true}),
            json!({"name": "body_storage", "type": "string", "nullable": true}),
            json!({"name": "labels", "type": "array", "items": {"type": "string"}}),
            json!({"name": "properties", "type": "object"}),
            json!({"name": "web_url", "type": "string", "nullable": true}),
            json!({"name": "created_at", "type": "string", "nullable": true}),
            json!({"name": "updated_at", "type": "string", "nullable": true}),
        ]
    };

    match path {
        "page get" | "page list" | "page tree" | "page move" | "page create" | "page update"
        | "blog get" | "blog list" | "blog create" | "blog update" => content_fields(),

        "page delete" | "blog delete" => {
            vec![
                json!({"name": "id", "type": "string"}),
                json!({"name": "deleted", "type": "boolean"}),
            ]
        }

        "attachment delete" => vec![
            json!({"name": "attachment_id", "type": "string"}),
            json!({"name": "deleted", "type": "boolean"}),
        ],

        "comment delete" => vec![
            json!({"name": "comment_id", "type": "string"}),
            json!({"name": "deleted", "type": "boolean"}),
        ],

        "property delete" => vec![
            json!({"name": "key", "type": "string"}),
            json!({"name": "deleted", "type": "boolean"}),
        ],

        "label remove" => vec![
            json!({"name": "label", "type": "string"}),
            json!({"name": "removed", "type": "boolean"}),
        ],

        "space list" | "space get" => vec![
            json!({"name": "id", "type": "string"}),
            json!({"name": "key", "type": "string"}),
            json!({"name": "name", "type": "string"}),
            json!({"name": "space_type", "type": "string", "nullable": true}),
            json!({"name": "homepage_id", "type": "string", "nullable": true}),
            json!({"name": "web_url", "type": "string", "nullable": true}),
        ],

        "search" => vec![
            json!({"name": "id", "type": "string"}),
            json!({"name": "kind", "type": "string"}),
            json!({"name": "space_key", "type": "string", "nullable": true}),
            json!({"name": "title", "type": "string"}),
            json!({"name": "excerpt", "type": "string", "nullable": true}),
            json!({"name": "web_url", "type": "string", "nullable": true}),
        ],

        "attachment list" | "attachment upload" => vec![
            json!({"name": "id", "type": "string"}),
            json!({"name": "title", "type": "string"}),
            json!({"name": "media_type", "type": "string", "nullable": true}),
            json!({"name": "file_size", "type": "integer", "nullable": true}),
            json!({"name": "download_url", "type": "string", "nullable": true}),
            json!({"name": "comment", "type": "string", "nullable": true}),
        ],

        "comment list" | "comment add" | "comment update" => vec![
            json!({"name": "id", "type": "string"}),
            json!({"name": "author", "type": "string", "nullable": true}),
            json!({"name": "created_at", "type": "string", "nullable": true}),
            json!({"name": "body_storage", "type": "string"}),
            json!({"name": "version", "type": "integer", "nullable": true}),
        ],

        // `value` is arbitrary JSON, which clispec v0.3's compact field types cannot express.
        "property list" | "property get" | "property set" => vec![
            json!({"name": "id", "type": "string", "nullable": true}),
            json!({"name": "key", "type": "string"}),
            json!({"name": "version", "type": "integer", "nullable": true}),
        ],

        "auth login" | "profile add" => vec![
            json!({"name": "name", "type": "string"}),
            json!({"name": "provider", "type": "string"}),
            json!({"name": "base_url", "type": "string"}),
            json!({"name": "api_path", "type": "string"}),
            json!({"name": "credential_store", "type": "string"}),
            json!({"name": "cloud_id", "type": "string", "nullable": true}),
            json!({"name": "token_kind", "type": "string"}),
            json!({"name": "expires_at", "type": "string", "nullable": true}),
            json!({"name": "read_only", "type": "boolean"}),
        ],

        "auth status" => vec![
            json!({"name": "name", "type": "string"}),
            json!({"name": "provider", "type": "string"}),
            json!({"name": "base_url", "type": "string"}),
            json!({"name": "api_path", "type": "string"}),
            json!({"name": "credential_store", "type": "string"}),
            json!({"name": "cloud_id", "type": "string", "nullable": true}),
            json!({"name": "token_kind", "type": "string"}),
            json!({"name": "expires_at", "type": "string", "nullable": true}),
            json!({"name": "expiration_status", "type": "string"}),
            json!({"name": "read_only", "type": "boolean"}),
            json!({"name": "verified", "type": "boolean"}),
            json!({"name": "current_user", "type": "object", "nullable": true}),
        ],

        "auth logout" => vec![
            json!({"name": "profile", "type": "string"}),
            json!({"name": "status", "type": "string"}),
        ],

        "auth migrate" => vec![
            json!({"name": "profile", "type": "string"}),
            json!({"name": "migrated", "type": "boolean"}),
            json!({"name": "credential_store", "type": "string"}),
        ],

        "init" => vec![
            json!({"name": "configPath", "type": "string"}),
            json!({"name": "configExists", "type": "boolean"}),
            json!({"name": "cloudTokenUrl", "type": "string"}),
            json!({"name": "dcPatDocs", "type": "string"}),
            json!({"name": "envVars", "type": "object"}),
            json!({"name": "example", "type": "object"}),
        ],

        "profile list" => vec![
            json!({"name": "name", "type": "string"}),
            json!({"name": "provider", "type": "string"}),
            json!({"name": "base_url", "type": "string"}),
            json!({"name": "api_path", "type": "string"}),
            json!({"name": "credential_store", "type": "string"}),
            json!({"name": "token_kind", "type": "string"}),
            json!({"name": "expires_at", "type": "string", "nullable": true}),
            json!({"name": "read_only", "type": "boolean"}),
            json!({"name": "active", "type": "boolean"}),
        ],

        "profile use" => vec![
            json!({"name": "profile", "type": "string"}),
            json!({"name": "active", "type": "boolean"}),
        ],

        "profile remove" => vec![
            json!({"name": "profile", "type": "string"}),
            json!({"name": "removed", "type": "boolean"}),
        ],

        "config show" => vec![
            json!({"name": "name", "type": "string"}),
            json!({"name": "provider", "type": "string"}),
            json!({"name": "base_url", "type": "string"}),
            json!({"name": "api_path", "type": "string"}),
            json!({"name": "credential_store", "type": "string"}),
            json!({"name": "token_kind", "type": "string"}),
            json!({"name": "expires_at", "type": "string", "nullable": true}),
            json!({"name": "read_only", "type": "boolean"}),
        ],

        "config path" => vec![json!({"name": "config_path", "type": "string"})],

        "pull page" | "pull tree" | "pull space" => vec![json!({"name": "path", "type": "string"})],

        "doctor" => vec![
            json!({"name": "config_path", "type": "string"}),
            json!({"name": "config_exists", "type": "boolean"}),
            json!({"name": "active_profile", "type": "string", "nullable": true}),
            json!({"name": "stored_profiles", "type": "integer"}),
            json!({"name": "resolved_profile", "type": "object", "nullable": true}),
            json!({"name": "checks", "type": "array", "items": {"type": "object"}}),
            json!({"name": "summary", "type": "object"}),
        ],

        "attachment download" => vec![
            json!({"name": "path", "type": "string"}),
            json!({"name": "downloaded", "type": "boolean"}),
        ],

        "label list" => vec![json!({"name": "label", "type": "string"})],

        "label add" => vec![
            json!({"name": "label", "type": "string"}),
            json!({"name": "added", "type": "boolean"}),
        ],

        // completions: outputs shell completion scripts (unstructured text, not records)
        // schema: outputs the schema itself (not a structured record)
        "apply" => vec![
            json!({"name": "action", "type": "string"}),
            json!({"name": "title", "type": "string"}),
            json!({"name": "content_id", "type": "string", "nullable": true}),
            json!({"name": "path", "type": "string"}),
            json!({"name": "details", "type": "string"}),
        ],

        "plan" => vec![
            json!({"name": "action", "type": "string"}),
            json!({"name": "title", "type": "string"}),
            json!({"name": "content_id", "type": "string", "nullable": true}),
            json!({"name": "path", "type": "string"}),
            json!({"name": "details", "type": "string"}),
            json!({"name": "diff", "type": "string", "optional": true}),
        ],

        _ => vec![],
    }
}

/// Commands that get --limit/--offset/--fields injected in the schema
/// because they are list commands (even if the clap definition lacks some).
const LIST_COMMANDS: &[&str] = &[
    "space list",
    "page list",
    "blog list",
    "search",
    "attachment list",
    "label list",
    "comment list",
    "property list",
];

fn walk_commands(cmd: &clap::Command, prefix: &str, out: &mut Vec<Value>) {
    let global_ids = [
        "help",
        "output_format",
        "json",
        "profile",
        "quiet",
        "no_color",
        "yes",
    ];

    for sub in cmd.get_subcommands() {
        let name = sub.get_name();
        if name == "help" {
            continue;
        }

        let path = if prefix.is_empty() {
            name.to_string()
        } else {
            format!("{prefix} {name}")
        };

        let has_subcommands = sub.get_subcommands().any(|s| s.get_name() != "help");
        if has_subcommands {
            walk_commands(sub, &path, out);
        } else {
            let mut args: Vec<Value> = Vec::new();

            for arg in sub.get_arguments() {
                if arg.is_global_set()
                    || global_ids.contains(&arg.get_id().as_str())
                    || arg.is_hide_set()
                {
                    continue;
                }
                args.push(arg_to_json(arg));
            }

            let mut entry = serde_json::Map::new();
            entry.insert("name".into(), json!(path));

            if let Some(about) = sub.get_about().map(|a| a.to_string()) {
                entry.insert("description".into(), json!(about));
            } else {
                entry.insert(
                    "description".into(),
                    json!(format!("Run the {path} command")),
                );
            }

            entry.insert("mutating".into(), json!(is_mutating(&path)));
            entry.insert("effects".into(), json!(effect_kind(&path)));
            entry.insert("idempotent".into(), json!(is_idempotent(&path)));
            entry.insert("destructive".into(), json!(is_destructive(&path)));
            entry.insert("requires_confirmation".into(), json!(is_destructive(&path)));

            if !args.is_empty() {
                entry.insert("args".into(), json!(args));
            }

            let fields = output_fields_for(&path);
            if !fields.is_empty() {
                entry.insert("output_fields".into(), json!(fields));
            }

            out.push(Value::Object(entry));
        }
    }
}

pub fn generate(cmd: &clap::Command) -> Value {
    let mut commands: Vec<Value> = Vec::new();
    walk_commands(cmd, "", &mut commands);

    let mut document = json!({
        "clispec": "0.3",
        "response_contract": "1",
        "name": "confluence",
        "version": env!("CARGO_PKG_VERSION"),
        "description": "A CLI for reading, searching, syncing, and automating Confluence",
        "output": {"tty": "text", "piped": "json"},
        "global_args": [
            {
                "name": "--output",
                "type": "string",
                "description": "Output format: auto (default), text, or json. Auto uses JSON when stdout is not a terminal.",
                "enum": ["auto", "text", "json"],
                "default": "auto"
            },
            {
                "name": "-o",
                "type": "string",
                "description": "Short form of --output.",
                "enum": ["auto", "text", "json"],
                "default": "auto"
            },
            {
                "name": "--profile",
                "type": "string",
                "description": "Configuration profile name"
            },
            {
                "name": "--quiet",
                "type": "boolean",
                "description": "Suppress progress and informational messages"
            },
            {
                "name": "--no-color",
                "type": "boolean",
                "description": "Disable ANSI color"
            },
            {
                "name": "--yes",
                "type": "boolean",
                "description": "Skip confirmation prompts for destructive operations"
            }
        ],
        "errors": [
            {
                "kind": "invalid_input",
                "exit_code": 2,
                "retryable": false,
                "description": "The command arguments or input data were invalid."
            },
            {
                "kind": "tty_required",
                "exit_code": 2,
                "retryable": false,
                "description": "Interactive setup was requested without a terminal."
            },
            {
                "kind": "confirmation_required",
                "exit_code": 2,
                "retryable": false,
                "description": "A destructive operation requires confirmation. Re-run with --yes to confirm."
            },
            {
                "kind": "read_only",
                "exit_code": 2,
                "retryable": false,
                "description": "The selected profile forbids write operations."
            },
            {
                "kind": "auth",
                "exit_code": 3,
                "retryable": false,
                "description": "Authentication failed or credentials are missing/invalid."
            },
            {
                "kind": "not_found",
                "exit_code": 4,
                "retryable": false,
                "description": "The requested resource was not found."
            },
            {
                "kind": "api_error",
                "exit_code": 5,
                "retryable": false,
                "description": "Confluence returned an API error."
            },
            {
                "kind": "network",
                "exit_code": 5,
                "retryable": true,
                "description": "A connection or timeout failure prevented the request."
            },
            {
                "kind": "rate_limit",
                "exit_code": 6,
                "retryable": true,
                "description": "Confluence rate-limited the request."
            },
            {
                "kind": "conflict",
                "exit_code": 7,
                "retryable": false,
                "description": "A conflict occurred, such as a version mismatch or duplicate resource."
            },
            {
                "kind": "unexpected_error",
                "exit_code": 1,
                "retryable": false,
                "description": "An unexpected local or transport error occurred."
            }
        ],
        "commands": commands
    });
    enrich_v03(&mut document);
    document
}

fn enrich_v03(document: &mut Value) {
    let Some(commands) = document.get_mut("commands").and_then(Value::as_array_mut) else {
        return;
    };
    for command in commands {
        let Some(object) = command.as_object_mut() else {
            continue;
        };
        let name = object
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        if name == "completions" {
            object.remove("output_fields");
            object.insert("output_kind".into(), json!("opaque"));
            object.insert("media_type".into(), json!("text/plain"));
            continue;
        }
        let unbounded = LIST_COMMANDS.contains(&name.as_str());
        object.insert(
            "cardinality".into(),
            json!(if unbounded { "unbounded" } else { "bounded" }),
        );
        if unbounded {
            object.insert(
                "pagination".into(),
                json!({"style":"offset","limit_arg":"--limit","offset_arg":"--offset"}),
            );
            object.insert("fields_arg".into(), json!("--fields"));
            object.insert(
                "output_envelope".into(),
                json!({
                    "items": "array",
                    "total": if name == "search" { "integer|null" } else { "integer" },
                    "limit": "integer",
                    "offset": "integer"
                }),
            );
        }
        if name == "apply" {
            object.insert("destructive_when".into(), json!(["--delete-remote"]));
            object.insert(
                "requires_confirmation_when".into(),
                json!(["--delete-remote"]),
            );
        }
        if name == "attachment upload" {
            object.insert("destructive_when".into(), json!(["--replace"]));
            object.insert("requires_confirmation_when".into(), json!(["--replace"]));
            object.insert("partial_success_possible".into(), json!(true));
        }
        if name.starts_with("pull ") {
            object.insert("mutating".into(), json!(true));
            object.insert("idempotent".into(), json!(false));
            object.insert("overwrites_when".into(), json!(["--force"]));
            object.insert("destructive_when".into(), json!(["--force"]));
            object.insert("pagination".into(), json!({"style":"none"}));
            object.insert(
                "output_envelope".into(),
                json!({
                    "items": "array",
                    "total": "integer",
                    "limit": "integer",
                    "offset": "integer"
                }),
            );
        }
        if matches!(name.as_str(), "plan" | "apply") {
            object.insert("pagination".into(), json!({"style":"none"}));
            object.insert("output_envelope".into(), json!({"items":"array"}));
        }
        if matches!(
            name.as_str(),
            "page create" | "page update" | "page move" | "blog create" | "blog update"
        ) {
            object.insert("partial_success_possible".into(), json!(true));
        }
        if name == "attachment download" {
            object.insert("overwrites_when".into(), json!(["--force"]));
        }
        if name == "profile list" {
            object.insert("example".into(), json!({"args":["profile","list"]}));
        }
        if name == "schema" {
            object.insert("cardinality".into(), json!("single"));
            object.insert(
                "stdout_schema".into(),
                json!({"$ref":"https://clispec.dev/schema/v0.3.json"}),
            );
        }
        if !object.contains_key("output_fields") && !object.contains_key("stdout_schema") {
            object.insert("stdout_schema".into(), json!({}));
        }
    }
}

pub fn print_schema(command_filter: Option<&str>) -> bool {
    use clap::CommandFactory;
    let cmd = super::cli::Cli::command();
    let mut schema = generate(&cmd);
    if let Some(filter) = command_filter {
        schema["commands"] = Value::Array(
            schema["commands"]
                .as_array()
                .cloned()
                .unwrap_or_default()
                .into_iter()
                .filter(|command| command["name"] == filter)
                .collect(),
        );
    }
    let found = command_filter.is_none()
        || schema["commands"]
            .as_array()
            .is_some_and(|commands| !commands.is_empty());
    if found {
        println!(
            "{}",
            serde_json::to_string_pretty(&schema).expect("serialize schema")
        );
    }
    found
}

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

    fn test_cmd() -> clap::Command {
        crate::cli::Cli::command()
    }

    #[test]
    fn schema_has_required_top_level_keys() {
        let schema = generate(&test_cmd());
        assert!(schema.get("name").is_some());
        assert!(schema.get("version").is_some());
        assert!(schema.get("global_args").is_some());
        assert!(schema.get("errors").is_some());
        assert!(schema.get("commands").is_some());
        assert_eq!(schema["clispec"], "0.3");
    }

    #[test]
    fn schema_is_valid_json() {
        let schema = generate(&test_cmd());
        let serialized = serde_json::to_string_pretty(&schema).unwrap();
        let _: Value = serde_json::from_str(&serialized).unwrap();
    }

    #[test]
    fn schema_commands_is_array() {
        let schema = generate(&test_cmd());
        assert!(schema["commands"].is_array(), "commands must be an array");
    }

    #[test]
    fn schema_includes_leaf_commands() {
        let schema = generate(&test_cmd());
        let commands = schema["commands"].as_array().unwrap();
        let names: Vec<&str> = commands.iter().filter_map(|c| c["name"].as_str()).collect();
        assert!(names.contains(&"space list"));
        assert!(names.contains(&"page get"));
        assert!(names.contains(&"auth login"));
    }

    #[test]
    fn schema_mutating_markers_present() {
        let schema = generate(&test_cmd());
        let commands = schema["commands"].as_array().unwrap();
        for cmd in commands {
            assert!(
                cmd.get("mutating").is_some(),
                "command {} missing mutating field",
                cmd["name"]
            );
        }
    }

    #[test]
    fn schema_effects_conform_to_clispec_v03_and_agree_with_mutating() {
        let schema = generate(&test_cmd());
        let commands = schema["commands"].as_array().unwrap();
        for command in commands {
            let effects = command["effects"].as_str().unwrap_or_default();
            assert!(
                matches!(effects, "read_only" | "idempotent" | "non_idempotent"),
                "command {} has invalid effects value {effects}",
                command["name"]
            );
            assert_eq!(
                command["mutating"],
                json!(effects != "read_only"),
                "command {} has contradictory mutating and effects declarations",
                command["name"]
            );
        }

        let command = |name: &str| {
            commands
                .iter()
                .find(|command| command["name"] == name)
                .unwrap()
        };
        assert_eq!(command("page get")["effects"], "read_only");
        assert_eq!(command("profile use")["effects"], "idempotent");
        assert_eq!(command("page create")["effects"], "non_idempotent");
        assert_eq!(command("pull page")["effects"], "non_idempotent");
        assert_eq!(command("attachment download")["effects"], "non_idempotent");
    }

    #[test]
    fn schema_output_field_types_conform_to_clispec_v03() {
        let schema = generate(&test_cmd());
        for command in schema["commands"].as_array().unwrap() {
            for field in command["output_fields"].as_array().into_iter().flatten() {
                let field_type = field["type"].as_str().unwrap_or_default();
                assert!(
                    matches!(
                        field_type,
                        "string" | "integer" | "number" | "boolean" | "object" | "array"
                    ),
                    "field {} on command {} has invalid type {field_type}",
                    field["name"],
                    command["name"]
                );
                if field_type == "array" {
                    assert!(
                        field.get("items").is_some(),
                        "array field {} on command {} is missing items",
                        field["name"],
                        command["name"]
                    );
                }
            }
        }
    }

    #[test]
    fn schema_errors_have_exit_codes() {
        let schema = generate(&test_cmd());
        let errors = schema["errors"].as_array().unwrap();
        for err in errors {
            assert!(
                err.get("exit_code").is_some(),
                "error {} missing exit_code",
                err["kind"]
            );
        }
    }

    #[test]
    fn schema_has_no_generated_placeholder_descriptions() {
        let schema = generate(&test_cmd());
        for command in schema["commands"].as_array().unwrap() {
            let description = command["description"].as_str().unwrap_or_default();
            assert!(
                !description.starts_with("Run the ") && !description.trim().is_empty(),
                "command {} has placeholder documentation",
                command["name"]
            );
            for argument in command["args"].as_array().into_iter().flatten() {
                assert!(
                    argument.get("description").is_some(),
                    "argument {} on {} lacks a description",
                    argument["name"],
                    command["name"]
                );
            }
        }
    }

    #[test]
    fn list_schema_uses_only_real_clap_arguments() {
        let schema = generate(&test_cmd());
        for command in schema["commands"].as_array().unwrap() {
            let name = command["name"].as_str().unwrap();
            if !LIST_COMMANDS.contains(&name) {
                continue;
            }
            let argument_names = command["args"]
                .as_array()
                .unwrap()
                .iter()
                .filter_map(|argument| argument["name"].as_str())
                .collect::<Vec<_>>();
            for required in ["--limit", "--offset", "--fields"] {
                assert!(
                    argument_names.contains(&required),
                    "{name} lacks real {required} support"
                );
            }
        }
    }

    #[test]
    fn delete_and_remove_output_contracts_match_runtime_keys() {
        let schema = generate(&test_cmd());
        let fields = |name: &str| {
            schema["commands"]
                .as_array()
                .unwrap()
                .iter()
                .find(|command| command["name"] == name)
                .unwrap()["output_fields"]
                .as_array()
                .unwrap()
                .iter()
                .map(|field| field["name"].as_str().unwrap().to_string())
                .collect::<Vec<_>>()
        };
        assert_eq!(fields("attachment delete"), ["attachment_id", "deleted"]);
        assert_eq!(fields("comment delete"), ["comment_id", "deleted"]);
        assert_eq!(fields("property delete"), ["key", "deleted"]);
        assert_eq!(fields("label remove"), ["label", "removed"]);
    }

    #[test]
    fn schema_versions_response_contract_and_declares_runtime_errors() {
        let schema = generate(&test_cmd());
        assert_eq!(schema["response_contract"], "1");
        let kinds = schema["errors"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|error| error["kind"].as_str())
            .collect::<Vec<_>>();
        assert!(kinds.contains(&"read_only"));
        assert!(kinds.contains(&"network"));
    }

    #[test]
    fn schema_preserves_required_options_and_numeric_argument_types() {
        let schema = generate(&test_cmd());
        let command = |name: &str| {
            schema["commands"]
                .as_array()
                .unwrap()
                .iter()
                .find(|command| command["name"] == name)
                .unwrap()
        };
        let profile_name = command("profile add")["args"]
            .as_array()
            .unwrap()
            .iter()
            .find(|argument| argument["name"] == "--name")
            .unwrap();
        assert_eq!(profile_name["required"], true);

        for argument_name in ["--limit", "--offset"] {
            let argument = command("attachment list")["args"]
                .as_array()
                .unwrap()
                .iter()
                .find(|argument| argument["name"] == argument_name)
                .unwrap();
            assert_eq!(argument["type"], "integer");
        }
    }

    #[test]
    fn schema_exposes_command_local_version_arguments() {
        let schema = generate(&test_cmd());
        for name in ["page update", "blog update"] {
            let command = schema["commands"]
                .as_array()
                .unwrap()
                .iter()
                .find(|command| command["name"] == name)
                .unwrap();
            assert!(
                command["args"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .any(|argument| argument["name"] == "--version"),
                "{name} omitted --version"
            );
        }
    }

    #[test]
    fn schema_marks_conditional_overwrites_and_non_idempotent_property_sets() {
        let schema = generate(&test_cmd());
        let command = |name: &str| {
            schema["commands"]
                .as_array()
                .unwrap()
                .iter()
                .find(|command| command["name"] == name)
                .unwrap()
        };
        assert_eq!(command("property set")["idempotent"], false);
        for name in ["pull page", "pull tree", "pull space"] {
            assert_eq!(command(name)["mutating"], true);
            assert_eq!(command(name)["overwrites_when"], json!(["--force"]));
            assert_eq!(command(name)["destructive_when"], json!(["--force"]));
        }
        assert_eq!(
            command("attachment upload")["requires_confirmation_when"],
            json!(["--replace"])
        );
    }

    #[test]
    fn schema_declares_non_pageable_collection_envelopes() {
        let schema = generate(&test_cmd());
        let command = |name: &str| {
            schema["commands"]
                .as_array()
                .unwrap()
                .iter()
                .find(|command| command["name"] == name)
                .unwrap()
        };

        for name in ["pull page", "pull tree", "pull space"] {
            let entry = command(name);
            assert_eq!(entry["cardinality"], "bounded");
            assert_eq!(entry["pagination"], json!({"style":"none"}));
            assert_eq!(
                entry["output_envelope"],
                json!({
                    "items": "array",
                    "total": "integer",
                    "limit": "integer",
                    "offset": "integer"
                })
            );
        }

        for name in ["plan", "apply"] {
            let entry = command(name);
            assert_eq!(entry["cardinality"], "bounded");
            assert_eq!(entry["pagination"], json!({"style":"none"}));
            assert_eq!(entry["output_envelope"], json!({"items":"array"}));
        }
    }

    #[test]
    fn plan_schema_declares_optional_diff_field() {
        let schema = generate(&test_cmd());
        let commands = schema["commands"].as_array().unwrap();
        let fields = |name: &str| {
            commands
                .iter()
                .find(|command| command["name"] == name)
                .unwrap()["output_fields"]
                .as_array()
                .unwrap()
        };

        let diff = fields("plan")
            .iter()
            .find(|field| field["name"] == "diff")
            .expect("plan should declare its optional diff field");
        assert_eq!(diff["type"], "string");
        assert_eq!(diff["optional"], true);
        assert!(
            fields("apply").iter().all(|field| field["name"] != "diff"),
            "apply never emits diffs"
        );
    }

    #[test]
    fn schema_output_fields_are_unique_and_include_runtime_content_fields() {
        let schema = generate(&test_cmd());
        for command in schema["commands"].as_array().unwrap() {
            let mut seen = std::collections::BTreeSet::new();
            for field in command["output_fields"].as_array().into_iter().flatten() {
                let name = field["name"].as_str().unwrap();
                assert!(seen.insert(name), "duplicate output field {name}");
            }
        }
        let page_get = schema["commands"]
            .as_array()
            .unwrap()
            .iter()
            .find(|command| command["name"] == "page get")
            .unwrap();
        let fields = page_get["output_fields"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|field| field["name"].as_str())
            .collect::<Vec<_>>();
        for expected in ["body_storage", "labels", "properties", "web_url"] {
            assert!(fields.contains(&expected), "missing {expected}");
        }
    }
}