mecha10-cli 0.6.3

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
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
//! Init command handler
//!
//! Orchestrates project initialization using InitService and ProjectTemplateService.
//!
//! Templates are downloaded on-demand from GitHub releases and cached locally.
//! This ensures users always get the latest templates without rebuilding the CLI.

use crate::commands::InitArgs;
use crate::context::CliContext;
use crate::init::validation;
use crate::paths;
use crate::services::CredentialsService;
use crate::types::EnvironmentsConfig;
use crate::ui::init_wizard::run_wizard_tui;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// Result type for init processing: (project_name, project_path, template, nodes)
type InitProcessResult = (String, PathBuf, Option<String>, Vec<String>);

/// Cleanup partially created project directory on error
async fn cleanup_on_error(project_path: &Path) {
    if project_path.exists() {
        if let Err(e) = tokio::fs::remove_dir_all(project_path).await {
            eprintln!("⚠️  Failed to cleanup directory: {}", e);
        } else {
            println!("🧹 Cleaned up incomplete project directory");
        }
    }
}

/// Download latest templates from GitHub releases
///
/// Returns the template version on success.
async fn download_templates(ctx: &mut CliContext) -> Result<String> {
    let template_download = ctx.template_download();

    // Prefer a locally `--install`ed dev build over the latest published
    // version, so `scripts/release/index.py --component templates --install`
    // lets you iterate on template changes fully offline. Falls back to the
    // latest published version (network call) when nothing is installed
    // locally.
    let version = template_download.resolve_version().await?;

    // Ensure templates are downloaded and cached
    template_download.ensure_templates(&version).await?;

    Ok(version)
}

/// Copy templates from downloaded GitHub release
///
/// Copies config files, behaviors, and assets from the downloaded template cache.
async fn copy_downloaded_templates(ctx: &mut CliContext, project_path: &Path, version: &str) -> Result<()> {
    let template_download = ctx.template_download();

    // Copy node configs (configs/nodes/@mecha10/* -> configs/nodes/@mecha10/*)
    template_download.copy_template_dir(
        version,
        "configs/nodes/@mecha10",
        &project_path.join(paths::config::NODES_MECHA10_DIR),
    )?;

    // Copy simulation config
    template_download.copy_template_file(
        version,
        "configs/simulation/config.json",
        &project_path.join(paths::config::SIMULATION_CONFIG),
    )?;

    // Copy behaviors (nested under configs/ since LAB-2072, so `mecha10 config push` syncs
    // them - see `paths::project::BEHAVIORS_DIR`)
    template_download.copy_template_dir(
        version,
        "configs/behaviors",
        &project_path.join(paths::project::BEHAVIORS_DIR),
    )?;

    // Copy assets
    template_download.copy_template_dir(version, "assets", &project_path.join(paths::project::ASSETS_DIR))?;

    // Copy the bundled simulation asset catalog (models/environments/tasks) - folded into the
    // templates tarball by `package-templates.sh` (LAB-2019), replacing the old separate
    // `~/.mecha10/simulation` runtime download/cache. `copy_template_dir` no-ops silently on a
    // missing source directory (e.g. a stale cached templates version predating this fold-in),
    // which `perform_init`'s post-copy fallback (see `ensure_simulation_catalog_fallback`) covers.
    template_download.copy_template_dir(
        version,
        "simulation/models",
        &project_path.join(paths::project::SIMULATION_MODELS_DIR),
    )?;
    template_download.copy_template_dir(
        version,
        "simulation/environments",
        &project_path.join(paths::project::SIMULATION_ENVIRONMENTS_DIR),
    )?;
    template_download.copy_template_dir(
        version,
        "simulation/tasks",
        &project_path.join(paths::project::SIMULATION_TASKS_DIR),
    )?;

    Ok(())
}

/// A leading path segment that only makes sense relative to the *mecha10 framework repo* root,
/// never a scaffolded project's root - see [`rewrite_bundled_image_source_paths`].
const FRAMEWORK_ROOT_PREFIX: &str = "packages/";

/// Fix up `type: "image"` billboard objects' `source` paths in every copied
/// `simulation/environments/*/environment.json` so they resolve relative to the *project* root
/// instead of the *framework* root, pointing at the project's canonical `assets/images/` tree
/// (see `mecha10_cli_core::simulation_assets` for the shared-vs-env-specific tier convention this
/// applies) rather than a duplicated per-environment copy.
///
/// The downloaded templates tarball (`copy_downloaded_templates`, built by
/// `scripts/release/build/package-templates.sh`) copies
/// `packages/simulation/environments/<name>/environment.json` byte-for-byte into the project
/// (minus its `assets/` subdirectory). That file's `features.objects[].source` fields for
/// `type: "image"` entries are
/// authored relative to the *mecha10 framework repo root* (e.g.
/// `"packages/simulation/environments/basic_arena/assets/images/aiko.jpg"` - see
/// `packages/simulation/schemas/environment-config.schema.json`'s `imageObject.source` doc),
/// which is correct when that same `environment.json` is loaded from inside the framework repo
/// itself, but a scaffolded project's root has no `packages/` directory. Left unrewritten, every
/// image billboard's `source` resolves to a nonexistent path once copied into a project -
/// previously undetected until the supervised MuJoCo subprocess logged an opaque
/// `unsupported content type: ""` deep inside the external `mecha10_rl.mujoco.mjcf_generator`,
/// with no indication the actual cause was a bad asset path.
///
/// The rewritten `source` must land wherever the downloaded-templates tarball's
/// `templates/assets/` (built by `package-templates.sh`, statically laid out under
/// `packages/mecha10-templates/templates/assets/`) actually placed the file, applying the
/// shared-vs-env-specific tier rule computed here from whatever set of environments got copied
/// into *this* project.
///
/// The single placeholder environment written by `ProjectTemplateService::
/// create_simulation_environment_json` (the last-resort fallback when neither the downloaded
/// templates nor a framework checkout populated the real catalog, see
/// `ensure_simulation_catalog_fallback`) doesn't have this problem - it's authored with
/// project-root-relative `source` paths already (no `packages/` prefix) - so this function skips
/// any `source` that doesn't carry the `packages/` prefix, leaving it untouched.
///
/// Best-effort: a missing `simulation/environments` directory, or an `environment.json` that
/// fails to parse, is skipped rather than failing the whole `mecha10 init` run over what is, at
/// worst, a broken image billboard in one bundled demo environment.
async fn rewrite_bundled_image_source_paths(project_path: &Path) -> Result<()> {
    let environments_dir = project_path.join(paths::project::SIMULATION_ENVIRONMENTS_DIR);

    let mut env_dirs: Vec<PathBuf> = Vec::new();
    let mut dir_entries = match tokio::fs::read_dir(&environments_dir).await {
        Ok(entries) => entries,
        Err(_) => return Ok(()),
    };
    while let Ok(Some(entry)) = dir_entries.next_entry().await {
        if entry.file_type().await.map(|t| t.is_dir()).unwrap_or(false) {
            env_dirs.push(entry.path());
        }
    }

    // Pass 1: parse every copied `environment.json`, collecting `(env_name, basename)` for each
    // `type: "image"` object whose `source` still carries the framework-root-relative `packages/`
    // prefix, so tier assignment (env-specific vs shared) accounts for every environment actually
    // present in this project, not just the one being rewritten.
    let mut parsed: Vec<(PathBuf, String, serde_json::Value)> = Vec::new();
    let mut references: Vec<(String, String)> = Vec::new();
    for env_dir in &env_dirs {
        let env_name = env_dir
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let env_json_path = env_dir.join("environment.json");
        let Ok(content) = tokio::fs::read_to_string(&env_json_path).await else {
            continue;
        };
        let Ok(value) = serde_json::from_str::<serde_json::Value>(&content) else {
            continue;
        };

        if let Some(objects) = value
            .get("features")
            .and_then(|f| f.get("objects"))
            .and_then(|o| o.as_array())
        {
            for object in objects {
                if object.get("type").and_then(|t| t.as_str()) != Some("image") {
                    continue;
                }
                let Some(source) = object.get("source").and_then(|s| s.as_str()) else {
                    continue;
                };
                if !source.starts_with(FRAMEWORK_ROOT_PREFIX) {
                    continue;
                }
                if let Some(basename) = Path::new(source).file_name().map(|f| f.to_string_lossy().into_owned()) {
                    references.push((env_name.clone(), basename));
                }
            }
        }

        parsed.push((env_json_path, env_name, value));
    }

    let usage = mecha10_cli_core::simulation_assets::count_referencing_environments(
        references
            .iter()
            .map(|(env, basename)| (env.as_str(), basename.as_str())),
    );

    // Pass 2: rewrite each `source` that still carries the `packages/` prefix to point at wherever
    // the matching tier (env-specific or shared) actually placed the file.
    for (env_json_path, env_name, mut value) in parsed {
        let mut changed = false;
        if let Some(objects) = value
            .get_mut("features")
            .and_then(|f| f.get_mut("objects"))
            .and_then(|o| o.as_array_mut())
        {
            for object in objects {
                if object.get("type").and_then(|t| t.as_str()) != Some("image") {
                    continue;
                }
                let Some(source) = object.get("source").and_then(|s| s.as_str()).map(str::to_string) else {
                    continue;
                };
                if !source.starts_with(FRAMEWORK_ROOT_PREFIX) {
                    continue;
                }
                let Some(basename) = Path::new(&source).file_name().map(|f| f.to_string_lossy().into_owned()) else {
                    continue;
                };
                let referencing_env_count = usage.get(&basename).map(|envs| envs.len()).unwrap_or(1);
                let new_source = mecha10_cli_core::simulation_assets::bundled_image_project_path(
                    &env_name,
                    &basename,
                    referencing_env_count,
                );
                object["source"] = serde_json::Value::String(new_source);
                changed = true;
            }
        }

        if changed {
            if let Ok(rewritten) = serde_json::to_string_pretty(&value) {
                let _ = tokio::fs::write(&env_json_path, rewritten).await;
            }
        }
    }

    Ok(())
}

/// Directory listing an empty simulation asset catalog would still populate (`.gitkeep`) - used
/// by [`ensure_simulation_catalog_fallback`] to tell "the real catalog was copied" apart from
/// "only `create_project_directories`'s empty scaffold exists here".
async fn dir_has_any_subdirectory(dir: &Path) -> bool {
    let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
        return false;
    };
    while let Ok(Some(entry)) = entries.next_entry().await {
        if entry.file_type().await.map(|t| t.is_dir()).unwrap_or(false) {
            return true;
        }
    }
    false
}

/// Write the single embedded placeholder `model.json`/`environment.json` when the
/// downloaded-templates copy (attempted earlier in `perform_init`) didn't populate the real
/// bundled simulation asset catalog - see the call site's doc comment. Never writes a placeholder
/// task config (none is embedded), so this fallback alone cannot resolve `task1` - only the real
/// downloaded-templates catalog can.
async fn ensure_simulation_catalog_fallback(ctx: &mut CliContext, project_path: &Path) -> Result<()> {
    let tasks_dir = project_path.join(paths::project::SIMULATION_TASKS_DIR);
    let models_dir = project_path.join(paths::project::SIMULATION_MODELS_DIR);

    if dir_has_any_subdirectory(&tasks_dir).await || dir_has_any_subdirectory(&models_dir).await {
        return Ok(());
    }

    ctx.project_template_service()
        .create_simulation_model_json(project_path)
        .await?;
    ctx.project_template_service()
        .create_simulation_environment_json(project_path)
        .await?;

    Ok(())
}

/// Create mecha10.json from template file
///
/// Loads the mecha10.json.template from downloaded templates and replaces placeholders.
/// This ensures the generated config always matches the template (single source of truth).
///
/// `mecha10 init` has exactly one template-resolution path - the downloaded archive - so this
/// errors out loudly (rather than silently degrading to embedded content) if the downloaded
/// template can't be read.
async fn create_mecha10_json_from_template(
    ctx: &mut CliContext,
    project_path: &Path,
    project_name: &str,
    template: &Option<String>,
    template_version: &str,
) -> Result<()> {
    let platform = template.as_deref().unwrap_or("basic");
    let project_id = project_name.replace('-', "_");
    let version = template_version;

    let content = ctx
        .template_download()
        .read_template(version, "config/mecha10.json.template")
        .with_context(|| format!("Failed to read config/mecha10.json.template from downloaded templates v{version}"))?;

    // Replace placeholders in template
    let mut config_str = content
        .replace("{{project_name}}", project_name)
        .replace("{{project_id}}", &project_id)
        .replace("{{platform}}", platform);

    // Parse, add version, and re-serialize to ensure valid JSON
    let mut config: serde_json::Value = serde_json::from_str(&config_str)?;
    config["template_version"] = serde_json::json!(version);
    config_str = serde_json::to_string_pretty(&config)?;

    tokio::fs::write(project_path.join(paths::PROJECT_CONFIG), config_str).await?;

    Ok(())
}

/// Process init command arguments in non-interactive mode
///
/// Validates and processes command-line arguments for project initialization.
/// This is used when:
/// - Running in a non-TTY environment
/// - User specifies --non-interactive flag
/// - Interactive wizard fails
///
/// # Arguments
///
/// * `args` - Init command arguments
/// * `working_dir` - Working directory for resolving relative paths
/// * `catalog` - Component catalog service for loading nodes
///
/// # Returns
///
/// A tuple of (project_name, project_path, template, nodes)
fn process_non_interactive_args(
    args: &InitArgs,
    working_dir: &Path,
    catalog: &crate::services::ComponentCatalogService,
) -> Result<InitProcessResult> {
    use crate::init::get_template_defaults;

    // Require project name in non-interactive mode
    let name = args.name.clone().ok_or_else(|| {
        anyhow::anyhow!(
            "Project name required in non-interactive mode.\n\
             Usage: mecha10 init <PROJECT_NAME> [OPTIONS]\n\
             Example: mecha10 init my-robot"
        )
    })?;

    // Check if it's a path or just a name
    let path_buf = PathBuf::from(&name);
    let (project_name, project_path) = if path_buf.is_absolute() || name.contains('/') || name.contains('\\') {
        // It's a path - extract the final component as the name
        let final_name = path_buf
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&name)
            .to_string();
        (final_name, path_buf)
    } else {
        // It's just a name - create path relative to working directory
        let final_path = working_dir.join(&name);
        (name, final_path)
    };

    let template = args.template.clone();

    // Apply template defaults for nodes unless --no-examples is specified
    let nodes = if args.no_examples {
        Vec::new()
    } else {
        let mut node_components = catalog.get_by_category("nodes");
        node_components.sort_by(|a, b| a.name.cmp(&b.name));
        let node_ids: Vec<String> = node_components.iter().map(|c| c.id.clone()).collect();

        let defaults = get_template_defaults(&template, &node_ids);

        node_ids
            .iter()
            .enumerate()
            .filter(|(i, _)| defaults[*i])
            .map(|(_, id)| id.clone())
            .collect()
    };

    Ok((project_name, project_path, template, nodes))
}

/// Handle init command
///
/// Creates a new Mecha10 project with interactive wizard or command-line arguments.
///
/// # Arguments
///
/// * `ctx` - CLI execution context
/// * `args` - Init command arguments
pub async fn handle_init(ctx: &mut CliContext, args: &InitArgs) -> Result<()> {
    // Handle --update flag for existing projects
    if args.update {
        return handle_update_existing(ctx, args).await;
    }

    // Clear terminal before starting to avoid menu display issues
    print!("\x1B[2J\x1B[1;1H");

    // Check if user is logged in
    let credentials_service = CredentialsService::new();
    if !credentials_service.is_logged_in() {
        println!();
        println!("You must be logged in to create a project.");
        println!();
        println!("Run `mecha10 auth login` to authenticate.");
        println!();
        return Ok(());
    }

    println!();
    println!("🤖 Initialize Mecha10 Project");
    println!();

    // Capture working_dir before borrowing catalog
    let working_dir = ctx.working_dir.clone();

    // Load component catalog for example selection
    let catalog = ctx.component_catalog();

    // Determine if we should use interactive wizard
    let is_tty = atty::is(atty::Stream::Stdin) && atty::is(atty::Stream::Stdout);
    let use_wizard = is_tty && !args.non_interactive;

    let (project_name, project_path, template, nodes) = if use_wizard {
        // Try interactive wizard with TUI
        let default_name = args.name.clone();
        match run_wizard_tui(default_name.as_deref(), catalog) {
            Ok((name, template, selected_nodes)) => {
                // Check if it's a path or just a name
                let path_buf = std::path::PathBuf::from(&name);
                let (final_name, path) = if path_buf.is_absolute() || name.contains('/') || name.contains('\\') {
                    // It's a path - extract the final component as the name
                    let final_name = path_buf
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or(&name)
                        .to_string();
                    (final_name, path_buf)
                } else {
                    // It's just a name - create path relative to working directory
                    let final_path = ctx.working_dir.join(&name);
                    (name, final_path)
                };

                (final_name, path, template, selected_nodes)
            }
            Err(e) => {
                println!("⚠️  Wizard failed: {}", e);
                println!("Using command-line arguments...\n");

                // Fall back to non-interactive mode
                process_non_interactive_args(args, &working_dir, catalog)?
            }
        }
    } else {
        if !is_tty {
            println!("ℹ️  Non-interactive mode\n");
        }

        // Non-interactive mode - use provided arguments
        process_non_interactive_args(args, &working_dir, catalog)?
    };

    // Check if directory already exists BEFORE any processing
    validation::check_directory_not_exists(&project_path)?;

    // Download latest templates from GitHub. `mecha10 init` has exactly one template-resolution
    // path - the downloaded archive - so a failure here is fatal rather than a silent degrade to
    // embedded content (see `download_templates`'s doc comment for why a local `--install`ed dev
    // build still works fully offline).
    let template_version = download_templates(ctx).await.context(
        "Failed to download project templates - mecha10 init cannot continue without them.\n\
         This usually means either the network is unreachable, or the requested template \
         version doesn't exist.\n\
         \n\
         Try:\n\
         \x20 - Checking your network connection\n\
         \x20 - Running `scripts/release/index.py --component templates --install` for a local \
         dev build if you're iterating on template changes offline",
    )?;
    println!("📦 Using templates v{}", template_version);

    // Wrap the entire project creation in cleanup logic
    let result = perform_init(ctx, &project_path, &project_name, &template, &nodes, &template_version).await;

    // If init failed, cleanup and propagate error
    if let Err(e) = result {
        cleanup_on_error(&project_path).await;
        return Err(e);
    }

    // Success message
    print_success_message(&project_name);

    Ok(())
}

/// Handle --update flag: sync missing configs for existing project
async fn handle_update_existing(ctx: &mut CliContext, args: &InitArgs) -> Result<()> {
    use crate::services::ConfigService;

    println!();
    println!("🔄 Updating existing project");
    println!();

    // Determine project path
    let project_path = if let Some(name) = &args.name {
        let path = std::path::PathBuf::from(name);
        if path.is_absolute() {
            path
        } else {
            ctx.working_dir.join(name)
        }
    } else {
        // Use current directory
        ctx.working_dir.clone()
    };

    // Check that mecha10.json exists
    let config_path = project_path.join(crate::paths::PROJECT_CONFIG);
    if !config_path.exists() {
        anyhow::bail!(
            "No mecha10.json found at {}. Use 'mecha10 init' to create a new project.",
            project_path.display()
        );
    }

    // Load project config to get list of nodes
    let config = ConfigService::load_from(&config_path).await?;
    let nodes: Vec<String> = config.nodes.0.keys().map(|s| s.to_string()).collect();

    println!("📦 Found {} nodes in project", nodes.len());

    // Sync configs for each node
    let init_service = ctx.init_service();
    let mut synced = 0;

    for node_id in &nodes {
        // Extract node name from identifier (e.g., "@mecha10/motor" -> "motor")
        let node_name = node_id.strip_prefix("@mecha10/").unwrap_or(node_id);

        // Check if config already exists (V2 structure)
        let v2_dev_exists = project_path
            .join("configs")
            .join("dev")
            .join("nodes")
            .join(node_name)
            .join("config.json")
            .exists();

        // Check legacy structure
        let legacy_exists = project_path
            .join("configs")
            .join("nodes")
            .join("@mecha10")
            .join(node_name)
            .join("config.json")
            .exists();

        if !v2_dev_exists && !legacy_exists {
            // Try to copy config
            if let Err(e) = init_service.add_example_node(&project_path, node_name).await {
                // Ignore errors for nodes without configs
                tracing::debug!("Could not add config for {}: {}", node_name, e);
            } else {
                println!("✅ Added config for: {}", node_name);
                synced += 1;
            }
        }
    }

    if synced > 0 {
        println!();
        println!("✨ Synced {} node configs", synced);
    } else {
        println!();
        println!("✅ All node configs already present");
    }

    Ok(())
}

/// Perform the actual project initialization
///
/// # Arguments
///
/// * `ctx` - CLI context
/// * `project_path` - Path to create the project
/// * `project_name` - Name of the project
/// * `template` - Robot template (rover, humanoid, etc.)
/// * `nodes` - List of nodes to add
/// * `template_version` - Downloaded template version (the only template-resolution path)
async fn perform_init(
    ctx: &mut CliContext,
    project_path: &Path,
    project_name: &str,
    template: &Option<String>,
    nodes: &[String],
    template_version: &str,
) -> Result<()> {
    // Create project directory structure
    ctx.init_service().create_project_directories(project_path).await?;

    // Copy templates from the downloaded archive - the only template-resolution path.
    copy_downloaded_templates(ctx, project_path, template_version).await?;

    // Generate mecha10.json from template file (single source of truth)
    create_mecha10_json_from_template(ctx, project_path, project_name, template, template_version).await?;

    // Fall back to a single placeholder model/environment when the downloaded templates didn't
    // include the real simulation asset catalog (e.g. a stale cached templates version predating
    // the LAB-2019 fold-in - see `copy_downloaded_templates`'s doc comment). Guarded on
    // `simulation/tasks` being empty rather than run unconditionally (LAB-2019): the real catalog
    // copy always includes `simulation/tasks/task1`, so its absence is the signal the real
    // catalog never landed, and running this unconditionally used to silently overwrite the real
    // catalog's `rover`/`basic_arena` files with these placeholders on every `mecha10 init`.
    ensure_simulation_catalog_fallback(ctx, project_path).await?;

    // Fix up any copied `environment.json`'s image `source` paths that are still relative to the
    // framework repo root rather than this project's root - see
    // `rewrite_bundled_image_source_paths`'s doc comment for why this is needed regardless of
    // which catalog source above actually ran.
    rewrite_bundled_image_source_paths(project_path).await?;
    println!("✅ Simulation assets");
    println!("✅ Node configurations");

    // Create project files
    ctx.project_template_service()
        .create_readme(project_path, project_name)
        .await?;

    ctx.project_template_service().create_gitignore(project_path).await?;

    ctx.project_template_service()
        .create_package_json(project_path, project_name)
        .await?;

    ctx.project_template_service()
        .create_requirements_txt(project_path)
        .await?;

    // Generate the standard RL training bundle (rover env + ppo algorithm, LAB-1743) for
    // `rover` template projects: default sentinel-override config, RL package dependencies
    // appended to requirements.txt, and a Kestra-flow-templates placeholder (Phase 5 / LAB-1745
    // hasn't landed yet). Gated on the `rover` template since the bundled env is rover-specific;
    // other templates (basic/arm/humanoid) don't get an RL training config they can't use.
    if template.as_deref() == Some("rover") {
        ctx.project_template_service()
            .create_rl_training_bundle(project_path)
            .await?;
        println!("✅ RL training bundle (rover/ppo)");
    }

    // Create Rust project files
    ctx.project_template_service()
        .create_cargo_toml(project_path, project_name)
        .await?;

    ctx.project_template_service()
        .create_main_rs(project_path, project_name)
        .await?;

    ctx.project_template_service().create_build_rs(project_path).await?;

    ctx.project_template_service()
        .create_env_example(project_path, project_name)
        .await?;

    ctx.project_template_service().create_rustfmt_toml(project_path).await?;

    ctx.project_template_service()
        .create_docker_compose(project_path, project_name)
        .await?;

    // Create remote node Docker files (for AI nodes running in containers)
    ctx.project_template_service()
        .create_remote_docker_files(project_path)
        .await?;
    println!("✅ Project files");

    // Add nodes if any were selected
    if !nodes.is_empty() {
        for node_name in nodes {
            if let Err(e) = ctx.init_service().add_example_node(project_path, node_name).await {
                println!("⚠️  Failed to add {}: {}", node_name, e);
            } else {
                println!("✅ Node: {}", node_name);
            }
        }
        println!();
    }

    Ok(())
}

/// Print success message after initialization
fn print_success_message(project_name: &str) {
    println!("✨ Project {} created successfully!", project_name);
    println!();
    println!("📋 Next steps:");
    println!("  1. cd {}", project_name);
    println!("  2. Configure .env");
    println!("  3. Start development:");
    println!("     mecha10 dev");
    println!();
    println!("  's' → Start simulation         'wasd' → Teleop control");
    // Use default config since this matches what's generated in mecha10.json
    println!("  Dashboard: {}", EnvironmentsConfig::default().dashboard_url());
    println!();
}

#[cfg(test)]
mod mecha10_json_template_tests {
    //! Coverage for `mecha10.json.template` - the single source of truth read by
    //! [`create_mecha10_json_from_template`] from the downloaded templates archive at
    //! `mecha10 init` time (no compile-time embedded fallback exists anymore, LAB-2034). Reads
    //! the source file directly out of `packages/mecha10-templates/templates/config/` - the same
    //! file `scripts/release/build/package-templates.sh` bundles into the archive - rather than
    //! exercising the download/cache path, so these stay fast, offline unit tests.
    //!
    //! These guard against regressing the "simulation" lifecycle mode wiring (LAB-1775): it must
    //! spawn `@mecha10/simulator` (the real MuJoCo bridge) rather than the deleted
    //! `@mecha10/simulation-bridge`, and both `simulator` and `teleop` must be declared as
    //! top-level nodes so they can be resolved.
    //!
    //! Also guards against regressing the dashboard-disconnect-on-simulation-mode bug: since
    //! `mecha10_runtime::lifecycle::diff_nodes` stops any currently-running node that isn't in
    //! the target mode's node list, `websocket-bridge` must be declared in *every* mode's node
    //! list (dev, simulation, hardware) — otherwise switching into a mode that omits it kills
    //! the very process the dashboard's websocket client is connected to.

    fn parsed_template() -> serde_json::Value {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../mecha10-templates/templates/config/mecha10.json.template");
        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("failed to read source mecha10.json.template at {}: {e}", path.display()));
        serde_json::from_str(&content).expect("source mecha10.json.template must be valid JSON")
    }

    #[test]
    fn simulation_mode_spawns_simulator_and_teleop() {
        let config = parsed_template();
        let nodes = config["lifecycle"]["modes"]["simulation"]["nodes"]
            .as_array()
            .expect("simulation mode must declare a nodes array");
        let nodes: Vec<&str> = nodes.iter().map(|v| v.as_str().unwrap()).collect();

        assert!(
            nodes.contains(&"@mecha10/simulator"),
            "simulation mode must spawn @mecha10/simulator, got {nodes:?}"
        );
        assert!(
            nodes.contains(&"@mecha10/teleop"),
            "simulation mode must spawn @mecha10/teleop so 's' can enter keyboard control, got {nodes:?}"
        );
        assert!(
            !nodes.iter().any(|n| n.contains("simulation-bridge")),
            "simulation mode must not reference the deleted @mecha10/simulation-bridge, got {nodes:?}"
        );
    }

    #[test]
    fn every_lifecycle_mode_keeps_websocket_bridge_running() {
        // Regression test: the dashboard connects to the robot exclusively through
        // `@mecha10/websocket-bridge`. `handle_mode_change` (packages/cli/src/handlers/dev/ops/lifecycle.rs)
        // stops any running node not present in the target mode's node list, so if any mode
        // omits `@mecha10/websocket-bridge`, switching into that mode kills the dashboard's
        // websocket connection even though the robot itself is still fully connected.
        let config = parsed_template();
        let modes = config["lifecycle"]["modes"]
            .as_object()
            .expect("lifecycle.modes must be an object");

        for (mode_name, mode_config) in modes {
            let nodes = mode_config["nodes"]
                .as_array()
                .unwrap_or_else(|| panic!("mode '{mode_name}' must declare a nodes array"));
            let nodes: Vec<&str> = nodes.iter().map(|v| v.as_str().unwrap()).collect();

            assert!(
                nodes.contains(&"@mecha10/websocket-bridge"),
                "mode '{mode_name}' must declare @mecha10/websocket-bridge so switching into it \
                 doesn't stop the node the dashboard's websocket client is connected to, got {nodes:?}"
            );
        }
    }

    #[test]
    fn every_lifecycle_mode_keeps_diagnostics_running() {
        // Regression test (mirrors every_lifecycle_mode_keeps_websocket_bridge_running above):
        // `diff_nodes` stops any running node that isn't in the target mode's node list, so if
        // any mode omits `@mecha10/diagnostics` switching into that mode would silently kill
        // Docker/system-resource metrics reporting.
        let config = parsed_template();
        let modes = config["lifecycle"]["modes"]
            .as_object()
            .expect("lifecycle.modes must be an object");

        for (mode_name, mode_config) in modes {
            let nodes = mode_config["nodes"]
                .as_array()
                .unwrap_or_else(|| panic!("mode '{mode_name}' must declare a nodes array"));
            let nodes: Vec<&str> = nodes.iter().map(|v| v.as_str().unwrap()).collect();

            assert!(
                nodes.contains(&"@mecha10/diagnostics"),
                "mode '{mode_name}' must declare @mecha10/diagnostics so switching into it \
                 doesn't stop system diagnostics reporting, got {nodes:?}"
            );
        }
    }

    #[test]
    fn top_level_nodes_map_declares_simulator_and_no_simulation_bridge() {
        let config = parsed_template();
        let node_map = config["nodes"].as_object().expect("nodes map must be an object");

        assert!(
            node_map.contains_key("@mecha10/simulator"),
            "top-level nodes map must declare @mecha10/simulator so it resolves via get_node_specs()"
        );
        assert!(
            !node_map.contains_key("@mecha10/simulation-bridge"),
            "top-level nodes map must not declare the deleted @mecha10/simulation-bridge"
        );
    }
}

#[cfg(test)]
mod create_mecha10_json_from_template_error_tests {
    //! Regression coverage for LAB-2034: `mecha10 init` has exactly one template-resolution
    //! path - the downloaded archive - so an unresolvable template must fail loudly with an
    //! actionable error, never silently fall back to embedded content (no such fallback exists
    //! anymore).

    use super::create_mecha10_json_from_template;
    use crate::context::CliContextBuilder;
    use crate::paths;

    #[tokio::test]
    async fn errors_loudly_instead_of_silently_falling_back_when_template_is_unresolvable() {
        let project_dir = tempfile::tempdir().unwrap();
        // A version string guaranteed to never be cached locally, so `read_template` can't
        // resolve it regardless of what's in this machine's real `~/.mecha10/templates`.
        let unresolvable_version = "lab-2034-no-such-template-version-ever-cached";

        let mut ctx = CliContextBuilder::new()
            .working_dir(project_dir.path().to_path_buf())
            .build()
            .unwrap();

        let result =
            create_mecha10_json_from_template(&mut ctx, project_dir.path(), "my-robot", &None, unresolvable_version)
                .await;

        let err = result.expect_err("unresolvable template version must produce an error, not a silent fallback");
        let message = format!("{err:#}");
        assert!(
            message.contains("mecha10.json.template") || message.contains(unresolvable_version),
            "error should name what failed to help the user act on it, got: {message}"
        );

        // No mecha10.json should have been written - a failed resolution must not leave behind
        // partial or stale (e.g. previously embedded-fallback) content.
        assert!(
            !project_dir.path().join(paths::PROJECT_CONFIG).exists(),
            "mecha10.json must not be written when template resolution fails"
        );
    }
}

#[cfg(test)]
mod rewrite_bundled_image_source_paths_tests {
    //! Regression coverage for the "unsupported content tyoe" bug and its asset-layout
    //! consolidation follow-up: a project's copied `simulation/environments/<name>/environment.json`
    //! (from either the downloaded templates tarball or a framework dev-mode checkout) carries
    //! `type: "image"` `source` paths relative to the *framework* repo root
    //! (`packages/simulation/environments/...`), which don't resolve against the project's own
    //! root. This must rewrite them to the project's canonical `assets/images/` tree, per
    //! `mecha10_cli_core::simulation_assets`'s shared-vs-env-specific tier rule - never back into
    //! a nested `simulation/environments/<name>/assets/...` copy. See
    //! [`super::rewrite_bundled_image_source_paths`].

    use super::rewrite_bundled_image_source_paths;
    use std::path::Path;

    async fn write_environment_json(project_root: &Path, env_name: &str, body: &str) {
        let dir = project_root.join("simulation/environments").join(env_name);
        tokio::fs::create_dir_all(&dir).await.unwrap();
        tokio::fs::write(dir.join("environment.json"), body).await.unwrap();
    }

    async fn read_environment_json(project_root: &Path, env_name: &str) -> serde_json::Value {
        let content = tokio::fs::read_to_string(
            project_root
                .join("simulation/environments")
                .join(env_name)
                .join("environment.json"),
        )
        .await
        .unwrap();
        serde_json::from_str(&content).unwrap()
    }

    #[tokio::test]
    async fn rewrites_framework_root_relative_source_to_the_env_specific_tier() {
        let temp = tempfile::tempdir().unwrap();
        write_environment_json(
            temp.path(),
            "basic_arena",
            r#"{
                "id": "basic_arena",
                "features": {
                    "objects": [
                        {
                            "type": "image",
                            "source": "packages/simulation/environments/basic_arena/assets/images/aiko.jpg",
                            "position": [0.0, 0.0, 0.0]
                        }
                    ]
                }
            }"#,
        )
        .await;

        rewrite_bundled_image_source_paths(temp.path()).await.unwrap();

        let rewritten = read_environment_json(temp.path(), "basic_arena").await;
        // basic_arena is the only environment referencing aiko.jpg here, so it belongs in the
        // env-specific tier, not the old nested `simulation/environments/.../assets/...` copy.
        assert_eq!(
            rewritten["features"]["objects"][0]["source"],
            "assets/images/basic_arena/aiko.jpg"
        );
    }

    #[tokio::test]
    async fn rewrites_source_shared_by_more_than_one_environment_to_the_shared_tier() {
        let temp = tempfile::tempdir().unwrap();
        write_environment_json(
            temp.path(),
            "basic_arena",
            r#"{
                "id": "basic_arena",
                "features": {
                    "objects": [
                        {
                            "type": "image",
                            "source": "packages/simulation/environments/basic_arena/assets/images/logo.jpg",
                            "position": [0.0, 0.0, 0.0]
                        }
                    ]
                }
            }"#,
        )
        .await;
        write_environment_json(
            temp.path(),
            "obstacle_course",
            r#"{
                "id": "obstacle_course",
                "features": {
                    "objects": [
                        {
                            "type": "image",
                            "source": "packages/simulation/environments/obstacle_course/assets/images/logo.jpg",
                            "position": [0.0, 0.0, 0.0]
                        }
                    ]
                }
            }"#,
        )
        .await;

        rewrite_bundled_image_source_paths(temp.path()).await.unwrap();

        let basic_arena = read_environment_json(temp.path(), "basic_arena").await;
        let obstacle_course = read_environment_json(temp.path(), "obstacle_course").await;
        assert_eq!(
            basic_arena["features"]["objects"][0]["source"],
            "assets/images/logo.jpg"
        );
        assert_eq!(
            obstacle_course["features"]["objects"][0]["source"],
            "assets/images/logo.jpg"
        );
    }

    #[tokio::test]
    async fn leaves_already_project_relative_sources_untouched() {
        let temp = tempfile::tempdir().unwrap();
        write_environment_json(
            temp.path(),
            "basic_arena",
            r#"{
                "id": "basic_arena",
                "features": {
                    "objects": [
                        {
                            "type": "image",
                            "source": "assets/images/basic_arena/aiko.jpg",
                            "position": [0.0, 0.0, 0.0]
                        }
                    ]
                }
            }"#,
        )
        .await;

        rewrite_bundled_image_source_paths(temp.path()).await.unwrap();

        let rewritten = read_environment_json(temp.path(), "basic_arena").await;
        assert_eq!(
            rewritten["features"]["objects"][0]["source"],
            "assets/images/basic_arena/aiko.jpg"
        );
    }

    #[tokio::test]
    async fn leaves_non_image_objects_untouched() {
        let temp = tempfile::tempdir().unwrap();
        write_environment_json(
            temp.path(),
            "basic_arena",
            r#"{
                "id": "basic_arena",
                "features": {
                    "objects": [
                        {
                            "type": "cube",
                            "position": [0.0, 0.0, 0.0]
                        }
                    ]
                }
            }"#,
        )
        .await;

        rewrite_bundled_image_source_paths(temp.path()).await.unwrap();

        let rewritten = read_environment_json(temp.path(), "basic_arena").await;
        assert_eq!(rewritten["features"]["objects"][0]["type"], "cube");
        assert!(rewritten["features"]["objects"][0].get("source").is_none());
    }

    #[tokio::test]
    async fn is_a_noop_when_no_environments_directory_exists() {
        let temp = tempfile::tempdir().unwrap();

        // Should not error just because `mecha10 init` never scaffolded a simulation catalog
        // (e.g. a non-simulation project template).
        rewrite_bundled_image_source_paths(temp.path()).await.unwrap();
    }
}