pji 0.1.8

A CLI for managing, finding, and opening Git repositories.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
use crate::config::{PjiConfig, PjiMetadata};
use crate::repo::PjiRepo;
use crate::util::{list_dir, try_get_repo_from_dir};
use crate::worktree::{
    self, add_worktree, get_default_worktree_path, get_main_repo_from_worktree, is_linked_worktree,
    list_local_branches, list_remote_branches, list_worktrees, prune_worktrees, remove_worktree,
    GitWorktree,
};
use arboard::Clipboard;
use comfy_table::Table;
use dialoguer::{console::style, Confirm, FuzzySelect, Input, Select};
use std::env;
use std::fs::{create_dir_all, remove_dir_all, remove_file};
use std::io;
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::{Command, Stdio};

pub struct PjiApp {
    config: PjiConfig,
    metadata: PjiMetadata,
}

impl PjiApp {
    pub fn new() -> Self {
        let config = PjiConfig::load();
        let metadata = PjiMetadata::load();
        Self { config, metadata }
    }

    pub fn start_config(&mut self) {
        self.add_root();
    }

    fn add_root(&mut self) -> &PathBuf {
        let name: String = Input::new()
            .with_prompt("Enter the full path for the new pji root directory")
            .default(PjiConfig::get_default_root().display().to_string())
            .interact_text()
            .unwrap();
        let path = PathBuf::from(&name);
        let has_root = self.config.roots.contains(&path);
        if has_root {
            Self::warn_message(&format!(
                "Root '{}' already exists. Please choose another.",
                name
            ));
            self.add_root()
        } else {
            if !path.exists() {
                println!("Creating directory '{}'...", path.display());
                create_dir_all(&path).expect("should create dir success");
                Self::success_message(&format!("Directory '{}' created.", path.display()));
            }
            self.config.roots.push(path);
            self.config.save().expect("should save config file success");
            Self::success_message(&format!(
                "Root '{}' added successfully.",
                self.config.roots.last().unwrap().display()
            ));
            self.config.roots.last().unwrap()
        }
    }

    fn get_working_root(&mut self) -> &PathBuf {
        let len = self.config.roots.len();
        if len == 0 {
            Self::warn_message("No pji roots found. Let's add one first.");
            self.add_root()
        } else if len == 1 {
            &self.config.roots[0]
        } else {
            let items = self
                .config
                .roots
                .iter()
                .map(|x| x.display().to_string())
                .collect::<Vec<_>>();
            let selection = Select::new()
                .with_prompt("Select root directory")
                .default(0)
                .items(&items)
                .interact()
                .unwrap();
            &self.config.roots[selection]
        }
    }

    pub fn add(&mut self, repo_uri_str: &str) {
        let root = self.get_working_root();
        let repo = PjiRepo::new(repo_uri_str, root);
        if self.metadata.has_repo(&repo) {
            Self::warn_message(&format!(
                "Repository '{}' already exists in pji.",
                repo.git_uri.uri
            ));
            return;
        }
        create_dir_all(&repo.dir).expect("should create repo dir success");
        let repo_dir = repo.dir.display().to_string();
        println!("Cloning '{}' into '{}'...", repo.git_uri.uri, repo_dir);
        Self::clone_repo(&repo.git_uri.uri, &repo_dir).expect("should clone repo success");
        self.metadata.add_repo(&repo).save();
        Self::success_message(&format!(
            "✨ Repository '{}' added to '{}'.",
            &repo.git_uri.uri, &repo_dir
        ));
        Self::copy_to_clipboard(
            &format!("cd {}", repo_dir),
            "Paste to navigate to the repository.",
        );
    }

    pub fn remove(&mut self, repo_uri_str: &str) {
        let root = self.get_working_root();
        let repo = PjiRepo::new(repo_uri_str, root);
        if !self.metadata.has_repo(&repo) {
            Self::warn_message(&format!(
                "Repository '{}' not found in pji.",
                repo.git_uri.uri
            ));
            return;
        }
        let confirmation = Self::confirm(&format!(
            "Are you sure you want to remove the repository '{}' from disk and pji?",
            repo.git_uri.uri
        ));
        if !confirmation {
            println!("✖️ Removal cancelled.");
            return;
        }
        println!("Removing directory '{}'...", repo.dir.display());
        remove_dir_all(&repo.dir).expect("should remove repo dir success");
        self.metadata.remove_repo(&repo).save();
        Self::success_message(&format!(
            "🗑️ Repository '{}' removed successfully from '{}'.",
            &repo.git_uri.uri,
            &repo.dir.display()
        ));
    }

    pub fn list(&mut self, long_format: bool) {
        self.metadata
            .repos
            .sort_by(|a, b| b.last_open_time.cmp(&a.last_open_time));
        if long_format {
            let mut table = Table::new();
            table.set_header(vec!["dir", "hostname", "user", "repo", "worktrees", "full uri"]);
            self.metadata.repos.iter().for_each(|repo| {
                let worktree_count = match list_worktrees(&repo.dir) {
                    Some(wts) if wts.has_linked() => format!("{}", wts.count()),
                    _ => "-".to_string(),
                };
                table.add_row(vec![
                    &repo.dir.display().to_string(),
                    &repo.git_uri.hostname,
                    &repo.git_uri.user,
                    &repo.git_uri.repo,
                    &worktree_count,
                    &repo.git_uri.uri,
                ]);
            });
            println!("{table}");
        } else {
            self.metadata.repos.iter().for_each(|repo| {
                println!("{}", repo.dir.display());
            });
        }
    }

    pub fn find(&mut self, query: &str) {
        let repo = self
            .find_repo("🔍 Search and select repository: ", query)
            .expect("repo not found");
        repo.update_open_time();
        let repo_dir = repo.dir.clone();

        // Save metadata before exec (exec replaces process, so we won't return)
        self.metadata.save();

        // Check if the repository has worktrees
        if let Some(worktrees) = list_worktrees(&repo_dir) {
            if worktrees.has_linked() {
                // Show worktree picker
                if let Some(wt) = self.select_worktree(&worktrees, "") {
                    self.exec_into_dir(&wt.path);
                    return;
                }
            }
        }

        // No worktrees or only main worktree - exec into repo dir
        self.exec_into_dir(&repo_dir);
    }

    pub fn scan(&mut self) {
        let mut total_new_repos_added = 0;
        // Clean up duplicates before scanning
        self.metadata.deduplicate();

        for root in self.config.roots.as_slice() {
            println!("🔍 Scanning {}...", root.display());
            if let Some(repos) = Self::get_repos_from_root(&root) {
                for repo in repos {
                    if !(self.metadata.has_repo(&repo)) {
                        println!("  ✨ Added: {}", repo.dir.display());
                        self.metadata.repos.push(repo);
                        total_new_repos_added += 1;
                    }
                }
            }
        }
        self.metadata.save();
        if total_new_repos_added > 0 {
            let repo_str = if total_new_repos_added == 1 {
                "repository"
            } else {
                "repositories"
            };
            Self::success_message(&format!(
                "Scan complete. {} new {} added.",
                total_new_repos_added, repo_str
            ));
        } else {
            Self::success_message("Scan complete. No new repositories found.");
        }
    }

    pub fn clean() {
        if let Ok(config_path) = PjiConfig::get_config_file_path() {
            remove_file(config_path).expect("Failed to remove config file");
        }

        if let Ok(metadata_path) = PjiMetadata::get_metadata_file_path() {
            remove_file(metadata_path).expect("Failed to remove metadata file");
        }

        Self::success_message("🧹 Project data cleaned successfully.");
    }

    fn get_repos_from_root(root: &PathBuf) -> Option<Vec<PjiRepo>> {
        if !root.is_dir() {
            return None;
        }
        let mut repos = vec![];
        let mut invalid_repo_paths: Vec<String> = Vec::new();

        if let Ok(hostname_dirs) = list_dir(root) {
            for hostname_dir in hostname_dirs {
                if let Ok(user_dirs) = list_dir(&hostname_dir) {
                    for user_dir in user_dirs {
                        if let Ok(repo_dirs) = list_dir(&user_dir) {
                            for repo_dir in repo_dirs {
                                // Skip linked worktrees - they belong to their main repo
                                if is_linked_worktree(&repo_dir) {
                                    continue;
                                }

                                // Skip .worktrees directories
                                if repo_dir
                                    .file_name()
                                    .and_then(|n| n.to_str())
                                    .map(|n| n.ends_with(".worktrees"))
                                    .unwrap_or(false)
                                {
                                    continue;
                                }

                                if let Some(repo_url) = try_get_repo_from_dir(&repo_dir) {
                                    let repo = PjiRepo::new(&repo_url, root);
                                    if repo.dir == repo_dir {
                                        repos.push(repo);
                                    } else {
                                        invalid_repo_paths.push(repo_dir.display().to_string());
                                    }
                                } else {
                                    invalid_repo_paths.push(repo_dir.display().to_string());
                                }
                            }
                        }
                    }
                }
            }
        }
        if !invalid_repo_paths.is_empty() {
            Self::warn_message("The following paths were found but are not valid pji repositories or have an unexpected structure:");
            for path_str in invalid_repo_paths {
                println!("  - {}", path_str);
            }
        }
        Some(repos)
    }

    pub fn open_home(&mut self, query: Option<String>) {
        let repo = match query {
            Some(query) => self
                .find_repo("Open repo: ", &query)
                .expect("repo not found"),
            None => self
                .get_cwd_repo()
                .expect("No repo found in current directory"),
        };

        let url = repo
            .get_home_url()
            .expect(&format!("No home URL found for {}", repo.git_uri.uri));
        Self::open_url(&url);
    }

    pub fn open_pr(&self, pr: Option<u32>) {
        let repo = self
            .get_cwd_repo()
            .expect("No repo found in current directory");

        let url = repo
            .get_pr_url(pr)
            .expect(&format!("No PR found for {}", repo.git_uri.uri));
        Self::open_url(&url);
    }

    pub fn open_issue(&self, issue: Option<u32>) {
        let repo = self
            .get_cwd_repo()
            .expect("No repo found in current directory");
        let url = repo
            .get_issue_url(issue)
            .expect(&format!("No issue found for {}", repo.git_uri.uri));
        Self::open_url(&url);
    }

    fn get_cwd_repo(&self) -> Option<&PjiRepo> {
        let cwd = env::current_dir().ok()?;

        // First check if we're in a linked worktree and resolve to main repo
        let resolved_dir = if is_linked_worktree(&cwd) {
            get_main_repo_from_worktree(&cwd)?
        } else {
            // Check if any parent is a linked worktree
            let mut check_dir = cwd.clone();
            let mut found_main = None;
            loop {
                if is_linked_worktree(&check_dir) {
                    found_main = get_main_repo_from_worktree(&check_dir);
                    break;
                }
                if !check_dir.pop() {
                    break;
                }
            }
            found_main.unwrap_or(cwd)
        };

        // Find the repo that matches the resolved directory
        self.metadata
            .repos
            .iter()
            .find(|repo| resolved_dir.starts_with(&repo.dir))
    }

    fn open_url(url: &str) {
        println!("🌐 Opening URL in browser: {}", style(url).cyan());
        webbrowser::open(url).expect("Failed to open browser");
    }

    fn clone_repo(repo: &str, dir: &str) -> io::Result<()> {
        let mut cmd = Command::new("git");
        cmd.args(["clone", repo, dir]);
        cmd.stdout(Stdio::inherit());
        cmd.stderr(Stdio::inherit());

        // Spawn the command
        let mut child = cmd.spawn()?;

        // Wait for the command to finish
        let status = child.wait()?;
        if !status.success() {
            return Err(io::Error::new(io::ErrorKind::Other, "git clone failed"));
        }
        Ok(())
    }

    fn find_repo(&mut self, prompt: &str, query: &str) -> Option<&mut PjiRepo> {
        self.metadata
            .repos
            .sort_by(|a, b| b.last_open_time.cmp(&a.last_open_time));

        let mut counts = std::collections::HashMap::new();
        for repo in &self.metadata.repos {
            let key = format!("{}/{}", repo.git_uri.user, repo.git_uri.repo);
            *counts.entry(key).or_insert(0) += 1;
        }

        let items = self
            .metadata
            .repos
            .iter()
            .map(|repo| {
                let key = format!("{}/{}", repo.git_uri.user, repo.git_uri.repo);
                // if there are multiple repos with the same user/repo, show the full path
                if *counts.get(&key).unwrap_or(&0) > 1 {
                    repo.dir.display().to_string()
                } else {
                    key
                }
            })
            .collect::<Vec<String>>();

        let selection = FuzzySelect::new()
            .with_prompt(prompt)
            .with_initial_text(query)
            .default(0)
            .highlight_matches(true)
            .max_length(10)
            .items(&items)
            .interact()
            .unwrap();

        self.metadata.repos.get_mut(selection)
    }

    fn success_message(message: &str) {
        println!("🚀 {}", style(message).green());
    }

    fn warn_message(message: &str) {
        println!("⚠️  {}", style(message).yellow());
    }

    fn copy_to_clipboard(text: &str, context_message: &str) {
        Clipboard::new()
            .expect("can't find clipboard")
            .set_text(text)
            .expect("can't set clipboard");

        println!(
            "📋 Copied \"{}\" to clipboard. {}", // Changed
            style(text).green(),
            context_message
        )
    }

    fn confirm(message: &str) -> bool {
        let confirmation = Confirm::new()
            .with_prompt(format!("{}", style(message).yellow()))
            .interact()
            .unwrap();
        confirmation
    }

    // ==================== Worktree Commands ====================

    /// List worktrees for current or selected repository
    pub fn worktree_list(&mut self, query: Option<String>) {
        let repo_dir = self.get_worktree_repo_dir(query);
        let repo_dir = match repo_dir {
            Some(dir) => dir,
            None => {
                Self::warn_message("No repository found.");
                return;
            }
        };

        match list_worktrees(&repo_dir) {
            Some(worktrees) => {
                let mut table = Table::new();
                table.set_header(vec!["Path", "Branch", "Status"]);

                for wt in worktrees.all() {
                    let status = if wt.is_main {
                        "main".to_string()
                    } else if wt.locked {
                        "locked".to_string()
                    } else if wt.prunable {
                        "prunable".to_string()
                    } else {
                        "".to_string()
                    };

                    table.add_row(vec![
                        wt.path.display().to_string(),
                        wt.branch.clone().unwrap_or_else(|| format!("({})", &wt.commit[..8.min(wt.commit.len())])),
                        status,
                    ]);
                }

                println!("{table}");
                println!("\nTotal: {} worktree(s)", worktrees.count());
            }
            None => {
                println!("No worktrees found for this repository.");
            }
        }
    }

    /// Fuzzy select and switch to a worktree
    pub fn worktree_switch(&mut self, query: Option<String>) {
        let repo_dir = self.get_worktree_repo_dir(None);
        let repo_dir = match repo_dir {
            Some(dir) => dir,
            None => {
                Self::warn_message("No repository found in current directory.");
                return;
            }
        };

        let worktrees = match list_worktrees(&repo_dir) {
            Some(wts) if wts.count() > 1 => wts,
            Some(_) => {
                Self::warn_message("Only one worktree exists. Nothing to switch to.");
                return;
            }
            None => {
                Self::warn_message("No worktrees found for this repository.");
                return;
            }
        };

        let selected = self.select_worktree(&worktrees, query.as_deref().unwrap_or(""));
        if let Some(wt) = selected {
            self.exec_into_dir(&wt.path);
        }
    }

    /// Create a new worktree with interactive flow
    pub fn worktree_add(&mut self) {
        let repo_dir = self.get_worktree_repo_dir(None);
        let repo_dir = match repo_dir {
            Some(dir) => dir,
            None => {
                Self::warn_message("No repository found in current directory.");
                return;
            }
        };

        // Interactive flow
        let (final_branch, create_new, base_branch) =
            match self.select_branch_for_worktree(&repo_dir) {
                Some(result) => result,
                None => return,
            };

        // Get default path and allow user to edit
        let default_path = get_default_worktree_path(&repo_dir, &final_branch);
        let worktree_path: String = Input::new()
            .with_prompt("Worktree path")
            .default(default_path.display().to_string())
            .interact_text()
            .unwrap();

        let worktree_path = PathBuf::from(worktree_path);

        match add_worktree(
            &repo_dir,
            &final_branch,
            Some(worktree_path.clone()),
            create_new,
            base_branch.as_deref(),
        ) {
            Ok(worktree_path) => {
                Self::success_message(&format!(
                    "Worktree created at '{}'",
                    worktree_path.display()
                ));
                self.exec_into_dir(&worktree_path);
            }
            Err(e) => {
                eprintln!("Failed to create worktree: {}", e);
            }
        }
    }

    /// Interactive branch selection for worktree creation
    /// Returns: (branch_name, create_new_branch, base_branch)
    fn select_branch_for_worktree(
        &self,
        repo_dir: &PathBuf,
    ) -> Option<(String, bool, Option<String>)> {
        // Step 1: Select branch source
        let source_options = vec!["Local branch", "Remote branch", "New branch"];
        let source_selection = Select::new()
            .with_prompt("Select branch source")
            .default(0)
            .items(&source_options)
            .interact()
            .ok()?;

        match source_selection {
            0 => {
                // Local branch
                let local_branches = list_local_branches(repo_dir);
                if local_branches.is_empty() {
                    Self::warn_message("No local branches found.");
                    return None;
                }

                // Put main at the front
                let local_branches = Self::prioritize_main_branch(local_branches, "main");

                let selection = FuzzySelect::new()
                    .with_prompt("Select local branch")
                    .default(0)
                    .highlight_matches(true)
                    .max_length(10)
                    .items(&local_branches)
                    .interact()
                    .ok()?;

                Some((local_branches[selection].clone(), false, None))
            }
            1 => {
                // Remote branch
                let remote_branches = list_remote_branches(repo_dir);
                if remote_branches.is_empty() {
                    Self::warn_message("No remote branches found. Try running 'git fetch' first.");
                    return None;
                }

                // Put origin/main at the front
                let remote_branches = Self::prioritize_main_branch(remote_branches, "origin/main");

                let selection = FuzzySelect::new()
                    .with_prompt("Select remote branch")
                    .default(0)
                    .highlight_matches(true)
                    .max_length(10)
                    .items(&remote_branches)
                    .interact()
                    .ok()?;

                Some((remote_branches[selection].clone(), false, None))
            }
            2 => {
                // New branch
                let new_branch_name: String = Input::new()
                    .with_prompt("Enter new branch name")
                    .interact_text()
                    .ok()?;

                if new_branch_name.is_empty() {
                    Self::warn_message("Branch name cannot be empty.");
                    return None;
                }

                // Get all branches for base selection
                let local_branches = list_local_branches(repo_dir);
                let remote_branches = list_remote_branches(repo_dir);

                // Combine branches
                let mut all_branches: Vec<String> = Vec::new();
                all_branches.extend(remote_branches);
                all_branches.extend(local_branches);

                if all_branches.is_empty() {
                    // No branches to base off, will use HEAD
                    return Some((new_branch_name, true, None));
                }

                // Put origin/main or main at the front
                let all_branches = Self::prioritize_main_branch(all_branches, "origin/main");

                let selection = FuzzySelect::new()
                    .with_prompt("Select base branch")
                    .default(0)
                    .highlight_matches(true)
                    .max_length(10)
                    .items(&all_branches)
                    .interact()
                    .ok()?;

                Some((
                    new_branch_name,
                    true,
                    Some(all_branches[selection].clone()),
                ))
            }
            _ => None,
        }
    }

    /// Move the preferred branch to the front of the list
    fn prioritize_main_branch(mut branches: Vec<String>, preferred: &str) -> Vec<String> {
        if let Some(idx) = branches.iter().position(|b| b == preferred) {
            let branch = branches.remove(idx);
            branches.insert(0, branch);
        } else if preferred == "origin/main" {
            // Fallback to main if origin/main not found
            if let Some(idx) = branches.iter().position(|b| b == "main") {
                let branch = branches.remove(idx);
                branches.insert(0, branch);
            }
        }
        branches
    }

    /// Remove a worktree
    pub fn worktree_remove(&mut self, worktree: Option<String>, force: bool) {
        let repo_dir = self.get_worktree_repo_dir(None);
        let repo_dir = match repo_dir {
            Some(dir) => dir,
            None => {
                Self::warn_message("No repository found in current directory.");
                return;
            }
        };

        let worktrees = match list_worktrees(&repo_dir) {
            Some(wts) if !wts.linked.is_empty() => wts,
            Some(_) => {
                Self::warn_message("No linked worktrees to remove.");
                return;
            }
            None => {
                Self::warn_message("No worktrees found for this repository.");
                return;
            }
        };

        // Determine which worktree to remove
        let worktree_path = match worktree {
            Some(wt_str) => {
                // Try to find worktree by path or branch name
                let found = worktrees.linked.iter().find(|wt| {
                    wt.path.to_string_lossy().contains(&wt_str)
                        || wt.branch.as_deref() == Some(&wt_str)
                });
                match found {
                    Some(wt) => wt.path.clone(),
                    None => {
                        Self::warn_message(&format!("Worktree '{}' not found.", wt_str));
                        return;
                    }
                }
            }
            None => {
                // Interactive selection from linked worktrees only
                let items: Vec<String> = worktrees
                    .linked
                    .iter()
                    .map(|wt| {
                        format!(
                            "{} ({})",
                            wt.branch.as_deref().unwrap_or("detached"),
                            wt.path.display()
                        )
                    })
                    .collect();

                let selection = FuzzySelect::new()
                    .with_prompt("Select worktree to remove")
                    .default(0)
                    .highlight_matches(true)
                    .items(&items)
                    .interact()
                    .unwrap();

                worktrees.linked[selection].path.clone()
            }
        };

        // Confirm removal
        if !Self::confirm(&format!(
            "Remove worktree at '{}'?",
            worktree_path.display()
        )) {
            println!("Removal cancelled.");
            return;
        }

        match remove_worktree(&repo_dir, &worktree_path, force) {
            Ok(()) => {
                Self::success_message(&format!(
                    "Worktree '{}' removed successfully.",
                    worktree_path.display()
                ));
            }
            Err(e) => {
                eprintln!("Failed to remove worktree: {}", e);
                if !force {
                    println!("Tip: Use --force to force removal of dirty worktrees.");
                }
            }
        }
    }

    /// Clean up stale worktree information
    pub fn worktree_prune(&self) {
        let repo_dir = self.get_cwd_repo_dir();
        let repo_dir = match repo_dir {
            Some(dir) => dir,
            None => {
                Self::warn_message("No repository found in current directory.");
                return;
            }
        };

        match prune_worktrees(&repo_dir) {
            Ok(output) => {
                if output.is_empty() {
                    println!("No stale worktree entries to prune.");
                } else {
                    println!("{}", output);
                    Self::success_message("Worktree pruning complete.");
                }
            }
            Err(e) => {
                eprintln!("Failed to prune worktrees: {}", e);
            }
        }
    }

    /// Get the repository directory for worktree operations
    /// If in a worktree, returns the main repo directory
    fn get_worktree_repo_dir(&mut self, query: Option<String>) -> Option<PathBuf> {
        match query {
            Some(q) => {
                let repo = self.find_repo("Select repository: ", &q)?;
                Some(repo.dir.clone())
            }
            None => self.get_cwd_repo_dir(),
        }
    }

    /// Get the current working directory's repository directory
    /// Handles both main repos and linked worktrees
    fn get_cwd_repo_dir(&self) -> Option<PathBuf> {
        let cwd = env::current_dir().ok()?;

        // First check if we're in a linked worktree
        if is_linked_worktree(&cwd) {
            return get_main_repo_from_worktree(&cwd);
        }

        // Check if cwd or any parent is a linked worktree
        let mut check_dir = cwd.clone();
        loop {
            if is_linked_worktree(&check_dir) {
                return get_main_repo_from_worktree(&check_dir);
            }
            if check_dir.join(".git").is_dir() {
                return Some(check_dir);
            }
            if !check_dir.pop() {
                break;
            }
        }

        // Fall back to checking metadata repos
        self.metadata
            .repos
            .iter()
            .find(|repo| cwd.starts_with(&repo.dir))
            .map(|repo| repo.dir.clone())
    }

    /// Select a worktree from the list using fuzzy selection
    fn select_worktree<'a>(
        &self,
        worktrees: &'a worktree::WorktreeList,
        query: &str,
    ) -> Option<&'a GitWorktree> {
        let all_worktrees = worktrees.all();
        let items: Vec<String> = all_worktrees
            .iter()
            .map(|wt| {
                let status = if wt.is_main { " (main)" } else { "" };
                format!(
                    "{}{}  {}",
                    wt.branch.as_deref().unwrap_or("detached"),
                    status,
                    wt.path.display()
                )
            })
            .collect();

        let selection = FuzzySelect::new()
            .with_prompt("Select worktree")
            .with_initial_text(query)
            .default(0)
            .highlight_matches(true)
            .max_length(10)
            .items(&items)
            .interact()
            .unwrap();

        all_worktrees.get(selection).copied()
    }

    /// Execute into a directory (replace current process with shell in that directory)
    fn exec_into_dir(&self, dir: &PathBuf) {
        let shell = env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());

        let err = Command::new(&shell).current_dir(dir).exec();

        eprintln!("Failed to exec shell: {}", err);
    }
}