ascfix 0.7.1

Automatic ASCII diagram repair tool for Markdown 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
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
//! Quality validation for ASCII diagram processing
//!
//! This module provides comprehensive quality validation for diagram processing,
//! ensuring that all transformations maintain high quality standards and preserve
//! original content integrity.

#![allow(dead_code)] // Reason: Framework for future quality validation features

// Quality validation module
use crate::cli::Mode;
use crate::config::Config;
use crate::modes;
use crate::transformation_analysis::{analyze_transformations, TransformationType};

/// Comprehensive quality report for diagram processing
#[derive(Debug, Clone)]
pub struct QualityReport {
    /// Overall quality score (0.0 to 1.0)
    pub score: f32,
    /// Specific quality issues found
    pub issues: Vec<QualityIssue>,
    /// Detailed quality metrics
    pub metrics: QualityMetrics,
}

/// Specific quality issues that can be detected
#[derive(Debug, Clone)]
pub enum QualityIssue {
    /// Text content was corrupted (e.g., arrows/pipes in text)
    TextCorruption {
        line: usize,
        expected: String,
        got: String,
    },
    /// Content was lost entirely
    DataLoss {
        content_type: LostContent,
        line: usize,
    },
    /// Structure corruption (e.g., malformed boxes)
    StructureCorruption {
        issue_type: StructureType,
        location: Point,
    },
    /// Visual inconsistency (e.g., misaligned elements)
    VisualInconsistency {
        issue_type: Inconsistency,
        location: Point,
    },
}

/// Types of content that can be lost
#[derive(Debug, Clone)]
pub enum LostContent {
    TextLine,
    BoxBorder,
    Arrow,
    ConnectionLine,
    Label,
}

/// Types of structure corruption
#[derive(Debug, Clone)]
pub enum StructureType {
    MalformedBox,
    BrokenArrow,
    InvalidConnection,
    NestedConflict,
}

/// Types of visual inconsistencies
#[derive(Debug, Clone)]
pub enum Inconsistency {
    MisalignedBoxes,
    InconsistentSpacing,
    BorderOverlap,
    TextOverflow,
}

/// Detailed quality metrics
#[derive(Debug, Clone)]
pub struct QualityMetrics {
    /// Percentage of original text preserved (0.0 to 1.0)
    pub text_preservation: f32,
    /// Percentage of structural elements preserved (0.0 to 1.0)
    pub structure_preservation: f32,
    /// Visual consistency score (0.0 to 1.0)
    pub visual_consistency: f32,
    /// Change in line count (can be negative)
    pub line_count_delta: i32,
    /// Number of text corruption instances
    pub text_corruption_count: usize,
    /// Number of data loss instances
    pub data_loss_count: usize,
}

/// 2D point for location reporting
#[derive(Debug, Clone, Copy)]
pub struct Point {
    pub row: usize,
    pub col: usize,
}

/// Quality validation configuration
#[derive(Debug, Clone)]
pub struct QualityConfig {
    /// Minimum acceptable text preservation (default: 0.95)
    pub min_text_preservation: f32,
    /// Minimum acceptable structure preservation (default: 0.90)
    pub min_structure_preservation: f32,
    /// Maximum allowed line count delta (default: 0)
    pub max_line_count_delta: i32,
    /// Whether to allow any text corruption (default: false)
    pub allow_text_corruption: bool,
    /// Whether to allow any data loss (default: false)
    pub allow_data_loss: bool,
}

impl Default for QualityConfig {
    fn default() -> Self {
        Self {
            min_text_preservation: 0.95,
            min_structure_preservation: 0.90,
            max_line_count_delta: 0,
            allow_text_corruption: false,
            allow_data_loss: false,
        }
    }
}

impl QualityReport {
    /// Check if the quality meets acceptable standards
    #[must_use]
    pub fn is_acceptable(&self, config: &QualityConfig) -> bool {
        self.score >= 0.8
            && self.metrics.text_preservation >= config.min_text_preservation
            && self.metrics.structure_preservation >= config.min_structure_preservation
            && self.metrics.line_count_delta.abs() <= config.max_line_count_delta.abs()
            && (config.allow_text_corruption || self.metrics.text_corruption_count == 0)
            && (config.allow_data_loss || self.metrics.data_loss_count == 0)
    }
}

/// Validate the quality of diagram processing with intelligent transformation analysis
#[must_use]
pub fn validate_quality(input: &str, output: &str) -> QualityReport {
    let mut report = QualityReport {
        score: 1.0,
        issues: Vec::new(),
        metrics: QualityMetrics {
            text_preservation: 1.0,
            structure_preservation: 1.0,
            visual_consistency: 1.0,
            line_count_delta: 0,
            text_corruption_count: 0,
            data_loss_count: 0,
        },
    };

    let input_lines: Vec<&str> = input.lines().collect();
    let output_lines: Vec<&str> = output.lines().collect();

    // Basic metrics
    #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
    {
        report.metrics.line_count_delta = output_lines.len() as i32 - input_lines.len() as i32;
    }

    // Advanced transformation analysis
    let transformation_analysis = analyze_transformations(input, output);

    // Update metrics based on transformation analysis
    report.metrics.text_corruption_count = transformation_analysis.summary.destructive_count;
    report.metrics.data_loss_count = transformation_analysis
        .transformations
        .iter()
        .filter(|t| matches!(t.transform_type, TransformationType::Destructive(_)))
        .count();

    // Calculate text preservation considering constructive transformations
    let original_text_chars = count_text_chars(&input_lines);
    let output_text_chars = count_text_chars(&output_lines);
    #[allow(clippy::cast_precision_loss)]
    let base_preservation = if original_text_chars > 0 {
        output_text_chars as f32 / original_text_chars as f32
    } else {
        1.0
    };

    // Adjust preservation score based on constructive transformations
    // Constructive changes (like arrow duplication) shouldn't penalize preservation
    #[allow(clippy::cast_precision_loss)]
    let constructive_bonus = transformation_analysis.summary.constructive_count as f32 * 0.02;
    report.metrics.text_preservation = (base_preservation + constructive_bonus).min(1.0);

    // Traditional checks (for compatibility)
    check_text_corruption(&input_lines, &output_lines, &mut report);
    check_data_loss(&input_lines, &output_lines, &mut report);
    check_visual_consistency(&output_lines, &mut report);

    // Enhanced structure preservation based on transformation analysis
    report.metrics.structure_preservation =
        calculate_structure_preservation(&transformation_analysis);

    // Calculate overall score with transformation awareness
    report.score = calculate_enhanced_overall_score(&report.metrics, &transformation_analysis);

    // Add transformation insights to issues
    for transformation in &transformation_analysis.transformations {
        if matches!(
            transformation.transform_type,
            TransformationType::Destructive(_)
        ) {
            report.issues.push(QualityIssue::TextCorruption {
                line: transformation.location.line,
                expected: "original content".to_string(),
                got: transformation.description.clone(),
            });
        }
    }

    report
}

/// Check for text corruption (arrows/pipes appearing in text content)
fn check_text_corruption(input_lines: &[&str], output_lines: &[&str], report: &mut QualityReport) {
    for (line_idx, output_line) in output_lines.iter().enumerate() {
        let chars: Vec<char> = output_line.chars().collect();

        for (col_idx, &ch) in chars.iter().enumerate() {
            // Check for corruption indicators - arrows that appear to be in text
            if ch == '' || ch == '' || ch == '' || ch == '' {
                // Only flag as corruption if arrow appears to be replacing a letter
                if is_arrow_corrupting_text(&chars, col_idx) {
                    report.issues.push(QualityIssue::TextCorruption {
                        line: line_idx,
                        expected: "text content".to_string(),
                        got: ch.to_string(),
                    });
                    report.metrics.text_corruption_count += 1;
                }
            }

            // Check for pipes that appear to be in text content (not borders)
            if ch == '' {
                // Only flag if pipe appears to be in the middle of text
                if is_pipe_in_text_content(&chars, col_idx) {
                    report.issues.push(QualityIssue::TextCorruption {
                        line: line_idx,
                        expected: "text content".to_string(),
                        got: ch.to_string(),
                    });
                    report.metrics.text_corruption_count += 1;
                }
            }
        }
    }

    // Calculate text preservation score
    let original_text_chars = count_text_chars(input_lines);
    let output_text_chars = count_text_chars(output_lines);
    #[allow(clippy::cast_precision_loss)]
    {
        report.metrics.text_preservation = if original_text_chars > 0 {
            output_text_chars as f32 / original_text_chars as f32
        } else {
            1.0
        };
    }
}

/// Check for data loss
fn check_data_loss(input_lines: &[&str], output_lines: &[&str], report: &mut QualityReport) {
    // Check if line count changed significantly
    let line_diff = output_lines.len().saturating_sub(input_lines.len());
    if line_diff > 2 {
        // Allow some line additions for formatting, but not losses
        report.metrics.data_loss_count += 1;
        report.issues.push(QualityIssue::DataLoss {
            content_type: LostContent::TextLine,
            line: input_lines.len(),
        });
    }

    // Check for significant content reduction
    let input_content_size = input_lines.iter().map(|l| l.len()).sum::<usize>();
    let output_content_size = output_lines.iter().map(|l| l.len()).sum::<usize>();

    if input_content_size > 100 && output_content_size < input_content_size / 2 {
        report.metrics.data_loss_count += 1;
        report.issues.push(QualityIssue::DataLoss {
            content_type: LostContent::TextLine,
            line: 0,
        });
    }
}

/// Check visual consistency
fn check_visual_consistency(output_lines: &[&str], report: &mut QualityReport) {
    // Check for obvious visual issues
    for (line_idx, line) in output_lines.iter().enumerate() {
        // Check for broken box borders
        if line.contains("") && !line.contains("") {
            report.metrics.visual_consistency -= 0.1;
            report.issues.push(QualityIssue::StructureCorruption {
                issue_type: StructureType::MalformedBox,
                location: Point {
                    row: line_idx,
                    col: 0,
                },
            });
        }

        // Check for inconsistent spacing (simplified)
        let spaces = line.chars().filter(|&c| c == ' ').count();
        let non_spaces = line.chars().filter(|&c| c != ' ').count();
        #[allow(clippy::cast_precision_loss)]
        if non_spaces > 0 && spaces as f32 / non_spaces as f32 > 5.0 {
            report.metrics.visual_consistency -= 0.05;
        }
    }

    report.metrics.visual_consistency = report.metrics.visual_consistency.max(0.0);
}

/// Calculate structure preservation based on transformation analysis
#[allow(clippy::cast_precision_loss)]
fn calculate_structure_preservation(
    analysis: &crate::transformation_analysis::TransformationAnalysis,
) -> f32 {
    let destructive = analysis.summary.destructive_count as f32;
    let constructive = analysis.summary.constructive_count as f32;
    let neutral = analysis.summary.neutral_count as f32;
    let total = destructive + constructive + neutral;

    if total == 0.0 {
        return 1.0; // No transformations = perfect preservation
    }

    // Structure preservation considers constructive changes as neutral
    let preserved = constructive + neutral;
    preserved / total
}

/// Calculate enhanced overall score with transformation awareness
#[allow(clippy::cast_precision_loss)]
fn calculate_enhanced_overall_score(
    metrics: &QualityMetrics,
    analysis: &crate::transformation_analysis::TransformationAnalysis,
) -> f32 {
    let mut score = 1.0;

    // Base score from traditional metrics
    score *= metrics.text_preservation;
    score *= metrics.structure_preservation;
    score *= metrics.visual_consistency;

    // Adjust based on transformation quality impact
    score += analysis.summary.net_quality_impact * 0.1; // Scale the impact

    // Heavy penalty for destructive transformations
    let destructive_penalty = analysis.summary.destructive_count as f32 * 0.2;
    score -= destructive_penalty;

    // Light penalty for line count changes
    score -= (metrics.line_count_delta.abs() as f32 * 0.02).min(0.1);

    // Bonus for constructive transformations
    let constructive_bonus = analysis.summary.constructive_count as f32 * 0.05;
    score += constructive_bonus.min(0.2); // Cap the bonus

    score.clamp(0.0, 1.0)
}

/// Check if an arrow appears to be corrupting text (replacing a letter)
fn is_arrow_corrupting_text(line_chars: &[char], col: usize) -> bool {
    if col == 0 || col >= line_chars.len() - 1 {
        return false;
    }

    let prev = line_chars[col - 1];
    let next = line_chars[col + 1];

    // If arrow is between letters, it's likely corruption
    prev.is_alphabetic() && next.is_alphabetic()
}

/// Check if a pipe appears to be in text content (not a legitimate border)
fn is_pipe_in_text_content(line_chars: &[char], col: usize) -> bool {
    if col == 0 || col >= line_chars.len() - 1 {
        return false;
    }

    let prev = line_chars[col - 1];
    let next = line_chars[col + 1];

    // Check for common text corruption patterns
    // Pipe between letters, or pipe where there should be a letter
    (prev.is_alphabetic() && next.is_alphabetic())
        || (prev.is_alphabetic() && next == ' ')
        || (prev == ' ' && next.is_alphabetic())
}

/// Count text characters (letters, numbers, punctuation)
fn count_text_chars(lines: &[&str]) -> usize {
    lines
        .iter()
        .map(|line| {
            line.chars()
                .filter(|&c| {
                    c.is_alphabetic() || c.is_numeric() || c.is_ascii_punctuation() || c == ' '
                })
                .count()
        })
        .sum()
}

/// Validate a fixture against quality standards
///
/// # Errors
///
/// Returns an error if the fixture files cannot be read or if quality validation fails.
pub fn validate_fixture(
    input_path: &str,
    expected_path: &str,
    config: &QualityConfig,
) -> Result<(), String> {
    validate_fixture_with_options(input_path, expected_path, config, false)
}

/// Validate a fixture against quality standards with fence repair option
///
/// # Errors
///
/// Returns an error if the fixture files cannot be read or if quality validation fails.
pub fn validate_fixture_with_fences(
    input_path: &str,
    expected_path: &str,
    config: &QualityConfig,
) -> Result<(), String> {
    validate_fixture_with_options(input_path, expected_path, config, true)
}

/// Internal function to validate a fixture with configurable fence repair
fn validate_fixture_with_options(
    input_path: &str,
    expected_path: &str,
    config: &QualityConfig,
    repair_fences: bool,
) -> Result<(), String> {
    let input = std::fs::read_to_string(input_path)
        .map_err(|e| format!("Failed to read input {input_path}: {e}"))?;

    let expected = std::fs::read_to_string(expected_path)
        .map_err(|e| format!("Failed to read expected {expected_path}: {e}"))?;

    // Process the input
    let processed =
        modes::process_by_mode(&Mode::Diagram, &input, repair_fences, &Config::default());

    // Validate quality
    let report = validate_quality(&input, &processed);

    if !report.is_acceptable(config) {
        return Err(format!(
            "Quality validation failed for {}:\n\
             Score: {:.2}\n\
             Text preservation: {:.2} (min: {:.2})\n\
             Structure preservation: {:.2} (min: {:.2})\n\
             Line delta: {} (max: {})\n\
             Text corruption: {} (allowed: {})\n\
             Data loss: {} (allowed: {})\n\
             Issues: {}",
            input_path,
            report.score,
            report.metrics.text_preservation,
            config.min_text_preservation,
            report.metrics.structure_preservation,
            config.min_structure_preservation,
            report.metrics.line_count_delta,
            config.max_line_count_delta,
            report.metrics.text_corruption_count,
            config.allow_text_corruption,
            report.metrics.data_loss_count,
            config.allow_data_loss,
            report.issues.len()
        ));
    }

    // Also check that output matches expected (with normalization)
    let processed_normalized = normalize_output(&processed);
    let expected_normalized = normalize_output(&expected);

    if processed_normalized != expected_normalized {
        return Err(format!(
            "Output mismatch for {}\n\
             Expected length: {}\n\
             Got length: {}",
            input_path,
            expected_normalized.len(),
            processed_normalized.len()
        ));
    }

    Ok(())
}

/// Normalize output for comparison (strip trailing whitespace, normalize line endings)
fn normalize_output(output: &str) -> String {
    output
        .lines()
        .map(str::trim_end)
        .collect::<Vec<_>>()
        .join("\n")
        .trim()
        .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_quality_validation_clean_input() {
        let input = r"
┌──────────┐
│ Clean    │
│ Text     │
└──────────┘
";

        let output = input; // Perfect preservation
        let report = validate_quality(input, output);

        assert!(report.score > 0.95, "Clean input should have high score");
        assert_eq!(report.metrics.text_corruption_count, 0);
        assert_eq!(report.metrics.data_loss_count, 0);
        assert!(report.metrics.text_preservation > 0.95);
    }

    #[test]
    fn test_quality_validation_text_corruption() {
        let input = r"
┌──────────┐
│ Clean    │
│ Text     │
└──────────┘
";

        let output = r"
┌──────────┐
│ Clean↑   │
│ Text     │
└──────────┘
";

        let report = validate_quality(input, output);

        assert!(
            report.score < 0.9,
            "Corrupted output should have lower score"
        );
        assert!(report.metrics.text_corruption_count > 0);
        assert!(report
            .issues
            .iter()
            .any(|issue| matches!(issue, QualityIssue::TextCorruption { .. })));
    }

    #[test]
    fn test_quality_validation_data_loss() {
        let input = r"
┌──────────┐
│ Original │
│ Content  │
└──────────┘
";

        let output = r"
┌──────────┐
│ Original │
└──────────┘
";

        let report = validate_quality(input, output);

        assert!(
            report.metrics.line_count_delta < 0,
            "Should detect line loss"
        );
        assert!(report.score < 1.0, "Data loss should reduce score");
    }
}