password_manager 0.2.5

Ultra-secure password manager with quantum-resistant encryption
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
use super::{clipboard::copy_to_clipboard, progress::demo_progress_indicator};
use crate::database::DatabaseManager;
use crate::models::{
    BaseItem, Credential, Folder, Item, ItemType, Key, KeyType, KeyUsage, Note, NoteFormat,
    SecureNote, SecurityLevel, Url,
};
use anyhow::{anyhow, Result};
use chrono::Utc;
use clap::{Args, Parser, Subcommand};
use console::{style, Term};
use dialoguer::{Confirm, Input, Password};
use std::{path::Path, time::Duration};
use uuid::Uuid;
use zeroize::Zeroizing;

#[derive(Parser)]
#[command(name = "password_manager")]
#[command(about = "Ultra-secure password manager with quantum-resistant encryption")]
pub struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Create a new password database
    Create(CreateArgs),
    /// Open an existing password database
    Open(OpenArgs),
    /// List all items in the database
    List(ListArgs),
    /// Add a new item to the database
    Add(AddArgs),
    /// Show details of a specific item
    Show(ShowArgs),
    /// Edit an existing item
    Edit(EditArgs),
    /// Remove an item from the database
    Remove(RemoveArgs),
    /// Search for items
    Search(SearchArgs),
    /// Generate a random password
    Generate(GenerateArgs),
    /// Show database statistics
    Stats(StatsArgs),
    /// Verify database integrity
    Verify(VerifyArgs),
    /// Export database to JSON
    Export(ExportArgs),
    /// Import database from JSON
    Import(ImportArgs),
    /// Change master password
    ChangePassword(ChangePasswordArgs),
    /// Lock the database
    Lock(LockArgs),
    /// Unlock the database
    Unlock(UnlockArgs),
    /// Demo progress indicator
    Demo,
    /// Show hardware acceleration info
    Hardware,
}

#[derive(Args)]
pub struct CreateArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Database name
    #[arg(short, long)]
    name: Option<String>,

    /// Security level (standard, high, quantum)
    #[arg(short, long, default_value = "high")]
    security: Option<String>,
}

#[derive(Args)]
pub struct OpenArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,
}

#[derive(Args)]
pub struct ListArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Filter by item type
    #[arg(short, long)]
    type_filter: Option<String>,
}

#[derive(Args)]
pub struct AddArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Item type (credential, folder, key, url, note, secure_note)
    #[arg(short, long)]
    item_type: String,

    /// Item name
    #[arg(short, long)]
    name: String,
}

#[derive(Args)]
pub struct ShowArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Item ID
    #[arg(short, long)]
    id: String,
}

#[derive(Args)]
pub struct EditArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Item ID
    #[arg(short, long)]
    id: String,
}

#[derive(Args)]
pub struct RemoveArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Item ID
    #[arg(short, long)]
    id: String,
}

#[derive(Args)]
pub struct SearchArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Search query
    #[arg(short, long)]
    query: String,
}

#[derive(Args)]
pub struct GenerateArgs {
    /// Password length
    #[arg(long, default_value = "20")]
    length: u32,

    /// Include uppercase letters
    #[arg(long, default_value = "true")]
    uppercase: bool,

    /// Include lowercase letters
    #[arg(long, default_value = "true")]
    lowercase: bool,

    /// Include numbers
    #[arg(long, default_value = "true")]
    numbers: bool,

    /// Include symbols
    #[arg(long, default_value = "true")]
    symbols: bool,

    /// Display the generated password in the terminal
    #[arg(long)]
    show: bool,

    /// Seconds before the clipboard is cleared
    #[arg(long, default_value = "30")]
    timeout: u64,
}

#[derive(Args)]
pub struct StatsArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,
}

#[derive(Args)]
pub struct VerifyArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,
}

#[derive(Args)]
pub struct ExportArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Output JSON file path
    #[arg(short, long)]
    output: String,
}

#[derive(Args)]
pub struct ImportArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,

    /// Input JSON file path
    #[arg(short, long)]
    input: String,
}

#[derive(Args)]
pub struct ChangePasswordArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,
}

#[derive(Args)]
pub struct LockArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,
}

#[derive(Args)]
pub struct UnlockArgs {
    /// Database file path
    #[arg(short, long)]
    file: String,
}

pub struct CliHandler;

impl CliHandler {
    pub fn run() -> Result<()> {
        let cli = Cli::parse();

        match cli.command {
            Commands::Create(args) => Self::handle_create(args),
            Commands::Open(args) => Self::handle_open(args),
            Commands::List(args) => Self::handle_list(args),
            Commands::Add(args) => Self::handle_add(args),
            Commands::Show(args) => Self::handle_show(args),
            Commands::Edit(args) => Self::handle_edit(args),
            Commands::Remove(args) => Self::handle_remove(args),
            Commands::Search(args) => Self::handle_search(args),
            Commands::Generate(args) => Self::handle_generate(args),
            Commands::Stats(args) => Self::handle_stats(args),
            Commands::Verify(args) => Self::handle_verify(args),
            Commands::Export(args) => Self::handle_export(args),
            Commands::Import(args) => Self::handle_import(args),
            Commands::ChangePassword(args) => Self::handle_change_password(args),
            Commands::Lock(args) => Self::handle_lock(args),
            Commands::Unlock(args) => Self::handle_unlock(args),
            Commands::Demo => Self::handle_demo(),
            Commands::Hardware => Self::handle_hardware(),
        }
    }

    /// Prompt the user for a password and zeroize it when dropped.
    fn prompt_password(prompt: &str) -> Result<Zeroizing<String>> {
        let password = Password::new().with_prompt(prompt).interact()?;
        Ok(Zeroizing::new(password))
    }

    /// Prompt the user for a password with confirmation and zeroize it.
    fn prompt_password_confirm(prompt: &str, confirm_prompt: &str) -> Result<Zeroizing<String>> {
        let password = Password::new()
            .with_prompt(prompt)
            .with_confirmation(confirm_prompt, "Passwords don't match")
            .interact()?;
        Ok(Zeroizing::new(password))
    }

    /// Prompt for the master password and load the database.
    ///
    /// Returning the password alongside the `DatabaseManager` allows
    /// callers that need to persist changes to reuse the same
    /// `Zeroizing` buffer, ensuring the secret is cleared from memory
    /// as soon as it goes out of scope.
    fn load_manager(file: &str) -> Result<(DatabaseManager, Zeroizing<String>)> {
        let master_password = Self::prompt_password("Enter master password")?;
        let manager = DatabaseManager::load_from_file(file, &master_password)?;
        Ok((manager, master_password))
    }

    fn handle_create(args: CreateArgs) -> Result<()> {
        let term = Term::stdout();

        let name = args.name.unwrap_or_else(|| {
            Input::<String>::new()
                .with_prompt("Enter database name")
                .interact()
                .unwrap_or_else(|_| "My Passwords".to_string())
        });

        let security_level = match args.security.as_deref() {
            Some("standard") => SecurityLevel::Standard,
            Some("high") => SecurityLevel::High,
            Some("quantum") => SecurityLevel::Quantum,
            _ => SecurityLevel::High,
        };

        let master_password =
            Self::prompt_password_confirm("Enter master password", "Confirm master password")?;

        let mut manager = DatabaseManager::new(name, security_level)?;
        manager.save_to_file(&args.file, &master_password)?;

        term.write_line(&style("Database created successfully!").green().to_string())?;
        Ok(())
    }

    fn handle_open(args: OpenArgs) -> Result<()> {
        let term = Term::stdout();

        if !Path::new(&args.file).exists() {
            return Err(anyhow!("Database file does not exist"));
        }

        let (manager, _master_password) = Self::load_manager(&args.file)?;

        term.write_line(&style("Database opened successfully!").green().to_string())?;
        term.write_line(&format!("Database: {}", manager.get_metadata().name))?;
        term.write_line(&format!("Items: {}", manager.database.items.len()))?;

        Ok(())
    }

    fn handle_list(args: ListArgs) -> Result<()> {
        let term = Term::stdout();

        let (manager, _master_password) = Self::load_manager(&args.file)?;

        let items = if let Some(type_filter) = args.type_filter {
            let item_type = match type_filter.as_str() {
                "credential" => ItemType::Credential,
                "folder" => ItemType::Folder,
                "key" => ItemType::Key,
                "url" => ItemType::Url,
                "note" => ItemType::Note,
                "secure_note" => ItemType::SecureNote,
                _ => return Err(anyhow!("Invalid item type")),
            };
            manager.get_items_by_type(&item_type)
        } else {
            manager.database.items.iter().collect()
        };

        if items.is_empty() {
            term.write_line("No items found.")?;
            return Ok(());
        }

        term.write_line(&style("Items:").bold().to_string())?;
        for item in items {
            let item_type = match item.get_type() {
                ItemType::Credential => "Credential",
                ItemType::Folder => "Folder",
                ItemType::Key => "Key",
                ItemType::Url => "URL",
                ItemType::Note => "Note",
                ItemType::SecureNote => "Secure Note",
            };

            term.write_line(&format!(
                "{} - {} ({})",
                item.get_id(),
                item.get_name(),
                item_type
            ))?;
        }

        Ok(())
    }

    fn handle_add(args: AddArgs) -> Result<()> {
        let term = Term::stdout();

        let (mut manager, master_password) = Self::load_manager(&args.file)?;

        let item_type = match args.item_type.as_str() {
            "credential" => ItemType::Credential,
            "folder" => ItemType::Folder,
            "key" => ItemType::Key,
            "url" => ItemType::Url,
            "note" => ItemType::Note,
            "secure_note" => ItemType::SecureNote,
            _ => return Err(anyhow!("Invalid item type")),
        };

        let item = Self::create_item_interactive(&args.name, item_type)?;
        manager.add_item(item)?;
        manager.save_to_file(&args.file, &master_password)?;

        term.write_line(&style("Item added successfully!").green().to_string())?;
        Ok(())
    }

    fn handle_show(args: ShowArgs) -> Result<()> {
        let _term = Term::stdout();

        let (manager, _master_password) = Self::load_manager(&args.file)?;

        let item_id = Uuid::parse_str(&args.id)?;
        if let Some(item) = manager.get_item(item_id) {
            Self::display_item(item)?;
        } else {
            return Err(anyhow!("Item not found"));
        }

        Ok(())
    }

    fn handle_edit(args: EditArgs) -> Result<()> {
        let term = Term::stdout();

        let (mut manager, master_password) = Self::load_manager(&args.file)?;

        let item_id = Uuid::parse_str(&args.id)?;
        if let Some(item) = manager.get_item(item_id) {
            let updated_item = Self::edit_item_interactive(item)?;
            manager.update_item(item_id, updated_item)?;
            manager.save_to_file(&args.file, &master_password)?;

            term.write_line(&style("Item updated successfully!").green().to_string())?;
        } else {
            return Err(anyhow!("Item not found"));
        }

        Ok(())
    }

    fn handle_remove(args: RemoveArgs) -> Result<()> {
        let term = Term::stdout();

        let (mut manager, master_password) = Self::load_manager(&args.file)?;

        let item_id = Uuid::parse_str(&args.id)?;

        if Confirm::new()
            .with_prompt("Are you sure you want to remove this item?")
            .interact()?
        {
            manager.remove_item(item_id)?;
            manager.save_to_file(&args.file, &master_password)?;
            term.write_line(&style("Item removed successfully!").green().to_string())?;
        }

        Ok(())
    }

    fn handle_search(args: SearchArgs) -> Result<()> {
        let term = Term::stdout();

        let (manager, _master_password) = Self::load_manager(&args.file)?;

        let results = manager.search_items(&args.query);

        if results.is_empty() {
            term.write_line("No items found.")?;
            return Ok(());
        }

        term.write_line(&style("Search Results:").bold().to_string())?;
        for item in results {
            let item_type = match item.get_type() {
                ItemType::Credential => "Credential",
                ItemType::Folder => "Folder",
                ItemType::Key => "Key",
                ItemType::Url => "URL",
                ItemType::Note => "Note",
                ItemType::SecureNote => "Secure Note",
            };

            term.write_line(&format!(
                "{} - {} ({})",
                item.get_id(),
                item.get_name(),
                item_type
            ))?;
        }

        Ok(())
    }

    fn handle_generate(args: GenerateArgs) -> Result<()> {
        let term = Term::stdout();

        let settings = crate::models::PasswordGeneratorSettings {
            length: args.length,
            use_uppercase: args.uppercase,
            use_lowercase: args.lowercase,
            use_numbers: args.numbers,
            use_symbols: args.symbols,
            exclude_similar: true,
            exclude_ambiguous: false,
        };

        let password = Zeroizing::new(crate::crypto::generate_password(&settings));
        copy_to_clipboard(&password, Some(Duration::from_secs(args.timeout)))?;
        if args.show {
            term.write_line(&format!("Generated password: {}", *password))?;
        } else {
            term.write_line("Password copied to clipboard.")?;
        }

        Ok(())
    }

    fn handle_stats(args: StatsArgs) -> Result<()> {
        let term = Term::stdout();

        let (manager, _master_password) = Self::load_manager(&args.file)?;

        let stats = manager.get_statistics();
        term.write_line(&stats.to_string())?;

        Ok(())
    }

    fn handle_verify(args: VerifyArgs) -> Result<()> {
        let term = Term::stdout();

        let (manager, _master_password) = Self::load_manager(&args.file)?;

        if manager.verify_integrity()? {
            term.write_line(
                &style("Database integrity verified successfully!")
                    .green()
                    .to_string(),
            )?;
        } else {
            term.write_line(&style("Database integrity check failed!").red().to_string())?;
        }

        Ok(())
    }

    fn handle_export(args: ExportArgs) -> Result<()> {
        let term = Term::stdout();

        let (manager, _master_password) = Self::load_manager(&args.file)?;

        manager.export_to_json(&args.output)?;
        term.write_line(&style("Database exported successfully!").green().to_string())?;

        Ok(())
    }

    fn handle_import(args: ImportArgs) -> Result<()> {
        let term = Term::stdout();

        let (mut manager, master_password) = Self::load_manager(&args.file)?;

        manager.import_from_json(&args.input)?;
        manager.save_to_file(&args.file, &master_password)?;

        term.write_line(&style("Database imported successfully!").green().to_string())?;

        Ok(())
    }

    fn handle_change_password(args: ChangePasswordArgs) -> Result<()> {
        let term = Term::stdout();

        let old_password = Self::prompt_password("Enter current master password")?;

        let new_password = Self::prompt_password_confirm(
            "Enter new master password",
            "Confirm new master password",
        )?;

        let mut manager = DatabaseManager::load_from_file(&args.file, &old_password)?;
        manager.change_master_password(&new_password)?;
        manager.save_to_file(&args.file, &new_password)?;

        term.write_line(
            &style("Master password changed successfully!")
                .green()
                .to_string(),
        )?;

        Ok(())
    }

    fn handle_lock(args: LockArgs) -> Result<()> {
        let term = Term::stdout();

        let (mut manager, master_password) = Self::load_manager(&args.file)?;
        manager.lock();
        manager.save_to_file(&args.file, &master_password)?;

        term.write_line(&style("Database locked successfully!").green().to_string())?;

        Ok(())
    }

    fn handle_unlock(args: UnlockArgs) -> Result<()> {
        let term = Term::stdout();

        let (mut manager, master_password) = Self::load_manager(&args.file)?;
        manager.unlock(&master_password)?;

        term.write_line(&style("Database unlocked successfully!").green().to_string())?;

        Ok(())
    }

    fn handle_demo() -> Result<()> {
        if let Err(e) = demo_progress_indicator() {
            println!("Error: {e}");
        }
        Ok(())
    }

    fn handle_hardware() -> Result<()> {
        use crate::hardware::HardwareAccelerator;

        println!("🔧 Hardware Acceleration Information");
        println!("===================================");
        println!();

        let capabilities = HardwareAccelerator::get_capabilities_info();
        let is_available = HardwareAccelerator::is_available();
        let optimal_threads = HardwareAccelerator::optimal_thread_count();

        println!("📊 Capabilities: {capabilities}");
        println!(
            "⚡ Hardware Acceleration: {}",
            if is_available {
                "✅ Available"
            } else {
                "❌ Not Available"
            }
        );
        println!("🧵 Optimal Thread Count: {optimal_threads}");
        println!();

        if is_available {
            println!("🚀 Hardware acceleration is active in AES-GCM operations (via aes-gcm).");
            println!(
                "   Expect significant performance improvements on supported Apple Silicon and x86_64."
            );
        } else {
            println!("⚠️  No hardware acceleration detected. Using software implementations.");
            println!("   Performance may be slower on this system.");
        }

        Ok(())
    }

    fn create_item_interactive(name: &str, item_type: ItemType) -> Result<Item> {
        let base = BaseItem {
            id: Uuid::new_v4(),
            name: name.to_string(),
            item_type: item_type.clone(),
            folder_id: None,
            tags: Vec::new(),
            attachments: Vec::new(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            hmac: String::new(),
        };

        match item_type {
            ItemType::Credential => {
                let username = Input::<String>::new().with_prompt("Username").interact()?;

                let password = Self::prompt_password("Password")?;

                let url = Input::<String>::new()
                    .with_prompt("URL (optional)")
                    .allow_empty(true)
                    .interact()?;

                let notes = Input::<String>::new()
                    .with_prompt("Notes (optional)")
                    .allow_empty(true)
                    .interact()?;

                let credential = Credential {
                    base,
                    username,
                    password: password.to_string(),
                    url: if url.is_empty() { None } else { Some(url) },
                    notes: if notes.is_empty() { None } else { Some(notes) },
                    totp_secret: None,
                    last_used: None,
                    password_history: Vec::new(),
                };

                Ok(Item::Credential(credential))
            }
            ItemType::Folder => {
                let description = Input::<String>::new()
                    .with_prompt("Description (optional)")
                    .allow_empty(true)
                    .interact()?;

                let folder = Folder {
                    base,
                    description: if description.is_empty() {
                        None
                    } else {
                        Some(description)
                    },
                    color: None,
                };

                Ok(Item::Folder(folder))
            }
            ItemType::Key => {
                let key_data = Self::prompt_password("Key data (base64)")?;

                let key = Key {
                    base,
                    key_type: KeyType::Symmetric,
                    key_data: key_data.to_string(),
                    algorithm: "AES-256".to_string(),
                    key_size: 256,
                    usage: vec![KeyUsage::Encryption, KeyUsage::Decryption],
                };

                Ok(Item::Key(key))
            }
            ItemType::Url => {
                let url = Input::<String>::new().with_prompt("URL").interact()?;

                let title = Input::<String>::new()
                    .with_prompt("Title (optional)")
                    .allow_empty(true)
                    .interact()?;

                let url_item = Url {
                    base,
                    url,
                    title: if title.is_empty() { None } else { Some(title) },
                    favicon: None,
                    notes: None,
                };

                Ok(Item::Url(url_item))
            }
            ItemType::Note => {
                let content = Input::<String>::new()
                    .with_prompt("Note content")
                    .interact()?;

                let note = Note {
                    base,
                    content,
                    is_encrypted: false,
                    format: NoteFormat::PlainText,
                };

                Ok(Item::Note(note))
            }
            ItemType::SecureNote => {
                let content = Self::prompt_password("Secure note content")?;

                let secure_note = SecureNote {
                    base,
                    encrypted_content: content.to_string(),
                    content_type: "text/plain".to_string(),
                    additional_metadata: std::collections::HashMap::new(),
                };

                Ok(Item::SecureNote(secure_note))
            }
        }
    }

    fn edit_item_interactive(item: &Item) -> Result<Item> {
        // For simplicity, we'll just return the item as-is
        // In a real implementation, you'd want to provide an interactive editor
        Ok(item.clone())
    }

    fn display_item(item: &Item) -> Result<()> {
        let term = Term::stdout();

        term.write_line(&format!("ID: {}", item.get_id()))?;
        term.write_line(&format!("Name: {}", item.get_name()))?;
        term.write_line(&format!("Type: {:?}", item.get_type()))?;
        term.write_line(&format!("Created: {}", item.get_base().created_at))?;
        term.write_line(&format!("Updated: {}", item.get_base().updated_at))?;

        match item {
            Item::Credential(c) => {
                term.write_line(&format!("Username: {}", c.username))?;
                term.write_line(&format!("Password: {}", "*".repeat(c.password.len())))?;
                if let Some(url) = &c.url {
                    term.write_line(&format!("URL: {url}"))?;
                }
                if let Some(notes) = &c.notes {
                    term.write_line(&format!("Notes: {notes}"))?;
                }
            }
            Item::Folder(f) => {
                if let Some(desc) = &f.description {
                    term.write_line(&format!("Description: {desc}"))?;
                }
            }
            Item::Key(k) => {
                term.write_line(&format!("Algorithm: {}", k.algorithm))?;
                term.write_line(&format!("Key Size: {}", k.key_size))?;
                term.write_line(&format!("Key Type: {:?}", k.key_type))?;
            }
            Item::Url(u) => {
                term.write_line(&format!("URL: {}", u.url))?;
                if let Some(title) = &u.title {
                    term.write_line(&format!("Title: {title}"))?;
                }
            }
            Item::Note(n) => {
                term.write_line(&format!("Content: {}", n.content))?;
                term.write_line(&format!("Format: {:?}", n.format))?;
                term.write_line(&format!("Encrypted: {}", n.is_encrypted))?;
            }
            Item::SecureNote(s) => {
                term.write_line(&format!("Content Type: {}", s.content_type))?;
                term.write_line(&format!(
                    "Content: {}",
                    "*".repeat(s.encrypted_content.len())
                ))?;
            }
        }

        Ok(())
    }
}

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

    #[test]
    fn parses_create_command() {
        let cli = Cli::parse_from(["app", "create", "-f", "test.db"]);
        match cli.command {
            Commands::Create(args) => assert_eq!(args.file, "test.db"),
            _ => panic!("expected create command"),
        }
    }
}