dataprof 0.7.1

High-performance data profiler with ISO 8000/25012 quality metrics for CSV, JSON/JSONL, and Parquet files
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
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
use is_terminal::IsTerminal;
use std::fmt::Write;
use std::io::{stderr, stdout};
use std::time::{Duration, Instant};

use crate::core::memory_tracker::MemoryTracker;

/// Enhanced progress indicators for CLI operations
pub struct ProgressManager {
    pub show_progress: bool,
    pub verbosity: u8,
    pub memory_tracker: Option<MemoryTracker>,
    pub is_stdout_terminal: bool,
    pub is_stderr_terminal: bool,
}

impl ProgressManager {
    pub fn new(show_progress: bool, verbosity: u8) -> Self {
        Self {
            show_progress,
            verbosity,
            memory_tracker: None,
            is_stdout_terminal: stdout().is_terminal(),
            is_stderr_terminal: stderr().is_terminal(),
        }
    }

    /// Create a new ProgressManager with memory tracking enabled
    pub fn with_memory_tracking(
        show_progress: bool,
        verbosity: u8,
        leak_threshold_mb: usize,
    ) -> Self {
        Self {
            show_progress,
            verbosity,
            memory_tracker: Some(MemoryTracker::new(leak_threshold_mb)),
            is_stdout_terminal: stdout().is_terminal(),
            is_stderr_terminal: stderr().is_terminal(),
        }
    }

    /// Check if output is going to a terminal (interactive) vs pipe/redirect
    pub fn is_interactive(&self) -> bool {
        self.is_stdout_terminal && self.is_stderr_terminal
    }

    /// Check if output should be machine-readable (for pipes/CI)
    pub fn should_use_machine_readable_format(&self) -> bool {
        !self.is_interactive()
    }

    /// Get current memory usage from tracker
    pub fn get_memory_usage(&self) -> Option<(usize, usize, usize)> {
        self.memory_tracker
            .as_ref()
            .map(|tracker| tracker.get_memory_stats())
    }

    /// Track a memory allocation
    pub fn track_allocation(&self, resource_id: String, size_bytes: usize, resource_type: &str) {
        if let Some(ref tracker) = self.memory_tracker {
            tracker.track_allocation(resource_id, size_bytes, resource_type);
        }
    }

    /// Track a memory deallocation
    pub fn track_deallocation(&self, resource_id: &str) {
        if let Some(ref tracker) = self.memory_tracker {
            tracker.track_deallocation(resource_id);
        }
    }

    /// Create a progress bar for file processing
    pub fn create_file_progress(&self, file_size: u64, file_name: &str) -> Option<ProgressBar> {
        if !self.show_progress {
            return None;
        }

        let pb = ProgressBar::new(file_size);
        if let Ok(style) = ProgressStyle::with_template(
            "{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta}) {msg}",
        ) {
            pb.set_style(
                style
                    .with_key("eta", |state: &ProgressState, w: &mut dyn Write| {
                        let _ = write!(w, "{:.1}s", state.eta().as_secs_f64());
                    })
                    .progress_chars("=>-"),
            );
        }

        pb.set_message(format!("Processing {}", file_name));
        Some(pb)
    }

    /// Create a progress bar for batch processing
    pub fn create_batch_progress(&self, total_files: u64) -> Option<ProgressBar> {
        if !self.show_progress {
            return None;
        }

        let pb = ProgressBar::new(total_files);
        if let Ok(style) = ProgressStyle::with_template(
            "{spinner:.green} [{elapsed_precise}] [{wide_bar:.yellow/orange}] {pos:>3}/{len:3} files ({eta}) {msg}",
        ) {
            pb.set_style(
                style
                    .with_key("eta", |state: &ProgressState, w: &mut dyn Write| {
                        let _ = write!(w, "{:.1}s", state.eta().as_secs_f64());
                    })
                    .progress_chars("=>-"),
            );
        }

        pb.set_message("Processing files...");
        Some(pb)
    }

    /// Create a progress bar for ML analysis
    pub fn create_ml_progress(&self, total_steps: u64) -> Option<ProgressBar> {
        if !self.show_progress {
            return None;
        }

        let pb = ProgressBar::new(total_steps);
        if let Ok(style) = ProgressStyle::with_template(
            "{spinner:.magenta} [{elapsed_precise}] [{wide_bar:.magenta/pink}] {pos:>2}/{len:2} {msg}",
        ) {
            pb.set_style(style.progress_chars("=>-"));
        }

        pb.set_message("ML Readiness Analysis...");
        Some(pb)
    }

    /// Create a progress bar for quality checking
    pub fn create_quality_progress(&self, total_columns: u64) -> Option<ProgressBar> {
        if !self.show_progress {
            return None;
        }

        let pb = ProgressBar::new(total_columns);
        if let Ok(style) = ProgressStyle::with_template(
            "{spinner:.blue} [{elapsed_precise}] [{wide_bar:.blue/cyan}] {pos:>3}/{len:3} columns {msg}",
        ) {
            pb.set_style(style.progress_chars("=>-"));
        }

        pb.set_message("Quality checking...");
        Some(pb)
    }

    /// Create an indeterminate spinner for unknown-duration tasks
    pub fn create_spinner(&self, message: &str) -> Option<ProgressBar> {
        if !self.show_progress {
            return None;
        }

        let pb = ProgressBar::new_spinner();
        if let Ok(style) = ProgressStyle::with_template("{spinner:.green} {msg}") {
            pb.set_style(style.tick_strings(&["", "", "", "", "", "", "", "", "", ""]));
        }
        pb.set_message(message.to_string());
        pb.enable_steady_tick(Duration::from_millis(80));
        Some(pb)
    }

    /// Create enhanced progress bar with memory tracking and performance metrics
    pub fn create_enhanced_file_progress(
        &self,
        file_size: u64,
        file_name: &str,
    ) -> Option<EnhancedProgressBar> {
        if !self.show_progress {
            return None;
        }

        let pb = if self.is_interactive() {
            // Rich interactive progress bar with colors
            let pb = ProgressBar::new(file_size);
            if let Ok(style) = ProgressStyle::with_template(
                "{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}) | {msg}",
            ) {
                pb.set_style(
                    style
                        .with_key("eta", |state: &ProgressState, w: &mut dyn Write| {
                            let _ = write!(w, "{:.1}s", state.eta().as_secs_f64());
                        })
                        .progress_chars("=>-"),
                );
            }
            pb
        } else {
            // Simple machine-readable progress for pipes/CI
            let pb = ProgressBar::new(file_size);
            if let Ok(style) = ProgressStyle::with_template(
                "[{elapsed_precise}] {bytes}/{total_bytes} {bytes_per_sec} {msg}",
            ) {
                pb.set_style(style.progress_chars("=>-"));
            }
            pb
        };

        pb.set_message(format!("Processing {}", file_name));
        Some(EnhancedProgressBar::new(pb, self.memory_tracker.clone()))
    }

    /// Create adaptive progress bar based on terminal context
    pub fn create_adaptive_progress(&self, total: u64, operation: &str) -> Option<ProgressBar> {
        if !self.show_progress {
            return None;
        }

        let pb = ProgressBar::new(total);

        let template = if self.is_interactive() {
            // Rich template for interactive terminals
            "{spinner:.blue} [{elapsed_precise}] [{wide_bar:.blue/cyan}] {pos:>7}/{len:7} {per_sec} | {msg}"
        } else {
            // Simple template for non-interactive (pipes, CI)
            "[{elapsed_precise}] {pos}/{len} {per_sec} {msg}"
        };

        if let Ok(style) = ProgressStyle::with_template(template) {
            pb.set_style(style.progress_chars("=>-"));
        }

        pb.set_message(operation.to_string());
        Some(pb)
    }

    /// Create a multi-progress for complex operations
    pub fn create_multi_progress(&self) -> Option<indicatif::MultiProgress> {
        if !self.show_progress {
            return None;
        }

        Some(indicatif::MultiProgress::new())
    }

    /// Display verbose information
    pub fn verbose(&self, level: u8, message: &str) {
        if self.verbosity >= level {
            match level {
                1 => println!("[INFO] {}", message),
                2 => println!("[DEBUG] {}", message),
                3 => println!("[TRACE] {}", message),
                _ => println!("{}", message),
            }
        }
    }

    /// Display success message
    pub fn success(&self, message: &str) {
        if self.show_progress || self.verbosity > 0 {
            println!("[OK] {}", message);
        }
    }

    /// Display warning message
    pub fn warning(&self, message: &str) {
        if self.show_progress || self.verbosity > 0 {
            println!("[WARN] {}", message);
        }
    }

    /// Display error message
    pub fn error(&self, message: &str) {
        println!("[ERROR] {}", message);
    }

    /// Display info message
    pub fn info(&self, message: &str) {
        if self.verbosity > 0 {
            println!("[INFO] {}", message);
        }
    }
}

/// Progress tracker for streaming operations
pub struct StreamingProgress {
    pub progress_bar: Option<ProgressBar>,
    pub start_time: Instant,
    pub last_update: Instant,
    pub update_interval: Duration,
}

impl StreamingProgress {
    pub fn new(progress_bar: Option<ProgressBar>) -> Self {
        Self {
            progress_bar,
            start_time: Instant::now(),
            last_update: Instant::now(),
            update_interval: Duration::from_millis(100), // Update every 100ms
        }
    }

    /// Update progress with current position
    pub fn update(&mut self, position: u64, message: Option<&str>) {
        if let Some(pb) = &self.progress_bar {
            let now = Instant::now();
            if now.duration_since(self.last_update) >= self.update_interval {
                pb.set_position(position);
                if let Some(msg) = message {
                    pb.set_message(msg.to_string());
                }
                self.last_update = now;
            }
        }
    }

    /// Update progress with increment
    pub fn increment(&mut self, delta: u64, message: Option<&str>) {
        if let Some(pb) = &self.progress_bar {
            let now = Instant::now();
            if now.duration_since(self.last_update) >= self.update_interval {
                pb.inc(delta);
                if let Some(msg) = message {
                    pb.set_message(msg.to_string());
                }
                self.last_update = now;
            }
        }
    }

    /// Finish progress with final message
    pub fn finish(&self, message: &str) {
        if let Some(pb) = &self.progress_bar {
            pb.finish_with_message(message.to_string());
        }
    }

    /// Finish progress and clear
    pub fn finish_and_clear(&self) {
        if let Some(pb) = &self.progress_bar {
            pb.finish_and_clear();
        }
    }

    /// Get elapsed time
    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }
}

/// Enhanced progress bar with memory tracking and performance metrics
pub struct EnhancedProgressBar {
    pub progress_bar: ProgressBar,
    pub memory_tracker: Option<MemoryTracker>,
    pub start_time: Instant,
    pub last_update: Instant,
    pub update_interval: Duration,
    pub bytes_processed: u64,
    pub rows_processed: u64,
    pub columns_processed: u64,
}

impl EnhancedProgressBar {
    pub fn new(progress_bar: ProgressBar, memory_tracker: Option<MemoryTracker>) -> Self {
        Self {
            progress_bar,
            memory_tracker,
            start_time: Instant::now(),
            last_update: Instant::now(),
            update_interval: Duration::from_millis(100),
            bytes_processed: 0,
            rows_processed: 0,
            columns_processed: 0,
        }
    }

    /// Update progress with enhanced metrics
    pub fn update(&mut self, position: u64, rows: u64, columns: u64, message: Option<&str>) {
        self.bytes_processed = position;
        self.rows_processed = rows;
        self.columns_processed = columns;

        let now = Instant::now();
        if now.duration_since(self.last_update) >= self.update_interval {
            self.progress_bar.set_position(position);

            // Calculate performance metrics
            let elapsed = now.duration_since(self.start_time).as_secs_f64();
            let mb_per_sec = if elapsed > 0.0 {
                (position as f64 / 1_048_576.0) / elapsed
            } else {
                0.0
            };
            let rows_per_sec = if elapsed > 0.0 {
                rows as f64 / elapsed
            } else {
                0.0
            };
            let cols_per_sec = if elapsed > 0.0 {
                columns as f64 / elapsed
            } else {
                0.0
            };

            // Get memory info if available
            let memory_info = self
                .memory_tracker
                .as_ref()
                .map(|tracker| tracker.get_memory_stats())
                .map(|(_, _, mb)| format!(" | Mem: {}MB", mb))
                .unwrap_or_default();

            let enhanced_message = format!(
                "{} | {:.1} MB/s | {:.0} rows/s | {:.0} cols/s{}",
                message.unwrap_or("Processing"),
                mb_per_sec,
                rows_per_sec,
                cols_per_sec,
                memory_info
            );

            self.progress_bar.set_message(enhanced_message);
            self.last_update = now;
        }
    }

    /// Update with performance hints
    pub fn update_with_hints(&mut self, position: u64, rows: u64, columns: u64, hints: Vec<&str>) {
        let hint_text = if !hints.is_empty() {
            format!(" Hint: {}", hints.join(" | "))
        } else {
            String::new()
        };

        let message = format!("Processing{}", hint_text);
        self.update(position, rows, columns, Some(&message));
    }

    /// Finish with summary
    pub fn finish_with_summary(&self) {
        let elapsed = self.start_time.elapsed().as_secs_f64();
        let final_mb_per_sec = if elapsed > 0.0 {
            (self.bytes_processed as f64 / 1_048_576.0) / elapsed
        } else {
            0.0
        };

        let summary = format!(
            "Completed: {} rows, {} columns, {:.1} MB/s avg",
            self.rows_processed, self.columns_processed, final_mb_per_sec
        );

        self.progress_bar.finish_with_message(summary);
    }

    /// Check for memory leaks and report
    pub fn check_memory_leaks(&self) -> Option<String> {
        self.memory_tracker
            .as_ref()
            .map(|tracker| tracker.report_leaks())
    }
}

/// Generate performance hints based on current processing state
pub fn generate_performance_hints(
    file_size_mb: f64,
    rows_processed: u64,
    processing_speed: f64,
    memory_usage_mb: Option<usize>,
) -> Vec<String> {
    let mut hints = Vec::new();

    // File size based hints
    if file_size_mb > 100.0 && processing_speed < 1000.0 {
        hints.push("Consider --streaming for large files".to_string());
    }

    if file_size_mb > 500.0 {
        hints.push("Use --chunk-size for memory efficiency".to_string());
    }

    // Memory based hints
    if let Some(mem_mb) = memory_usage_mb {
        if mem_mb > 1000 {
            hints.push("High memory usage detected".to_string());
        }

        // Suggest streaming if memory usage is growing too fast
        if mem_mb as f64 > file_size_mb * 2.0 {
            hints.push("Consider streaming mode".to_string());
        }
    }

    // Performance based hints
    if processing_speed > 10000.0 {
        hints.push("Excellent processing speed".to_string());
    } else if processing_speed < 100.0 && rows_processed > 1000 {
        hints.push("Slow processing detected".to_string());
    }

    hints
}

/// Create a fancy startup banner
pub fn display_startup_banner(version: &str, _colored: bool) {
    println!("DataProfiler CLI v{}", version);
    println!("High-performance data profiling with ISO 8000/25012 quality metrics");
}

/// Display completion summary
pub fn display_completion_summary(files_processed: usize, total_time: Duration, _colored: bool) {
    let time_str = if total_time.as_secs() > 60 {
        format!(
            "{}m {:.1}s",
            total_time.as_secs() / 60,
            total_time.as_secs_f64() % 60.0
        )
    } else {
        format!("{:.2}s", total_time.as_secs_f64())
    };

    println!(
        "\nAnalysis complete! Processed {} files in {}",
        files_processed, time_str
    );
}