entangle-mirror 0.1.2

Easy setup for mirroring GitHub repos to Tangled.org in one command
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
//! Handler for `entangle init`.
//!
//! Full flow across Steps 8–10:
//!
//!  1. Check config is valid; refer to `entangle setup` if not.        ← Step 8
//!  2. Collect repo name and optional alias (CLI args or prompts).      ← Step 8
//!  3. Validate repo name(s).                                           ← Step 8
//!  4. Build prospective GitHub and Tangled SSH URLs.                   ← Step 8
//!  5. Detect git repo status; `git init` if needed.                   ← Step 8
//!  6. Suggest `.gitignore` / `README.md` if absent.                   ← Step 8
//!  7. Inspect existing remotes; handle overwrite/proceed prompts.      ← Step 9
//!  8. Add non-origin push URL, then origin push URL (order matters).  ← Step 10
//!  9. Print final remote state and suggest `entangle shove`.           ← Step 10
//!
//! ## Testability
//!
//! [`run`] resolves the platform config path and current working directory, then
//! delegates to [`run_with_paths`], which accepts explicit paths so tests can
//! pass a `tempfile` config path and a temp work directory without touching the
//! user's real config or cwd.
//!
//! ## Interactive vs. CLI-arg mode
//!
//! - `entangle init`                 → prompts for repo name and optional alias
//! - `entangle init myrepo`          → uses `myrepo`, no alias (no prompt)
//! - `entangle init myrepo myalias`  → uses `myrepo` + `myalias` (no prompt)
//!
//! Interactive prompts use `dialoguer` and require a TTY. When a repo name is
//! supplied as a CLI arg, no dialoguer is invoked, making that path fully
//! testable with piped stdin.

use std::path::Path;

use dialoguer::{Input, theme::ColorfulTheme};

use crate::config::{Config, VerbosityLevel};
use crate::git;
use crate::output;
use crate::remote;
use crate::urls::resolve_urls;
use crate::validate::validate_repo_name;

// ---------------------------------------------------------------------------
// Verbosity helper
// ---------------------------------------------------------------------------

/// Print a formatted message if `$verbosity` is at or above `$level`.
///
/// Usage mirrors `println!` — format string and arguments are forwarded as-is.
/// The level is named without the `VerbosityLevel::` prefix for brevity:
///
/// ```ignore
/// vlog!(verbosity, Verbose, "✓ {}", message);
/// vlog!(verbosity, Debug,   "  push_urls: {:?}", urls);
/// ```
macro_rules! vlog {
    ($verbosity:expr, $level:ident, $($arg:tt)*) => {
        if $verbosity >= VerbosityLevel::$level {
            println!($($arg)*);
        }
    };
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Entry point called by `main.rs` for the `init` subcommand.
///
/// `quiet` and `debug` map directly to the `-q` / `--debug` CLI flags and
/// override the `verbosity_preference` stored in the config file.
///
/// Remote validation can be bypassed for integration tests by setting the
/// `ENTANGLE_SKIP_REMOTE_CHECK` environment variable to any value. This avoids
/// real SSH connections in tests that spawn the binary as a subprocess.
pub fn run(
    repo: Option<String>,
    alias: Option<String>,
    quiet: bool,
    debug: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::load()?;
    let work_dir = std::env::current_dir()?;
    let skip_check = std::env::var("ENTANGLE_SKIP_REMOTE_CHECK").is_ok();
    run_with_paths(
        repo,
        alias,
        config,
        &work_dir,
        quiet,
        debug,
        |origin, mirror| {
            if skip_check {
                return Ok(());
            }
            remote::validate_remotes(origin, mirror)
                .map_err(|e| -> Box<dyn std::error::Error> { Box::new(e) })
        },
    )
}

// ---------------------------------------------------------------------------
// Testable core
// ---------------------------------------------------------------------------

/// Run init against an explicit config path and working directory.
///
/// Separated from [`run`] so tests can supply a [`tempfile`] config path and
/// temp work directory instead of touching the user's real config or cwd.
///
/// `quiet` and `debug` correspond to the CLI flags; they override the
/// `verbosity_preference` field in the loaded config. Pass both as `false`
/// to use the config-file preference (which defaults to [`VerbosityLevel::Verbose`]).
///
/// `remote_validator` is called with `(origin_url, mirror_url)` to verify
/// that both remotes are reachable before touching `.git/config`. In
/// production this is [`remote::validate_remotes`] (which does real SSH
/// ls-refs). In unit tests pass `|_, _| Ok(())` to skip network I/O.
pub fn run_with_paths(
    repo: Option<String>,
    alias: Option<String>,
    config: Config,
    work_dir: &Path,
    quiet: bool,
    debug: bool,
    remote_validator: impl Fn(&str, &str) -> Result<(), Box<dyn std::error::Error>>,
) -> Result<(), Box<dyn std::error::Error>> {
    let verbosity = config.effective_verbosity(quiet, debug);

    // ── 2 & 3. Collect and validate repo name ───────────────────────────────
    //
    // Interactive mode (no CLI arg): prompt loops until the user provides a
    // valid name — prompt_repo_name() validates internally and only returns Ok
    // on success. We also offer an alias prompt in this mode.
    //
    // CLI mode (arg provided): validate immediately and error without prompting.
    // The alias, if not given as a second CLI arg, is simply absent — no prompt.
    let (repo_name, interactive) = match repo {
        Some(r) => {
            // Validation error propagates via ? — main.rs prints "Error: …".
            let v = validate_repo_name(&r)?;
            (v, false)
        }
        None => (prompt_repo_name()?, true),
    };

    let alias_name: Option<String> = match (alias, interactive) {
        // Alias supplied via CLI — validate it.
        (Some(a), _) => {
            let v = validate_repo_name(&a)?;
            Some(v)
        }
        // Interactive mode, no CLI alias → prompt (blank = no alias).
        (None, true) => prompt_alias_optional()?,
        // CLI mode, no alias arg → no alias, no prompt.
        (None, false) => None,
    };

    // ── 4. Build prospective URLs ────────────────────────────────────────────
    let (origin_url, mirror_url) = resolve_urls(&config, &repo_name, alias_name.as_deref());

    // ── 5. Detect / initialize git repo ─────────────────────────────────────
    let was_initialized = git::init_if_needed(work_dir)?;
    if was_initialized {
        vlog!(
            verbosity,
            Verbose,
            "{}",
            output::progress("Folder is not a git repository — initializing...")
        );
        vlog!(
            verbosity,
            Verbose,
            "{}",
            output::success("Git repository initialized.")
        );
    } else {
        vlog!(
            verbosity,
            Verbose,
            "{}",
            output::success("Git repository detected.")
        );
    }

    // ── 6. Suggest .gitignore / README.md if absent ──────────────────────────
    if !git::has_gitignore(work_dir) {
        vlog!(
            verbosity,
            Verbose,
            "{}",
            output::tip("Add a .gitignore to avoid committing build artifacts.")
        );
    }
    if !git::has_readme(work_dir) {
        vlog!(
            verbosity,
            Verbose,
            "{}",
            output::tip("Add a README.md to describe your project.")
        );
    }

    // ── 6b. Preview resolved URLs ─────────────────────────────────────────────
    vlog!(verbosity, Verbose, "");
    vlog!(verbosity, Verbose, "Configuring remotes for '{repo_name}':");
    vlog!(
        verbosity,
        Verbose,
        "  Origin (fetch + push): {}",
        output::url(&origin_url)
    );
    vlog!(
        verbosity,
        Verbose,
        "  Mirror (push only):    {}",
        output::url(&mirror_url)
    );

    // ── 7. Inspect existing remotes ──────────────────────────────────────────
    use crate::git::OriginStatus;

    let origin_status = git::get_origin_status(work_dir)?;

    vlog!(
        verbosity,
        Debug,
        "  {} origin status: {:?}",
        output::debug_tag(),
        origin_status
    );

    // ── 7a. Early exit if already fully configured ────────────────────────────
    //
    // Both push URLs present → a previous `entangle init` (or manual setup)
    // already wired the dual-push configuration. Exit cleanly before hitting
    // the network — no point validating if nothing needs to change.
    if let OriginStatus::Present { push_urls, .. } = &origin_status {
        let has_origin_push = push_urls.iter().any(|u| u == &origin_url);
        let has_mirror_push = push_urls.iter().any(|u| u == &mirror_url);

        vlog!(
            verbosity,
            Debug,
            "  {} push_urls={push_urls:?} has_origin_push={has_origin_push} has_mirror_push={has_mirror_push}",
            output::debug_tag()
        );

        if has_origin_push && has_mirror_push {
            vlog!(verbosity, Verbose, "");
            vlog!(
                verbosity,
                Verbose,
                "{}",
                output::success("Both push remotes are already configured. Nothing to do.")
            );
            vlog!(
                verbosity,
                Verbose,
                "  Run {} to push all branches and tags to both forges.",
                output::cmd("entangle shove")
            );
            return Ok(());
        }
    }

    // ── 7b. Validate remote accessibility ─────────────────────────────────────
    //
    // Verify both SSH endpoints are reachable (or the user accepts the offline
    // override) before touching `.git/config`. Placed after URL preview so the
    // user sees the intended targets before we go to the network, and after the
    // early-exit check so we don't hit the network for already-configured repos.
    //
    // Three outcomes from the validator:
    //   • Ok(())           → both reachable (or user accepted offline override).
    //   • NotFound/Auth    → hard stop; user must fix the URL or SSH key first.
    //   • NetworkError declined → OfflineAborted; user cancelled at the prompt.
    vlog!(verbosity, Verbose, "");
    // Spin while the SSH ls-refs call runs — gix is silent during the check
    // so without a spinner the terminal appears frozen for several seconds.
    // In non-TTY environments (CI, piped output) indicatif disables itself.
    let spinner = create_remote_check_spinner(verbosity);
    let check_result = remote_validator(&origin_url, &mirror_url);
    if let Some(sp) = spinner {
        sp.finish_and_clear();
    }
    check_result?;
    vlog!(
        verbosity,
        Verbose,
        "{}",
        output::success("Both remotes are accessible.")
    );

    // ── 7c. Handle overwrite prompt if fetch URL doesn't match ───────────────
    //
    // Two variables capture the decisions made here so Step 10 and the
    // post-action note can use them:
    //
    //   `replace_fetch_url`   — true if the user chose to replace the existing
    //                           origin fetch URL. Step 10 swaps it before
    //                           adding push URLs.
    //
    //   `kept_existing_fetch` — Some(url) if the user chose to proceed without
    //                           replacing. Step 10 skips touching the fetch URL;
    //                           a ⚠ note is shown after Step 10 completes.
    let mut replace_fetch_url = false;
    let mut kept_existing_fetch: Option<String> = None;

    match &origin_status {
        OriginStatus::Absent => {
            // No existing `origin` remote — Step 10 will create one from scratch.
            vlog!(
                verbosity,
                Debug,
                "  {} no origin remote found; will create from scratch",
                output::debug_tag()
            );
        }

        OriginStatus::Present {
            fetch_url,
            push_urls: _,
        } => {
            if fetch_url != &origin_url {
                // Fetch URL mismatch (e.g., GitLab remote, a fork, different user).
                // Three outcomes: replace, proceed-as-is, or abort.
                vlog!(
                    verbosity,
                    Debug,
                    "  {} fetch URL mismatch: existing={fetch_url} expected={origin_url}",
                    output::debug_tag()
                );

                let replace = prompt_replace_origin(fetch_url, &origin_url)?;

                if replace {
                    replace_fetch_url = true;
                } else {
                    let proceed = prompt_proceed_anyway(fetch_url)?;
                    if !proceed {
                        // Always printed — the user's confirmation that the abort
                        // happened, not a suppressible informational tip.
                        println!("Init cancelled. No changes were made.");
                        return Ok(());
                    }
                    kept_existing_fetch = Some(fetch_url.clone());
                }
            }
            // If fetch_url == origin_url, Step 10 adds missing push URLs silently.
        }
    }

    vlog!(
        verbosity,
        Debug,
        "  {} replace_fetch_url={replace_fetch_url} kept_existing_fetch={kept_existing_fetch:?}",
        output::debug_tag()
    );

    // ── Step 10: Configure remotes ───────────────────────────────────────────
    //
    // Three paths depending on what Step 9 found and decided:
    //
    //   Absent              → create origin from scratch with both push URLs.
    //   Present, replaced   → replace fetch URL, then add both push URLs.
    //   Present, kept/match → leave fetch URL alone, add whichever push URLs
    //                         are missing (the caller already checked that at
    //                         least one is absent — the "both present" path
    //                         returned early in Step 9).
    match &origin_status {
        OriginStatus::Absent => {
            // Non-default (mirror) forge first, default (origin) forge last.
            // This matches the convention in the Tangled docs and in DESIGN.md
            // steps 9–10: the origin URL is "re-added" as a push URL after the
            // mirror, so it appears last in the config.
            git::create_origin_remote(
                work_dir,
                &origin_url,
                &[mirror_url.as_str(), origin_url.as_str()],
            )?;
            vlog!(
                verbosity,
                Debug,
                "  {} created origin remote with fetch + 2 push URLs",
                output::debug_tag()
            );
        }

        OriginStatus::Present {
            fetch_url: _,
            push_urls,
        } => {
            if replace_fetch_url {
                git::set_origin_fetch_url(work_dir, &origin_url)?;
                vlog!(
                    verbosity,
                    Debug,
                    "  {} replaced origin fetch URL → {origin_url}",
                    output::debug_tag()
                );
            }

            // Add whichever push URLs are not yet present, preserving the
            // non-default-first, default-last ordering convention.
            let mut to_add: Vec<&str> = Vec::new();
            if !push_urls.iter().any(|u| u == &mirror_url) {
                to_add.push(mirror_url.as_str());
            }
            if !push_urls.iter().any(|u| u == &origin_url) {
                to_add.push(origin_url.as_str());
            }
            vlog!(
                verbosity,
                Debug,
                "  {} push URLs to add: {:?}",
                output::debug_tag(),
                to_add
            );
            if !to_add.is_empty() {
                git::add_push_urls_to_origin(work_dir, &to_add)?;
            }
        }
    }

    // ── Print final remote state ─────────────────────────────────────────────
    //
    // Show a `git remote -v`-style summary of what origin looks like after the
    // changes. The fetch URL is `origin_url` unless the user chose to keep an
    // existing URL (`kept_existing_fetch`).
    let final_fetch_url = match &kept_existing_fetch {
        Some(url) => url.as_str(),
        None => origin_url.as_str(),
    };

    vlog!(verbosity, Verbose, "");
    // Display mirrors the actual config order: mirror (non-default) first,
    // origin (default) last — matching `git remote -v` output conventions.
    vlog!(
        verbosity,
        Verbose,
        "{}",
        output::success(&format!("Remotes configured for '{repo_name}':"))
    );
    vlog!(verbosity, Verbose, "");
    vlog!(
        verbosity,
        Verbose,
        "  origin  {}  (fetch)",
        output::url(final_fetch_url)
    );
    vlog!(
        verbosity,
        Verbose,
        "  origin  {}  (push)",
        output::url(&mirror_url)
    );
    vlog!(
        verbosity,
        Verbose,
        "  origin  {}  (push)",
        output::url(&origin_url)
    );
    vlog!(verbosity, Verbose, "");
    vlog!(
        verbosity,
        Verbose,
        "Run {} to push all branches and tags to both forges.",
        output::cmd("entangle shove")
    );

    // ── Post-action note for the "kept existing fetch URL" path ──────────────
    //
    // Placed here — after Step 10 — so "was kept" and "have been added" are
    // factually accurate at the point the user reads them.
    if let Some(ref existing_url) = kept_existing_fetch {
        vlog!(verbosity, Verbose, "");
        vlog!(
            verbosity,
            Verbose,
            "{}",
            output::warn(&format!(
                "Note: origin fetch URL ({existing_url}) was kept as-is."
            ))
        );
        vlog!(
            verbosity,
            Verbose,
            "   Push URLs have been added — pushes will reach both forges,"
        );
        vlog!(
            verbosity,
            Verbose,
            "   but fetches will come from this origin."
        );
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Prompt helpers (interactive mode)
// ---------------------------------------------------------------------------

/// Ask the user whether to replace an existing origin with a different URL.
///
/// Prints the existing URL on its own line before the `Confirm` so the long
/// URLs don't crowd the prompt itself. Default is `true` (replace).
#[cfg_attr(test, mutants::skip)]
fn prompt_replace_origin(
    existing_url: &str,
    new_url: &str,
) -> Result<bool, Box<dyn std::error::Error>> {
    println!();
    println!("An origin remote already exists: {existing_url}");
    let theme = ColorfulTheme::default();
    match dialoguer::Confirm::with_theme(&theme)
        .with_prompt(format!("Replace it with {new_url}?"))
        .default(true)
        .interact()
    {
        Ok(v) => Ok(v),
        Err(e) if is_cancelled(&e) => {
            eprintln!("\nInit cancelled. No changes were made.");
            Err(e.into())
        }
        Err(e) => Err(e.into()),
    }
}

/// Ask the user whether to add push URLs to an origin whose fetch URL we are
/// NOT replacing. Default is `true` (proceed).
#[cfg_attr(test, mutants::skip)]
fn prompt_proceed_anyway(existing_url: &str) -> Result<bool, Box<dyn std::error::Error>> {
    let theme = ColorfulTheme::default();
    match dialoguer::Confirm::with_theme(&theme)
        .with_prompt(format!(
            "Add push URLs to existing origin ({existing_url}) anyway?"
        ))
        .default(true)
        .interact()
    {
        Ok(v) => Ok(v),
        Err(e) if is_cancelled(&e) => {
            eprintln!("\nInit cancelled. No changes were made.");
            Err(e.into())
        }
        Err(e) => Err(e.into()),
    }
}

/// Prompt for the repository name, re-prompting on validation failure.
#[cfg_attr(test, mutants::skip)]
fn prompt_repo_name() -> Result<String, Box<dyn std::error::Error>> {
    let theme = ColorfulTheme::default();
    loop {
        let raw = match Input::<String>::with_theme(&theme)
            .with_prompt("Repository name (on your origin forge)")
            .interact_text()
        {
            Ok(v) => v,
            Err(e) if is_cancelled(&e) => {
                eprintln!("\nInit cancelled. No changes were made.");
                return Err(e.into());
            }
            Err(e) => return Err(e.into()),
        };

        match validate_repo_name(&raw) {
            Ok(validated) => return Ok(validated),
            Err(e) => eprintln!("{}", output::error_inline(&e.to_string())),
        }
    }
}

/// Prompt for an optional Tangled alias. Empty input → `None`.
#[cfg_attr(test, mutants::skip)]
fn prompt_alias_optional() -> Result<Option<String>, Box<dyn std::error::Error>> {
    let theme = ColorfulTheme::default();
    loop {
        let raw = match Input::<String>::with_theme(&theme)
            .with_prompt("Alias on mirror forge (leave blank to use the same name)")
            .allow_empty(true)
            .interact_text()
        {
            Ok(v) => v,
            Err(e) if is_cancelled(&e) => {
                eprintln!("\nInit cancelled. No changes were made.");
                return Err(e.into());
            }
            Err(e) => return Err(e.into()),
        };

        if raw.trim().is_empty() {
            return Ok(None);
        }

        match validate_repo_name(&raw) {
            Ok(validated) => return Ok(Some(validated)),
            Err(e) => eprintln!("{e}"),
        }
    }
}

/// Create a spinner if the verbosity level warrants it.
#[cfg_attr(test, mutants::skip)]
fn create_remote_check_spinner(verbosity: VerbosityLevel) -> Option<indicatif::ProgressBar> {
    if verbosity >= VerbosityLevel::Verbose {
        Some(output::remote_check_spinner(
            "Checking remote accessibility…",
        ))
    } else {
        None
    }
}

/// Returns `true` if a dialoguer error looks like a user cancellation (Ctrl+C or
/// broken pipe) rather than an unexpected infrastructure failure.
#[cfg_attr(test, mutants::skip)]
fn is_cancelled(e: &dialoguer::Error) -> bool {
    match e {
        dialoguer::Error::IO(io_err) => matches!(
            io_err.kind(),
            std::io::ErrorKind::Interrupted | std::io::ErrorKind::BrokenPipe
        ),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Config, OriginPreference};
    use tempfile::TempDir;

    // ── Helpers ──────────────────────────────────────────────────────────────

    /// No-op remote validator for unit tests — skips all network I/O.
    ///
    /// Pass this wherever `run_with_paths` requires a `remote_validator`.
    /// Integration tests that spawn the binary use `ENTANGLE_SKIP_REMOTE_CHECK`
    /// instead; this function is only for in-process unit tests.
    fn skip_validate(_: &str, _: &str) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    /// A valid config matching the sample data used throughout the tests.
    fn test_config() -> Config {
        Config {
            github_username: "cyrusae".to_string(),
            tangled_username: "atdot.fyi".to_string(),
            origin_preference: OriginPreference::Github,
            verbosity_preference: Default::default(),
        }
    }

    /// Create a throwaway work directory. Returns the [`TempDir`] guard (keep
    /// it alive for the duration of the test) and the path to the work dir.
    fn fresh_work_dir() -> (TempDir, std::path::PathBuf) {
        let dir = TempDir::new().unwrap();
        let work_dir = dir.path().join("work");
        std::fs::create_dir(&work_dir).unwrap();
        (dir, work_dir)
    }

    // ── Git init behaviour ────────────────────────────────────────────────────

    #[test]
    fn run_initializes_git_repo_in_fresh_directory() {
        let (_dir, work_dir) = fresh_work_dir();
        assert!(
            !git::is_git_repo(&work_dir),
            "precondition: not yet a git repo"
        );

        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();

        assert!(
            git::is_git_repo(&work_dir),
            "work_dir must be a git repo after run_with_paths"
        );
    }

    #[test]
    fn run_is_idempotent_on_existing_repo() {
        let (_dir, work_dir) = fresh_work_dir();

        // First run — initializes.
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();
        // Second run — must not error.
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();

        assert!(git::is_git_repo(&work_dir));
    }

    // ── Validation ────────────────────────────────────────────────────────────

    #[test]
    fn invalid_repo_name_returns_error() {
        let (_dir, work_dir) = fresh_work_dir();

        let result = run_with_paths(
            Some("-invalid-leading-hyphen".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        );
        assert!(result.is_err(), "invalid repo name must cause an error");
        // No git repo should have been created.
        assert!(
            !git::is_git_repo(&work_dir),
            "git repo must not be created when repo name is invalid"
        );
    }

    #[test]
    fn invalid_alias_returns_error() {
        let (_dir, work_dir) = fresh_work_dir();

        let result = run_with_paths(
            Some("my-repo".to_string()),
            Some("-bad-alias".to_string()),
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        );
        assert!(result.is_err(), "invalid alias must cause an error");
    }

    #[test]
    fn valid_alias_is_accepted() {
        let (_dir, work_dir) = fresh_work_dir();

        run_with_paths(
            Some("my-repo".to_string()),
            Some("mirror-name".to_string()),
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();
    }

    // ── Remote inspection paths (non-interactive) ─────────────────────────────
    //
    // Tests that exercise Step 9 logic without triggering dialoguer (which
    // needs a TTY). All cases here are ones where no prompt is shown:
    //
    //   (a) No `origin` remote       → proceeds silently to Step 10
    //   (b) Both push URLs present   → early-exit success message
    //   (c) Origin URL matches       → proceeds silently to Step 10
    //
    // Cases that trigger a prompt (origin URL mismatch) are tested via
    // PTY integration tests in `tests/init_integration.rs`.

    /// Write a [remote "origin"] section to .git/config; appends to the
    /// existing gix-generated config so its core settings are preserved.
    fn append_origin(work_dir: &Path, fetch_url: &str, push_urls: &[&str]) {
        use std::io::Write as _;
        let cfg = work_dir.join(".git").join("config");
        let mut f = std::fs::OpenOptions::new().append(true).open(cfg).unwrap();
        writeln!(f, "\n[remote \"origin\"]").unwrap();
        writeln!(f, "\turl = {fetch_url}").unwrap();
        writeln!(f, "\tfetch = +refs/heads/*:refs/remotes/origin/*").unwrap();
        for u in push_urls {
            writeln!(f, "\tpushurl = {u}").unwrap();
        }
    }

    #[test]
    fn run_with_no_origin_proceeds_to_url_preview() {
        // Fresh repo, no remotes — must print the URL preview and return Ok.
        let (_dir, work_dir) = fresh_work_dir();
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .expect("must succeed when no origin remote is configured");
    }

    #[test]
    fn run_with_matching_origin_url_proceeds_to_url_preview() {
        // Origin fetch URL already matches what we'd set — no prompt, proceed.
        let (_dir, work_dir) = fresh_work_dir();
        // First run initializes the git repo.
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();
        // Set up an origin with a matching URL (what a github-preference config gives).
        append_origin(&work_dir, "git@github.com:cyrusae/entangle.git", &[]);
        // Second run sees matching origin — must not error, no prompt.
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .expect("must succeed when origin fetch URL matches expected URL");
    }

    #[test]
    fn run_exits_early_when_both_push_urls_already_configured() {
        // Both push URLs present → early exit with success, no changes needed.
        let (_dir, work_dir) = fresh_work_dir();
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();

        // Add origin with BOTH push URLs already set.
        append_origin(
            &work_dir,
            "git@github.com:cyrusae/entangle.git",
            &[
                "git@github.com:cyrusae/entangle.git",
                "git@tangled.org:atdot.fyi/entangle",
            ],
        );

        // Should return Ok (early exit, not an error).
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .expect("must succeed (early exit) when both push URLs are already configured");
    }

    #[test]
    fn run_proceeds_when_only_one_push_url_present() {
        // Only one push URL present → must proceed (not early-exit) so Step 10
        // can add the missing one.
        let (_dir, work_dir) = fresh_work_dir();
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();

        // Add origin with only the GitHub push URL (Tangled missing).
        append_origin(
            &work_dir,
            "git@github.com:cyrusae/entangle.git",
            &["git@github.com:cyrusae/entangle.git"],
        );

        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .expect("must succeed when only one push URL is configured");
    }

    // ── Step 10: Verify configured remote state ───────────────────────────────
    //
    // These tests use `git::get_origin_status` to read back the actual `.git/config`
    // state after `run_with_paths` completes, confirming that Step 10 wrote the
    // correct entries.

    #[test]
    fn run_configures_origin_remote_in_fresh_repo() {
        // After the very first run on a fresh directory, origin must have the
        // expected fetch URL and both push URLs in the correct order:
        // mirror (Tangled) first, origin (GitHub) last — matching the Tangled
        // docs convention and DESIGN.md steps 9–10.
        let (_dir, work_dir) = fresh_work_dir();
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();

        let status = git::get_origin_status(&work_dir).unwrap();
        match status {
            git::OriginStatus::Present {
                fetch_url,
                push_urls,
            } => {
                assert_eq!(fetch_url, "git@github.com:cyrusae/entangle.git");
                assert_eq!(
                    push_urls.len(),
                    2,
                    "must configure both push URLs: {push_urls:?}"
                );
                // Order: mirror (Tangled, non-default) first, origin (GitHub, default) last.
                assert_eq!(
                    push_urls[0], "git@tangled.org:atdot.fyi/entangle",
                    "Tangled (mirror) must be the first push URL"
                );
                assert_eq!(
                    push_urls[1], "git@github.com:cyrusae/entangle.git",
                    "GitHub (origin) must be the second (last) push URL"
                );
            }
            git::OriginStatus::Absent => panic!("expected Present after init, got Absent"),
        }
    }

    #[test]
    fn run_adds_both_push_urls_when_origin_has_matching_url_but_none() {
        // Origin fetch URL already matches what entangle would set, but no push
        // URLs are configured. run_with_paths must add both without a prompt,
        // in the correct order (mirror first, origin last).
        let (_dir, work_dir) = fresh_work_dir();
        gix::init(&work_dir).unwrap();

        // Write origin with correct fetch URL but no push URLs.
        {
            use std::io::Write as _;
            let cfg = work_dir.join(".git").join("config");
            let mut f = std::fs::OpenOptions::new().append(true).open(cfg).unwrap();
            writeln!(f, "\n[remote \"origin\"]").unwrap();
            writeln!(f, "\turl = git@github.com:cyrusae/entangle.git").unwrap();
            writeln!(f, "\tfetch = +refs/heads/*:refs/remotes/origin/*").unwrap();
        }

        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();

        let status = git::get_origin_status(&work_dir).unwrap();
        match status {
            git::OriginStatus::Present {
                fetch_url,
                push_urls,
            } => {
                assert_eq!(fetch_url, "git@github.com:cyrusae/entangle.git");
                assert_eq!(
                    push_urls.len(),
                    2,
                    "both push URLs must be added: {push_urls:?}"
                );
                // Order: mirror (Tangled, non-default) first, origin (GitHub, default) last.
                assert_eq!(
                    push_urls[0], "git@tangled.org:atdot.fyi/entangle",
                    "Tangled (mirror) must be the first push URL"
                );
                assert_eq!(
                    push_urls[1], "git@github.com:cyrusae/entangle.git",
                    "GitHub (origin) must be the second (last) push URL"
                );
            }
            git::OriginStatus::Absent => panic!("expected Present"),
        }
    }

    #[test]
    fn run_is_fully_idempotent_after_step_10() {
        // Running twice on the same repo must succeed both times.
        // Second run sees both push URLs → early-exits cleanly.
        let (_dir, work_dir) = fresh_work_dir();
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();
        run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();

        let status = git::get_origin_status(&work_dir).unwrap();
        match status {
            git::OriginStatus::Present { push_urls, .. } => {
                // Must still have exactly the two push URLs — second run must
                // not have duplicated them.
                let origin_count = push_urls
                    .iter()
                    .filter(|u| u.as_str() == "git@github.com:cyrusae/entangle.git")
                    .count();
                let mirror_count = push_urls
                    .iter()
                    .filter(|u| u.as_str() == "git@tangled.org:atdot.fyi/entangle")
                    .count();
                assert_eq!(origin_count, 1, "origin push URL must not be duplicated");
                assert_eq!(mirror_count, 1, "mirror push URL must not be duplicated");
            }
            git::OriginStatus::Absent => panic!("expected Present"),
        }
    }

    #[test]
    fn run_with_alias_uses_alias_for_tangled_push_url() {
        // When an alias is supplied, the Tangled push URL must use the alias
        // instead of the primary repo name.
        let (_dir, work_dir) = fresh_work_dir();
        run_with_paths(
            Some("my-repo".to_string()),
            Some("mirror-alias".to_string()),
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        )
        .unwrap();

        let status = git::get_origin_status(&work_dir).unwrap();
        match status {
            git::OriginStatus::Present { push_urls, .. } => {
                assert!(
                    push_urls.iter().any(|u| u.contains("mirror-alias")),
                    "Tangled push URL must use the alias: {push_urls:?}"
                );
                assert!(
                    push_urls.iter().any(|u| u.contains("my-repo")),
                    "GitHub push URL must use the primary repo name: {push_urls:?}"
                );
            }
            git::OriginStatus::Absent => panic!("expected Present"),
        }
    }

    // ── Resilience: corrupt .git/config ──────────────────────────────────────

    /// Verifies that a corrupt `.git/config` does not cause a panic.
    ///
    /// The exact outcome (Ok or Err) depends on how lenient gix is about the
    /// specific corruption. What must NOT happen is an unwrap panic or process
    /// abort — the test passing without panicking is the verification.
    #[test]
    fn corrupt_git_config_does_not_panic() {
        let (_dir, work_dir) = fresh_work_dir();
        gix::init(&work_dir).unwrap();

        // Overwrite .git/config with a syntactically broken section header
        // (missing closing bracket). This is the corruption pattern the
        // adversarial review flagged as a potential panic source.
        let config_path = work_dir.join(".git").join("config");
        std::fs::write(
            &config_path,
            "[core\n\trepositoryformatversion = 0\nfilemode = true\n",
        )
        .unwrap();

        // Must return Ok or Err — not panic.
        let result = run_with_paths(
            Some("entangle".to_string()),
            None,
            test_config(),
            &work_dir,
            false,
            false,
            skip_validate,
        );
        // Either outcome is valid: gix may tolerate the corruption (Ok) or
        // surface it as an error (Err). The test asserts only that no panic
        // occurred, which is proven by reaching this line.
        drop(result);
    }
}