mecha10-cli 0.7.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
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
//! 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::{catalog_client, CredentialsService};
use crate::types::EnvironmentsConfig;
use crate::ui::init_wizard::run_wizard_tui;
use crate::ui::prompts::is_interactive_terminal;
use anyhow::{Context, Result};
use dialoguer::{theme::ColorfulTheme, Confirm, Input};
use mecha10_robot_config::RobotConfigClient;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

type InitProcessResult = (String, PathBuf, Option<String>, Vec<String>, 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();

    let version = template_download.resolve_version().await?;

    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();

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

    // Framework node schemas live in a separate `nodes/@mecha10/<name>/` template subtree
    // (wave 10), apart from `configs/nodes/@mecha10/<name>/` (config.json only) copied just
    // above. Best-effort/skippable the same way: `copy_template_dir` is a no-op if the
    // template archive lacks this directory.
    template_download.copy_template_dir(
        version,
        "nodes/@mecha10",
        &project_path.join(paths::project::NODES_MECHA10_DIR),
    )?;

    template_download.copy_template_dir(
        version,
        "configs/behaviors",
        &project_path.join(paths::project::BEHAVIORS_DIR),
    )?;

    template_download.copy_template_dir(
        version,
        "configs/simulation/images",
        &project_path.join(paths::project::SIMULATION_IMAGES_DIR),
    )?;

    template_download.copy_template_dir(
        version,
        "configs/simulation/models",
        &project_path.join(paths::project::SIMULATION_MODELS_DIR),
    )?;
    template_download.copy_template_dir(
        version,
        "configs/simulation/environments",
        &project_path.join(paths::project::SIMULATION_ENVIRONMENTS_DIR),
    )?;
    template_download.copy_template_dir(
        version,
        "configs/rl/tasks",
        &project_path.join(paths::project::RL_TASKS_DIR),
    )?;

    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.
///
/// `config["version"]` is set to `initial_version` - normally `template_version` (the latest
/// published templates version resolved from `mecha10-api` by `download_templates`) rather than
/// left at the template's hardcoded `"0.1.0"` placeholder, so a freshly scaffolded project's
/// declared version starts matching the templates it was actually generated from. But when this
/// project links to an *already-registered* robot, `resolve_initial_project_version` resolves
/// `initial_version` to that robot's actual latest build version instead (see its doc comment) -
/// `template_version` still separately drives which downloaded templates content is read below,
/// since the two are independent axes.
#[allow(clippy::too_many_arguments)]
async fn create_mecha10_json_from_template(
    ctx: &mut CliContext,
    project_path: &Path,
    project_name: &str,
    template: &Option<String>,
    nodes: &[String],
    template_version: &str,
    initial_version: &str,
    robot_platform: &str,
    remote_platform: &[String],
    robot_id: &str,
    robot_name: &str,
) -> Result<()> {
    let platform = template.as_deref().unwrap_or("rover");
    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}"))?;

    let mut config_str = content
        .replace("{{project_name}}", project_name)
        .replace("{{project_id}}", &project_id)
        .replace("{{platform}}", platform);

    let mut config: serde_json::Value = serde_json::from_str(&config_str)?;
    config["template_version"] = serde_json::json!(version);
    if version != mecha10_templates::services::template_download::DEV_VERSION {
        config["version"] = serde_json::json!(initial_version);
    }
    config["robot_id"] = serde_json::json!(robot_id);
    config["robot_name"] = serde_json::json!(robot_name);
    set_robot_platform(&mut config, robot_platform);
    set_remote_platforms(&mut config, remote_platform);
    set_simulation_model(&mut config, platform);

    // Live-catalog-sourced node placement (see `build_node_placement`'s doc comment) - a fresh
    // fetch rather than threading the catalog `process_non_interactive_args`/`run_wizard_tui`
    // already fetched through every caller's signature, consistent with every other
    // `catalog_client` call in this CLI: no caching, every call is its own round-trip.
    let node_targets: HashMap<String, Vec<String>> = catalog_client::fetch_node_catalog()
        .await
        .context("Failed to fetch node catalog - mecha10 init cannot continue without it")?
        .into_iter()
        .map(|entry| (entry.name, entry.targets))
        .collect();
    build_node_placement(&mut config, nodes, &node_targets);

    config_str = serde_json::to_string_pretty(&config)?;

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

    Ok(())
}

/// Overrides a freshly-rendered `mecha10.json` template's hardcoded `targets.robot.platforms`
/// default with whatever hardware the wizard's "where will your robot run" step (or
/// `--robot-platform` in non-interactive mode) resolved to.
fn set_robot_platform(config: &mut serde_json::Value, robot_platform: &str) {
    config["targets"]["robot"]["platforms"] = serde_json::json!([robot_platform]);
}

/// Overrides a freshly-rendered `mecha10.json` template's hardcoded `targets.remote.platforms`
/// default with whatever platform(s) the wizard's "remote platform(s)" step (or
/// `--remote-platform` in non-interactive mode) resolved to. Unlike `targets.robot.platforms`,
/// remote can plausibly be multiple platforms (e.g. a cloud/dev machine could be x86_64 Linux
/// AND Apple Silicon), so this accepts a list rather than a single triple.
fn set_remote_platforms(config: &mut serde_json::Value, remote_platform: &[String]) {
    config["targets"]["remote"]["platforms"] = serde_json::json!(remote_platform);
}

/// Templates whose `configs/simulation/models/<name>/` directory is unconditionally copied into
/// every scaffolded project (see `copy_downloaded_templates`), and so is safe to point
/// `simulation.model` at.
const SIMULATION_MODEL_TEMPLATES: [&str; 4] = ["rover", "drone", "arm", "sentry"];

/// Overrides a freshly-rendered `mecha10.json` template's hardcoded `simulation.model` default
/// (`"rover"`) with whatever template the project was scaffolded from, so the simulation model
/// actually matches the selected template instead of always being the rover's. Only applies when
/// `platform` is one of [`SIMULATION_MODEL_TEMPLATES`] - an unrecognized template name has no
/// matching `configs/simulation/models/<platform>/` directory, so the hardcoded `"rover"` default
/// is left untouched rather than pointed at a nonexistent directory.
fn set_simulation_model(config: &mut serde_json::Value, platform: &str) {
    if SIMULATION_MODEL_TEMPLATES.contains(&platform) {
        if let Some(simulation) = config.get_mut("simulation") {
            simulation["model"] = serde_json::Value::String(platform.to_string());
        }
    }
}

#[cfg(test)]
mod set_robot_platform_tests {
    use super::set_robot_platform;
    use serde_json::json;

    #[test]
    fn overwrites_robot_platforms_leaving_remote_untouched() {
        let mut config = json!({
            "targets": {
                "robot": { "platforms": ["aarch64-unknown-linux-gnu"] },
                "remote": { "platforms": ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"] },
            },
        });

        set_robot_platform(&mut config, "x86_64-unknown-linux-gnu");

        assert_eq!(
            config["targets"]["robot"]["platforms"],
            json!(["x86_64-unknown-linux-gnu"])
        );
        assert_eq!(
            config["targets"]["remote"]["platforms"],
            json!(["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"])
        );
    }
}

#[cfg(test)]
mod set_remote_platforms_tests {
    use super::set_remote_platforms;
    use serde_json::json;

    #[test]
    fn overwrites_remote_platforms_leaving_robot_untouched() {
        let mut config = json!({
            "targets": {
                "robot": { "platforms": ["aarch64-unknown-linux-gnu"] },
                "remote": { "platforms": ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"] },
            },
        });

        set_remote_platforms(
            &mut config,
            &[
                "aarch64-apple-darwin".to_string(),
                "x86_64-unknown-linux-gnu".to_string(),
            ],
        );

        assert_eq!(
            config["targets"]["remote"]["platforms"],
            json!(["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"])
        );
        assert_eq!(
            config["targets"]["robot"]["platforms"],
            json!(["aarch64-unknown-linux-gnu"])
        );
    }

    #[test]
    fn when_default_remote_platform_is_preserved_it_is_generic_linux() {
        let mut config = json!({ "targets": { "remote": { "platforms": ["something-stale"] } } });

        set_remote_platforms(&mut config, &super::resolve_remote_platforms(None));

        assert_eq!(
            config["targets"]["remote"]["platforms"],
            json!(["x86_64-unknown-linux-gnu"])
        );
    }
}

/// Resolve `--robot-platform`'s value (a target triple or a `BUILD_PLATFORMS` label,
/// case-insensitive) to the triple written into `targets.robot.platforms`. Falls back to
/// `BUILD_PLATFORMS`'s first entry (Raspberry Pi 4/5) when omitted, matching the template's
/// prior hardcoded default. An unrecognized value is passed through as-is so a hand-typed
/// triple outside `BUILD_PLATFORMS` (e.g. a newer board not yet added there) still works.
fn resolve_robot_platform(input: Option<&str>) -> String {
    use crate::services::build_platforms::BUILD_PLATFORMS;

    match input {
        None => BUILD_PLATFORMS[0].triple.to_string(),
        Some(value) => BUILD_PLATFORMS
            .iter()
            .find(|p| p.triple == value || p.label.eq_ignore_ascii_case(value))
            .map_or_else(|| value.to_string(), |p| p.triple.to_string()),
    }
}

#[cfg(test)]
mod set_simulation_model_tests {
    use super::set_simulation_model;
    use serde_json::json;

    #[test]
    fn sets_model_for_each_known_template() {
        for platform in ["rover", "drone", "arm", "sentry"] {
            let mut config =
                json!({ "simulation": { "model": "rover", "environment": "basic_arena", "preset": "default" } });

            set_simulation_model(&mut config, platform);

            assert_eq!(config["simulation"]["model"], json!(platform));
            assert_eq!(config["simulation"]["environment"], json!("basic_arena"));
            assert_eq!(config["simulation"]["preset"], json!("default"));
        }
    }

    #[test]
    fn leaves_default_model_untouched_for_unrecognized_template() {
        let mut config =
            json!({ "simulation": { "model": "rover", "environment": "basic_arena", "preset": "default" } });

        set_simulation_model(&mut config, "some-future-template");

        assert_eq!(config["simulation"]["model"], json!("rover"));
    }
}

#[cfg(test)]
mod resolve_robot_platform_tests {
    use super::resolve_robot_platform;

    #[test]
    fn defaults_to_raspberry_pi_when_omitted() {
        assert_eq!(resolve_robot_platform(None), "aarch64-unknown-linux-gnu");
    }

    #[test]
    fn accepts_a_known_triple_unchanged() {
        assert_eq!(
            resolve_robot_platform(Some("x86_64-unknown-linux-gnu")),
            "x86_64-unknown-linux-gnu"
        );
    }

    #[test]
    fn matches_a_label_case_insensitively() {
        assert_eq!(
            resolve_robot_platform(Some("raspberry pi 4/5 (64-bit linux)")),
            "aarch64-unknown-linux-gnu"
        );
    }

    #[test]
    fn passes_through_an_unrecognized_value() {
        assert_eq!(
            resolve_robot_platform(Some("riscv64-unknown-linux-gnu")),
            "riscv64-unknown-linux-gnu"
        );
    }
}

const DEFAULT_REMOTE_PLATFORMS: [&str; 1] = ["x86_64-unknown-linux-gnu"];

/// Resolve `--remote-platform`'s value (a comma-separated list of target triples or
/// `BUILD_PLATFORMS` labels, case-insensitive) to the triples written into
/// `targets.remote.platforms`. Falls back to [`DEFAULT_REMOTE_PLATFORMS`] when omitted, matching
/// the template's prior hardcoded default. An unrecognized entry is passed through as-is so a
/// hand-typed triple outside `BUILD_PLATFORMS` (e.g. a newer board not yet added there) still
/// works.
fn resolve_remote_platforms(input: Option<&str>) -> Vec<String> {
    use crate::services::build_platforms::BUILD_PLATFORMS;

    match input {
        None => DEFAULT_REMOTE_PLATFORMS.iter().map(|s| s.to_string()).collect(),
        Some(value) => value
            .split(',')
            .map(str::trim)
            .filter(|entry| !entry.is_empty())
            .map(|entry| {
                BUILD_PLATFORMS
                    .iter()
                    .find(|p| p.triple == entry || p.label.eq_ignore_ascii_case(entry))
                    .map_or_else(|| entry.to_string(), |p| p.triple.to_string())
            })
            .collect(),
    }
}

#[cfg(test)]
mod resolve_remote_platforms_tests {
    use super::resolve_remote_platforms;

    #[test]
    fn defaults_to_generic_linux_when_omitted() {
        assert_eq!(
            resolve_remote_platforms(None),
            vec!["x86_64-unknown-linux-gnu".to_string()]
        );
    }

    #[test]
    fn parses_a_comma_separated_list_of_known_triples() {
        assert_eq!(
            resolve_remote_platforms(Some("x86_64-unknown-linux-gnu,aarch64-apple-darwin")),
            vec![
                "x86_64-unknown-linux-gnu".to_string(),
                "aarch64-apple-darwin".to_string()
            ]
        );
    }

    #[test]
    fn matches_labels_case_insensitively_and_trims_whitespace() {
        assert_eq!(
            resolve_remote_platforms(Some(
                " generic 64-bit linux (x86_64) , Apple Silicon Mac (dev/simulation only) "
            )),
            vec![
                "x86_64-unknown-linux-gnu".to_string(),
                "aarch64-apple-darwin".to_string()
            ]
        );
    }

    #[test]
    fn passes_through_unrecognized_entries() {
        assert_eq!(
            resolve_remote_platforms(Some("riscv64-unknown-linux-gnu")),
            vec!["riscv64-unknown-linux-gnu".to_string()]
        );
    }
}

/// Build a freshly-rendered `mecha10.json` template's `nodes` map and every
/// `targets.<key>.nodes` list from the node set the user actually selected (wizard checkboxes,
/// or `--nodes`/`--no-examples` in non-interactive mode), using each selected node's own live
/// `targets` field (`node_targets`, see [`catalog_client::NodeCatalogEntry::targets`]) as the
/// single source of truth for which target(s) it belongs in.
///
/// This replaces an earlier approach (`filter_config_to_selected_nodes`) that filtered the
/// static template's own pre-populated `nodes`/`targets.*.nodes` lists down to the selected set
/// - the template no longer carries any per-node placement at all (see
/// `mecha10.json.template`'s module docs / `targets.<key>` entries, which are now just an empty
/// shell plus `platforms`), so there is nothing left to filter: every node/target entry is built
/// here from scratch instead of narrowed from a pre-existing superset.
///
/// `websocket-bridge`/`diagnostics` are always included regardless of selection, same as the
/// filtering approach this replaces - unchecking either in the wizard must not silently kill
/// the dashboard's websocket client or system diagnostics reporting on the very first `mecha10
/// dev` (see `build_node_placement_tests::always_includes_websocket_bridge_and_diagnostics_even_when_unselected`
/// below, which guards the underlying invariant this preserves).
fn build_node_placement(config: &mut serde_json::Value, nodes: &[String], node_targets: &HashMap<String, Vec<String>>) {
    const ALWAYS_INCLUDED: [&str; 2] = ["websocket-bridge", "diagnostics"];

    let mut selected: Vec<&str> = nodes.iter().map(|s| s.as_str()).collect();
    for always in ALWAYS_INCLUDED {
        if node_targets.contains_key(always) && !selected.contains(&always) {
            selected.push(always);
        }
    }

    let nodes_map: serde_json::Map<String, serde_json::Value> = selected
        .iter()
        .map(|id| (format!("@mecha10/{id}"), serde_json::json!(env!("CARGO_PKG_VERSION"))))
        .collect();
    config["nodes"] = serde_json::Value::Object(nodes_map);

    let mut placement: HashMap<&str, Vec<String>> = HashMap::new();
    for id in &selected {
        let Some(targets) = node_targets.get(*id) else {
            continue;
        };
        let identifier = format!("@mecha10/{id}");
        for target in targets {
            placement.entry(target.as_str()).or_default().push(identifier.clone());
        }
    }

    if let Some(targets) = config.get_mut("targets").and_then(|v| v.as_object_mut()) {
        for (key, target_config) in targets.iter_mut() {
            target_config["nodes"] = serde_json::json!(placement.get(key.as_str()).cloned().unwrap_or_default());
        }
    }
}

#[cfg(test)]
mod build_node_placement_tests {
    use super::build_node_placement;
    use serde_json::json;
    use std::collections::HashMap;

    fn node_targets(pairs: &[(&str, &[&str])]) -> HashMap<String, Vec<String>> {
        pairs
            .iter()
            .map(|(id, targets)| (id.to_string(), targets.iter().map(|t| t.to_string()).collect()))
            .collect()
    }

    #[test]
    fn places_each_selected_node_into_exactly_the_targets_its_catalog_entry_names() {
        let mut config = json!({
            "nodes": {},
            "targets": { "robot": {}, "remote": {} },
        });
        let catalog = node_targets(&[("motor", &["robot"]), ("camera", &["robot"]), ("llm-command", &["remote"])]);

        build_node_placement(&mut config, &["motor".to_string(), "llm-command".to_string()], &catalog);

        assert_eq!(config["nodes"].as_object().unwrap().len(), 2);
        assert!(config["nodes"].get("@mecha10/motor").is_some());
        assert!(config["nodes"].get("@mecha10/llm-command").is_some());
        assert!(
            config["nodes"].get("@mecha10/camera").is_none(),
            "an unselected node must not appear in the built nodes map"
        );
        assert_eq!(config["targets"]["robot"]["nodes"], json!(["@mecha10/motor"]));
        assert_eq!(config["targets"]["remote"]["nodes"], json!(["@mecha10/llm-command"]));
    }

    #[test]
    fn always_includes_websocket_bridge_and_diagnostics_even_when_unselected() {
        let mut config = json!({
            "nodes": {},
            "targets": { "dev": {}, "robot": {} },
        });
        let catalog = node_targets(&[
            ("websocket-bridge", &["dev", "robot"]),
            ("diagnostics", &["dev", "robot"]),
            ("motor", &["robot"]),
        ]);

        build_node_placement(&mut config, &[], &catalog);

        let nodes = config["nodes"].as_object().unwrap();
        assert!(nodes.contains_key("@mecha10/websocket-bridge"));
        assert!(nodes.contains_key("@mecha10/diagnostics"));
        assert!(!nodes.contains_key("@mecha10/motor"));
        let dev_nodes = config["targets"]["dev"]["nodes"].as_array().unwrap();
        let dev_nodes: Vec<&str> = dev_nodes.iter().map(|v| v.as_str().unwrap()).collect();
        assert!(dev_nodes.contains(&"@mecha10/websocket-bridge"));
        assert!(dev_nodes.contains(&"@mecha10/diagnostics"));
    }

    #[test]
    fn a_node_in_multiple_targets_is_placed_in_every_one() {
        let mut config = json!({
            "nodes": {},
            "targets": { "simulation": {}, "remote": {} },
        });
        let catalog = node_targets(&[("image-classifier", &["simulation", "remote"])]);

        build_node_placement(&mut config, &["image-classifier".to_string()], &catalog);

        assert_eq!(
            config["targets"]["simulation"]["nodes"],
            json!(["@mecha10/image-classifier"])
        );
        assert_eq!(config["targets"]["remote"]["nodes"], json!(["@mecha10/image-classifier"]));
    }

    #[test]
    fn a_selected_node_absent_from_the_live_catalog_is_still_listed_but_unplaced() {
        // Defensive: a selected id with no matching catalog entry (e.g. a stale selection from a
        // template whose node list briefly outran the live catalog) must not panic - it's listed
        // in `nodes` (so `mecha10 add`'s "already in mecha10.json" dedup still works) but placed
        // into no target at all, same as any other node absent from every target.
        let mut config = json!({ "nodes": {}, "targets": { "robot": {} } });

        build_node_placement(&mut config, &["ghost-node".to_string()], &HashMap::new());

        assert!(config["nodes"].get("@mecha10/ghost-node").is_some());
        assert_eq!(config["targets"]["robot"]["nodes"], json!([]));
    }
}

/// Resolve this project's robot identity with the backend (`POST /api/robots/register`,
/// LAB-2132), returning the `(id, name, created)` to write into `mecha10.json`'s
/// `robot_id`/`robot_name` fields - `created` is `false` when this linked to an
/// already-registered robot rather than registering a brand new one, which the caller uses to
/// decide whether to seed the scaffolded project's version off that robot's last build instead
/// of the templates release version (see `resolve_initial_project_version`).
///
/// Before this, `robot_id` in `mecha10.json` was just an arbitrary user-typed/templated string
/// with no backend record, which is why config push/pull failed persistently for any project
/// whose `robot_id` wasn't a real registered robot. This gives every scaffolded project a real
/// registered robot from the moment it's created.
///
/// Runs *before* any local directory or template download, so a name collision is caught up
/// front rather than after scaffolding partway through (which would otherwise need
/// `cleanup_on_error`). In interactive mode, prompts for a robot name (defaulting to the project
/// name) and, if a robot with that name is already registered under the caller's account, asks
/// whether to link this new project to it - looping until the user either links to an existing
/// robot or picks a name that registers a new one. In non-interactive mode there's no terminal to
/// prompt on, so it registers under the project name directly and silently links to an existing
/// robot of that name if one exists.
async fn resolve_robot_link(project_name: &str, interactive: bool) -> Result<(String, String, bool)> {
    let credentials_service = CredentialsService::new();
    let credentials = if crate::context::is_ci_environment() {
        credentials_service
            .load()?
            .ok_or_else(|| anyhow::anyhow!("Not logged in. Run `mecha10 auth login` first."))?
    } else {
        mecha10_auth::ensure_authenticated_interactive(&credentials_service).await?
    };

    let control_plane_url = EnvironmentsConfig::default().control_plane_url();
    let config_url = format!("{}/api/robots", control_plane_url.trim_end_matches('/'));
    let client = RobotConfigClient::with_user_id(config_url, credentials.api_key, Some(credentials.user_id));

    let theme = ColorfulTheme::default();
    let mut candidate_name = project_name.to_string();

    loop {
        if interactive {
            candidate_name = loop {
                match Input::with_theme(&theme)
                    .with_prompt("Robot name")
                    .with_initial_text(&candidate_name)
                    .interact_text()
                {
                    Ok(name) => break name,
                    // The read syscall can be interrupted by an unrelated signal (e.g. SIGWINCH on
                    // terminal resize) without anything actually being wrong; retry instead of
                    // failing the whole command out from under the user.
                    Err(dialoguer::Error::IO(ref e)) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                    Err(e) => return Err(anyhow::anyhow!("Failed to read robot name: {e}")),
                }
            };
        }

        let response = client
            .register_robot(&candidate_name)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to register robot '{candidate_name}': {e}"))?;

        if response.created {
            println!("✅ Registered robot '{}' (id: {})", response.name, response.id);
            return Ok((response.id, response.name, true));
        }

        if !interactive {
            println!(
                "ℹ️  Linking to already-registered robot '{}' (id: {})",
                response.name, response.id
            );
            return Ok((response.id, response.name, false));
        }

        let link = Confirm::new()
            .with_prompt(format!(
                "A project named '{}' is already registered to your account (id: {}). Link this new project to it?",
                response.name, response.id
            ))
            .default(true)
            .interact()
            .map_err(|e| anyhow::anyhow!("Failed to read confirmation: {e}"))?;

        if link {
            println!("🔗 Linked to robot '{}' (id: {})", response.name, response.id);
            return Ok((response.id, response.name, false));
        }
    }
}

/// Resolve the version to seed a freshly scaffolded project's `mecha10.json` with.
///
/// For a brand new robot (`robot_created`) there's no prior build to anchor to, so this just
/// returns `template_version` unchanged (the pre-existing behavior). For a project linking to an
/// *existing* robot, `mecha10.json`'s `version` should reflect that robot's actual last deployed
/// build (`mecha10 build <target>`'s registered version), not the CLI's own templates release
/// version - the two are unrelated axes (templates version tracks scaffolding content; build
/// version tracks what's actually running on the robot), and defaulting to the latter here
/// previously made a newly scaffolded project silently regress a robot's build-version bookkeeping
/// back to whatever templates happened to be current.
///
/// Checks every target in `BUILD_TARGETS` (robot/remote/rl all share the same `mecha10.json`
/// `version`, bumped together by `mecha10 build`) and seeds with the highest published build
/// version found across all of them - checking only `"robot"` missed robots whose latest build
/// was actually for `"remote"`/`"rl"`.
///
/// Looked up by `robot_id`, not by `project_name` (every earlier revision of this function was) -
/// `project_name` is just whatever arbitrary local directory/project name *this* `mecha10 init`
/// run happens to be scaffolding, which is not the same thing as the name the *existing* robot's
/// builds were actually uploaded under. `resolve_robot_link`'s "link to an already-registered
/// robot" prompt explicitly lets the user type a different name there than their new project's
/// name - that's the entire point of linking to an existing robot instead of registering a new
/// one - so keying this lookup off `project_name` silently 404s (indistinguishable from "no prior
/// build") every time the two names diverge, which is exactly the "still doesn't work, no error"
/// failure mode across several earlier fix attempts here. `robot_id` is the one value every
/// `mecha10 upload` call actually tags each binary with that identifies the robot itself,
/// independent of whichever local checkout's name produced the build.
///
/// Also checks the last `mecha10 config push`ed `mecha10.json`'s `version` field (its own
/// `"mecha10.json"` config key, per `handle_config_push`/`collect_config_files`) alongside the
/// build targets above, and seeds with whichever source published the highest version.
///
/// A prior revision of this function (#954/"simplify mecha10 init version seeding to use highest
/// published build version only") deliberately dropped this source, reasoning that a pushed-but-
/// never-built version "may never have actually been built/published" and so was unreliable. That
/// reasoning doesn't hold up: `mecha10 config push` is itself a publish action - the server
/// versions the `"mecha10.json"` key on every upsert (see `handle_config_push`'s doc comment) -
/// and it is the *primary* way many projects' versions are bumped day to day; `mecha10 build`
/// (which is what the removed source's replacement, build-catalog version, actually tracks) is a
/// separate, less frequently run step. Dropping this source is exactly why LAB-4079 kept
/// reopening after being marked Done: any robot whose version was bumped and pushed via `mecha10
/// config push` but never (yet) built fell straight through to the `template_version` fallback,
/// silently reproducing the original "matched-project version prompt not populating mecha10.json
/// version correctly" bug this function exists to fix. Folding both sources back in and taking the
/// highest (not only the pushed-config version, since a build can likewise be ahead of the last
/// push) is the actual root cause fix, not another symptom patch on top of either side alone.
///
/// Falls back to `template_version` whenever no lookup can be completed (offline, not logged in,
/// or the robot really has no prior build/config push yet) - this must never block `mecha10 init`.
async fn resolve_initial_project_version(robot_id: &str, robot_created: bool, template_version: &str) -> String {
    if robot_created {
        return template_version.to_string();
    }

    let credentials_service = CredentialsService::new();
    let Ok(Some(credentials)) = credentials_service.load() else {
        return template_version.to_string();
    };

    let control_plane_url = EnvironmentsConfig::default().control_plane_url();
    let mut candidates: Vec<(String, String)> = Vec::new();

    for target in BUILD_TARGETS {
        match crate::services::latest_build_version::fetch_latest_build_version(
            &control_plane_url,
            robot_id,
            target,
            &credentials.api_key,
            &credentials.user_id,
        )
        .await
        {
            Ok(Some(version)) => candidates.push((version, format!("{target} build"))),
            Ok(None) => {}
            Err(e) => {
                println!(
                    "⚠️  Could not look up robot '{}''s last {} build version: {e:#}",
                    robot_id, target
                );
            }
        }
    }

    let config_url = format!(
        "{}{}",
        control_plane_url.trim_end_matches('/'),
        crate::handlers::config::ROBOT_CONFIG_PATH
    );
    let config_client = RobotConfigClient::with_user_id(
        config_url,
        credentials.api_key.clone(),
        Some(credentials.user_id.clone()),
    );
    if let Ok(response) = config_client.get_config(robot_id, "mecha10.json").await {
        if let Some(version) = response.config_value.get("version").and_then(|v| v.as_str()) {
            candidates.push((version.to_string(), "last pushed config".to_string()));
        }
    }

    match pick_highest_published_version(robot_id, candidates) {
        Some(version) => {
            println!(
                "📦 Using highest published build/config version v{} from robot '{}'",
                version, robot_id
            );
            version
        }
        None => template_version.to_string(),
    }
}

/// Pick the highest parseable semver out of `(version, source_label)` candidates gathered from
/// every build target plus the last pushed config (see [`resolve_initial_project_version`]),
/// logging and skipping any that don't parse as semver. Split out from the async lookup above so
/// the actual "combine every source and take the highest" selection logic - the part previous
/// fix attempts kept getting wrong by dropping one source or the other - is covered by fast,
/// offline unit tests instead of only being exercisable through a real network round trip.
fn pick_highest_published_version(robot_id: &str, candidates: Vec<(String, String)>) -> Option<String> {
    let mut highest: Option<(u32, u32, u32, String)> = None;

    for (version, source) in candidates {
        match parse_semver_tuple(&version) {
            Some(tuple) => {
                let is_higher = match &highest {
                    Some((ma, mi, pa, _)) => tuple > (*ma, *mi, *pa),
                    None => true,
                };
                if is_higher {
                    highest = Some((tuple.0, tuple.1, tuple.2, version));
                }
            }
            None => println!(
                "⚠️  Ignoring unparsable {} version '{}' for robot '{}'.",
                source, version, robot_id
            ),
        }
    }

    highest.map(|(_, _, _, version)| version)
}

#[cfg(test)]
mod pick_highest_published_version_tests {
    use super::pick_highest_published_version;

    #[test]
    fn picks_the_highest_build_target_version() {
        let candidates = vec![
            ("1.2.0".to_string(), "robot build".to_string()),
            ("1.4.0".to_string(), "remote build".to_string()),
            ("1.3.0".to_string(), "rl build".to_string()),
        ];

        assert_eq!(
            pick_highest_published_version("robot-1", candidates),
            Some("1.4.0".to_string())
        );
    }

    /// Regression coverage for LAB-4079 continuing to reopen after being marked Done: the last
    /// pushed config's version must win when it's ahead of every build target, not be silently
    /// dropped the way the #954 "simplify" revision dropped this source entirely.
    #[test]
    fn prefers_the_pushed_config_version_when_it_is_ahead_of_every_build() {
        let candidates = vec![
            ("1.0.0".to_string(), "robot build".to_string()),
            ("1.1.0".to_string(), "remote build".to_string()),
            ("2.0.0".to_string(), "last pushed config".to_string()),
        ];

        assert_eq!(
            pick_highest_published_version("robot-1", candidates),
            Some("2.0.0".to_string())
        );
    }

    /// The reverse must also hold: a build that's ahead of the last push (push bumped locally,
    /// built and uploaded, but not pushed again) still wins.
    #[test]
    fn prefers_a_build_version_when_it_is_ahead_of_the_pushed_config() {
        let candidates = vec![
            ("3.0.0".to_string(), "robot build".to_string()),
            ("2.5.0".to_string(), "last pushed config".to_string()),
        ];

        assert_eq!(
            pick_highest_published_version("robot-1", candidates),
            Some("3.0.0".to_string())
        );
    }

    #[test]
    fn ignores_unparsable_candidates_and_still_picks_the_best_valid_one() {
        let candidates = vec![
            ("not-a-version".to_string(), "last pushed config".to_string()),
            ("1.5.0".to_string(), "robot build".to_string()),
        ];

        assert_eq!(
            pick_highest_published_version("robot-1", candidates),
            Some("1.5.0".to_string())
        );
    }

    #[test]
    fn returns_none_when_no_candidates_parse() {
        assert_eq!(pick_highest_published_version("robot-1", vec![]), None);
    }
}

const BUILD_TARGETS: [&str; 3] = ["robot", "remote", "rl"];

/// Parse "major.minor.patch[-pre]" into a comparable `(u32, u32, u32)` tuple, ignoring any
/// prerelease suffix - mirrors `handlers::build::bump_semver`'s parsing. Returns `None` for a
/// version string that doesn't parse, so a malformed registry response can't crash comparison -
/// the caller just skips it.
fn parse_semver_tuple(version: &str) -> Option<(u32, u32, u32)> {
    let parts: Vec<&str> = version.split('.').collect();
    if parts.len() < 3 {
        return None;
    }
    let major = parts[0].parse().ok()?;
    let minor = parts[1].parse().ok()?;
    let patch = parts[2].split('-').next().unwrap_or("0").parse().ok()?;
    Some((major, minor, patch))
}

#[cfg(test)]
mod parse_semver_tuple_tests {
    use super::*;

    #[test]
    fn parses_plain_version() {
        assert_eq!(parse_semver_tuple("1.2.3"), Some((1, 2, 3)));
    }

    #[test]
    fn ignores_prerelease_suffix() {
        assert_eq!(parse_semver_tuple("1.2.3-beta"), Some((1, 2, 3)));
    }

    #[test]
    fn rejects_too_few_components() {
        assert_eq!(parse_semver_tuple("1.2"), None);
    }

    #[test]
    fn rejects_non_numeric_components() {
        assert_eq!(parse_semver_tuple("a.b.c"), None);
    }

    #[test]
    fn orders_by_major_then_minor_then_patch() {
        assert!(parse_semver_tuple("2.0.0") > parse_semver_tuple("1.9.9"));
        assert!(parse_semver_tuple("1.3.0") > parse_semver_tuple("1.2.9"));
        assert!(parse_semver_tuple("1.2.4") > parse_semver_tuple("1.2.3"));
    }
}

/// 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
///
/// # Returns
///
/// A tuple of (project_name, project_path, template, nodes)
///
/// Fetches the template/node catalogs live from `mecha10-api` (see
/// `crate::services::catalog_client`) rather than reading the compiled-in
/// `mecha10_templates::init` catalog - the non-interactive counterpart to
/// `ui::init_wizard::run_wizard_tui`'s equivalent migration. A `--template` name that doesn't
/// match any fetched template catalog entry is not a hard error here (same as before this
/// migration): `template_node_defaults` falls back to a fixed basic node selection instead, so
/// scripted/CI callers passing an unrecognized or stale template name keep working rather than
/// failing outright.
async fn process_non_interactive_args(args: &InitArgs, working_dir: &Path) -> Result<InitProcessResult> {
    use crate::services::catalog_client::{self, template_node_defaults};

    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"
        )
    })?;

    let path_buf = PathBuf::from(&name);
    let (project_name, project_path) = if path_buf.is_absolute() || name.contains('/') || name.contains('\\') {
        let final_name = path_buf
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&name)
            .to_string();
        (final_name, path_buf)
    } else {
        let final_path = working_dir.join(&name);
        (name, final_path)
    };

    let template = args.template.clone();

    let templates = catalog_client::fetch_template_catalog()
        .await
        .context("Failed to fetch template catalog - mecha10 init cannot continue without it")?;

    let nodes: Vec<String> = {
        let mut node_entries = catalog_client::fetch_node_catalog()
            .await
            .context("Failed to fetch node catalog - mecha10 init cannot continue without it")?;
        node_entries.sort_by(|a, b| a.name.cmp(&b.name));
        let node_ids: Vec<String> = node_entries.into_iter().map(|e| e.name).collect();

        let defaults = template_node_defaults(&templates, &template, &node_ids);

        let mut selected: Vec<String> = node_ids
            .iter()
            .enumerate()
            .filter(|(i, _)| defaults[*i])
            .map(|(_, id)| id.clone())
            .collect();

        if args.no_examples {
            selected.retain(|id| id != "speaker" && id != "listener");
        }

        selected
    };

    let robot_platform = resolve_robot_platform(args.robot_platform.as_deref());
    let remote_platform = resolve_remote_platforms(args.remote_platform.as_deref());

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

/// 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<()> {
    if args.update {
        return handle_update_existing(ctx, args).await;
    }

    print!("\x1B[2J\x1B[1;1H");

    let credentials_service = CredentialsService::new();
    if crate::context::is_ci_environment() {
        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(());
        }
    } else {
        mecha10_auth::ensure_authenticated_interactive(&credentials_service).await?;
    }

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

    let working_dir = ctx.working_dir.clone();

    let catalog = ctx.component_catalog();

    let use_wizard = is_interactive_terminal() && !args.non_interactive;

    let (project_name, project_path, template, nodes, robot_platform, remote_platform) = if use_wizard {
        let default_name = args.name.clone();
        match run_wizard_tui(default_name.as_deref(), catalog).await {
            Ok((name, template, selected_nodes, robot_platform, remote_platform)) => {
                let path_buf = std::path::PathBuf::from(&name);
                let (final_name, path) = if path_buf.is_absolute() || name.contains('/') || name.contains('\\') {
                    let final_name = path_buf
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or(&name)
                        .to_string();
                    (final_name, path_buf)
                } else {
                    let final_path = ctx.working_dir.join(&name);
                    (name, final_path)
                };

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

                process_non_interactive_args(args, &working_dir).await?
            }
        }
    } else {
        if !is_interactive_terminal() {
            println!("ℹ️  Non-interactive mode\n");
        }

        process_non_interactive_args(args, &working_dir).await?
    };

    validation::check_directory_not_exists(&project_path)?;

    let (robot_id, robot_name, robot_created) = resolve_robot_link(&project_name, use_wizard).await?;

    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);

    let initial_version = resolve_initial_project_version(&robot_id, robot_created, &template_version).await;

    let result = perform_init(
        ctx,
        &project_path,
        &project_name,
        &template,
        &nodes,
        &template_version,
        &initial_version,
        &robot_platform,
        &remote_platform,
        &robot_id,
        &robot_name,
    )
    .await;

    if let Err(e) = result {
        cleanup_on_error(&project_path).await;
        return Err(e);
    }

    let setup_ran = auto_run_setup(ctx, &project_path).await;

    print_success_message(&project_name, setup_ran);

    Ok(())
}

/// Run `mecha10 setup` against the freshly created project directory, as part of `mecha10
/// init`'s success path. `handle_setup` resolves its paths (`.venv`, `requirements.txt`)
/// relative to the process's current directory rather than `ctx.working_dir`, so this
/// temporarily changes into `project_path` for the call and restores the original working
/// directory afterward regardless of outcome.
///
/// Returns whether setup completed successfully - `false` (not an error) on any failure, so the
/// caller can fall back to telling the user to run `mecha10 setup` manually instead of aborting
/// the whole `mecha10 init` run over what is, at worst, a missing local dev prerequisite.
async fn auto_run_setup(ctx: &mut CliContext, project_path: &Path) -> bool {
    let Ok(original_cwd) = std::env::current_dir() else {
        return false;
    };

    if std::env::set_current_dir(project_path).is_err() {
        return false;
    }

    let setup_args = crate::handlers::setup::SetupArgs {
        check_only: false,
        install_deps: true,
        quiet: true,
    };
    let result = crate::handlers::setup::handle_setup(ctx, &setup_args).await;

    let _ = std::env::set_current_dir(&original_cwd);

    match result {
        Ok(()) => true,
        Err(e) => {
            println!("⚠️  Automatic setup failed: {}", e);
            println!("   Run `mecha10 setup` manually inside the project directory.");
            false
        }
    }
}

/// 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!();

    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 {
        ctx.working_dir.clone()
    };

    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()
        );
    }

    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());

    let init_service = ctx.init_service();
    let mut synced = 0;

    for node_id in &nodes {
        let node_name = node_id.strip_prefix("@mecha10/").unwrap_or(node_id);

        let v2_dev_exists = project_path
            .join("configs")
            .join("dev")
            .join("nodes")
            .join(node_name)
            .join("config.json")
            .exists();

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

        if !v2_dev_exists && !legacy_exists {
            if let Err(e) = init_service.add_example_node(&project_path, node_name).await {
                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, drone, sentry, arm)
/// * `nodes` - List of nodes to add
/// * `template_version` - Downloaded template version (the only template-resolution path)
/// * `robot_platform` - Target triple for `targets.robot.platforms` (wizard selection, or
///   `--robot-platform`/default in non-interactive mode)
/// * `remote_platform` - Target triples for `targets.remote.platforms` (wizard selection, or
///   `--remote-platform`/default in non-interactive mode)
/// * `robot_id`/`robot_name` - Resolved by [`resolve_robot_link`] before any of this ran (LAB-2132
///   registration or link-to-existing), written into `mecha10.json`'s `robot_id`/`robot_name`
///   fields by [`create_mecha10_json_from_template`]
#[allow(clippy::too_many_arguments)]
async fn perform_init(
    ctx: &mut CliContext,
    project_path: &Path,
    project_name: &str,
    template: &Option<String>,
    nodes: &[String],
    template_version: &str,
    initial_version: &str,
    robot_platform: &str,
    remote_platform: &[String],
    robot_id: &str,
    robot_name: &str,
) -> Result<()> {
    ctx.init_service().create_project_directories(project_path).await?;

    copy_downloaded_templates(ctx, project_path, template_version).await?;

    create_mecha10_json_from_template(
        ctx,
        project_path,
        project_name,
        template,
        nodes,
        template_version,
        initial_version,
        robot_platform,
        remote_platform,
        robot_id,
        robot_name,
    )
    .await?;
    println!("✅ Robot registered");
    println!("✅ Simulation assets");
    println!("✅ Node configurations");

    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?;

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

    // Gate on the `simulator` node being selected, not the template name - the RL bundle's
    // Python deps (`mecha10-rl`/`mecha10-rl-task-runner`) are what `simulator` needs at runtime
    // to import `mecha10_rl.mujoco.cli` (see `check_mecha10_rl_importable`,
    // `handlers/dev/ops/preflight.rs`'s same reasoning), independent of which model/env it's
    // configured against. `template.as_deref() == Some("rover")` used to gate this, but every
    // other default-resolution path in this module treats an omitted `--template` as `"rover"`
    // (`unwrap_or("rover")`) while this check only matched the literal string - so `mecha10
    // init` without `--template` scaffolded the `simulator`/`rl` nodes but silently skipped
    // appending their Python deps to `requirements.txt`.
    if nodes.contains(&"simulator".to_string()) {
        ctx.project_template_service()
            .create_rl_training_bundle(project_path)
            .await?;
        println!("✅ RL training bundle (rover/ppo)");

        ctx.project_template_service()
            .create_rl_docker_files(project_path)
            .await?;
        println!("✅ rl target Docker files (run trained policies via `mecha10 run rl`)");
    }

    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?;

    ctx.project_template_service()
        .create_remote_docker_files(project_path)
        .await?;
    println!("✅ Project files");

    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!();

        // Best-effort: pull each selected node's default config/schema from the live node
        // catalog (see `mecha10_robot_config::pull_node_catalog_configs`'s doc comment). This
        // never fails `mecha10 init`. `template` selects a per-template override when the
        // catalog has one for a given node (e.g. `teleop` defaulting to actuator mode for
        // `sentry`, which has no drivetrain).
        mecha10_robot_config::pull_node_catalog_configs(project_path, nodes, template.as_deref()).await;
    }

    Ok(())
}

/// Print success message after initialization
///
/// `setup_ran` reflects whether [`auto_run_setup`] completed successfully: when it did, the
/// printed steps drop the now-redundant `mecha10 setup` (already ran); when it didn't (or
/// failed), that step is added back so the user knows to run it manually. Either way,
/// `source .venv/bin/activate` stays a manual step - `source` mutates the parent shell's own
/// environment, which a subprocess like this CLI cannot do on the user's behalf.
fn print_success_message(project_name: &str, setup_ran: bool) {
    println!("✨ Project {} created successfully!", project_name);
    println!();
    println!("📋 Next steps:");
    if setup_ran {
        println!("  1. cd {} && source .venv/bin/activate", project_name);
        println!("  2. mecha10 dev");
    } else {
        println!("  1. cd {}", project_name);
        println!("  2. mecha10 setup");
        println!("  3. source .venv/bin/activate");
        println!("  4. mecha10 dev");
    }
    println!();
    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.
    //!
    //! As of the node->target(s) live-placement migration, the template itself no longer carries
    //! *any* per-node placement (no static `nodes` map entries, no static `targets.*.nodes`
    //! arrays) - every node's placement now comes exclusively from `mecha10-api`'s live node
    //! catalog via [`build_node_placement`] (see that function's module docs for why, and
    //! `build_node_placement_tests` above for the LAB-1775/dashboard-disconnect regression
    //! coverage this test module used to carry against the template's own static content). These
    //! tests instead guard the template's remaining, deliberately-static shape.

    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 top_level_nodes_map_starts_empty() {
        let config = parsed_template();

        assert_eq!(
            config["nodes"].as_object().expect("nodes map must be an object").len(),
            0,
            "the template's top-level nodes map must be built entirely by build_node_placement \
             from the live catalog, not pre-populated with any static node"
        );
    }

    #[test]
    fn no_target_declares_a_static_nodes_array() {
        let config = parsed_template();

        for target_name in ["dev", "simulation", "robot", "remote"] {
            let target = &config["targets"][target_name];
            assert!(
                target.get("nodes").is_none(),
                "targets.{target_name} must not pre-populate a static nodes array - placement \
                 comes exclusively from build_node_placement now, got {target:?}"
            );
        }
    }

    #[test]
    fn robot_and_remote_still_declare_their_default_platforms() {
        let config = parsed_template();

        assert!(
            config["targets"]["robot"]["platforms"].as_array().is_some_and(|a| !a.is_empty()),
            "targets.robot.platforms is unrelated to node placement and must survive"
        );
        assert!(
            config["targets"]["remote"]["platforms"].as_array().is_some_and(|a| !a.is_empty()),
            "targets.remote.platforms is unrelated to node placement and must survive"
        );
    }

    #[test]
    fn declares_exactly_one_robot_target_key() {
        // Regression guard for a literal duplicate `"robot"` JSON key once present in this file
        // (two separate `"robot": {...}` object entries under `targets`) - `serde_json` silently
        // keeps only the last one on parse, so a round-trip through `parsed_template()` can't
        // catch this by itself; grep the raw source text instead.
        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();

        let occurrences = content.matches("\"robot\": {").count();
        assert_eq!(
            occurrences, 1,
            "mecha10.json.template must declare targets.robot exactly once, found {occurrences} occurrences"
        );
    }

    #[test]
    fn simulation_config_declares_a_preset_for_dev_preview() {
        let config = parsed_template();

        assert_eq!(
            config["simulation"]["preset"].as_str(),
            Some("default"),
            "mecha10.json's simulation.preset drives mecha10 dev's plain preview/teleop \
             session - it must be scaffolded, not left for `mecha10 dev` to fall back on a \
             bundled RL task that no longer exists (LAB-3629)"
        );
    }
}

#[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();
        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,
            unresolvable_version,
            "aarch64-unknown-linux-gnu",
            &[
                "x86_64-unknown-linux-gnu".to_string(),
                "aarch64-unknown-linux-gnu".to_string(),
            ],
            "11111111-1111-1111-1111-111111111111",
            "my-robot",
        )
        .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}"
        );

        assert!(
            !project_dir.path().join(paths::PROJECT_CONFIG).exists(),
            "mecha10.json must not be written when template resolution fails"
        );
    }
}