void-cli 0.0.4

CLI for void — anonymous encrypted source control
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
//! Identity management for void P2P sharing.
//!
//! Manages Ed25519 signing keys and X25519 recipient keys for P2P sharing.
//! Identity is stored at `~/.void/identity/` with:
//! - `profile.json` — username metadata
//! - `signing.pub` — hex-encoded signing public key
//! - `recipient.pub` — hex-encoded recipient public key
//! - `keys.enc` — PIN-encrypted private keys (Argon2id + AES-256-GCM)

use std::io::IsTerminal;

use rand::seq::SliceRandom;
use serde::Serialize;
use void_core::collab::Identity;

use crate::context::{
    identity_exists, load_identity_cached, load_public_identity, save_identity,
    validate_identity_username,
};
use crate::output::{run_command, CliError, CliOptions};

/// Command-line arguments for identity.
#[derive(Debug)]
pub struct IdentityArgs {
    /// Subcommand: init, show, export, or recover.
    pub subcommand: IdentitySubcommand,
}

/// Identity subcommands.
#[derive(Debug)]
pub enum IdentitySubcommand {
    /// Generate new identity from mnemonic seed phrase.
    Init {
        /// Force overwrite if identity already exists.
        force: bool,
        /// Username for the identity.
        username: Option<String>,
    },
    /// Show identity string (public keys). No PIN needed.
    Show,
    /// Export identity string for sharing. No PIN needed.
    Export,
    /// Recover identity from a mnemonic seed phrase.
    Recover {
        /// Force overwrite if identity already exists.
        force: bool,
        /// Username for the recovered identity.
        username: Option<String>,
    },
    /// Clear cached identity keys from OS keyring.
    Lock,
    /// Pre-cache identity keys in OS keyring (prompts for PIN).
    Unlock,
}

/// JSON output for the identity init command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InitOutput {
    /// Whether a new identity was created (vs already existed).
    pub created: bool,
    /// Path to the identity directory.
    pub path: String,
    /// Signing public key (hex-encoded).
    pub signing_pubkey: String,
    /// Recipient public key (hex-encoded).
    pub recipient_pubkey: String,
    /// Nostr x-only public key (hex-encoded, if available).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nostr_pubkey: Option<String>,
    /// The 24-word mnemonic phrase (only shown at creation time).
    pub mnemonic: String,
    /// Username for the identity.
    pub username: String,
    /// Email address (optional contact metadata).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// Signal handle (optional contact metadata).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signal: Option<String>,
}

/// JSON output for the identity show command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ShowOutput {
    /// Username (if set).
    pub username: Option<String>,
    /// Signing public key (hex-encoded).
    pub signing_pubkey: String,
    /// Recipient public key (hex-encoded).
    pub recipient_pubkey: String,
    /// Nostr x-only public key (hex-encoded, if available).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nostr_pubkey: Option<String>,
}

/// JSON output for the identity export command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportOutput {
    /// The identity string for sharing.
    pub identity: String,
}

/// JSON output for the identity recover command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RecoverOutput {
    /// Whether the identity was recovered successfully.
    pub recovered: bool,
    /// Path to the identity directory.
    pub path: String,
    /// Signing public key (hex-encoded).
    pub signing_pubkey: String,
    /// Recipient public key (hex-encoded).
    pub recipient_pubkey: String,
    /// Username for the recovered identity.
    pub username: String,
}

/// JSON output for the identity lock command.
#[derive(Debug, Serialize)]
pub struct LockOutput {
    pub locked: bool,
}

/// JSON output for the identity unlock command.
#[derive(Debug, Serialize)]
pub struct UnlockOutput {
    pub unlocked: bool,
}

/// Run the identity command.
pub fn run(args: IdentityArgs, opts: &CliOptions) -> Result<(), CliError> {
    match args.subcommand {
        IdentitySubcommand::Init {
            force,
            username,
        } => run_init(force, username, opts),
        IdentitySubcommand::Show => run_show(opts),
        IdentitySubcommand::Export => run_export(opts),
        IdentitySubcommand::Recover { force, username } => run_recover(force, username, opts),
        IdentitySubcommand::Lock => run_lock(opts),
        IdentitySubcommand::Unlock => run_unlock(opts),
    }
}

/// Initialize a new identity with a BIP-39 seed phrase.
fn run_init(
    force: bool,
    username: Option<String>,
    opts: &CliOptions,
) -> Result<(), CliError> {
    run_command("identity init", opts, |ctx| {
        ctx.progress("Checking for existing identity...");

        if identity_exists() {
            if !force {
                return Err(CliError::conflict(
                    "Identity already exists. Use --force to overwrite.",
                ));
            }
            ctx.info("Overwriting existing identity (--force).");
        }

        let is_interactive = !ctx.use_json() && std::io::stdin().is_terminal();

        // Get username — interactive prompt when TTY + human mode, silent fallback otherwise
        let username = if let Some(u) = username.clone() {
            // Explicit --username flag: use directly, no prompt
            u
        } else if is_interactive {
            let system_user = std::env::var("USER")
                .or_else(|_| std::env::var("USERNAME"))
                .unwrap_or_else(|_| "user".to_string());
            dialoguer::Input::new()
                .with_prompt("Choose your username")
                .default(system_user)
                .validate_with(|input: &String| -> std::result::Result<(), String> {
                    validate_identity_username(input).map_err(|e| e.to_string())
                })
                .interact_text()
                .map_err(|e| CliError::internal(format!("prompt failed: {e}")))?
        } else {
            std::env::var("USER")
                .or_else(|_| std::env::var("USERNAME"))
                .unwrap_or_else(|_| "user".to_string())
        };
        validate_identity_username(&username)?;

        // Optional contact metadata (interactive only)
        let (email, signal) = if is_interactive {
            let email: String = dialoguer::Input::new()
                .with_prompt("Email (optional, press ENTER to skip)")
                .allow_empty(true)
                .interact_text()
                .map_err(|e| CliError::internal(format!("prompt failed: {e}")))?;
            let signal: String = dialoguer::Input::new()
                .with_prompt("Signal (optional, press ENTER to skip)")
                .allow_empty(true)
                .interact_text()
                .map_err(|e| CliError::internal(format!("prompt failed: {e}")))?;
            let email = if email.is_empty() { None } else { Some(email) };
            let signal = if signal.is_empty() { None } else { Some(signal) };
            (email, signal)
        } else {
            (None, None)
        };

        ctx.progress("Generating new identity with seed phrase...");
        let (identity, mnemonic) = Identity::generate_with_mnemonic()
            .map_err(|e| CliError::internal(format!("failed to generate identity: {}", e)))?;

        // Prompt for PIN
        ctx.info("Choose a PIN to protect your identity keys.");
        let pin = prompt_pin_with_confirm()?;

        ctx.progress("Encrypting and saving identity...");
        save_identity(
            &identity,
            &username,
            &pin,
            email.as_deref(),
            signal.as_deref(),
        )?;

        // Cache in OS keyring so subsequent commands skip PIN prompt
        let signing_pubkey_hex = identity.signing_pubkey().to_hex();
        crate::keyring::cache_keys(&signing_pubkey_hex, &identity);

        let path = crate::context::get_identity_dir().display().to_string();
        let signing_pubkey = signing_pubkey_hex;
        let recipient_pubkey = identity.recipient_pubkey().to_hex();
        let nostr_pubkey = identity.nostr_pubkey().map(|k| k.to_hex());

        if !ctx.use_json() {
            eprintln!();
            eprintln!("Identity created for '{}'", username);
            eprintln!();
            eprintln!(
                "  Signing key (Ed25519)    \u{2014} proves commits are yours"
            );
            eprintln!("    {}", signing_pubkey);
            eprintln!();
            eprintln!(
                "  Encryption key (X25519)  \u{2014} lets others share repos with you"
            );
            eprintln!("    {}", recipient_pubkey);
            if let Some(ref npub) = nostr_pubkey {
                eprintln!();
                eprintln!(
                    "  Nostr key (Secp256k1)    \u{2014} links to your Nostr identity"
                );
                eprintln!("    {}", npub);
            }
            eprintln!();
            eprintln!("  Keys saved to: {}", path);
            eprintln!();

            // Display formatted mnemonic grid
            let grid = format_mnemonic_grid(&mnemonic);
            eprint!("{}", grid);

            // Interactive verification with [p] to print (only when stdin is a real TTY)
            if std::io::stdin().is_terminal() {
                run_mnemonic_verification(&mnemonic, &username, &signing_pubkey)?;
            }
        }

        Ok(InitOutput {
            created: true,
            path,
            signing_pubkey,
            recipient_pubkey,
            nostr_pubkey,
            mnemonic,
            username,
            email,
            signal,
        })
    })
}

/// Show identity information. No PIN needed — reads public keys only.
fn run_show(opts: &CliOptions) -> Result<(), CliError> {
    run_command("identity show", opts, |ctx| {
        ctx.progress("Loading identity...");
        let (username, signing_pubkey, recipient_pubkey, nostr_pubkey) = load_public_identity()?;

        let signing_hex = hex::encode(signing_pubkey.as_bytes());
        let recipient_hex = hex::encode(recipient_pubkey.as_bytes());
        let nostr_hex = nostr_pubkey.as_ref().map(|k| k.to_hex());

        if !ctx.use_json() {
            if let Some(ref name) = username {
                ctx.info(format!("Username: {}", name));
            }
            ctx.info(format!("Signing pubkey: {}", signing_hex));
            ctx.info(format!("Recipient pubkey: {}", recipient_hex));
            if let Some(ref npub) = nostr_hex {
                ctx.info(format!("Nostr pubkey: {}", npub));
            }
        }

        Ok(ShowOutput {
            username,
            signing_pubkey: signing_hex,
            recipient_pubkey: recipient_hex,
            nostr_pubkey: nostr_hex,
        })
    })
}

/// Export identity string for sharing. No PIN needed — uses public keys only.
fn run_export(opts: &CliOptions) -> Result<(), CliError> {
    run_command("identity export", opts, |ctx| {
        ctx.progress("Loading identity...");
        let (username, signing_pubkey, recipient_pubkey, nostr_pubkey) = load_public_identity()?;

        // Build identity string with username and optional nostr key
        let signing_hex = hex::encode(signing_pubkey.as_bytes());
        let recipient_hex = hex::encode(recipient_pubkey.as_bytes());

        let mut identity_string = if let Some(ref name) = username {
            format!(
                "void://{}@ed25519:{}/x25519:{}",
                name, signing_hex, recipient_hex
            )
        } else {
            format!("void://ed25519:{}/x25519:{}", signing_hex, recipient_hex)
        };

        if let Some(nostr) = nostr_pubkey {
            identity_string.push_str(&format!("/nostr:{}", nostr.to_hex()));
        }

        if !ctx.use_json() {
            ctx.info(identity_string.clone());
        }

        Ok(ExportOutput {
            identity: identity_string,
        })
    })
}

/// Recover identity from a mnemonic seed phrase.
fn run_recover(force: bool, username: Option<String>, opts: &CliOptions) -> Result<(), CliError> {
    run_command("identity recover", opts, |ctx| {
        ctx.progress("Recovering identity from seed phrase...");

        if identity_exists() {
            if force {
                ctx.info("Overwriting existing identity (--force).");
            } else {
                return Err(CliError::conflict(
                    "Identity already exists. Use --force to overwrite.",
                ));
            }
        }

        // Prompt for mnemonic
        ctx.info("Enter your 24-word recovery phrase:");
        let mnemonic = rpassword::prompt_password("Recovery phrase: ")
            .map_err(|e| CliError::io_error(format!("failed to read recovery phrase: {}", e)))?;
        let mnemonic = mnemonic.trim().to_string();

        if mnemonic.is_empty() {
            return Err(CliError::invalid_args("recovery phrase must not be empty"));
        }

        // Derive identity from mnemonic
        let seed = void_core::collab::mnemonic_to_seed(&mnemonic)
            .map_err(|e| CliError::invalid_args(format!("invalid recovery phrase: {}", e)))?;
        let identity = Identity::from_seed(&seed)
            .map_err(|e| CliError::internal(format!("failed to derive identity: {}", e)))?;

        // Get username
        let username = username.clone().unwrap_or_else(|| {
            std::env::var("USER")
                .or_else(|_| std::env::var("USERNAME"))
                .unwrap_or_else(|_| "user".to_string())
        });
        validate_identity_username(&username)?;

        // Prompt for new PIN
        ctx.info("Choose a PIN to protect your recovered identity keys.");
        let pin = prompt_pin_with_confirm()?;

        ctx.progress("Encrypting and saving recovered identity...");
        save_identity(&identity, &username, &pin, None, None)?;

        // Cache in OS keyring so subsequent commands skip PIN prompt
        let signing_pubkey_hex = identity.signing_pubkey().to_hex();
        crate::keyring::cache_keys(&signing_pubkey_hex, &identity);

        let path = crate::context::get_identity_dir().display().to_string();
        let signing_pubkey = signing_pubkey_hex;
        let recipient_pubkey = identity.recipient_pubkey().to_hex();

        if !ctx.use_json() {
            ctx.info(format!("Identity recovered for '{}'", username));
            ctx.info(format!("Signing pubkey: {}", signing_pubkey));
            ctx.info(format!("Recipient pubkey: {}", recipient_pubkey));
            ctx.info(format!("Keys saved to: {}", path));
        }

        Ok(RecoverOutput {
            recovered: true,
            path,
            signing_pubkey,
            recipient_pubkey,
            username,
        })
    })
}

/// Clear cached identity keys from the OS keyring.
fn run_lock(opts: &CliOptions) -> Result<(), CliError> {
    run_command("identity lock", opts, |ctx| {
        let (_, signing_pubkey, _, _) = load_public_identity()?;
        let signing_hex = signing_pubkey.to_hex();
        let cleared = crate::keyring::clear_cached_keys(&signing_hex);

        if !ctx.use_json() {
            if cleared {
                ctx.info("Identity keys cleared from OS keyring.");
            } else {
                ctx.info("No cached keys found in OS keyring.");
            }
        }

        Ok(LockOutput { locked: cleared })
    })
}

/// Pre-cache identity keys in the OS keyring (prompts for PIN if not cached).
fn run_unlock(opts: &CliOptions) -> Result<(), CliError> {
    run_command("identity unlock", opts, |ctx| {
        ctx.progress("Unlocking identity...");
        let _identity = load_identity_cached()?;

        if !ctx.use_json() {
            ctx.info("Identity keys cached in OS keyring.");
        }

        Ok(UnlockOutput { unlocked: true })
    })
}

/// Format a 24-word mnemonic as a numbered 4×6 grid with box-drawing frame.
///
/// Words are arranged column-first: 1-6 in column 1, 7-12 in column 2, etc.
fn format_mnemonic_grid(mnemonic: &str) -> String {
    let words: Vec<&str> = mnemonic.split_whitespace().collect();
    let rows = 6;
    let cols = 4;

    // Find the max word length in each column for alignment
    let mut col_widths = [0usize; 4];
    for col in 0..cols {
        for row in 0..rows {
            let idx = col * rows + row;
            if idx < words.len() {
                col_widths[col] = col_widths[col].max(words[idx].len());
            }
        }
    }

    // Build each row: "  N. word" with right-aligned numbers
    let mut lines = Vec::new();
    for row in 0..rows {
        let mut parts = Vec::new();
        for col in 0..cols {
            let idx = col * rows + row;
            if idx < words.len() {
                let num = idx + 1;
                let word = words[idx];
                // Right-align the number (2 chars), left-pad word to column width
                parts.push(format!("{:>2}. {:<width$}", num, word, width = col_widths[col]));
            }
        }
        lines.push(format!("{}", parts.join("   ")));
    }

    // Calculate inner width from the first content line
    let inner_width = if let Some(first) = lines.first() {
        // Subtract the box chars (│ on each side)
        first.chars().count() - 2
    } else {
        56
    };

    let title = "RECOVERY PHRASE — 24 WORDS";
    let title_pad = inner_width.saturating_sub(title.len());
    let title_left = title_pad / 2;
    let title_right = title_pad - title_left;

    let warning1 = "Write these words down and store them safely.";
    let warning1_pad_left = 1;
    let warning1_pad_right = inner_width.saturating_sub(warning1.len() + warning1_pad_left);

    let warning2 = "This is the ONLY way to recover your identity.";
    let warning2_pad_left = 1;
    let warning2_pad_right = inner_width.saturating_sub(warning2.len() + warning2_pad_left);

    let mut output = String::new();
    output.push_str(&format!("{}\n", "".repeat(inner_width)));
    output.push_str(&format!(
        "{}{}{}\n",
        " ".repeat(title_left),
        title,
        " ".repeat(title_right)
    ));
    output.push_str(&format!("{}\n", " ".repeat(inner_width)));
    for line in &lines {
        output.push_str(line);
        output.push('\n');
    }
    output.push_str(&format!("{}\n", " ".repeat(inner_width)));
    output.push_str(&format!(
        "{}{}{}\n",
        " ".repeat(warning1_pad_left),
        warning1,
        " ".repeat(warning1_pad_right)
    ));
    output.push_str(&format!(
        "{}{}{}\n",
        " ".repeat(warning2_pad_left),
        warning2,
        " ".repeat(warning2_pad_right)
    ));
    output.push_str(&format!("{}\n", "".repeat(inner_width)));

    output
}

/// Interactive mnemonic verification: pause with [p] to print, then quiz 2 random words.
///
/// Only called when stdin is a TTY and output is human mode.
fn run_mnemonic_verification(
    mnemonic: &str,
    username: &str,
    signing_pubkey: &str,
) -> Result<(), CliError> {
    use console::{Key, Term};

    let words: Vec<&str> = mnemonic.split_whitespace().collect();
    if words.len() != 24 {
        return Ok(()); // Skip verification for non-standard mnemonics
    }

    // Combined pause + print prompt (single keypress)
    eprintln!();
    eprint!("Press ENTER to continue, or [p] to print recovery phrase...");
    let term = Term::stderr();
    match term.read_key() {
        Ok(Key::Char('p') | Key::Char('P')) => {
            eprintln!();
            print_recovery_phrase(mnemonic, username, signing_pubkey)?;
        }
        _ => {
            eprintln!(); // newline after the prompt
        }
    }

    // Pick 2 random positions to verify
    let mut rng = rand::thread_rng();
    let mut positions: Vec<usize> = (0..24).collect();
    positions.shuffle(&mut rng);
    let check_positions = &positions[..2];

    let max_attempts = 3;
    for &pos in check_positions {
        let expected = words[pos];
        let mut verified = false;

        for attempt in 0..max_attempts {
            let answer: String = dialoguer::Input::new()
                .with_prompt(format!("Verify word #{}", pos + 1))
                .interact_text()
                .map_err(|e| CliError::internal(format!("prompt failed: {e}")))?;

            if answer.trim().eq_ignore_ascii_case(expected) {
                verified = true;
                break;
            }

            let remaining = max_attempts - attempt - 1;
            if remaining > 0 {
                eprintln!(
                    "Incorrect. {} {} remaining.",
                    remaining,
                    if remaining == 1 { "attempt" } else { "attempts" }
                );
            }
        }

        if !verified {
            eprintln!("Warning: verification failed. Make sure you have the correct phrase written down.");
            // Re-display the grid so they can try again
            let grid = format_mnemonic_grid(mnemonic);
            eprint!("{}", grid);
            return Ok(());
        }
    }

    eprintln!("✓ Recovery phrase confirmed.");
    Ok(())
}

/// Discover available CUPS printers via `lpstat -a`.
///
/// Returns a list of printer names. Falls back to empty vec on error.
fn discover_printers() -> Vec<String> {
    let output = match std::process::Command::new("lpstat")
        .arg("-a")
        .output()
    {
        Ok(o) if o.status.success() => o,
        _ => return Vec::new(),
    };

    let stdout = String::from_utf8_lossy(&output.stdout);
    stdout
        .lines()
        .filter_map(|line| {
            // lpstat -a output: "PrinterName accepting requests since ..."
            line.split_whitespace().next().map(String::from)
        })
        .collect()
}

/// Print recovery phrase to a user-selected printer via CUPS `lp`.
fn print_recovery_phrase(mnemonic: &str, username: &str, signing_pubkey: &str) -> Result<(), CliError> {
    let words: Vec<&str> = mnemonic.split_whitespace().collect();
    let rows = 6;
    let cols = 4;

    let mut col_widths = [0usize; 4];
    for col in 0..cols {
        for row in 0..rows {
            let idx = col * rows + row;
            if idx < words.len() {
                col_widths[col] = col_widths[col].max(words[idx].len());
            }
        }
    }

    let date = chrono::Local::now().format("%Y-%m-%d").to_string();
    let key_short = if signing_pubkey.len() >= 8 {
        format!("{}...{}", &signing_pubkey[..4], &signing_pubkey[signing_pubkey.len() - 4..])
    } else {
        signing_pubkey.to_string()
    };

    let sep = "".repeat(47);
    let mut doc = String::new();
    doc.push_str(&format!("{}\n", sep));
    doc.push_str("  VOID IDENTITY — RECOVERY PHRASE\n");
    doc.push_str(&format!("{}\n", sep));
    doc.push_str(&format!("  Generated: {}\n", date));
    doc.push_str(&format!("  Username:  {}\n", username));
    doc.push_str(&format!("  Key ID:    {}\n", key_short));
    doc.push('\n');

    for row in 0..rows {
        let mut parts = Vec::new();
        for col in 0..cols {
            let idx = col * rows + row;
            if idx < words.len() {
                parts.push(format!("{:>2}. {:<width$}", idx + 1, words[idx], width = col_widths[col]));
            }
        }
        doc.push_str(&format!("  {}\n", parts.join("   ")));
    }

    doc.push('\n');
    doc.push_str("  KEEP THIS DOCUMENT SECURE.\n");
    doc.push_str("  Destroy after transferring to durable storage.\n");
    doc.push_str(&format!("{}\n", sep));

    // Pick a printer
    let printers = discover_printers();
    let printer_arg: Option<String> = if printers.len() > 1 {
        // Multiple printers — let user choose
        let selection = dialoguer::Select::new()
            .with_prompt("Select printer")
            .items(&printers)
            .default(0)
            .interact()
            .map_err(|e| CliError::internal(format!("prompt failed: {e}")))?;
        Some(printers[selection].clone())
    } else if printers.len() == 1 {
        // Single printer — use it directly, tell the user
        eprintln!("Printing to: {}", printers[0]);
        Some(printers[0].clone())
    } else {
        // No printers found — fall back to system default
        None
    };

    // Write to temp file and send to printer
    let temp_dir = std::env::temp_dir();
    let temp_path = temp_dir.join(format!("void-recovery-{}.txt", uuid::Uuid::new_v4()));

    std::fs::write(&temp_path, &doc)
        .map_err(|e| CliError::io_error(format!("failed to write temp file: {e}")))?;

    let mut cmd = std::process::Command::new("lp");
    if let Some(ref printer) = printer_arg {
        cmd.arg("-d").arg(printer);
    }
    cmd.arg(&temp_path);

    let status = cmd
        .status()
        .map_err(|e| CliError::io_error(format!("failed to run lp: {e}")))?;

    // Clean up temp file regardless of print result
    let _ = std::fs::remove_file(&temp_path);

    if status.success() {
        let dest = printer_arg.as_deref().unwrap_or("default printer");
        eprintln!("Recovery phrase sent to {}.", dest);
    } else {
        eprintln!("Warning: print command exited with status {}. Check printer.", status);
    }

    Ok(())
}

// TODO(release+1): --stl flag for 3D-printable recovery phrase plate

/// Prompt for PIN with confirmation (for init and recover).
fn prompt_pin_with_confirm() -> Result<String, CliError> {
    let pin = rpassword::prompt_password("Enter PIN: ")
        .map_err(|e| CliError::io_error(format!("failed to read PIN: {}", e)))?;

    if pin.is_empty() {
        return Err(CliError::invalid_args("PIN must not be empty"));
    }

    let confirm = rpassword::prompt_password("Confirm PIN: ")
        .map_err(|e| CliError::io_error(format!("failed to read PIN: {}", e)))?;

    if pin != confirm {
        return Err(CliError::invalid_args("PINs do not match"));
    }

    Ok(pin)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::PathBuf;
    use tempfile::tempdir;

    /// Test helper to save identity to a specific directory using the new format.
    fn save_identity_to(
        identity: &Identity,
        identity_dir: &PathBuf,
        username: &str,
        pin: &str,
    ) -> Result<(), CliError> {
        fs::create_dir_all(identity_dir).map_err(|e| CliError::io_error(e.to_string()))?;

        // Write public keys
        fs::write(
            identity_dir.join("signing.pub"),
            identity.signing_pubkey().to_hex(),
        )
        .map_err(|e| CliError::io_error(e.to_string()))?;
        fs::write(
            identity_dir.join("recipient.pub"),
            identity.recipient_pubkey().to_hex(),
        )
        .map_err(|e| CliError::io_error(e.to_string()))?;

        // Write profile
        let profile = serde_json::json!({ "username": username });
        fs::write(
            identity_dir.join("profile.json"),
            serde_json::to_string_pretty(&profile).unwrap(),
        )
        .map_err(|e| CliError::io_error(e.to_string()))?;

        // Encrypt and save keys
        let signing_secret = identity.signing_key_bytes();
        let recipient_secret = identity.recipient_key_bytes();
        let nostr_secret = identity
            .nostr_key_bytes()
            .unwrap_or_else(|| void_core::collab::NostrSecretKey::from_bytes([0xbb; 32]));
        let encrypted = void_core::collab::encrypt_identity_keys(
            &signing_secret,
            &recipient_secret,
            &nostr_secret,
            pin,
        )
        .unwrap();
        fs::write(identity_dir.join("keys.enc"), &encrypted)
            .map_err(|e| CliError::io_error(e.to_string()))?;

        Ok(())
    }

    /// Test helper to load identity from a specific directory using the new format.
    fn load_identity_from(identity_dir: &PathBuf, pin: &str) -> Result<Identity, CliError> {
        let keys_path = identity_dir.join("keys.enc");

        if !keys_path.exists() {
            return Err(CliError::not_found(
                "identity not initialized, run 'void identity init'",
            ));
        }

        let encrypted = fs::read(&keys_path).map_err(|e| CliError::io_error(e.to_string()))?;

        let (signing_secret, recipient_secret, nostr_secret) =
            void_core::collab::decrypt_identity_keys(&encrypted, pin)
                .map_err(|e| CliError::internal(format!("failed to decrypt identity: {}", e)))?;

        Ok(match nostr_secret {
            Some(nostr) => {
                Identity::from_bytes_with_nostr(&signing_secret, &recipient_secret, nostr)
            }
            None => Identity::from_bytes(&signing_secret, &recipient_secret),
        })
    }

    #[test]
    fn test_identity_not_found() {
        let temp_dir = tempdir().unwrap();
        let identity_dir = temp_dir.path().join("identity");
        let result = load_identity_from(&identity_dir, "pin");
        assert!(result.is_err());
    }

    #[test]
    fn test_identity_roundtrip() {
        let temp_dir = tempdir().unwrap();
        let identity_dir = temp_dir.path().join("identity");

        let identity = Identity::generate();
        let pin = "test-pin";
        save_identity_to(&identity, &identity_dir, "alice", pin).unwrap();

        let loaded = load_identity_from(&identity_dir, pin).unwrap();
        assert_eq!(identity.signing_pubkey(), loaded.signing_pubkey());
        assert_eq!(identity.recipient_pubkey(), loaded.recipient_pubkey());
    }

    #[test]
    fn test_identity_exists() {
        let temp_dir = tempdir().unwrap();
        let identity_dir = temp_dir.path().join("identity");

        let keys_enc_path = identity_dir.join("keys.enc");
        assert!(!keys_enc_path.exists());

        let identity = Identity::generate();
        save_identity_to(&identity, &identity_dir, "bob", "pin123").unwrap();

        assert!(keys_enc_path.exists());
        assert!(identity_dir.join("signing.pub").exists());
        assert!(identity_dir.join("recipient.pub").exists());
        assert!(identity_dir.join("profile.json").exists());
    }

    #[test]
    fn test_wrong_pin_fails() {
        let temp_dir = tempdir().unwrap();
        let identity_dir = temp_dir.path().join("identity");

        let identity = Identity::generate();
        save_identity_to(&identity, &identity_dir, "alice", "correct-pin").unwrap();

        let result = load_identity_from(&identity_dir, "wrong-pin");
        assert!(result.is_err());
    }

    #[test]
    fn test_profile_json_contains_username() {
        let temp_dir = tempdir().unwrap();
        let identity_dir = temp_dir.path().join("identity");

        let identity = Identity::generate();
        save_identity_to(&identity, &identity_dir, "charlie", "pin").unwrap();

        let profile_content = fs::read_to_string(identity_dir.join("profile.json")).unwrap();
        let profile: serde_json::Value = serde_json::from_str(&profile_content).unwrap();
        assert_eq!(profile["username"], "charlie");
    }
}