code2prompt 4.2.0

Command-line interface for code2prompt
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
//! Data structures and application state management for the TUI.
//!
//! This module contains the core data structures that represent the application state,
//! including the main Model struct, tab definitions, message types for event handling,
//! and all state management submodules. It serves as the central state container
//! for the terminal user interface.

pub mod commands;
pub mod prompt_output;
pub mod settings;
pub mod statistics;
pub mod template;

pub use commands::*;
pub use prompt_output::*;
pub use settings::*;
pub use statistics::*;
pub use template::*;

use crate::utils::directory_contains_selected_files;
use code2prompt_core::session::Code2PromptSession;

/// The five main tabs of the TUI
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tab {
    FileTree,
    Settings,
    Statistics,
    Template,
    PromptOutput,
}

/// Input mode for the FileTree tab
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileTreeInputMode {
    Normal,
    Search,
}

/// Hierarchical file node for TUI display with proper parent-child relationships
#[derive(Debug, Clone)]
pub struct DisplayFileNode {
    pub path: std::path::PathBuf,
    pub name: String,
    pub is_directory: bool,
    pub is_expanded: bool,
    pub level: usize,
    pub children_loaded: bool,
    pub children: Vec<DisplayFileNode>,
}

impl DisplayFileNode {
    pub fn new(path: std::path::PathBuf, level: usize) -> Self {
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| path.to_string_lossy().to_string());

        let is_directory = path.is_dir();

        Self {
            path,
            name,
            is_directory,
            is_expanded: false,
            level,
            children_loaded: false,
            children: Vec::new(),
        }
    }

    /// Find a node by path in the tree (recursive)
    pub fn find_node_mut(&mut self, target_path: &std::path::Path) -> Option<&mut DisplayFileNode> {
        if self.path == target_path {
            return Some(self);
        }

        for child in &mut self.children {
            if let Some(found) = child.find_node_mut(target_path) {
                return Some(found);
            }
        }

        None
    }

    /// Load children for this directory node
    pub fn load_children(
        &mut self,
        session: &mut code2prompt_core::session::Code2PromptSession,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if !self.is_directory || self.children_loaded {
            return Ok(());
        }

        self.children.clear();

        // Use ignore crate to respect gitignore
        use ignore::WalkBuilder;
        let walker = WalkBuilder::new(&self.path).max_depth(Some(1)).build();

        for entry in walker {
            let entry = entry?;
            let path = entry.path();

            if path == self.path {
                continue; // Skip self
            }

            let mut child = DisplayFileNode::new(path.to_path_buf(), self.level + 1);

            // Auto-expand if contains selected files
            if child.is_directory && directory_contains_selected_files(&child.path, session) {
                child.is_expanded = true;
            }

            self.children.push(child);
        }

        // Sort children: directories first, then alphabetically
        self.children
            .sort_by(|a, b| match (a.is_directory, b.is_directory) {
                (true, false) => std::cmp::Ordering::Less,
                (false, true) => std::cmp::Ordering::Greater,
                _ => a.name.cmp(&b.name),
            });

        self.children_loaded = true;
        Ok(())
    }
}

/// Messages for updating the model
#[derive(Debug, Clone)]
pub enum Message {
    SwitchTab(Tab),
    Quit,

    UpdateSearchQuery(String),
    ToggleFileSelection(usize),
    ExpandDirectory(usize),
    CollapseDirectory(usize),
    MoveTreeCursor(i32),
    RefreshFileTree,

    EnterSearchMode,
    ExitSearchMode,

    MoveSettingsCursor(i32),
    ToggleSetting(usize),
    CycleSetting(usize),

    RunAnalysis,
    AnalysisComplete(AnalysisResults),
    AnalysisError(String),

    CopyToClipboard,
    SaveToFile(String),
    ScrollOutput(i16),

    CycleStatisticsView(i8),
    ScrollStatistics(i16),

    SaveTemplate(String),
    ReloadTemplate,
    LoadTemplate,
    RefreshTemplates,

    SetTemplateFocus(TemplateFocus, FocusMode),
    SetTemplateFocusMode(FocusMode),
    TemplateEditorInput(ratatui::crossterm::event::KeyEvent),
    TemplatePickerMove(i32),

    VariableStartEditing(String),
    VariableInputChar(char),
    VariableInputBackspace,
    VariableInputEnter,
    VariableInputCancel,
    VariableNavigateUp,
    VariableNavigateDown,
}

/// Represents the overall state of the TUI application.
#[derive(Debug, Clone)]
pub struct Model {
    pub session: Code2PromptSession,
    pub current_tab: Tab,
    pub should_quit: bool,
    pub file_tree_input_mode: FileTreeInputMode,
    pub file_tree_nodes: Vec<DisplayFileNode>,
    pub search_query: String,
    pub tree_cursor: usize,
    pub file_tree_scroll: u16,
    pub settings: SettingsState,
    pub statistics: StatisticsState,
    pub template: TemplateState,
    pub prompt_output: PromptOutputState,
    pub status_message: String,
}

impl Default for Model {
    fn default() -> Self {
        let config = code2prompt_core::configuration::Code2PromptConfig::default();
        let session = Code2PromptSession::new(config);

        Model {
            session,
            current_tab: Tab::FileTree,
            should_quit: false,
            file_tree_input_mode: FileTreeInputMode::Normal,
            file_tree_nodes: Vec::new(),
            search_query: String::new(),
            tree_cursor: 0,
            file_tree_scroll: 0,
            settings: SettingsState::default(),
            statistics: StatisticsState::default(),
            template: TemplateState::default(),
            prompt_output: PromptOutputState::default(),
            status_message: String::new(),
        }
    }
}

impl Model {
    pub fn new(session: Code2PromptSession) -> Self {
        Model {
            session,
            current_tab: Tab::FileTree,
            should_quit: false,
            file_tree_input_mode: FileTreeInputMode::Normal,
            file_tree_nodes: Vec::new(),
            search_query: String::new(),
            tree_cursor: 0,
            file_tree_scroll: 0,
            settings: SettingsState::default(),
            statistics: StatisticsState::default(),
            template: TemplateState::default(),
            prompt_output: PromptOutputState::default(),
            status_message: String::new(),
        }
    }

    /// Get grouped settings for display
    pub fn get_settings_groups(&self) -> Vec<SettingsGroup> {
        crate::view::format_settings_groups(&self.session)
    }

    pub fn update(&self, message: Message) -> (Self, Cmd) {
        let mut new_model = self.clone();

        match message {
            Message::Quit => {
                new_model.should_quit = true;
                new_model.status_message = "Goodbye!".to_string();
                (new_model, Cmd::None)
            }

            Message::SwitchTab(tab) => {
                new_model.current_tab = tab;
                new_model.status_message = format!("Switched to {:?} tab", tab);
                (new_model, Cmd::None)
            }

            Message::RefreshFileTree => {
                new_model.status_message = "Refreshing file tree...".to_string();
                (new_model, Cmd::RefreshFileTree)
            }

            Message::UpdateSearchQuery(query) => {
                new_model.search_query = query;
                new_model.tree_cursor = 0; // Reset cursor when search changes
                new_model.file_tree_scroll = 0; // Reset scroll when search changes
                (new_model, Cmd::None)
            }

            Message::EnterSearchMode => {
                new_model.file_tree_input_mode = FileTreeInputMode::Search;
                new_model.status_message = "Search mode - Type to search, Esc to exit".to_string();
                (new_model, Cmd::None)
            }

            Message::ExitSearchMode => {
                new_model.file_tree_input_mode = FileTreeInputMode::Normal;
                new_model.status_message = "Exited search mode".to_string();
                (new_model, Cmd::None)
            }

            Message::MoveTreeCursor(delta) => {
                let visible_nodes = crate::utils::get_visible_nodes(
                    &new_model.file_tree_nodes,
                    &new_model.search_query,
                    &mut new_model.session,
                );
                let visible_count = visible_nodes.len();

                if visible_count > 0 {
                    let new_cursor = if delta > 0 {
                        (new_model.tree_cursor + delta as usize).min(visible_count - 1)
                    } else {
                        new_model.tree_cursor.saturating_sub((-delta) as usize)
                    };
                    new_model.tree_cursor = new_cursor;
                }
                (new_model, Cmd::None)
            }

            Message::MoveSettingsCursor(delta) => {
                let settings_count = new_model
                    .settings
                    .get_settings_items(&new_model.session)
                    .len();
                if settings_count > 0 {
                    let new_cursor = if delta > 0 {
                        (new_model.settings.settings_cursor + delta as usize)
                            .min(settings_count - 1)
                    } else {
                        new_model
                            .settings
                            .settings_cursor
                            .saturating_sub((-delta) as usize)
                    };
                    new_model.settings.settings_cursor = new_cursor;
                }
                (new_model, Cmd::None)
            }

            Message::ToggleFileSelection(index) => {
                let visible_nodes = crate::utils::get_visible_nodes(
                    &new_model.file_tree_nodes,
                    &new_model.search_query,
                    &mut new_model.session,
                );

                if let Some(display_node) = visible_nodes.get(index) {
                    let node_path = display_node.node.path.clone();
                    let name = display_node.node.name.clone();
                    let is_directory = display_node.node.is_directory;
                    let current = display_node.is_selected;

                    // Convert to relative path for session
                    let relative_path =
                        if let Ok(rel) = node_path.strip_prefix(&new_model.session.config.path) {
                            rel.to_path_buf()
                        } else {
                            node_path.clone()
                        };

                    // Update session selection state (single source of truth)
                    new_model.session.toggle_file_selection(relative_path);

                    let action = if current { "Deselected" } else { "Selected" };
                    let extra = if is_directory { " (and contents)" } else { "" };
                    new_model.status_message = format!("{} {}{}", action, name, extra);
                }
                (new_model, Cmd::None)
            }

            Message::ExpandDirectory(index) => {
                let visible_nodes = crate::utils::get_visible_nodes(
                    &new_model.file_tree_nodes,
                    &new_model.search_query,
                    &mut new_model.session,
                );

                if let Some(display_node) = visible_nodes.get(index)
                    && display_node.node.is_directory
                {
                    let node_path = display_node.node.path.clone();
                    let name = display_node.node.name.clone();

                    // Ensure the path exists in the tree first
                    if let Err(e) = crate::utils::ensure_path_exists_in_tree(
                        &mut new_model.file_tree_nodes,
                        &node_path,
                        &mut new_model.session,
                    ) {
                        new_model.status_message =
                            format!("Failed to ensure path exists for {}: {}", name, e);
                        return (new_model, Cmd::None);
                    }

                    // Find and expand the node in the tree
                    let mut found = false;
                    for root_node in &mut new_model.file_tree_nodes {
                        if let Some(node) = root_node.find_node_mut(&node_path) {
                            if !node.is_expanded {
                                node.is_expanded = true;
                                // Load children if not already loaded
                                if !node.children_loaded
                                    && let Err(e) = node.load_children(&mut new_model.session)
                                {
                                    new_model.status_message =
                                        format!("Failed to load children for {}: {}", name, e);
                                    return (new_model, Cmd::None);
                                }
                                new_model.status_message = format!("Expanded {}", name);
                            } else {
                                new_model.status_message = format!("{} is already expanded", name);
                            }
                            found = true;
                            break;
                        }
                    }

                    if !found {
                        new_model.status_message = format!("Could not find directory {}", name);
                    }
                }
                (new_model, Cmd::None)
            }

            Message::CollapseDirectory(index) => {
                let visible_nodes = crate::utils::get_visible_nodes(
                    &new_model.file_tree_nodes,
                    &new_model.search_query,
                    &mut new_model.session,
                );

                if let Some(display_node) = visible_nodes.get(index)
                    && display_node.node.is_directory
                {
                    let node_path = display_node.node.path.clone();
                    let name = display_node.node.name.clone();

                    // Find and collapse the node in the tree
                    let mut found = false;
                    for root_node in &mut new_model.file_tree_nodes {
                        if let Some(node) = root_node.find_node_mut(&node_path)
                            && node.is_expanded
                        {
                            node.is_expanded = false;
                            new_model.status_message = format!("Collapsed {}", name);
                            found = true;
                            break;
                        }
                    }

                    if !found {
                        new_model.status_message = format!("Could not find directory {}", name);
                    }
                }
                (new_model, Cmd::None)
            }

            Message::ToggleSetting(index) => {
                let items = new_model.settings.get_settings_items(&new_model.session);
                if let Some(item) = items.get(index) {
                    let setting_name = new_model.settings.update_setting_by_key(
                        &mut new_model.session,
                        item.key,
                        SettingAction::Toggle,
                    );
                    new_model.status_message = format!("Toggled {}", setting_name);
                } else {
                    new_model.status_message = format!("Invalid setting index: {}", index);
                }
                (new_model, Cmd::None)
            }

            Message::CycleSetting(index) => {
                let items = new_model.settings.get_settings_items(&new_model.session);
                if let Some(item) = items.get(index) {
                    let setting_name = new_model.settings.update_setting_by_key(
                        &mut new_model.session,
                        item.key,
                        SettingAction::Cycle,
                    );
                    new_model.status_message = format!("Cycled {}", setting_name);
                } else {
                    new_model.status_message = format!("Invalid setting index: {}", index);
                }
                (new_model, Cmd::None)
            }

            Message::RunAnalysis => {
                if !new_model.prompt_output.analysis_in_progress {
                    new_model.prompt_output.analysis_in_progress = true;
                    new_model.prompt_output.analysis_error = None;
                    new_model.status_message = "Running analysis...".to_string();
                    new_model.current_tab = Tab::PromptOutput; // Switch to output tab

                    let cmd = Cmd::RunAnalysis {
                        template_content: new_model.template.get_template_content().to_string(),
                        user_variables: new_model.template.variables.user_variables.clone(),
                    };
                    (new_model, cmd)
                } else {
                    new_model.status_message = "Analysis already in progress...".to_string();
                    (new_model, Cmd::None)
                }
            }

            Message::AnalysisComplete(results) => {
                new_model.prompt_output.analysis_in_progress = false;
                new_model.prompt_output.generated_prompt = Some(results.generated_prompt);
                new_model.prompt_output.token_count = results.token_count;
                new_model.prompt_output.file_count = results.file_count;
                // Reset output scroll so the new content starts at the top.
                new_model.prompt_output.output_scroll = 0;
                new_model.statistics.token_map_entries = results.token_map_entries;
                let tokens = results.token_count.unwrap_or(0);
                new_model.status_message = format!(
                    "Analysis complete! {} tokens, {} files",
                    tokens, results.file_count
                );
                (new_model, Cmd::None)
            }

            Message::AnalysisError(error) => {
                new_model.prompt_output.analysis_in_progress = false;
                new_model.prompt_output.analysis_error = Some(error.clone());
                new_model.status_message = format!("Analysis failed: {}", error);
                (new_model, Cmd::None)
            }

            Message::CopyToClipboard => {
                if let Some(prompt) = &new_model.prompt_output.generated_prompt {
                    let cmd = Cmd::CopyToClipboard(prompt.clone());
                    (new_model, cmd)
                } else {
                    new_model.status_message = "No prompt to copy".to_string();
                    (new_model, Cmd::None)
                }
            }

            Message::SaveToFile(filename) => {
                if let Some(prompt) = &new_model.prompt_output.generated_prompt {
                    let cmd = Cmd::SaveToFile {
                        filename,
                        content: prompt.clone(),
                    };
                    (new_model, cmd)
                } else {
                    new_model.status_message = "No prompt to save".to_string();
                    (new_model, Cmd::None)
                }
            }

            Message::ScrollOutput(delta) => {
                // Apply delta only; widgets will clamp based on actual viewport.
                let new_scroll = if delta < 0 {
                    new_model
                        .prompt_output
                        .output_scroll
                        .saturating_sub((-delta) as u16)
                } else {
                    new_model
                        .prompt_output
                        .output_scroll
                        .saturating_add(delta as u16)
                };
                new_model.prompt_output.output_scroll = new_scroll;
                (new_model, Cmd::None)
            }

            Message::CycleStatisticsView(direction) => {
                new_model.statistics.view = if direction > 0 {
                    new_model.statistics.view.next()
                } else {
                    new_model.statistics.view.prev()
                };
                new_model.statistics.scroll = 0;
                new_model.status_message =
                    format!("Switched to {} view", new_model.statistics.view.as_str());
                (new_model, Cmd::None)
            }

            Message::ScrollStatistics(delta) => {
                let new_scroll = if delta < 0 {
                    new_model.statistics.scroll.saturating_sub((-delta) as u16)
                } else {
                    new_model.statistics.scroll.saturating_add(delta as u16)
                };
                new_model.statistics.scroll = new_scroll;
                (new_model, Cmd::None)
            }

            Message::SaveTemplate(filename) => {
                let content = new_model.template.get_template_content().to_string();
                let cmd = Cmd::SaveTemplate {
                    filename: filename.clone(),
                    content,
                };
                new_model.status_message = "Saving template...".to_string();
                (new_model, cmd)
            }

            Message::ReloadTemplate => {
                new_model.template.editor = crate::model::template::EditorState::default();
                new_model.template.sync_variables_with_template();
                new_model.status_message = "Reloaded template".to_string();
                (new_model, Cmd::None)
            }

            Message::LoadTemplate => {
                let result = new_model.template.load_selected_template();
                match result {
                    Ok(template_name) => {
                        new_model.template.sync_variables_with_template();
                        new_model.status_message = format!("Loaded template: {}", template_name);
                    }
                    Err(e) => {
                        new_model.status_message = format!("Failed to load template: {}", e);
                    }
                }
                (new_model, Cmd::None)
            }

            Message::RefreshTemplates => {
                new_model.template.picker.refresh();
                new_model.status_message = "Templates refreshed".to_string();
                (new_model, Cmd::None)
            }

            Message::SetTemplateFocus(focus, mode) => {
                new_model.template.set_focus(focus);
                new_model.template.set_focus_mode(mode);
                if mode == crate::model::template::FocusMode::EditingVariable {
                    new_model
                        .template
                        .variables
                        .move_to_first_missing_variable();
                }
                new_model.status_message = format!("Template focus: {:?} ({:?})", focus, mode);
                (new_model, Cmd::None)
            }

            Message::SetTemplateFocusMode(mode) => {
                new_model.template.set_focus_mode(mode);
                new_model.status_message = format!("Template mode: {:?}", mode);
                (new_model, Cmd::None)
            }

            Message::TemplateEditorInput(key) => {
                new_model.template.editor.editor.input(key);
                new_model.template.editor.sync_content_from_textarea();
                new_model.template.editor.validate_template();
                new_model.template.sync_variables_with_template();
                (new_model, Cmd::None)
            }

            Message::TemplatePickerMove(delta) => {
                if delta > 0 {
                    new_model.template.picker.move_cursor_down();
                } else {
                    new_model.template.picker.move_cursor_up();
                }
                (new_model, Cmd::None)
            }

            Message::VariableStartEditing(var_name) => {
                new_model.template.variables.editing_variable = Some(var_name.clone());
                new_model.template.variables.show_variable_input = true;
                new_model.template.variables.variable_input_content.clear();
                new_model.status_message = format!("Editing variable: {}", var_name);
                (new_model, Cmd::None)
            }

            Message::VariableInputChar(c) => {
                new_model.template.variables.add_char_to_input(c);
                (new_model, Cmd::None)
            }

            Message::VariableInputBackspace => {
                new_model.template.variables.remove_char_from_input();
                (new_model, Cmd::None)
            }

            Message::VariableInputEnter => {
                if let Some((var_name, value)) = new_model.template.variables.finish_editing() {
                    new_model.status_message = format!("Set {} = {}", var_name, value);
                    new_model.template.sync_variables_with_template();
                }
                (new_model, Cmd::None)
            }

            Message::VariableInputCancel => {
                new_model.template.variables.cancel_editing();
                new_model.status_message = "Cancelled variable editing".to_string();
                (new_model, Cmd::None)
            }

            Message::VariableNavigateUp => {
                if new_model.template.variables.cursor > 0 {
                    new_model.template.variables.cursor -= 1;
                }
                (new_model, Cmd::None)
            }

            Message::VariableNavigateDown => {
                let variables = new_model.template.get_organized_variables();
                if new_model.template.variables.cursor < variables.len().saturating_sub(1) {
                    new_model.template.variables.cursor += 1;
                }
                (new_model, Cmd::None)
            }
        }
    }
}