ai-code-buddy 0.4.20

An AI-powered code review tool with elegant Bevy-based TUI
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
use bevy::prelude::*;
use bevy_ratatui::{error::exit_on_error, terminal::RatatuiContext};
use crossterm::event::{KeyCode, KeyEventKind};
use ratatui::{
    buffer::Buffer,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::Style,
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, Paragraph, StatefulWidgetRef, WidgetRef},
};

use crate::{
    bevy_states::app::AppState,
    events::{app::AppEvent, reports::ReportsEvent},
    theme::THEME,
    widget_states::{
        analysis::AnalysisWidgetState,
        reports::{ExportStatus, ReportFormat, ReportsWidgetState, ViewMode},
    },
};

pub struct ReportsPlugin;

impl Plugin for ReportsPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<ReportsEvent>()
            .init_resource::<ReportsWidgetState>()
            .add_systems(PreUpdate, reports_event_handler)
            .add_systems(Update, sync_analysis_data)
            .add_systems(Update, render_reports.pipe(exit_on_error));
    }
}

fn sync_analysis_data(
    analysis_state: Res<AnalysisWidgetState>,
    mut reports_state: ResMut<ReportsWidgetState>,
) {
    // Sync review data from analysis to reports
    if let Some(review) = &analysis_state.review {
        if reports_state.review.is_none() {
            reports_state.set_review(review.clone());
        }
    }
}

fn reports_event_handler(
    mut reports_events: EventReader<ReportsEvent>,
    mut reports_state: ResMut<ReportsWidgetState>,
    mut app_events: EventWriter<AppEvent>,
) {
    for event in reports_events.read() {
        match event {
            ReportsEvent::KeyEvent(key_event) => {
                match key_event.code {
                    KeyCode::Esc => {
                        // Handle escape based on current view mode
                        match reports_state.view_mode {
                            ViewMode::Report => {
                                // Go back to selection view
                                reports_state.back_to_selection();
                            }
                            ViewMode::Selection => {
                                // Go back to overview
                                app_events.send(AppEvent::SwitchTo(AppState::Overview));
                            }
                        }
                    }
                    _ => {
                        // Only handle other keys on release to avoid double-triggering
                        if key_event.kind == KeyEventKind::Release {
                            match key_event.code {
                                KeyCode::Left => {
                                    reports_state.previous_format();
                                }
                                KeyCode::Right => {
                                    reports_state.next_format();
                                }
                                KeyCode::Tab => {
                                    reports_state.next_format();
                                }
                                KeyCode::Enter => {
                                    match reports_state.view_mode {
                                        ViewMode::Selection => {
                                            // Generate and show the report
                                            reports_state.generate_report();
                                        }
                                        ViewMode::Report => {
                                            // Export the current report
                                            export_report(&mut reports_state);
                                        }
                                    }
                                }
                                KeyCode::Char('a') => {
                                    app_events.send(AppEvent::SwitchTo(AppState::Analysis));
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
            ReportsEvent::MouseEvent(_mouse_event) => {
                // Handle mouse events if needed
            }
        }
    }
}

fn export_report(reports_state: &mut ReportsWidgetState) {
    if let Some(_review) = &reports_state.review {
        let format = match reports_state.selected_format {
            ReportFormat::Summary => "summary".to_string(),
            ReportFormat::Detailed => "detailed".to_string(),
            ReportFormat::Json => "json".to_string(),
            ReportFormat::Markdown => "markdown".to_string(),
        };

        reports_state.start_export(format.clone());

        // TODO: Implement actual file export
        let filename = format!(
            "code_review_report.{}",
            match reports_state.selected_format {
                ReportFormat::Json => "json",
                ReportFormat::Markdown => "md",
                _ => "txt",
            }
        );

        reports_state.complete_export(filename);
    }
}

fn render_reports(
    app_state: Res<State<AppState>>,
    mut ratatui_context: ResMut<RatatuiContext>,
    mut reports_state: ResMut<ReportsWidgetState>,
) -> color_eyre::Result<()> {
    if app_state.get() != &AppState::Reports {
        return Ok(());
    }

    ratatui_context.draw(|frame| {
        let area = frame.area();
        frame.render_stateful_widget_ref(ReportsWidget, area, &mut reports_state);
    })?;

    Ok(())
}

struct ReportsWidget;

impl StatefulWidgetRef for ReportsWidget {
    type State = ReportsWidgetState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3), // Title
                Constraint::Min(10),   // Content
                Constraint::Length(3), // Status bar
            ])
            .split(area);

        // Render title
        let title_text = match state.view_mode {
            ViewMode::Selection => "📊 Reports & Export",
            ViewMode::Report => "📄 Generated Report",
        };

        let title = Paragraph::new(title_text)
            .style(THEME.title_style())
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(THEME.header_style()),
            );
        title.render_ref(chunks[0], buf);

        // Render content based on view mode
        match state.view_mode {
            ViewMode::Selection => {
                if state.review.is_some() {
                    self.render_report_content(chunks[1], buf, state);
                } else {
                    self.render_no_data(chunks[1], buf);
                }
            }
            ViewMode::Report => {
                self.render_generated_report(chunks[1], buf, state);
            }
        }

        // Render status bar
        self.render_status_bar(chunks[2], buf, state);
    }
}

impl ReportsWidget {
    fn render_no_data(&self, area: Rect, buf: &mut Buffer) {
        let content = Paragraph::new(vec![
            Line::from(""),
            Line::from("No analysis data available"),
            Line::from(""),
            Line::from("Please run an analysis first before generating reports."),
            Line::from(""),
            Line::from("Press 'A' to go to the Analysis screen."),
        ])
        .alignment(Alignment::Center)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("No Data")
                .title_style(THEME.warning_style()),
        );

        content.render_ref(area, buf);
    }

    fn render_report_content(&self, area: Rect, buf: &mut Buffer, state: &ReportsWidgetState) {
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(40), // Format selection
                Constraint::Percentage(60), // Preview/Export
            ])
            .split(area);

        // Format selection
        self.render_format_selection(chunks[0], buf, state);

        // Preview/Export area
        self.render_export_area(chunks[1], buf, state);
    }

    fn render_format_selection(&self, area: Rect, buf: &mut Buffer, state: &ReportsWidgetState) {
        let formats = [
            (
                "Summary",
                ReportFormat::Summary,
                "Quick overview with key findings",
            ),
            (
                "Detailed",
                ReportFormat::Detailed,
                "Complete issue breakdown",
            ),
            ("JSON", ReportFormat::Json, "Machine-readable format"),
            (
                "Markdown",
                ReportFormat::Markdown,
                "Documentation-friendly format",
            ),
        ];

        let items: Vec<ListItem> = formats
            .iter()
            .map(|(name, format, description)| {
                let is_selected = *format == state.selected_format;
                let style = if is_selected {
                    THEME.selected_style()
                } else {
                    Style::default()
                };

                ListItem::new(vec![
                    Line::from(vec![Span::styled(
                        *name,
                        if is_selected {
                            THEME.selected_style()
                        } else {
                            THEME.text_primary.into()
                        },
                    )]),
                    Line::from(vec![Span::styled(*description, THEME.info_style())]),
                ])
                .style(style)
            })
            .collect();

        let format_list = List::new(items).block(
            Block::default()
                .borders(Borders::ALL)
                .title("Export Format")
                .title_style(THEME.header_style()),
        );

        WidgetRef::render_ref(&format_list, area, buf);
    }

    fn render_export_area(&self, area: Rect, buf: &mut Buffer, state: &ReportsWidgetState) {
        if let Some(review) = &state.review {
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([
                    Constraint::Length(8), // Preview
                    Constraint::Length(5), // Export button
                    Constraint::Min(3),    // Export status
                ])
                .split(area);

            // Preview
            self.render_preview(chunks[0], buf, state, review);

            // Export button
            self.render_export_button(chunks[1], buf);

            // Export status
            self.render_export_status(chunks[2], buf, state);
        }
    }

    fn render_preview(
        &self,
        area: Rect,
        buf: &mut Buffer,
        state: &ReportsWidgetState,
        review: &crate::core::review::Review,
    ) {
        let preview_content = match state.selected_format {
            ReportFormat::Summary => {
                vec![
                    Line::from("# Code Review Summary"),
                    Line::from(""),
                    Line::from(format!("Files analyzed: {}", review.files_count)),
                    Line::from(format!("Total issues: {}", review.issues_count)),
                    Line::from(format!("Critical: {}", review.critical_issues)),
                    Line::from(format!("High: {}", review.high_issues)),
                ]
            }
            ReportFormat::Detailed => {
                vec![
                    Line::from("# Detailed Code Review Report"),
                    Line::from(""),
                    Line::from("## Issues Found:"),
                    Line::from(format!("- {} Critical issues", review.critical_issues)),
                    Line::from(format!("- {} High priority issues", review.high_issues)),
                    Line::from("(Full details in exported file)"),
                ]
            }
            ReportFormat::Json => {
                vec![
                    Line::from("{"),
                    Line::from(
                        "  \"files_count\": {},".replace("{}", &review.files_count.to_string()),
                    ),
                    Line::from(
                        "  \"issues_count\": {},".replace("{}", &review.issues_count.to_string()),
                    ),
                    Line::from(
                        "  \"critical_issues\": {},"
                            .replace("{}", &review.critical_issues.to_string()),
                    ),
                    Line::from("  \"issues\": [...]"),
                    Line::from("}"),
                ]
            }
            ReportFormat::Markdown => {
                vec![
                    Line::from("# Code Review Report"),
                    Line::from(""),
                    Line::from("## Summary"),
                    Line::from(format!("- **Files analyzed**: {}", review.files_count)),
                    Line::from(format!("- **Total issues**: {}", review.issues_count)),
                    Line::from(""),
                    Line::from("## Issues"),
                ]
            }
        };

        let preview = Paragraph::new(preview_content)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Preview")
                    .title_style(THEME.header_style()),
            )
            .wrap(ratatui::widgets::Wrap { trim: true });

        preview.render_ref(area, buf);
    }

    fn render_export_button(&self, area: Rect, buf: &mut Buffer) {
        let button = Paragraph::new("� Generate Report (Press Enter)")
            .style(THEME.button_style(false))
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(THEME.primary)),
            );

        button.render_ref(area, buf);
    }

    fn render_export_status(&self, area: Rect, buf: &mut Buffer, state: &ReportsWidgetState) {
        let (status_text, status_style) = match &state.export_status {
            ExportStatus::None => ("Ready to export".to_string(), THEME.info_style()),
            ExportStatus::Exporting(format) => (
                format!("Exporting {format} report..."),
                THEME.warning_style(),
            ),
            ExportStatus::Success(path) => (
                format!("✅ Exported successfully to: {path}"),
                THEME.success_style(),
            ),
        };

        let status = Paragraph::new(status_text)
            .style(status_style)
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Status")
                    .title_style(THEME.header_style()),
            );

        status.render_ref(area, buf);
    }

    fn render_status_bar(&self, area: Rect, buf: &mut Buffer, state: &ReportsWidgetState) {
        let status_text = match state.view_mode {
            ViewMode::Selection => {
                if state.review.is_some() {
                    "Use ←→ or Tab to change format, Enter to generate report, A for analysis, Esc to go back"
                } else {
                    "A to run analysis, Esc to go back"
                }
            }
            ViewMode::Report => "Enter to export report, Esc to go back to selection",
        };

        let status = Paragraph::new(status_text)
            .style(THEME.info_style())
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::TOP)
                    .border_style(THEME.info_style()),
            );

        status.render_ref(area, buf);
    }

    fn render_generated_report(&self, area: Rect, buf: &mut Buffer, state: &ReportsWidgetState) {
        if let Some(report_content) = &state.generated_report {
            // Split the report into lines for scrollable display
            let lines: Vec<Line> = report_content
                .lines()
                .map(|line| Line::from(line.to_string()))
                .collect();

            let report = Paragraph::new(lines)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title(format!(
                            " {} Report ",
                            match state.selected_format {
                                ReportFormat::Summary => "Summary",
                                ReportFormat::Detailed => "Detailed",
                                ReportFormat::Json => "JSON",
                                ReportFormat::Markdown => "Markdown",
                            }
                        ))
                        .title_style(THEME.header_style()),
                )
                .wrap(ratatui::widgets::Wrap { trim: false })
                .scroll((0, 0)); // TODO: Add scrolling support

            report.render_ref(area, buf);
        } else {
            let error = Paragraph::new("No report generated")
                .alignment(Alignment::Center)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title("Error")
                        .title_style(THEME.error_style()),
                );
            error.render_ref(area, buf);
        }
    }
}