opencrates 3.0.1

Enterprise-grade AI-powered Rust development companion with comprehensive automation, monitoring, and deployment capabilities
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
//! Enhanced Terminal User Interface for `OpenCrates`
//!
//! This module provides a comprehensive terminal-based interface for interacting
//! with `OpenCrates` functionality, including project analysis, crate generation,
//! and real-time monitoring of system health and metrics.

use anyhow::Result;
use crossterm::event::{poll, read, Event as CrosstermEvent, KeyCode, KeyEventKind};
use crossterm::execute;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::prelude::{Backend, CrosstermBackend, Terminal};
use std::io::{self, stdout};
use std::sync::Arc;
use std::time::Duration;

use crate::core::OpenCrates;
use crate::tui::app::App;
use crate::tui::event::{Event, EventHandler};
use crate::tui::ui as ui_module;
use tracing::{debug, error, info, warn};

/// Application state management for the TUI
pub mod app;
/// Event handling system for user input and system events
pub mod event;
/// User interface rendering and layout management
pub mod ui;

/// Main TUI wrapper that manages the terminal interface
/// Provides a complete terminal application experience with event handling and rendering
pub struct Tui<B: Backend> {
    terminal: Terminal<B>,
    /// The main application state and logic
    pub app: App,
    event_handler: EventHandler,
}

/// Main entry point for launching the TUI application
///
/// # Arguments
/// * `core` - The `OpenCrates` core instance to use for operations
///
/// # Returns
/// Result indicating success or failure of TUI execution
///
/// # Errors
/// Returns an error if terminal setup fails or if the application encounters a critical error
pub async fn run_tui(core: Arc<OpenCrates>) -> Result<()> {
    info!("Initializing OpenCrates TUI");

    // Setup terminal
    enable_raw_mode()?;
    execute!(stdout(), EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout());
    let terminal = Terminal::new(backend)?;

    // Create event handler with 60 FPS refresh rate
    let event_handler = EventHandler::new(16); // ~60 FPS

    // Create and run TUI
    let mut tui = Tui::new(terminal, event_handler, core);
    let result = tui.run().await;

    // Cleanup terminal
    tui.exit()?;

    match result {
        Ok(()) => {
            info!("TUI exited successfully");
            Ok(())
        }
        Err(e) => {
            error!("TUI exited with error: {}", e);
            Err(e)
        }
    }
}

/// Runs the TUI with enhanced error recovery and monitoring
///
/// # Arguments
/// * `core` - The `OpenCrates` core instance
///
/// # Returns
/// Result of TUI execution with detailed error information
///
/// # Errors
/// Returns comprehensive error information if the TUI fails to run
pub async fn run_tui_with_recovery(core: Arc<OpenCrates>) -> Result<()> {
    let mut retry_count = 0;
    const MAX_RETRIES: u32 = 3;

    loop {
        match run_tui(core.clone()).await {
            Ok(()) => return Ok(()),
            Err(e) => {
                error!("TUI failed: {}", e);
                retry_count += 1;

                if retry_count >= MAX_RETRIES {
                    error!("TUI failed after {} retries", MAX_RETRIES);
                    return Err(e);
                }

                warn!(
                    "Retrying TUI startup (attempt {}/{})",
                    retry_count + 1,
                    MAX_RETRIES
                );
                tokio::time::sleep(Duration::from_secs(1)).await;
            }
        }
    }
}

impl<B: Backend + std::io::Write> Tui<B> {
    /// Creates a new TUI instance with the provided components
    ///
    /// # Arguments
    /// * `terminal` - The terminal backend for rendering
    /// * `event_handler` - Event handler for processing user input
    /// * `core` - `OpenCrates` core instance for business logic
    ///
    /// # Returns
    /// A new Tui instance ready for execution
    pub fn new(terminal: Terminal<B>, event_handler: EventHandler, core: Arc<OpenCrates>) -> Self {
        debug!("Creating new TUI instance");
        let app = App {
            opencrates: core,
            analysis: None,
            health: None,
            dependencies: Vec::new(),
            should_quit: false,
        };
        Self {
            terminal,
            app,
            event_handler,
        }
    }

    /// Main event loop for the TUI application
    ///
    /// Continuously processes events and renders the interface until the user quits
    ///
    /// # Returns
    /// Result indicating successful completion or error
    ///
    /// # Errors
    /// Returns an error if rendering fails or if a critical application error occurs
    pub async fn run(&mut self) -> Result<()> {
        debug!("Starting TUI main loop");
        self.init()?;

        // Initial data refresh
        if let Err(e) = self.app.refresh().await {
            warn!("Failed to refresh initial data: {}", e);
        }

        let mut frame_count = 0;
        let start_time = std::time::Instant::now();

        loop {
            // Render the UI
            match self
                .terminal
                .draw(|frame| ui_module::render(&mut self.app, frame))
            {
                Ok(_) => {
                    frame_count += 1;
                    if frame_count % 100 == 0 {
                        let fps = f64::from(frame_count) / start_time.elapsed().as_secs_f64();
                        debug!("Rendered {} frames, average FPS: {:.2}", frame_count, fps);
                    }
                }
                Err(e) => {
                    error!("Failed to render UI: {}", e);
                    return Err(e.into());
                }
            }

            // Handle events
            match self.event_handler.next().await {
                Ok(event) => match event {
                    Event::Quit => break,
                    Event::Custom(_) => {}
                    Event::Key(key_event) => {
                        debug!("Key event: {:?}", key_event);

                        // Handle quit requests
                        if key_event.code == KeyCode::Char('q') {
                            info!("User requested quit");
                            self.app.should_quit = true;
                        }

                        // Handle refresh requests
                        if key_event.code == KeyCode::Char('r') {
                            info!("User requested refresh");
                            if let Err(e) = self.app.refresh().await {
                                warn!("Failed to refresh data: {}", e);
                            }
                        }

                        // Handle help toggle
                        if key_event.code == KeyCode::Char('?') {
                            debug!("Help toggled");
                            // TODO: Implement help system toggle
                        }

                        // Check if app wants to quit
                        if self.app.should_quit {
                            break;
                        }
                    }
                    Event::Tick => {
                        // Periodic update
                        if let Err(e) = self.app.update().await {
                            warn!("Failed to update app: {}", e);
                        }
                    }
                    Event::Mouse(mouse_event) => {
                        debug!("Mouse event: {:?}", mouse_event);
                        // TODO: Implement mouse interaction handling
                    }
                    Event::Resize(width, height) => {
                        debug!("Terminal resized to {}x{}", width, height);
                        if let Err(e) = self
                            .terminal
                            .resize(ratatui::prelude::Rect::new(0, 0, width, height))
                        {
                            warn!("Failed to handle terminal resize: {}", e);
                        }
                    }
                },
                Err(e) => {
                    error!("Event handler error: {}", e);
                    return Err(e);
                }
            }
        }

        info!("TUI main loop completed");
        Ok(())
    }

    /// Initializes the terminal for TUI operation
    ///
    /// Sets up raw mode, alternate screen, and other terminal settings
    ///
    /// # Returns
    /// Result indicating successful initialization
    ///
    /// # Errors
    /// Returns an error if terminal setup fails
    pub fn init(&mut self) -> Result<()> {
        debug!("Initializing terminal");
        enable_raw_mode()?;
        execute!(stdout(), EnterAlternateScreen)?;
        self.terminal.hide_cursor()?;
        self.terminal.clear()?;
        Ok(())
    }

    /// Properly cleans up terminal state before exiting
    ///
    /// Restores normal terminal mode and clears alternate screen
    ///
    /// # Returns
    /// Result indicating successful cleanup
    ///
    /// # Errors
    /// Returns an error if terminal cleanup fails
    pub fn exit(&mut self) -> Result<()> {
        debug!("Cleaning up terminal");
        disable_raw_mode()?;
        execute!(stdout(), LeaveAlternateScreen)?;
        self.terminal.show_cursor()?;
        Ok(())
    }

    /// Gets the current terminal size
    ///
    /// # Returns
    /// A tuple containing (width, height) of the terminal
    pub fn size(&self) -> io::Result<(u16, u16)> {
        let size = self.terminal.size()?;
        Ok((size.width, size.height))
    }

    /// Forces a redraw of the terminal interface
    ///
    /// # Returns
    /// Result indicating successful redraw
    ///
    /// # Errors
    /// Returns an error if redrawing fails
    pub fn force_redraw(&mut self) -> Result<()> {
        debug!("Forcing terminal redraw");
        self.terminal.clear()?;
        Ok(())
    }

    /// Gets a reference to the underlying application
    ///
    /// # Returns
    /// Immutable reference to the app
    pub fn app(&self) -> &App {
        &self.app
    }

    /// Gets a mutable reference to the underlying application
    ///
    /// # Returns
    /// Mutable reference to the app
    pub fn app_mut(&mut self) -> &mut App {
        &mut self.app
    }

    /// Checks if the TUI should continue running
    ///
    /// # Returns
    /// True if the TUI should continue, false if it should exit
    pub fn should_continue(&self) -> bool {
        !self.app.should_quit
    }

    /// Processes a batch of events efficiently
    ///
    /// # Arguments
    /// * `max_events` - Maximum number of events to process in one batch
    ///
    /// # Returns
    /// Number of events processed
    ///
    /// # Errors
    /// Returns an error if event processing fails
    pub async fn process_events_batch(&mut self, max_events: usize) -> Result<usize> {
        let mut processed = 0;

        while processed < max_events {
            // Check if there are pending events without blocking
            if !poll(Duration::from_millis(1))? {
                break;
            }

            match self.event_handler.next().await {
                Ok(event) => {
                    // Process event (simplified version of main loop logic)
                    match event {
                        Event::Key(key_event) => {
                            if key_event.code == KeyCode::Char('q') {
                                self.app.should_quit = true;
                            }
                        }
                        Event::Tick => {
                            if let Err(e) = self.app.update().await {
                                warn!("Failed to update app in batch processing: {}", e);
                            }
                        }
                        _ => {}
                    }
                    processed += 1;

                    if self.app.should_quit {
                        break;
                    }
                }
                Err(e) => {
                    warn!("Error in batch event processing: {}", e);
                    break;
                }
            }
        }

        debug!("Processed {} events in batch", processed);
        Ok(processed)
    }

    /// Enables or disables mouse support
    ///
    /// # Arguments
    /// * `enable` - Whether to enable mouse support
    ///
    /// # Returns
    /// Result indicating success or failure
    pub fn set_mouse_support(&mut self, enable: bool) -> Result<()> {
        if enable {
            debug!("Enabling mouse support");
            execute!(stdout(), crossterm::event::EnableMouseCapture)?;
        } else {
            debug!("Disabling mouse support");
            execute!(stdout(), crossterm::event::DisableMouseCapture)?;
        }
        Ok(())
    }

    /// Sets the terminal title
    ///
    /// # Arguments
    /// * `title` - The title to set
    ///
    /// # Returns
    /// Result indicating success or failure
    pub fn set_title(&mut self, title: &str) -> Result<()> {
        debug!("Setting terminal title: {}", title);
        execute!(stdout(), crossterm::terminal::SetTitle(title))?;
        Ok(())
    }
}