mecha10-cli 0.9.0

Mecha10 CLI tool
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
//! Export JSON Schema + Markdown reference docs for this repo's config kinds as raw JSON Schema
//! files plus a generated Markdown field reference, under `schemas/`.
//!
//! Usage:
//! ```bash
//! cargo run -p mecha10-cli --example export_schemas -- --out schemas
//! ```
//!
//! `scripts/ci/schema-docs-check.sh` re-runs this and diffs against what's committed, so
//! `schemas/` can never silently drift from the schemas it documents.

#![allow(
    clippy::print_stdout,
    reason = "example prints its report to the terminal, by design -- same as the handler this replaced"
)]

use anyhow::{bail, Context, Result};
use mecha10_templates::services::assets_download::AssetsDownloadService;
use serde_json::{json, Value};
use std::collections::BTreeSet;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};

const DEFAULT_SCHEMA_EXPORT_DIR: &str = "schemas";

fn main() -> Result<()> {
    let out_dir = parse_out_dir(std::env::args().skip(1).collect())?;

    println!();
    println!("📄 Schema Export");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!();

    // The environment-config schema now lives in `mecha10-assets` (published content, no
    // longer bundled in this repo -- see `environment_config_schema`'s doc comment below), so
    // fetching it means a network round-trip. This `main` stays a plain sync fn (so the many
    // existing sync `export_schemas(...)` unit tests below don't all need to become async) by
    // blocking on a throwaway runtime, the same pattern used by this repo's other sync
    // entry points that need one-off async work (e.g. `packages/cli/src/services/process/spawn_node.rs`).
    let assets_dir = tokio::runtime::Runtime::new()
        .context("Failed to create a Tokio runtime for the mecha10-assets fetch")?
        .block_on(AssetsDownloadService::new().fetch_and_extract())
        .context("Failed to download mecha10-assets - cannot export the environment-config schema without it")?;
    let schemas_dir = assets_dir.path().join("configs/simulation/schemas");

    let written = export_schemas(&out_dir, &schemas_dir)?;

    println!("Wrote {} file(s) to {}:", written.len(), out_dir.display());
    for path in &written {
        println!("  - {}", path.display());
    }
    println!();

    Ok(())
}

/// Parse `--out <dir>` from the given args, defaulting to
/// [`DEFAULT_SCHEMA_EXPORT_DIR`] when omitted.
///
/// # Errors
///
/// Returns an error if `--out` is given without a following value, or an
/// unrecognized argument is passed.
fn parse_out_dir(args: Vec<String>) -> Result<PathBuf> {
    let mut iter = args.into_iter();
    let mut out_dir = PathBuf::from(DEFAULT_SCHEMA_EXPORT_DIR);

    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--out" => {
                let value = iter.next().ok_or_else(|| anyhow::anyhow!("--out requires a value"))?;
                out_dir = PathBuf::from(value);
            }
            other => bail!("unrecognized argument: {other}"),
        }
    }

    Ok(out_dir)
}

struct ExportedSchema {
    relative_json_path: PathBuf,
    title: String,
    schema: Value,
}

/// Generate every schema this knows about and write it under `out_dir`:
/// raw JSON Schema files plus a single `README.md` field reference. Returns the
/// list of files written (relative to `out_dir`), for callers that want to report
/// what changed.
///
/// # Errors
///
/// Returns an error if `out_dir` can't be created, or a file can't be written.
fn export_schemas(out_dir: &Path, schemas_dir: &Path) -> Result<Vec<PathBuf>> {
    let schemas = collect_schemas(schemas_dir)?;
    let mut written = Vec::new();

    for exported in &schemas {
        let path = out_dir.join(&exported.relative_json_path);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| format!("Failed to create directory {}", parent.display()))?;
        }
        let pretty = serde_json::to_string_pretty(&exported.schema)
            .with_context(|| format!("Failed to serialize schema for {}", exported.title))?;
        fs::write(&path, format!("{pretty}\n")).with_context(|| format!("Failed to write {}", path.display()))?;
        written.push(exported.relative_json_path.clone());
    }

    let readme_path = out_dir.join("README.md");
    fs::create_dir_all(out_dir).with_context(|| format!("Failed to create directory {}", out_dir.display()))?;
    fs::write(&readme_path, render_readme(&schemas)).context("Failed to write schemas/README.md")?;
    written.push(PathBuf::from("README.md"));

    Ok(written)
}

/// Every schema this export knows about, in the order they should
/// appear in the generated Markdown.
fn collect_schemas(schemas_dir: &Path) -> Result<Vec<ExportedSchema>> {
    let mut schemas = vec![
        ExportedSchema {
            relative_json_path: PathBuf::from("mecha10.schema.json"),
            title: "Project config (mecha10.json)".to_string(),
            schema: full_project_schema(),
        },
        ExportedSchema {
            relative_json_path: PathBuf::from("base.schema.json"),
            title: "Node config base (common/reserved fields)".to_string(),
            schema: mecha10_schema_registry::schema_for::<mecha10_core::node_config_base::NodeConfigBase>(),
        },
    ];

    schemas.push(ExportedSchema {
        relative_json_path: PathBuf::from("model-catalog.schema.json"),
        title: "Model catalog (model_catalog.toml)".to_string(),
        schema: mecha10_schema_registry::model_catalog_schema(),
    });

    schemas.push(ExportedSchema {
        relative_json_path: PathBuf::from("environment.schema.json"),
        title: "Simulation environment (environment.json)".to_string(),
        schema: environment_config_schema(schemas_dir)?,
    });

    schemas.push(ExportedSchema {
        relative_json_path: PathBuf::from("behavior.schema.json"),
        title: "Behavior composition (behavior tree config.json)".to_string(),
        schema: mecha10_behavior_runtime::BehaviorConfig::schema_value(),
    });

    schemas.push(ExportedSchema {
        relative_json_path: PathBuf::from("rl-job.schema.json"),
        title: "RL training job (configs/rl/jobs/*.yml)".to_string(),
        schema: mecha10_schema_registry::schema_for::<mecha10_cli::services::train_jobs::JobDefinition>(),
    });

    Ok(schemas)
}

/// The hand-written draft-07 schema for `environment.json`, read from a freshly-fetched
/// `mecha10-assets` extraction at `schemas_dir` (see `mecha10_schema_registry::environment_config_schema`).
fn environment_config_schema(schemas_dir: &Path) -> Result<Value> {
    mecha10_schema_registry::environment_config_schema(schemas_dir)
}

/// The real `mecha10.json` schema: `ProjectConfig::schema_value()` plus a small hand-written
/// remainder for the handful of properties that struct doesn't model, spliced back in by
/// [`apply_legacy_project_schema_fragments`] and [`inject_build_target_triple_enum`] below.
fn full_project_schema() -> Value {
    let mut schema = mecha10_cli_core::types::project::ProjectConfig::schema_value();
    apply_legacy_project_schema_fragments(&mut schema);
    inject_build_target_triple_enum(&mut schema);
    schema
}

/// Splice the handful of `mecha10.json` properties `ProjectConfig` doesn't model at all into
/// `schema` (its `properties` and `$defs` maps, in place): `nodes` (legacy array shape),
/// `run_targets`, and `scripts`.
fn apply_legacy_project_schema_fragments(schema: &mut Value) {
    let legacy_properties = json!({
        "nodes": {
            "type": "object",
            "properties": {
                "drivers": {
                    "type": "array",
                    "items": { "$ref": "#/definitions/node" },
                    "description": "Hardware driver nodes (legacy array form - see this property's own description)"
                },
                "standard": {
                    "type": "array",
                    "items": { "$ref": "#/definitions/standardNode" },
                    "description": "Standard/pre-built nodes from packages (legacy array form - see this property's own description)"
                },
                "custom": {
                    "type": "array",
                    "items": { "$ref": "#/definitions/node" },
                    "description": "Custom application nodes (legacy array form - see this property's own description)"
                }
            },
            "description": "Node definitions (NodesConfig in mecha10-cli-core) - typically a flat identifier -> version map, though the legacy `drivers`/`standard`/`custom` arrays below also validate (no `additionalProperties` restriction). Keys: a framework node's full package id (\"@mecha10/speaker\"), a future registry node (\"@<org>/<name>\"), or a project node's own unprefixed name (\"my-custom\"); the legacy \"@local/*\" prefix is no longer supported.",
            "examples": [
                { "@mecha10/speaker": "latest", "@mecha10/motor": "latest", "my-custom": "0.1.0" }
            ]
        },
        "run_targets": {
            "type": "object",
            "patternProperties": {
                "^[a-z][a-z0-9_-]*$": {
                    "$ref": "#/definitions/runTarget"
                }
            },
            "description": "Execution targets (robot, remote, dev, etc.)"
        },
        "scripts": {
            "type": "object",
            "patternProperties": {
                "^[a-z][a-z0-9:_-]*$": {
                    "type": "string"
                }
            },
            "description": "Script shortcuts (npm scripts-like)"
        }
    });

    let legacy_definitions = json!({
        "node": {
            "type": "object",
            "required": ["name", "path"],
            "properties": {
                "name": {
                    "type": "string",
                    "pattern": "^[a-z][a-z0-9_]*$",
                    "description": "Node name (snake_case)"
                },
                "path": {
                    "type": "string",
                    "description": "Path to node source code"
                },
                "config": {
                    "type": "string",
                    "description": "Path to node configuration file"
                },
                "description": {
                    "type": "string",
                    "maxLength": 200,
                    "description": "Node description"
                },
                "run_target": {
                    "type": "string",
                    "description": "Where to run this node - a key of this project's `run_targets` map"
                },
                "enabled": {
                    "type": "boolean",
                    "default": true,
                    "description": "Whether node is enabled"
                },
                "auto_restart": {
                    "type": "boolean",
                    "default": true,
                    "description": "Auto-restart on crash"
                },
                "depends_on": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Node dependencies (other nodes that must start first)"
                }
            }
        },
        "standardNode": {
            "type": "object",
            "required": ["package", "binary"],
            "properties": {
                "package": {
                    "type": "string",
                    "pattern": "^@[a-z0-9-]+/[a-z0-9/-]+$",
                    "description": "Package identifier (e.g., @mecha10/speaker)",
                    "examples": ["@mecha10/speaker"]
                },
                "binary": {
                    "type": "string",
                    "description": "Binary name within package"
                },
                "config": {
                    "type": "string",
                    "description": "Path to configuration file"
                }
            }
        },
        "runTarget": {
            "type": "object",
            "properties": {
                "description": {
                    "type": "string",
                    "maxLength": 200,
                    "description": "Target description"
                },
                "includes": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Node groups to include"
                },
                "resources": {
                    "type": "object",
                    "properties": {
                        "cpu_limit": {
                            "type": "string",
                            "pattern": "^\\d+(\\.\\d+)?$",
                            "description": "CPU limit (e.g., '2.0')"
                        },
                        "memory_limit": {
                            "type": "string",
                            "pattern": "^\\d+(K|M|G|T)?$",
                            "description": "Memory limit (e.g., '512M', '16G')"
                        },
                        "gpu": {
                            "oneOf": [
                                { "type": "boolean" },
                                {
                                    "type": "object",
                                    "properties": {
                                        "enabled": { "type": "boolean" },
                                        "vendor": {
                                            "type": "string",
                                            "enum": ["nvidia", "amd", "intel"]
                                        },
                                        "count": {
                                            "type": "integer",
                                            "minimum": 1
                                        },
                                        "optional": { "type": "boolean" }
                                    }
                                }
                            ],
                            "description": "GPU requirements"
                        },
                        "storage_type": {
                            "type": "string",
                            "enum": ["local", "ssd", "hdd", "any"],
                            "description": "Storage type requirement"
                        },
                        "storage_size_gb": {
                            "type": "integer",
                            "minimum": 1,
                            "description": "Storage size in GB"
                        },
                        "model_cache": {
                            "type": "string",
                            "description": "Path to model cache directory"
                        },
                        "devices": {
                            "type": "array",
                            "items": {
                                "type": "string",
                                "pattern": "^/dev/.+$"
                            },
                            "description": "Required device files (e.g., /dev/video0)"
                        }
                    },
                    "description": "Resource requirements"
                }
            }
        }
    });

    if let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) {
        if let Some(legacy_properties) = legacy_properties.as_object() {
            for (name, value) in legacy_properties {
                properties.insert(name.clone(), value.clone());
            }
        }
    }

    if let Some(root) = schema.as_object_mut() {
        root.insert("definitions".to_string(), legacy_definitions);
    }
}

/// Recover the `buildTargetTriple` enum constraint (the 4 Rust target triples `mecha10 build`
/// cross-compiles for) on `targets.{robot,remote}.platforms`, which `schemars` can't derive
/// directly for a `Vec<String>` field.
fn inject_build_target_triple_enum(schema: &mut Value) {
    let triples = json!([
        "x86_64-apple-darwin",
        "aarch64-apple-darwin",
        "x86_64-unknown-linux-gnu",
        "aarch64-unknown-linux-gnu"
    ]);

    if let Some(items) = schema
        .get_mut("$defs")
        .and_then(|defs| defs.get_mut("TargetEntry"))
        .and_then(|target_entry| target_entry.get_mut("properties"))
        .and_then(|properties| properties.get_mut("platforms"))
        .and_then(|platforms| platforms.get_mut("items"))
    {
        if let Some(items) = items.as_object_mut() {
            items.insert("enum".to_string(), triples);
        }
    }
}

/// Render the full `README.md`: one section per schema, each with a field table
/// plus a subsection per nested `definitions` entry it references.
fn render_readme(schemas: &[ExportedSchema]) -> String {
    let mut out = String::new();
    out.push_str("# Schema reference\n\n");
    out.push_str(
        "Generated from this repo's JSON Schemas by `cargo run --example export_schemas` (LAB-1829) — \
         do not hand-edit. Regenerate with:\n\n```\ncargo run -p mecha10-cli --example export_schemas\n```\n\n\
         Descriptions come from the schemas themselves (Rust doc comments on node config \
         structs, via `schemars`, or `get_project_schema()`'s own `description` fields for \
         the project config). See [`docs/validate-configs.md`](../validate-configs.md) for how \
         these schemas are used to validate configs, and the raw `.schema.json` files \
         alongside this doc for the exact JSON Schema.\n\n\
         This directory is also mirrored verbatim to the public \
         [`mecha-industries/mecha10-schema`](https://github.com/mecha-industries/mecha10-schema) \
         repo (LAB-4067), kept in sync by CI (`scripts/ci/schema-mirror-publish.sh`) — that's the \
         fetchable location for consumers (e.g. the public dashboard docs page, LAB-4054) that \
         can't read this private repo directly.\n\n",
    );

    out.push_str("## Contents\n\n");
    for exported in schemas {
        let anchor = slugify(&exported.title);
        let _ = writeln!(out, "- [{}](#{anchor})", exported.title);
    }
    out.push('\n');

    for exported in schemas {
        let _ = writeln!(out, "## {}\n", exported.title);
        if let Some(description) = exported.schema.get("description").and_then(Value::as_str) {
            let _ = writeln!(out, "{description}\n");
        }
        let _ = writeln!(
            out,
            "Raw schema: [`{}`]({}).\n",
            exported.relative_json_path.display(),
            exported.relative_json_path.display()
        );

        render_schema_body(&exported.schema, &exported.schema, &mut out, &mut BTreeSet::new());
    }

    out
}

struct PendingSection {
    title: String,
    schema: Value,
}

/// Render one schema's body: its own field table (if it's an object schema, or a
/// "Variants" breakdown if it's a `oneOf`/`anyOf`), followed by a subsection per
/// `definitions` entry and anonymous nested object it (transitively) references.
/// `visited` dedupes sections reached from more than one place so each is only
/// rendered once.
fn render_schema_body(root: &Value, schema: &Value, out: &mut String, visited: &mut BTreeSet<String>) {
    let mut pending: Vec<PendingSection> = Vec::new();
    render_value_body(schema, out, &mut pending);

    for container_key in ["$defs", "definitions"] {
        if let Some(definitions) = root.get(container_key).and_then(Value::as_object) {
            let mut names: Vec<&String> = definitions.keys().collect();
            names.sort();
            for name in names {
                pending.push(PendingSection {
                    title: name.clone(),
                    schema: definitions[name].clone(),
                });
            }
        }
    }

    let mut index = 0;
    while index < pending.len() {
        if visited.insert(pending[index].title.clone()) {
            let _ = writeln!(out, "### {}\n", pending[index].title);
            if let Some(description) = pending[index].schema.get("description").and_then(Value::as_str) {
                let _ = writeln!(out, "{description}\n");
            }
            let schema_to_render = pending[index].schema.clone();
            render_value_body(&schema_to_render, out, &mut pending);
        }
        index += 1;
    }
}

/// Render a single schema value's field table or variant breakdown — no heading,
/// callers add their own. Queues any anonymous inline nested object schema it
/// finds (a property, or an array property's `items`, with its own `properties`
/// but no `$ref`) onto `pending` for [`render_schema_body`] to render as its own
/// subsection.
fn render_value_body(schema: &Value, out: &mut String, pending: &mut Vec<PendingSection>) {
    if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
        let required: BTreeSet<&str> = schema
            .get("required")
            .and_then(Value::as_array)
            .map(|values| values.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default();

        let mut names: Vec<&String> = properties.keys().collect();
        names.sort();

        out.push_str("| Field | Type | Required | Description |\n");
        out.push_str("| --- | --- | --- | --- |\n");
        for name in names {
            let field_schema = &properties[name];
            let type_label = type_label(field_schema);
            let is_required = if required.contains(name.as_str()) { "yes" } else { "no" };
            let description = field_description(field_schema).unwrap_or_default();
            let _ = writeln!(out, "| `{name}` | {type_label} | {is_required} | {description} |");
            if let Some(nested) = anonymous_nested_object(name, field_schema) {
                pending.push(nested);
            }
        }
        out.push('\n');
        return;
    }

    if let Some(variants) = schema
        .get("oneOf")
        .or_else(|| schema.get("anyOf"))
        .and_then(Value::as_array)
    {
        out.push_str("One of the following variants:\n\n");
        for (index, variant) in variants.iter().enumerate() {
            let label = variant_label(variant, index);
            let _ = writeln!(out, "- **{label}**");
        }
        out.push('\n');
        for (index, variant) in variants.iter().enumerate() {
            let is_bare_reference_or_null = (variant.get("$ref").is_some()
                || variant.get("type").and_then(Value::as_str) == Some("null"))
                && variant.get("properties").is_none();
            if is_bare_reference_or_null || (variant.get("enum").is_some() && variant.get("properties").is_none()) {
                continue;
            }
            let label = variant_label(variant, index);
            let _ = writeln!(out, "**{label}**\n");
            render_value_body(variant, out, pending);
        }
        return;
    }

    if let Some(items) = schema.get("enum").and_then(Value::as_array) {
        let values: Vec<String> = items.iter().map(display_scalar).collect();
        let _ = writeln!(out, "Allowed values: {}\n", values.join(", "));
    }
}

/// If `field_schema` (or, for an array field, its `items`) is an anonymous
/// inline object schema — has its own `properties` but isn't a `$ref`/`allOf`-
/// wrapped reference to a named `definitions` entry — return a [`PendingSection`]
/// for it, titled after `field_name` (or the schema's own `title`, if it has
/// one). This is what documents e.g. `model_catalog_schema()`'s `models[]` items
/// (`ModelCatalogEntry`, embedded inline rather than hoisted to `definitions` —
/// see that function's doc comment for why), which a `$ref`-only walk would
/// otherwise silently skip.
fn anonymous_nested_object(field_name: &str, field_schema: &Value) -> Option<PendingSection> {
    let candidate = if field_schema.get("type").and_then(Value::as_str) == Some("array") {
        field_schema.get("items")?
    } else {
        field_schema
    };

    if candidate.get("$ref").is_some() {
        return None;
    }
    if let Some(all_of) = candidate.get("allOf").and_then(Value::as_array) {
        if all_of.iter().any(|s| s.get("$ref").is_some()) {
            return None;
        }
    }
    if candidate.get("oneOf").is_some() || candidate.get("anyOf").is_some() {
        return None;
    }

    let has_properties = candidate
        .get("properties")
        .and_then(Value::as_object)
        .is_some_and(|props| !props.is_empty());
    if !has_properties {
        return None;
    }

    let title = candidate
        .get("title")
        .and_then(Value::as_str)
        .map(str::to_string)
        .unwrap_or_else(|| field_name.to_string());
    Some(PendingSection {
        title,
        schema: candidate.clone(),
    })
}

/// A human label for one `oneOf`/`anyOf` variant: its serde-tag discriminant value
/// if present (`properties.type.enum[0]`, the common internally-tagged-enum shape),
/// its own `enum` value if it's a plain string-enum member, else its `title`, else
/// a positional fallback.
fn variant_label(variant: &Value, index: usize) -> String {
    if let Some(tag) = variant
        .get("properties")
        .and_then(|p| p.get("type"))
        .and_then(|t| t.get("enum"))
        .and_then(Value::as_array)
        .and_then(|values| values.first())
        .and_then(Value::as_str)
    {
        return format!("`{tag}`");
    }
    if let Some(tag) = variant
        .get("enum")
        .and_then(Value::as_array)
        .and_then(|values| values.first())
        .and_then(Value::as_str)
    {
        return format!("`{tag}`");
    }
    if let Some(title) = variant.get("title").and_then(Value::as_str) {
        return title.to_string();
    }
    if variant.get("type").and_then(Value::as_str) == Some("null") {
        return "`null`".to_string();
    }
    if let Some(reference) = variant.get("$ref").and_then(Value::as_str) {
        return ref_type_label(reference);
    }
    format!("variant {index}")
}

/// The description for a property schema, accounting for the `{"description":
/// ..., "allOf": [{"$ref": ...}]}` wrapping `schemars` uses when a field has its
/// own doc comment on top of a `$ref` (draft-07 doesn't allow sibling keywords
/// next to `$ref` directly).
fn field_description(schema: &Value) -> Option<String> {
    schema
        .get("description")
        .and_then(Value::as_str)
        .map(|s| s.replace('\n', " ").trim().to_string())
        .filter(|s| !s.is_empty())
}

/// A short type label for a field/variant schema: resolves `$ref`/`allOf`-wrapped
/// refs to the referenced definition's name, arrays to `array of <item type>`,
/// and falls back to the JSON Schema `type` keyword otherwise.
fn type_label(schema: &Value) -> String {
    if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
        return ref_type_label(reference);
    }
    if let Some(all_of) = schema.get("allOf").and_then(Value::as_array) {
        if let Some(reference) = all_of.iter().find_map(|s| s.get("$ref")).and_then(Value::as_str) {
            return ref_type_label(reference);
        }
    }
    if let Some(one_of) = schema
        .get("oneOf")
        .or_else(|| schema.get("anyOf"))
        .and_then(Value::as_array)
    {
        let labels: Vec<String> = one_of.iter().map(type_label).collect();
        return format!("one of: {}", labels.join(", "));
    }
    if schema.get("type").and_then(Value::as_str) == Some("array") {
        let item_label = schema.get("items").map_or_else(|| "any".to_string(), type_label);
        return format!("array of {item_label}");
    }
    if schema.get("properties").is_some() {
        return schema
            .get("title")
            .and_then(Value::as_str)
            .map_or_else(|| "object".to_string(), |title| format!("`{title}`"));
    }
    match schema.get("type") {
        Some(Value::String(t)) => t.clone(),
        Some(Value::Array(types)) => types.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" or "),
        _ if schema.get("enum").is_some() => "enum".to_string(),
        _ => "any".to_string(),
    }
}

/// The definition name a `#/definitions/<Name>` ref points at, formatted for
/// display (backtick-quoted so it reads as a type name, not prose).
fn ref_type_label(reference: &str) -> String {
    let name = reference.rsplit('/').next().unwrap_or(reference);
    format!("`{name}`")
}

fn display_scalar(value: &Value) -> String {
    match value {
        Value::String(s) => format!("`{s}`"),
        other => format!("`{other}`"),
    }
}

/// GitHub-flavored-Markdown heading-anchor slug for the table of contents links
/// (lowercase, spaces to hyphens, parens dropped).
fn slugify(title: &str) -> String {
    title
        .to_lowercase()
        .chars()
        .filter_map(|c| {
            if c.is_alphanumeric() || c == ' ' || c == '-' {
                Some(if c == ' ' { '-' } else { c })
            } else {
                None
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::tempdir;

    /// The vendored copy of `configs/simulation/schemas/` under this crate's `tests/fixtures/`
    /// (mirrors `mecha10-schema-registry`'s own vendored fixtures), so these tests exercise the
    /// real schema content without a network round-trip to `mecha10-assets`.
    fn schemas_dir() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/schemas")
    }

    #[test]
    fn parse_out_dir_defaults_when_no_args() {
        assert_eq!(parse_out_dir(vec![]).unwrap(), PathBuf::from(DEFAULT_SCHEMA_EXPORT_DIR));
    }

    #[test]
    fn parse_out_dir_reads_out_flag() {
        let args = vec!["--out".to_string(), "custom/dir".to_string()];
        assert_eq!(parse_out_dir(args).unwrap(), PathBuf::from("custom/dir"));
    }

    #[test]
    fn parse_out_dir_rejects_unknown_arg() {
        assert!(parse_out_dir(vec!["--bogus".to_string()]).is_err());
    }

    #[test]
    fn parse_out_dir_rejects_missing_value() {
        assert!(parse_out_dir(vec!["--out".to_string()]).is_err());
    }

    #[test]
    fn type_label_resolves_plain_primitive() {
        let schema = json!({"type": "string"});
        assert_eq!(type_label(&schema), "string");
    }

    #[test]
    fn type_label_resolves_direct_ref() {
        let schema = json!({"$ref": "#/definitions/SourceConfig"});
        assert_eq!(type_label(&schema), "`SourceConfig`");
    }

    #[test]
    fn type_label_resolves_all_of_wrapped_ref() {
        let schema = json!({
            "description": "Frame source configuration",
            "allOf": [{"$ref": "#/definitions/SourceConfig"}]
        });
        assert_eq!(type_label(&schema), "`SourceConfig`");
    }

    #[test]
    fn type_label_resolves_array_of_ref() {
        let schema = json!({"type": "array", "items": {"$ref": "#/definitions/ModelCatalogEntry"}});
        assert_eq!(type_label(&schema), "array of `ModelCatalogEntry`");
    }

    #[test]
    fn field_description_reads_plain_description() {
        let schema = json!({"type": "string", "description": "Camera ID for identification"});
        assert_eq!(
            field_description(&schema).as_deref(),
            Some("Camera ID for identification")
        );
    }

    #[test]
    fn field_description_reads_all_of_wrapped_description() {
        let schema = json!({
            "description": "Frame source configuration",
            "allOf": [{"$ref": "#/definitions/SourceConfig"}]
        });
        assert_eq!(
            field_description(&schema).as_deref(),
            Some("Frame source configuration")
        );
    }

    #[test]
    fn render_value_body_produces_a_field_table_with_required_column() {
        let root = json!({
            "type": "object",
            "required": ["name"],
            "properties": {
                "name": {"type": "string", "description": "The name"},
                "note": {"type": "string", "description": "Optional note"}
            }
        });
        let mut out = String::new();
        render_value_body(&root, &mut out, &mut Vec::new());
        assert!(out.contains("| `name` | string | yes | The name |"));
        assert!(out.contains("| `note` | string | no | Optional note |"));
    }

    #[test]
    fn render_value_body_queues_anonymous_nested_array_item_object() {
        let root = json!({
            "type": "object",
            "properties": {
                "models": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {"name": {"type": "string", "description": "Model name"}}
                    }
                }
            }
        });
        let mut out = String::new();
        render_schema_body(&root, &root, &mut out, &mut BTreeSet::new());
        assert!(out.contains("### models"));
        assert!(out.contains("| `name` | string | no | Model name |"));
    }

    #[test]
    fn render_schema_body_documents_defs_entries_the_same_as_definitions_entries() {
        let root = json!({
            "type": "object",
            "properties": {
                "source": {"anyOf": [{"$ref": "#/$defs/SourceConfig"}, {"type": "null"}]}
            },
            "$defs": {
                "SourceConfig": {
                    "type": "object",
                    "properties": {"path": {"type": "string"}}
                }
            }
        });
        let mut out = String::new();
        render_schema_body(&root, &root, &mut out, &mut BTreeSet::new());
        assert!(out.contains("### SourceConfig"));
        assert!(out.contains("| `path` | string | no |"));
    }

    #[test]
    fn render_schema_body_documents_referenced_definitions_once() {
        let root = json!({
            "type": "object",
            "properties": {
                "source": {"allOf": [{"$ref": "#/definitions/SourceConfig"}]}
            },
            "definitions": {
                "SourceConfig": {
                    "type": "object",
                    "properties": {"path": {"type": "string"}}
                }
            }
        });
        let mut out = String::new();
        render_schema_body(&root, &root, &mut out, &mut BTreeSet::new());
        assert_eq!(out.matches("### SourceConfig").count(), 1);
        assert!(out.contains("| `path` | string | no |"));
    }

    #[test]
    fn project_schema_behaviors_property_reflects_the_real_behaviors_config_struct() {
        let schema = full_project_schema();
        let behaviors_ref = schema["properties"]["behaviors"]["anyOf"][0]["$ref"]
            .as_str()
            .expect("behaviors should be an anyOf with a $ref variant");
        let def_name = behaviors_ref
            .rsplit('/')
            .next()
            .expect("$ref should have a final segment");
        let behaviors = &schema["$defs"][def_name];

        assert_eq!(def_name, "BehaviorsConfig");
        assert!(
            behaviors["properties"].get("active").is_some(),
            "expected `behaviors.properties.active`, got: {behaviors}"
        );
        assert!(
            behaviors["properties"].get("default").is_none(),
            "`behaviors` schema still has a stale `default` field: {behaviors}"
        );
        let required: Vec<&str> = behaviors["required"]
            .as_array()
            .expect("BehaviorsConfig schema should have a `required` array")
            .iter()
            .filter_map(Value::as_str)
            .collect();
        assert_eq!(required, vec!["active"]);
    }

    #[test]
    fn full_project_schema_still_requires_only_name_and_version() {
        let schema = full_project_schema();
        let required: Vec<&str> = schema["required"]
            .as_array()
            .expect("ProjectConfig schema should have a `required` array")
            .iter()
            .filter_map(Value::as_str)
            .collect();
        assert_eq!(required, vec!["name", "version"]);
    }

    #[test]
    fn full_project_schema_still_rejects_an_unknown_build_target_triple_enum_value() {
        let schema = full_project_schema();
        let triples = schema["$defs"]["TargetEntry"]["properties"]["platforms"]["items"]["enum"]
            .as_array()
            .expect("platforms.items should carry the buildTargetTriple enum");
        assert!(triples.iter().any(|t| t == "aarch64-unknown-linux-gnu"));
        assert!(!triples.iter().any(|t| t == "not-a-real-triple"));
    }

    #[test]
    fn full_project_schema_still_accepts_legacy_nodes_drivers_standard_custom_arrays() {
        let schema = full_project_schema();
        let nodes = &schema["properties"]["nodes"];
        assert!(nodes["properties"].get("drivers").is_some());
        assert!(nodes["properties"].get("standard").is_some());
        assert!(nodes["properties"].get("custom").is_some());
        assert!(schema["definitions"].get("node").is_some());
        assert!(schema["definitions"].get("standardNode").is_some());
    }

    #[test]
    fn full_project_schema_still_covers_run_targets_and_scripts() {
        let schema = full_project_schema();
        assert!(schema["properties"].get("run_targets").is_some());
        assert!(schema["properties"].get("scripts").is_some());
        assert!(schema["definitions"].get("runTarget").is_some());
    }

    #[test]
    fn variant_label_prefers_serde_tag_discriminant() {
        let variant = json!({
            "type": "object",
            "properties": {"type": {"enum": ["mock"]}}
        });
        assert_eq!(variant_label(&variant, 0), "`mock`");
    }

    #[test]
    fn export_schemas_writes_json_and_readme() {
        let dir = tempdir().unwrap();
        let written = export_schemas(dir.path(), &schemas_dir()).unwrap();

        assert!(written.contains(&PathBuf::from("mecha10.schema.json")));
        assert!(written.contains(&PathBuf::from("base.schema.json")));
        assert!(written.contains(&PathBuf::from("model-catalog.schema.json")));
        assert!(written.contains(&PathBuf::from("environment.schema.json")));
        assert!(written.contains(&PathBuf::from("behavior.schema.json")));
        assert!(written.contains(&PathBuf::from("rl-job.schema.json")));
        assert!(written.contains(&PathBuf::from("README.md")));
        assert!(!written.iter().any(|p| p.starts_with("nodes")));

        assert!(dir.path().join("mecha10.schema.json").exists());
        assert!(dir.path().join("base.schema.json").exists());
        assert!(dir.path().join("model-catalog.schema.json").exists());
        assert!(dir.path().join("environment.schema.json").exists());
        assert!(dir.path().join("behavior.schema.json").exists());
        assert!(dir.path().join("rl-job.schema.json").exists());
        assert!(!dir.path().join("nodes").exists());

        let readme = fs::read_to_string(dir.path().join("README.md")).unwrap();
        assert!(readme.contains("# Schema reference"));
        assert!(readme.contains("## Project config (mecha10.json)"));
        assert!(readme.contains("## Node config base (common/reserved fields)"));
        assert!(!readme.contains("## Node config: camera"));
        assert!(readme.contains("## Model catalog (model_catalog.toml)"));
        assert!(readme.contains("## Simulation environment (environment.json)"));
        assert!(readme.contains("## Behavior composition (behavior tree config.json)"));
        assert!(readme.contains("## RL training job (configs/rl/jobs/*.yml)"));
        assert!(readme.contains("### ModelCatalogEntry"));
        assert!(readme.contains("| `name` |"));
    }

    #[test]
    fn export_schemas_environment_schema_matches_the_fetched_mecha10_assets_source() {
        let dir = tempdir().unwrap();
        export_schemas(dir.path(), &schemas_dir()).unwrap();

        let written: Value =
            serde_json::from_str(&fs::read_to_string(dir.path().join("environment.schema.json")).unwrap()).unwrap();
        let fetched: Value =
            serde_json::from_str(&fs::read_to_string(schemas_dir().join("environment-config.schema.json")).unwrap())
                .unwrap();
        assert_eq!(written, fetched);
    }

    #[test]
    fn export_schemas_behavior_schema_matches_behavior_runtimes_own_schema() {
        let dir = tempdir().unwrap();
        export_schemas(dir.path(), &schemas_dir()).unwrap();

        let written: Value =
            serde_json::from_str(&fs::read_to_string(dir.path().join("behavior.schema.json")).unwrap()).unwrap();
        assert_eq!(written, mecha10_behavior_runtime::BehaviorConfig::schema_value());
    }

    #[test]
    fn export_schemas_base_schema_matches_node_config_base_and_exposes_relay_topics() {
        let dir = tempdir().unwrap();
        export_schemas(dir.path(), &schemas_dir()).unwrap();

        let written: Value =
            serde_json::from_str(&fs::read_to_string(dir.path().join("base.schema.json")).unwrap()).unwrap();
        assert_eq!(
            written,
            mecha10_schema_registry::schema_for::<mecha10_core::node_config_base::NodeConfigBase>()
        );
        assert!(written["properties"].get("relay_topics").is_some());
    }

    /// Regression test for the LAB-4072 follow-up audit: pins a previously-missing `examples`
    /// keyword on a hand-written schema field so a future change can't silently regress
    /// coverage without a test failing.
    #[test]
    fn export_schemas_fills_in_previously_missing_examples_and_bounds() {
        let dir = tempdir().unwrap();
        export_schemas(dir.path(), &schemas_dir()).unwrap();

        let env: Value =
            serde_json::from_str(&fs::read_to_string(dir.path().join("environment.schema.json")).unwrap()).unwrap();
        assert_eq!(
            env["properties"]["dimensions"]["properties"]["width"]["examples"],
            serde_json::json!([20.0])
        );
    }

    #[test]
    fn export_schemas_output_is_deterministic() {
        let dir_a = tempdir().unwrap();
        let dir_b = tempdir().unwrap();
        export_schemas(dir_a.path(), &schemas_dir()).unwrap();
        export_schemas(dir_b.path(), &schemas_dir()).unwrap();

        let readme_a = fs::read_to_string(dir_a.path().join("README.md")).unwrap();
        let readme_b = fs::read_to_string(dir_b.path().join("README.md")).unwrap();
        assert_eq!(readme_a, readme_b);

        let schema_a = fs::read_to_string(dir_a.path().join("mecha10.schema.json")).unwrap();
        let schema_b = fs::read_to_string(dir_b.path().join("mecha10.schema.json")).unwrap();
        assert_eq!(schema_a, schema_b);
    }
}