gen-circleci-orb 0.1.0

Generate a CircleCI orb to provide the facilities offered by a CLI program
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
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
use anyhow::Result;
use indexmap::IndexMap;
use std::path::PathBuf;

use crate::{
    ci_patcher,
    commands::generate::Generate,
    help_parser::types::CliDefinition,
    orb_config::{CiSection, OrbConfig, OrbSection, RecordConfig, SubcommandConfig},
};

pub const DEFAULT_DOCKER_ORB_VERSION: &str = "3.0.1";
pub const DEFAULT_DOCKER_CONTEXT: &str = "docker-credentials";
pub const DEFAULT_ORB_CONTEXT: &str = "orb-publishing";
pub const DEFAULT_MCP_CONTEXT: &str = "pcu-app";
pub const DEFAULT_MCP_EARLIEST_VERSION: &str = "0.0.1";
/// Default jerus-org/gen-orb-mcp orb version pinned for the build_mcp_server job
/// (Mechanism A). Generator-owned (like the gen-circleci-orb pin) so the `update`
/// gate stays authoritative; Renovate keeps this default current.
pub const DEFAULT_GEN_ORB_MCP_ORB_VERSION: &str = "0.1.48";

/// Values resolved by the interactive dialogue (or non-interactive fallback).
/// These are used by both `PatchOpts` and the bootstrap config.
pub(crate) struct GatheredExtras {
    pub home_url: Option<String>,
    pub source_url: Option<String>,
    pub git_push_subcommands: Vec<String>,
    pub docker_context: String,
    pub orb_context: String,
    pub mcp_context: Vec<String>,
    pub mcp_earliest_version: String,
    pub record: Option<RecordConfig>,
}

fn is_non_interactive(dry_run: bool) -> bool {
    dry_run || std::env::var("CI").is_ok() || !console::Term::stderr().is_term()
}

/// Assemble the `[record]` config from explicit env-var names. Returns `Ok(None)`
/// when auto-record is not enabled. When enabled, every name must be present and
/// non-empty — there are no defaults, so the tool never imposes an env-var
/// convention on the consumer. Errors naming the first missing flag otherwise.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_record_config(
    enabled: bool,
    gpg_key_env: Option<&str>,
    gpg_trust_env: Option<&str>,
    user_name_env: Option<&str>,
    user_email_env: Option<&str>,
    signing_key_env: Option<&str>,
    push_ssh_fingerprint: Option<&str>,
    contexts: &[String],
) -> Result<Option<RecordConfig>> {
    if !enabled {
        return Ok(None);
    }
    let req = |v: Option<&str>, flag: &str| -> Result<String> {
        v.map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "auto-record is enabled but {flag} was not provided \
                     (no default — supply the env-var name)"
                )
            })
    };
    let contexts: Vec<String> = contexts
        .iter()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();
    if contexts.is_empty() {
        anyhow::bail!(
            "auto-record is enabled but no --record-context was provided \
             (the record job needs the CircleCI context(s) that supply the GPG \
             signing material)"
        );
    }
    Ok(Some(RecordConfig {
        enabled: true,
        gpg_key_env: req(gpg_key_env, "--record-gpg-key-env")?,
        gpg_trust_env: req(gpg_trust_env, "--record-gpg-trust-env")?,
        user_name_env: req(user_name_env, "--record-user-name-env")?,
        user_email_env: req(user_email_env, "--record-user-email-env")?,
        signing_key_env: req(signing_key_env, "--record-signing-key-env")?,
        // Optional: empty means the push falls back to ambient credentials.
        push_ssh_fingerprint: push_ssh_fingerprint
            .map(str::trim)
            .unwrap_or("")
            .to_string(),
        contexts,
    }))
}

/// Detect leaf subcommands that have a required `orb_path` parameter.
/// These should receive `default = "src/@orb.yml"` in the config so
/// orb consumers don't have to supply the path on every invocation.
pub(crate) fn detect_orb_path_subcommands(cli: &CliDefinition) -> Vec<String> {
    cli.subcommands
        .iter()
        .filter(|sub| {
            sub.is_leaf
                && sub
                    .parameters
                    .iter()
                    .any(|p| p.long_name == "orb_path" && p.required)
        })
        .map(|sub| sub.name.clone())
        .collect()
}

/// Add `[subcommand.<name>.param.orb_path] default = "src/@orb.yml"` for each
/// detected subcommand.  Existing entries (e.g. help suppression) are preserved.
pub(crate) fn populate_orb_path_defaults(
    config: &mut crate::orb_config::OrbConfig,
    subcommands: &[String],
) {
    use crate::orb_config::ParamOverride;
    if subcommands.is_empty() {
        return;
    }
    let sc_map = config
        .subcommand
        .get_or_insert_with(indexmap::IndexMap::new);
    for name in subcommands {
        let sc = sc_map.entry(name.clone()).or_default();
        let params = sc.param.get_or_insert_with(indexmap::IndexMap::new);
        params
            .entry("orb_path".to_string())
            .or_insert(ParamOverride {
                default: Some("src/@orb.yml".to_string()),
            });
    }
}

/// Detect leaf subcommands that are likely to push to git, based on whether
/// they have a `--push`, `--no-push`, or `--sign` parameter.
pub(crate) fn detect_git_push_subcommands(cli: &CliDefinition) -> Vec<String> {
    cli.subcommands
        .iter()
        .filter(|sub| {
            sub.is_leaf
                && sub
                    .parameters
                    .iter()
                    .any(|p| matches!(p.long_name.as_str(), "push" | "no_push" | "sign"))
        })
        .map(|sub| sub.name.clone())
        .collect()
}

/// Wire orb generation into an existing repo's CI configuration.
#[derive(Debug, clap::Args)]
pub struct Init {
    /// Name of the binary to introspect (must be on PATH).
    #[arg(long)]
    pub binary: String,

    /// CircleCI namespace(s) to publish the orb under as a public orb (repeatable).
    /// Must be set correctly on first init — visibility cannot be changed after the orb is created.
    #[arg(long = "public-orb-namespace")]
    pub public_orb_namespaces: Vec<String>,

    /// CircleCI namespace(s) to publish the orb under as a private orb (repeatable).
    /// Each listed namespace gets `--private` in its `circleci orb create` command.
    /// Must be set correctly on first init — visibility cannot be changed after the orb is created.
    #[arg(long = "private-orb-namespace")]
    pub private_orb_namespaces: Vec<String>,

    /// Name of the build/validation workflow to patch.
    #[arg(long)]
    pub build_workflow: String,

    /// Name of the release workflow to patch.
    #[arg(long)]
    pub release_workflow: String,

    /// Job in the build workflow that regenerate-orb should require.
    #[arg(long)]
    pub requires_job: Option<String>,

    /// Tag prefix used by `toolkit/release_crate` for the crate (e.g. `gen-orb-mcp-v`).
    /// Used to filter the `orb-release:` workflow trigger in config.yml and to normalise
    /// `CIRCLE_TAG` for `orb-tools/publish`.
    #[arg(long)]
    pub crate_tag_prefix: String,

    /// Job in the release workflow after which the generated release jobs
    /// (build-binary-release, pack-orb-release, build-container, ensure-orb-registered)
    /// should be gated. This is the sole mechanism for specifying where the generated
    /// jobs plug into the existing pipeline topology.
    #[arg(long)]
    pub release_after_job: String,

    /// Output directory for the generated orb source (relative to repo root).
    #[arg(long, default_value = "orb")]
    pub orb_dir: String,

    /// Path to the .circleci/ directory.
    #[arg(long, default_value = ".circleci")]
    pub ci_dir: PathBuf,

    /// circleci/orb-tools version to pin in generated CI.
    #[arg(long, default_value = "12.3.3")]
    pub orb_tools_version: String,

    /// circleci/docker orb version to pin in generated CI.
    #[arg(long, default_value = DEFAULT_DOCKER_ORB_VERSION)]
    pub docker_orb_version: String,

    /// Docker Hub (or registry) namespace for the built container image.
    #[arg(long)]
    pub docker_namespace: String,

    /// CircleCI context name holding Docker Hub credentials (DOCKER_LOGIN, DOCKER_PASSWORD).
    /// Prompted interactively if not supplied.
    #[arg(long)]
    pub docker_context: Option<String>,

    /// CircleCI context name holding orb publishing credentials (CIRCLECI_CLI_TOKEN).
    /// Prompted interactively if not supplied.
    #[arg(long)]
    pub orb_context: Option<String>,

    /// Version of the jerus-org/gen-circleci-orb orb to pin in generated CI.
    /// Defaults to the version of this binary (orb and crate are released together).
    #[arg(long, default_value = env!("CARGO_PKG_VERSION"))]
    pub gen_circleci_orb_version: String,

    /// Wire in gen-orb-mcp MCP server generation + publish after orb publish.
    #[arg(long)]
    pub mcp: bool,

    /// Earliest orb version to include when priming prior-version snapshots.
    /// Passed to gen-circleci-orb/build_mcp_server as `earliest_version`.
    /// Only used when --mcp is enabled. Prompted interactively if not supplied.
    #[arg(long)]
    pub mcp_earliest_version: Option<String>,

    /// CircleCI context name(s) for MCP server build + publish + save steps (repeatable or comma-separated).
    /// Needs: GITHUB_TOKEN (GitHub App token, contents:write + bypass branch protection),
    /// BOT_GPG_KEY, BOT_TRUST, BOT_USER_NAME, BOT_USER_EMAIL, BOT_SIGN_KEY.
    /// Only used when --mcp is enabled. Prompted interactively if not supplied.
    #[arg(long = "mcp-context", value_delimiter = ',')]
    pub mcp_context: Vec<String>,

    /// Subcommand names whose generated jobs should include a `set_https_remote` step
    /// (repeatable). Use for subcommands that push to git (e.g. `save`).
    #[arg(long, value_delimiter = ',')]
    pub git_push_subcommands: Vec<String>,

    /// Home URL for the orb (shown in the CircleCI registry).
    #[arg(long)]
    pub home_url: Option<String>,

    /// Source URL for the orb (shown in the CircleCI registry).
    #[arg(long)]
    pub source_url: Option<String>,

    /// Enable auto-record: after `generate`, the regenerate-orb CI job commits the
    /// regenerated orb source back (GPG-signed) and pushes it, so the published orb
    /// always reflects the CLI. When set, the `--record-*-env` flags name the
    /// environment variables that hold the GPG signing material at runtime (no
    /// defaults — they must be supplied). Prompted interactively if not set.
    #[arg(long)]
    pub record: bool,

    /// Name of the env var holding the base64-encoded GPG private key (auto-record).
    #[arg(long)]
    pub record_gpg_key_env: Option<String>,

    /// Name of the env var holding the GPG ownertrust export (auto-record).
    #[arg(long)]
    pub record_gpg_trust_env: Option<String>,

    /// Name of the env var holding the committer name (auto-record).
    #[arg(long)]
    pub record_user_name_env: Option<String>,

    /// Name of the env var holding the committer email (auto-record).
    #[arg(long)]
    pub record_user_email_env: Option<String>,

    /// Name of the env var holding the GPG signing key id (auto-record).
    #[arg(long)]
    pub record_signing_key_env: Option<String>,

    /// SSH key fingerprint (a public-key hash, not a secret) for the
    /// end-of-workflow push job (auto-record). Optional: when set, the push job
    /// loads this write key and drops the read-only checkout key; empty falls back
    /// to ambient credentials. A value, not an env-var name — add_ssh_keys resolves
    /// fingerprints at config-compile time and cannot read env vars.
    #[arg(long)]
    pub record_push_ssh_fingerprint: Option<String>,

    /// CircleCI context(s) that supply the auto-record env-var values
    /// (GPG signing material), repeatable or comma-separated.
    /// The record CI job attaches these.
    #[arg(long = "record-context", value_delimiter = ',')]
    pub record_contexts: Vec<String>,

    /// Show planned changes without modifying any files.
    #[arg(long)]
    pub dry_run: bool,
}

/// Subcommands present in the target binary that are interactive by default
/// ([`DEFAULT_INTERACTIVE`]) — the ones `init` prompts about and scaffolds.
pub(crate) fn present_default_interactive(cli: &CliDefinition) -> Vec<String> {
    cli.subcommands
        .iter()
        .filter(|s| crate::orb_generator::render::DEFAULT_INTERACTIVE.contains(&s.name.as_str()))
        .map(|s| s.name.clone())
        .collect()
}

pub(crate) fn build_bootstrap_config(
    binary: &str,
    namespaces: &[String],
    orb_dir: &str,
    home_url: Option<&str>,
    source_url: Option<&str>,
    git_push_subcommands: &[String],
    interactive: &[(String, bool)],
) -> OrbConfig {
    // `help` is reserved at the `--help` parser, so it needs no entry. Interactive
    // (CLI-only) subcommands — `init`/`config` by default, as confirmed at init
    // time — are fully excluded from the orb (job + command + script); a parent
    // (`config`) cascades to its whole subtree, so no per-child entries are needed.
    let mut subcommands = IndexMap::new();
    for (name, is_interactive) in interactive {
        subcommands.insert(
            name.clone(),
            SubcommandConfig {
                interactive: Some(*is_interactive),
                ..SubcommandConfig::default()
            },
        );
    }
    let subcommand = if subcommands.is_empty() {
        None
    } else {
        Some(subcommands)
    };
    OrbConfig {
        orb: Some(OrbSection {
            binary: Some(binary.to_string()),
            namespaces: Some(namespaces.to_vec()),
            orb_dir: Some(orb_dir.to_string()),
            base_image: None,
            builder_image: None,
            circleci_cli_version: None,
            install_method: None,
            apt_packages: None,
            home_url: home_url.map(str::to_string),
            source_url: source_url.map(str::to_string),
            git_push_subcommands: if git_push_subcommands.is_empty() {
                None
            } else {
                Some(git_push_subcommands.to_vec())
            },
            custom_files: None,
        }),
        ci: None, // populated by run() after gathering extras
        orbs: None,
        subcommand,
        job_group: None,
        extra_job: None,
        record: None, // populated by run() after gathering extras
    }
}

impl Init {
    /// Gather the `[record]` config. Name resolution: CLI flag > existing config.
    /// Non-interactive mode assembles from those sources (erroring if enabled but a
    /// name is missing); interactive mode confirms the need then prompts for each
    /// env-var name (no defaults beyond the user's own prior config).
    fn gather_record(&self, existing: &OrbConfig) -> Result<Option<RecordConfig>> {
        let ex = existing.record.as_ref();
        let resolve = |cli: Option<&String>, prev: Option<&str>| -> Option<String> {
            cli.filter(|s| !s.is_empty())
                .cloned()
                .or_else(|| prev.map(str::to_string))
        };
        let gpg_key = resolve(
            self.record_gpg_key_env.as_ref(),
            ex.map(|r| r.gpg_key_env.as_str()),
        );
        let gpg_trust = resolve(
            self.record_gpg_trust_env.as_ref(),
            ex.map(|r| r.gpg_trust_env.as_str()),
        );
        let user_name = resolve(
            self.record_user_name_env.as_ref(),
            ex.map(|r| r.user_name_env.as_str()),
        );
        let user_email = resolve(
            self.record_user_email_env.as_ref(),
            ex.map(|r| r.user_email_env.as_str()),
        );
        let sign_key = resolve(
            self.record_signing_key_env.as_ref(),
            ex.map(|r| r.signing_key_env.as_str()),
        );
        let push_fingerprint = resolve(
            self.record_push_ssh_fingerprint.as_ref(),
            ex.map(|r| r.push_ssh_fingerprint.as_str()),
        );
        let contexts: Vec<String> = if !self.record_contexts.is_empty() {
            self.record_contexts.clone()
        } else {
            ex.map(|r| r.contexts.clone()).unwrap_or_default()
        };

        if is_non_interactive(self.dry_run) {
            let enabled = self.record || ex.map(|r| r.enabled).unwrap_or(false);
            return build_record_config(
                enabled,
                gpg_key.as_deref(),
                gpg_trust.as_deref(),
                user_name.as_deref(),
                user_email.as_deref(),
                sign_key.as_deref(),
                push_fingerprint.as_deref(),
                &contexts,
            );
        }

        let enabled = if self.record {
            true
        } else {
            dialoguer::Confirm::new()
                .with_prompt("Enable auto-record (CI signs + pushes the regenerated orb)?")
                .default(ex.map(|r| r.enabled).unwrap_or(false))
                .interact()?
        };
        if !enabled {
            return Ok(None);
        }

        use dialoguer::Input;
        let prompt_name = |label: &str, current: Option<String>| -> Result<String> {
            let mut input = Input::<String>::new().with_prompt(label);
            if let Some(c) = current.filter(|s| !s.is_empty()) {
                input = input.default(c);
            }
            Ok(input.interact_text()?)
        };
        let gpg_key = prompt_name("Env var name — base64 GPG private key", gpg_key)?;
        let gpg_trust = prompt_name("Env var name — GPG ownertrust export", gpg_trust)?;
        let user_name = prompt_name("Env var name — committer name", user_name)?;
        let user_email = prompt_name("Env var name — committer email", user_email)?;
        let sign_key = prompt_name("Env var name — GPG signing key id", sign_key)?;
        // Optional: a fingerprint VALUE (public-key hash), or empty for ambient.
        let push_fingerprint = prompt_name(
            "SSH key fingerprint for the push job (optional; empty = ambient credentials)",
            push_fingerprint,
        )?;
        let contexts_default = if contexts.is_empty() {
            None
        } else {
            Some(contexts.join(","))
        };
        let contexts_raw = prompt_name(
            "CircleCI context(s) supplying the GPG signing material, comma-separated",
            contexts_default,
        )?;
        let contexts: Vec<String> = contexts_raw
            .split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .collect();
        build_record_config(
            true,
            Some(&gpg_key),
            Some(&gpg_trust),
            Some(&user_name),
            Some(&user_email),
            Some(&sign_key),
            Some(&push_fingerprint),
            &contexts,
        )
    }

    pub(crate) fn gather_extras(
        &self,
        detected: &[String],
        existing: &OrbConfig,
    ) -> Result<GatheredExtras> {
        // Resolution order: CLI flag > existing config > auto-detected / hardcoded default.
        let existing_ci = existing.ci.as_ref();
        let existing_orb = existing.orb.as_ref();
        let record = self.gather_record(existing)?;

        let effective_push = if !self.git_push_subcommands.is_empty() {
            self.git_push_subcommands.clone()
        } else {
            existing_orb
                .and_then(|o| o.git_push_subcommands.clone())
                .filter(|v| !v.is_empty())
                .unwrap_or_else(|| detected.to_vec())
        };

        if is_non_interactive(self.dry_run) {
            return Ok(GatheredExtras {
                home_url: self
                    .home_url
                    .clone()
                    .or_else(|| existing_orb.and_then(|o| o.home_url.clone())),
                source_url: self
                    .source_url
                    .clone()
                    .or_else(|| existing_orb.and_then(|o| o.source_url.clone())),
                git_push_subcommands: effective_push,
                docker_context: self
                    .docker_context
                    .clone()
                    .or_else(|| existing_ci.and_then(|ci| ci.docker_context.clone()))
                    .unwrap_or_else(|| DEFAULT_DOCKER_CONTEXT.to_string()),
                orb_context: self
                    .orb_context
                    .clone()
                    .or_else(|| existing_ci.and_then(|ci| ci.orb_context.clone()))
                    .unwrap_or_else(|| DEFAULT_ORB_CONTEXT.to_string()),
                mcp_context: if !self.mcp_context.is_empty() {
                    self.mcp_context.clone()
                } else {
                    existing_ci
                        .and_then(|ci| ci.mcp_context.clone())
                        .filter(|v| !v.is_empty())
                        .unwrap_or_else(|| vec![DEFAULT_MCP_CONTEXT.to_string()])
                },
                mcp_earliest_version: self
                    .mcp_earliest_version
                    .clone()
                    .or_else(|| existing_ci.and_then(|ci| ci.mcp_earliest_version.clone()))
                    .unwrap_or_else(|| DEFAULT_MCP_EARLIEST_VERSION.to_string()),
                record,
            });
        }

        // Interactive mode — prompt only for fields not already provided via CLI flag.
        // For un-set fields, the existing config value becomes the prompt default.
        use dialoguer::Input;

        let home_url = if let Some(v) = self.home_url.clone() {
            Some(v).filter(|s| !s.is_empty())
        } else {
            let default = existing_orb
                .and_then(|o| o.home_url.clone())
                .unwrap_or_default();
            let val = Input::<String>::new()
                .with_prompt("Home URL for orb registry (Enter to skip)")
                .default(default)
                .allow_empty(true)
                .interact_text()?;
            if val.is_empty() {
                None
            } else {
                Some(val)
            }
        };

        let source_url = if let Some(v) = self.source_url.clone() {
            Some(v).filter(|s| !s.is_empty())
        } else {
            let default = existing_orb
                .and_then(|o| o.source_url.clone())
                .unwrap_or_default();
            let val = Input::<String>::new()
                .with_prompt("Source URL for orb registry (Enter to skip)")
                .default(default)
                .allow_empty(true)
                .interact_text()?;
            if val.is_empty() {
                None
            } else {
                Some(val)
            }
        };

        let git_push_subcommands = if !self.git_push_subcommands.is_empty() {
            effective_push
        } else {
            let cfg_push = existing_orb
                .and_then(|o| o.git_push_subcommands.clone())
                .unwrap_or_default();
            let current = if !cfg_push.is_empty() {
                cfg_push.join(",")
            } else {
                detected.join(",")
            };
            let prompt = if !detected.is_empty() && cfg_push.is_empty() {
                format!(
                    "Push-capable subcommands detected: {} — confirm or override (comma-separated)",
                    detected.join(", ")
                )
            } else {
                "Subcommands that push to git, comma-separated (e.g. save)".to_string()
            };
            let val = Input::<String>::new()
                .with_prompt(prompt)
                .default(current)
                .allow_empty(true)
                .interact_text()?;
            val.split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect()
        };

        let docker_context = if let Some(v) = self.docker_context.clone() {
            v
        } else {
            let default = existing_ci
                .and_then(|ci| ci.docker_context.clone())
                .unwrap_or_else(|| DEFAULT_DOCKER_CONTEXT.to_string());
            Input::<String>::new()
                .with_prompt("Docker context name (needs: DOCKER_LOGIN, DOCKER_PASSWORD)")
                .default(default)
                .interact_text()?
        };

        let orb_context = if let Some(v) = self.orb_context.clone() {
            v
        } else {
            let default = existing_ci
                .and_then(|ci| ci.orb_context.clone())
                .unwrap_or_else(|| DEFAULT_ORB_CONTEXT.to_string());
            Input::<String>::new()
                .with_prompt("Orb publishing context name (needs: CIRCLECI_CLI_TOKEN)")
                .default(default)
                .interact_text()?
        };

        let mcp_context = if self.mcp {
            if !self.mcp_context.is_empty() {
                self.mcp_context.clone()
            } else {
                let default = existing_ci
                    .and_then(|ci| ci.mcp_context.as_ref())
                    .filter(|v| !v.is_empty())
                    .map(|v| v.join(","))
                    .unwrap_or_else(|| DEFAULT_MCP_CONTEXT.to_string());
                let val = Input::<String>::new()
                    .with_prompt(
                        "MCP context names, comma-separated (needs: GITHUB_TOKEN with contents:write + bypass branch protection, BOT_GPG_KEY, BOT_TRUST, BOT_USER_NAME, BOT_USER_EMAIL, BOT_SIGN_KEY)",
                    )
                    .default(default)
                    .interact_text()?;
                val.split(',')
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(str::to_string)
                    .collect()
            }
        } else if !self.mcp_context.is_empty() {
            self.mcp_context.clone()
        } else {
            existing_ci
                .and_then(|ci| ci.mcp_context.clone())
                .filter(|v| !v.is_empty())
                .unwrap_or_else(|| vec![DEFAULT_MCP_CONTEXT.to_string()])
        };

        let mcp_earliest_version = if self.mcp {
            if let Some(v) = self.mcp_earliest_version.clone() {
                v
            } else {
                let default = existing_ci
                    .and_then(|ci| ci.mcp_earliest_version.clone())
                    .unwrap_or_else(|| DEFAULT_MCP_EARLIEST_VERSION.to_string());
                Input::<String>::new()
                    .with_prompt("Earliest orb version to include in MCP snapshots")
                    .default(default)
                    .interact_text()?
            }
        } else {
            self.mcp_earliest_version
                .clone()
                .or_else(|| existing_ci.and_then(|ci| ci.mcp_earliest_version.clone()))
                .unwrap_or_else(|| DEFAULT_MCP_EARLIEST_VERSION.to_string())
        };

        Ok(GatheredExtras {
            home_url,
            source_url,
            git_push_subcommands,
            docker_context,
            orb_context,
            mcp_context,
            mcp_earliest_version,
            record,
        })
    }

    /// Decide which of the present default-interactive subcommands to reserve as
    /// interactive/CLI-only (fully excluded from the orb). Interactive terminal:
    /// prompt per subcommand, defaulting to reserved so the user confirms/overrides
    /// in the initial scaffold. Non-interactive (CI/dry-run): reserve all (the safe
    /// default), so the scaffold still records the choice explicitly.
    fn resolve_interactive(&self, present: &[String]) -> Result<Vec<(String, bool)>> {
        if is_non_interactive(self.dry_run) {
            return Ok(present.iter().map(|n| (n.clone(), true)).collect());
        }
        present
            .iter()
            .map(|name| -> Result<(String, bool)> {
                let reserve = dialoguer::Confirm::new()
                    .with_prompt(format!(
                        "Reserve `{name}` as interactive-only (CLI setup — excluded from the CI orb)?"
                    ))
                    .default(true)
                    .interact()?;
                Ok((name.clone(), reserve))
            })
            .collect()
    }

    pub fn run(&self) -> Result<()> {
        // Parse binary early: detect push-capable subcommands (for dialogue default)
        // and subcommands with a required orb_path param (for config defaults).
        let (detected_push, detected_orb_path, present_interactive) =
            match crate::help_parser::parse_binary(&self.binary) {
                Ok(cli) => (
                    detect_git_push_subcommands(&cli),
                    detect_orb_path_subcommands(&cli),
                    present_default_interactive(&cli),
                ),
                Err(_) => (vec![], vec![], vec![]),
            };

        let config_path = std::path::Path::new("gen-circleci-orb.toml");
        let existing_config = crate::orb_config::load_config(config_path)?;
        let extras = self.gather_extras(&detected_push, &existing_config)?;
        let namespaces: Vec<String> = self
            .public_orb_namespaces
            .iter()
            .chain(self.private_orb_namespaces.iter())
            .cloned()
            .collect();

        // Step 1: generate orb source files
        tracing::info!("Generating orb source into ./{}", self.orb_dir);
        let gen = Generate {
            binary: Some(self.binary.clone()),
            namespaces: namespaces.clone(),
            output: PathBuf::from("."),
            orb_dir: Some(self.orb_dir.clone()),
            install_method: None,
            base_image: None,
            home_url: extras.home_url.clone(),
            source_url: extras.source_url.clone(),
            git_push_subcommands: extras.git_push_subcommands.clone(),
            circleci_cli_version: None,
            apt_packages: vec![],
            dry_run: self.dry_run,
            config: None,
            // init is a local bootstrap, not a CI run — never auto-record/push.
            no_record: true,
            // init writes the orb for real; verify-only check mode is off.
            check: false,
        };
        gen.run()?;

        // Step 2: patch CI configs
        let opts = ci_patcher::PatchOpts {
            binary: self.binary.clone(),
            // Advanced knob — not gathered at init; set `[orb] rust_image` in the
            // toml when the workspace needs a clang-equipped build image.
            rust_image: String::new(),
            namespaces,
            docker_namespace: self.docker_namespace.clone(),
            orb_dir: self.orb_dir.clone(),
            build_workflow: self.build_workflow.clone(),
            release_workflow: self.release_workflow.clone(),
            requires_job: self.requires_job.clone(),
            crate_tag_prefix: self.crate_tag_prefix.clone(),
            release_after_job: self.release_after_job.clone(),
            orb_tools_version: self.orb_tools_version.clone(),
            docker_orb_version: self.docker_orb_version.clone(),
            docker_context: extras.docker_context.clone(),
            orb_context: extras.orb_context.clone(),
            private_namespaces: self.private_orb_namespaces.clone(),
            gen_circleci_orb_version: self.gen_circleci_orb_version.clone(),
            mcp: self.mcp,
            mcp_earliest_version: extras.mcp_earliest_version.clone(),
            mcp_context: extras.mcp_context.clone(),
            gen_orb_mcp_orb_version: DEFAULT_GEN_ORB_MCP_ORB_VERSION.to_string(),
            record_contexts: extras
                .record
                .as_ref()
                .map(|r| r.contexts.clone())
                .unwrap_or_default(),
            record_push_ssh_fingerprint: extras
                .record
                .as_ref()
                .map(|r| r.push_ssh_fingerprint.clone())
                .unwrap_or_default(),
        };

        let summary = ci_patcher::apply_patches(&self.ci_dir, &opts, self.dry_run)?;
        for line in &summary {
            println!("{line}");
        }

        // Step 3: write bootstrap gen-circleci-orb.toml
        let config_path = std::path::Path::new("gen-circleci-orb.toml");
        let interactive = self.resolve_interactive(&present_interactive)?;
        let mut bootstrap = build_bootstrap_config(
            &self.binary,
            opts.namespaces.as_slice(),
            &self.orb_dir,
            extras.home_url.as_deref(),
            extras.source_url.as_deref(),
            &extras.git_push_subcommands,
            &interactive,
        );
        populate_orb_path_defaults(&mut bootstrap, &detected_orb_path);
        bootstrap.ci = Some(CiSection {
            build_workflow: Some(self.build_workflow.clone()),
            release_workflow: Some(self.release_workflow.clone()),
            requires_job: self.requires_job.clone(),
            release_after_job: Some(self.release_after_job.clone()),
            crate_tag_prefix: Some(self.crate_tag_prefix.clone()),
            docker_namespace: Some(self.docker_namespace.clone()),
            docker_context: Some(extras.docker_context.clone()),
            orb_context: Some(extras.orb_context.clone()),
            mcp: Some(self.mcp),
            mcp_context: Some(extras.mcp_context.clone()),
            mcp_earliest_version: Some(extras.mcp_earliest_version.clone()),
            // Left unset so the pin tracks the generator default (like the
            // gen-circleci-orb pin); set it in the toml only to override.
            gen_orb_mcp_orb_version: None,
            // Advanced knob — not gathered at init; set `[ci] rust_image` in the
            // toml when the workspace needs a clang-equipped build image.
            rust_image: None,
        });
        bootstrap.record = extras.record.clone();
        if self.dry_run {
            let content = toml::to_string_pretty(&bootstrap)?;
            println!("(dry-run) Would write {}", config_path.display());
            println!("{content}");
            println!("(dry-run: no files written)");
        } else {
            crate::orb_config::save_config(config_path, &bootstrap)?;
            println!("Wrote {}", config_path.display());
            println!("Done.");
        }

        Ok(())
    }
}

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

    #[test]
    fn default_docker_orb_version_matches_registry() {
        // The CircleCI registry has circleci/docker@3.0.1 as latest.
        // 3.2.0 does not exist and causes "Cannot find circleci/docker@3.2.0" errors.
        assert_eq!(
            DEFAULT_DOCKER_ORB_VERSION, "3.0.1",
            "DEFAULT_DOCKER_ORB_VERSION must be the registry-available version"
        );
    }

    // ── Phase 6: bootstrap config written by init ───────────────────────────

    #[test]
    fn bootstrap_config_has_orb_section_with_binary() {
        let config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            None,
            None,
            &[],
            &[],
        );
        assert!(
            config.orb.is_some(),
            "bootstrap config must have [orb] section"
        );
        assert_eq!(
            config.orb.as_ref().unwrap().binary.as_deref(),
            Some("mytool")
        );
    }

    #[test]
    fn bootstrap_config_has_namespaces() {
        let config = build_bootstrap_config(
            "mytool",
            &["ns1".to_string(), "ns2".to_string()],
            "orb",
            None,
            None,
            &[],
            &[],
        );
        assert_eq!(
            config.orb.as_ref().unwrap().namespaces.as_deref(),
            Some(&["ns1".to_string(), "ns2".to_string()][..])
        );
    }

    #[test]
    fn bootstrap_config_scaffolds_interactive_decisions() {
        // The bootstrap scaffolds the init-time interactive decisions explicitly
        // (init reserved, config opted in) and does NOT emit a help entry — help is
        // reserved at the --help parser.
        let config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            None,
            None,
            &[],
            &[("init".to_string(), true), ("config".to_string(), false)],
        );
        let subcommands = config
            .subcommand
            .as_ref()
            .expect("subcommand section missing");
        assert_eq!(subcommands.get("init").unwrap().interactive, Some(true));
        assert_eq!(subcommands.get("config").unwrap().interactive, Some(false));
        assert!(
            !subcommands.contains_key("help"),
            "help is parser-reserved, not scaffolded into the toml"
        );
    }

    #[test]
    fn bootstrap_config_has_no_subcommand_section_without_interactive() {
        let config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            None,
            None,
            &[],
            &[],
        );
        assert!(
            config.subcommand.is_none(),
            "no interactive decisions → no [subcommand] section"
        );
    }

    #[test]
    fn present_default_interactive_returns_only_present_defaults() {
        use crate::help_parser::types::{CliDefinition, SubCommand};
        let sub = |name: &str| SubCommand {
            name: name.to_string(),
            description: String::new(),
            is_leaf: true,
            parameters: vec![],
            subcommands: vec![],
        };
        // `init` is a default-interactive name present here; `run` is not; `config`
        // is absent → only `init` is returned (the prompt fires only for present names).
        let cli = CliDefinition {
            binary_name: "mytool".to_string(),
            description: String::new(),
            subcommands: vec![sub("init"), sub("run")],
        };
        assert_eq!(present_default_interactive(&cli), vec!["init".to_string()]);
    }

    #[test]
    fn init_has_git_push_subcommands_field() {
        // Init must expose --git-push-subcommands so the caller can name subcommands
        // (e.g. "save") that need a set_https_remote step in their generated job.
        let init = Init {
            binary: "mytool".to_string(),
            public_orb_namespaces: vec!["my-org".to_string()],
            private_orb_namespaces: vec![],
            build_workflow: "validation".to_string(),
            release_workflow: "orb-release".to_string(),
            requires_job: None,
            crate_tag_prefix: "mytool-v".to_string(),
            release_after_job: "publish-orb".to_string(),
            orb_dir: "orb".to_string(),
            ci_dir: std::path::PathBuf::from(".circleci"),
            orb_tools_version: "12.3.3".to_string(),
            docker_orb_version: "3.0.1".to_string(),
            docker_namespace: "my-docker-ns".to_string(),
            docker_context: None,
            orb_context: None,
            gen_circleci_orb_version: "0.0.1".to_string(),
            mcp: false,
            mcp_earliest_version: None,
            mcp_context: vec![],
            dry_run: false,
            git_push_subcommands: vec!["save".to_string()],
            home_url: None,
            source_url: None,
            record: false,
            record_gpg_key_env: None,
            record_gpg_trust_env: None,
            record_user_name_env: None,
            record_user_email_env: None,
            record_signing_key_env: None,
            record_push_ssh_fingerprint: None,
            record_contexts: vec![],
        };
        assert_eq!(
            init.git_push_subcommands,
            vec!["save".to_string()],
            "Init must hold git_push_subcommands and pass it through to Generate"
        );
    }

    #[test]
    fn bootstrap_config_includes_git_push_subcommands() {
        let config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            None,
            None,
            &["save".to_string()],
            &[],
        );
        assert_eq!(
            config.orb.as_ref().unwrap().git_push_subcommands.as_deref(),
            Some(&["save".to_string()][..])
        );
    }

    #[test]
    fn bootstrap_config_git_push_subcommands_none_when_empty() {
        let config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            None,
            None,
            &[],
            &[],
        );
        assert_eq!(
            config.orb.as_ref().unwrap().git_push_subcommands,
            None,
            "empty slice must produce None (not an empty list) to keep the TOML clean"
        );
    }

    #[test]
    fn init_run_writes_ci_section_to_config() {
        let init = make_init(true);
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        let ci = CiSection {
            build_workflow: Some(init.build_workflow.clone()),
            release_workflow: Some(init.release_workflow.clone()),
            requires_job: init.requires_job.clone(),
            release_after_job: Some(init.release_after_job.clone()),
            crate_tag_prefix: Some(init.crate_tag_prefix.clone()),
            docker_namespace: Some(init.docker_namespace.clone()),
            docker_context: Some(extras.docker_context.clone()),
            orb_context: Some(extras.orb_context.clone()),
            mcp: Some(init.mcp),
            mcp_context: Some(extras.mcp_context.clone()),
            mcp_earliest_version: Some(extras.mcp_earliest_version.clone()),
            gen_orb_mcp_orb_version: None,
            rust_image: None,
        };
        assert_eq!(ci.build_workflow.as_deref(), Some("validation"));
        assert_eq!(ci.docker_context.as_deref(), Some(DEFAULT_DOCKER_CONTEXT));
        assert_eq!(ci.mcp, Some(false));
    }

    #[test]
    fn bootstrap_config_includes_home_and_source_url() {
        let config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            Some("https://example.com/home"),
            Some("https://example.com/source"),
            &[],
            &[],
        );
        assert_eq!(
            config.orb.as_ref().unwrap().home_url.as_deref(),
            Some("https://example.com/home")
        );
        assert_eq!(
            config.orb.as_ref().unwrap().source_url.as_deref(),
            Some("https://example.com/source")
        );
    }

    // ── detect_orb_path_subcommands + populate_orb_path_defaults ───────────

    fn make_cli_with_orb_path(
        sub_name: &str,
        required: bool,
    ) -> crate::help_parser::types::CliDefinition {
        use crate::help_parser::types::{CliDefinition, ParamType, Parameter, SubCommand};
        let p = Parameter {
            long_name: "orb_path".to_string(),
            short: Some('p'),
            param_type: ParamType::String,
            default: None,
            required,
            description: "Path to orb YAML".to_string(),
        };
        let sub = SubCommand {
            name: sub_name.to_string(),
            description: String::new(),
            is_leaf: true,
            parameters: vec![p],
            subcommands: vec![],
        };
        CliDefinition {
            binary_name: "mytool".to_string(),
            description: "My tool".to_string(),
            subcommands: vec![sub],
        }
    }

    #[test]
    fn detect_required_orb_path_subcommand() {
        let cli = make_cli_with_orb_path("generate", true);
        let detected = detect_orb_path_subcommands(&cli);
        assert_eq!(detected, vec!["generate".to_string()]);
    }

    #[test]
    fn optional_orb_path_not_detected() {
        let cli = make_cli_with_orb_path("generate", false);
        let detected = detect_orb_path_subcommands(&cli);
        assert!(
            detected.is_empty(),
            "optional orb_path must not trigger default injection"
        );
    }

    #[test]
    fn populate_orb_path_defaults_adds_subcommand_entries() {
        let mut config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            None,
            None,
            &[],
            &[],
        );
        populate_orb_path_defaults(
            &mut config,
            &["generate".to_string(), "validate".to_string()],
        );
        let subcommands = config.subcommand.as_ref().unwrap();
        let gen_params = subcommands.get("generate").unwrap().param.as_ref().unwrap();
        assert_eq!(
            gen_params.get("orb_path").unwrap().default.as_deref(),
            Some("src/@orb.yml")
        );
        let val_params = subcommands.get("validate").unwrap().param.as_ref().unwrap();
        assert_eq!(
            val_params.get("orb_path").unwrap().default.as_deref(),
            Some("src/@orb.yml")
        );
    }

    #[test]
    fn populate_orb_path_defaults_preserves_existing_subcommand_entries() {
        // An existing interactive entry (init reserved) must not be disturbed when
        // populate adds orb_path param defaults for another subcommand.
        let mut config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            None,
            None,
            &[],
            &[("init".to_string(), true)],
        );
        populate_orb_path_defaults(&mut config, &["generate".to_string()]);
        let subcommands = config.subcommand.as_ref().unwrap();
        assert_eq!(subcommands.get("init").unwrap().interactive, Some(true));
    }

    #[test]
    fn populate_orb_path_defaults_noop_when_empty() {
        let mut config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "orb",
            None,
            None,
            &[],
            &[],
        );
        let before = config.subcommand.clone();
        populate_orb_path_defaults(&mut config, &[]);
        assert_eq!(
            config.subcommand, before,
            "no change when no subcommands detected"
        );
    }

    // ── detect_git_push_subcommands ─────────────────────────────────────────

    #[test]
    fn detect_push_subcommand_with_push_param() {
        use crate::help_parser::types::{CliDefinition, ParamType, Parameter, SubCommand};
        let push_param = Parameter {
            long_name: "push".to_string(),
            short: None,
            param_type: ParamType::Enum(vec!["true".to_string(), "false".to_string()]),
            default: Some("true".to_string()),
            required: false,
            description: "Push after committing".to_string(),
        };
        let sub = SubCommand {
            name: "save".to_string(),
            description: "Save artifacts".to_string(),
            is_leaf: true,
            parameters: vec![push_param],
            subcommands: vec![],
        };
        let cli = CliDefinition {
            binary_name: "mytool".to_string(),
            description: "My tool".to_string(),
            subcommands: vec![sub],
        };
        let detected = detect_git_push_subcommands(&cli);
        assert_eq!(detected, vec!["save".to_string()]);
    }

    #[test]
    fn detect_push_subcommand_with_sign_param() {
        use crate::help_parser::types::{CliDefinition, ParamType, Parameter, SubCommand};
        let sign_param = Parameter {
            long_name: "sign".to_string(),
            short: None,
            param_type: ParamType::Boolean,
            default: None,
            required: false,
            description: "GPG sign".to_string(),
        };
        let sub = SubCommand {
            name: "commit".to_string(),
            description: "Commit".to_string(),
            is_leaf: true,
            parameters: vec![sign_param],
            subcommands: vec![],
        };
        let cli = CliDefinition {
            binary_name: "mytool".to_string(),
            description: "My tool".to_string(),
            subcommands: vec![sub],
        };
        let detected = detect_git_push_subcommands(&cli);
        assert_eq!(detected, vec!["commit".to_string()]);
    }

    #[test]
    fn non_push_subcommand_not_detected() {
        use crate::help_parser::types::{CliDefinition, ParamType, Parameter, SubCommand};
        let other_param = Parameter {
            long_name: "output".to_string(),
            short: None,
            param_type: ParamType::String,
            default: Some("./dist".to_string()),
            required: false,
            description: "Output dir".to_string(),
        };
        let sub = SubCommand {
            name: "generate".to_string(),
            description: "Generate".to_string(),
            is_leaf: true,
            parameters: vec![other_param],
            subcommands: vec![],
        };
        let cli = CliDefinition {
            binary_name: "mytool".to_string(),
            description: "My tool".to_string(),
            subcommands: vec![sub],
        };
        let detected = detect_git_push_subcommands(&cli);
        assert!(detected.is_empty());
    }

    #[test]
    fn gather_extras_uses_detected_when_cli_empty() {
        let init = make_init(true); // dry_run = true → non-interactive
        let extras = init
            .gather_extras(&["save".to_string()], &OrbConfig::default())
            .unwrap();
        assert_eq!(
            extras.git_push_subcommands,
            vec!["save".to_string()],
            "detected candidates must be used when --git-push-subcommands not set"
        );
    }

    #[test]
    fn gather_extras_cli_overrides_detected() {
        let init = Init {
            git_push_subcommands: vec!["custom".to_string()],
            dry_run: true,
            ..make_init(true)
        };
        let extras = init
            .gather_extras(&["save".to_string()], &OrbConfig::default())
            .unwrap();
        assert_eq!(
            extras.git_push_subcommands,
            vec!["custom".to_string()],
            "explicit CLI value must override detected candidates"
        );
    }

    // ── gather_extras / dialogue ────────────────────────────────────────────

    fn make_init(dry_run: bool) -> Init {
        Init {
            binary: "mytool".to_string(),
            public_orb_namespaces: vec!["my-org".to_string()],
            private_orb_namespaces: vec![],
            build_workflow: "validation".to_string(),
            release_workflow: "orb-release".to_string(),
            requires_job: None,
            crate_tag_prefix: "mytool-v".to_string(),
            release_after_job: "publish-orb".to_string(),
            orb_dir: "orb".to_string(),
            ci_dir: std::path::PathBuf::from(".circleci"),
            orb_tools_version: "12.3.3".to_string(),
            docker_orb_version: "3.0.1".to_string(),
            docker_namespace: "my-docker-ns".to_string(),
            docker_context: None,
            orb_context: None,
            gen_circleci_orb_version: "0.0.1".to_string(),
            mcp: false,
            mcp_earliest_version: None,
            mcp_context: vec![],
            dry_run,
            git_push_subcommands: vec![],
            home_url: None,
            source_url: None,
            record: false,
            record_gpg_key_env: None,
            record_gpg_trust_env: None,
            record_user_name_env: None,
            record_user_email_env: None,
            record_signing_key_env: None,
            record_push_ssh_fingerprint: None,
            record_contexts: vec![],
        }
    }

    // ── build_record_config ─────────────────────────────────────────────────

    #[test]
    fn build_record_config_disabled_returns_none() {
        let rec = build_record_config(false, None, None, None, None, None, None, &[])
            .expect("disabled is ok");
        assert!(rec.is_none(), "disabled must yield no [record] section");
    }

    #[test]
    fn build_record_config_collects_names_and_contexts() {
        let rec = build_record_config(
            true,
            Some("G_KEY"),
            Some("G_TRUST"),
            Some("G_NAME"),
            Some("G_EMAIL"),
            Some("G_SIGN"),
            None,
            &["release".to_string()],
        )
        .expect("all values present")
        .expect("enabled yields Some");
        assert!(rec.enabled);
        assert_eq!(rec.gpg_key_env, "G_KEY");
        assert_eq!(rec.signing_key_env, "G_SIGN");
        assert_eq!(rec.contexts, vec!["release"]);
    }

    #[test]
    fn build_record_config_errors_when_enabled_without_name() {
        let err = build_record_config(
            true,
            None, // missing gpg key env name
            Some("G_TRUST"),
            Some("G_NAME"),
            Some("G_EMAIL"),
            Some("G_SIGN"),
            None,
            &["release".to_string()],
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("--record-gpg-key-env"), "unexpected: {err}");
    }

    #[test]
    fn build_record_config_errors_when_enabled_without_context() {
        let err = build_record_config(
            true,
            Some("G_KEY"),
            Some("G_TRUST"),
            Some("G_NAME"),
            Some("G_EMAIL"),
            Some("G_SIGN"),
            None,
            &[], // no context supplied
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("--record-context"), "unexpected: {err}");
    }

    #[test]
    fn gather_extras_non_interactive_uses_hardcoded_defaults() {
        let init = make_init(true); // dry_run=true → non-interactive
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        assert_eq!(extras.docker_context, DEFAULT_DOCKER_CONTEXT);
        assert_eq!(extras.orb_context, DEFAULT_ORB_CONTEXT);
        assert_eq!(extras.mcp_context, vec![DEFAULT_MCP_CONTEXT.to_string()]);
        assert_eq!(extras.mcp_earliest_version, DEFAULT_MCP_EARLIEST_VERSION);
        assert_eq!(extras.home_url, None);
        assert_eq!(extras.source_url, None);
        assert!(extras.git_push_subcommands.is_empty());
    }

    #[test]
    fn gather_extras_cli_values_take_precedence_over_defaults() {
        let init = Init {
            docker_context: Some("my-docker".to_string()),
            orb_context: Some("my-orb-ctx".to_string()),
            mcp_context: vec!["my-mcp-ctx".to_string()],
            mcp_earliest_version: Some("1.2.3".to_string()),
            home_url: Some("https://example.com".to_string()),
            source_url: Some("https://src.example.com".to_string()),
            git_push_subcommands: vec!["save".to_string()],
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        assert_eq!(extras.docker_context, "my-docker");
        assert_eq!(extras.orb_context, "my-orb-ctx");
        assert_eq!(extras.mcp_context, vec!["my-mcp-ctx".to_string()]);
        assert_eq!(extras.mcp_earliest_version, "1.2.3");
        assert_eq!(extras.home_url.as_deref(), Some("https://example.com"));
        assert_eq!(
            extras.source_url.as_deref(),
            Some("https://src.example.com")
        );
        assert_eq!(extras.git_push_subcommands, vec!["save"]);
    }

    #[test]
    fn gather_extras_ci_env_var_is_non_interactive() {
        // When $CI is set the dialogue must be skipped even without --dry-run
        std::env::set_var("CI", "true");
        let init = make_init(false);
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        std::env::remove_var("CI");
        assert_eq!(extras.docker_context, DEFAULT_DOCKER_CONTEXT);
    }

    // ── gather_extras: skip prompts when field is explicitly set ───────────

    #[test]
    fn gather_extras_skips_docker_context_prompt_when_set() {
        let init = Init {
            docker_context: Some("explicit-docker".to_string()),
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        assert_eq!(extras.docker_context, "explicit-docker");
    }

    #[test]
    fn gather_extras_skips_orb_context_prompt_when_set() {
        let init = Init {
            orb_context: Some("explicit-orb".to_string()),
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        assert_eq!(extras.orb_context, "explicit-orb");
    }

    #[test]
    fn gather_extras_skips_mcp_context_prompt_when_set() {
        let init = Init {
            mcp: true,
            mcp_context: vec!["ctx-a".to_string(), "ctx-b".to_string()],
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        assert_eq!(extras.mcp_context, vec!["ctx-a", "ctx-b"]);
    }

    #[test]
    fn gather_extras_skips_mcp_earliest_version_prompt_when_set() {
        let init = Init {
            mcp: true,
            mcp_earliest_version: Some("3.0.0".to_string()),
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        assert_eq!(extras.mcp_earliest_version, "3.0.0");
    }

    #[test]
    fn gather_extras_skips_git_push_subcommands_prompt_when_set() {
        let init = Init {
            git_push_subcommands: vec!["deploy".to_string()],
            dry_run: true,
            ..make_init(true)
        };
        // detected list is different — CLI must win without prompting
        let extras = init
            .gather_extras(&["save".to_string()], &OrbConfig::default())
            .unwrap();
        assert_eq!(extras.git_push_subcommands, vec!["deploy"]);
    }

    #[test]
    fn gather_extras_skips_home_url_prompt_when_set() {
        let init = Init {
            home_url: Some("https://example.com/home".to_string()),
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        assert_eq!(extras.home_url.as_deref(), Some("https://example.com/home"));
    }

    #[test]
    fn gather_extras_skips_source_url_prompt_when_set() {
        let init = Init {
            source_url: Some("https://example.com/src".to_string()),
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &OrbConfig::default()).unwrap();
        assert_eq!(
            extras.source_url.as_deref(),
            Some("https://example.com/src")
        );
    }

    // ── gather_extras: existing config as fallback ─────────────────────────

    fn make_existing_config() -> OrbConfig {
        use crate::orb_config::CiSection;
        OrbConfig {
            orb: Some(OrbSection {
                home_url: Some("https://existing-home.example.com".to_string()),
                source_url: Some("https://existing-src.example.com".to_string()),
                git_push_subcommands: Some(vec!["existing-push".to_string()]),
                ..OrbSection::default()
            }),
            ci: Some(CiSection {
                docker_context: Some("existing-docker".to_string()),
                orb_context: Some("existing-orb".to_string()),
                mcp_context: Some(vec!["existing-mcp".to_string()]),
                mcp_earliest_version: Some("9.9.9".to_string()),
                ..CiSection::default()
            }),
            ..OrbConfig::default()
        }
    }

    #[test]
    fn gather_extras_falls_back_to_existing_docker_context() {
        let init = make_init(true); // dry_run → non-interactive
        let extras = init.gather_extras(&[], &make_existing_config()).unwrap();
        assert_eq!(
            extras.docker_context, "existing-docker",
            "should use [ci].docker_context from existing config when CLI flag not set"
        );
    }

    #[test]
    fn gather_extras_falls_back_to_existing_orb_context() {
        let init = make_init(true);
        let extras = init.gather_extras(&[], &make_existing_config()).unwrap();
        assert_eq!(extras.orb_context, "existing-orb");
    }

    #[test]
    fn gather_extras_falls_back_to_existing_mcp_context() {
        let init = Init {
            mcp: true,
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &make_existing_config()).unwrap();
        assert_eq!(extras.mcp_context, vec!["existing-mcp"]);
    }

    #[test]
    fn gather_extras_falls_back_to_existing_mcp_earliest_version() {
        let init = make_init(true);
        let extras = init.gather_extras(&[], &make_existing_config()).unwrap();
        assert_eq!(extras.mcp_earliest_version, "9.9.9");
    }

    #[test]
    fn gather_extras_falls_back_to_existing_home_url() {
        let init = make_init(true);
        let extras = init.gather_extras(&[], &make_existing_config()).unwrap();
        assert_eq!(
            extras.home_url.as_deref(),
            Some("https://existing-home.example.com")
        );
    }

    #[test]
    fn gather_extras_falls_back_to_existing_source_url() {
        let init = make_init(true);
        let extras = init.gather_extras(&[], &make_existing_config()).unwrap();
        assert_eq!(
            extras.source_url.as_deref(),
            Some("https://existing-src.example.com")
        );
    }

    #[test]
    fn gather_extras_falls_back_to_existing_git_push_subcommands() {
        let init = make_init(true);
        // No CLI flag, no detected — should fall back to existing config
        let extras = init.gather_extras(&[], &make_existing_config()).unwrap();
        assert_eq!(extras.git_push_subcommands, vec!["existing-push"]);
    }

    #[test]
    fn gather_extras_cli_takes_precedence_over_existing_config() {
        let init = Init {
            docker_context: Some("cli-docker".to_string()),
            orb_context: Some("cli-orb".to_string()),
            dry_run: true,
            ..make_init(true)
        };
        let extras = init.gather_extras(&[], &make_existing_config()).unwrap();
        assert_eq!(extras.docker_context, "cli-docker");
        assert_eq!(extras.orb_context, "cli-orb");
    }

    #[test]
    fn gather_extras_detected_used_when_neither_cli_nor_config_has_push_subcommands() {
        let init = make_init(true);
        let existing = OrbConfig::default(); // no git_push_subcommands in config
        let extras = init
            .gather_extras(&["detected-push".to_string()], &existing)
            .unwrap();
        assert_eq!(extras.git_push_subcommands, vec!["detected-push"]);
    }

    #[test]
    fn is_non_interactive_reflects_tty_state() {
        // Verify that is_non_interactive() correctly responds to the TTY state
        // of the current process. CI environments may allocate a PTY; local
        // subprocess runs (e.g. cargo test piped) do not.
        let ci_was = std::env::var("CI").ok();
        std::env::remove_var("CI");
        let is_tty = console::Term::stderr().is_term();
        let result = is_non_interactive(false);
        if let Some(val) = ci_was {
            std::env::set_var("CI", val);
        }
        if is_tty {
            assert!(
                !result,
                "is_non_interactive must be false when stderr IS a terminal \
                 (and neither dry_run nor $CI is set)"
            );
        } else {
            assert!(
                result,
                "is_non_interactive must be true when stderr is NOT a terminal"
            );
        }
    }

    #[test]
    fn init_docker_context_field_is_option() {
        // Compile-time guard: field must be Option<String> so we can distinguish
        // "explicitly set" from "not set (will prompt or use default)".
        let init = make_init(true);
        let _: Option<String> = init.docker_context;
    }

    #[test]
    fn bootstrap_config_has_orb_dir() {
        let config = build_bootstrap_config(
            "mytool",
            &["my-org".to_string()],
            "custom-orb",
            None,
            None,
            &[],
            &[],
        );
        assert_eq!(
            config.orb.as_ref().unwrap().orb_dir.as_deref(),
            Some("custom-orb")
        );
    }
}