linthis 0.17.2

A fast, cross-platform multi-language linter and formatter
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
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
// Copyright 2024 zhlinh and linthis Project Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at
//
// https://opensource.org/license/MIT
//
// The above copyright notice and this permission
// notice shall be included in all copies or
// substantial portions of the Software.

//! Interactive menu for reviewing lint issues.
//!
//! Provides:
//! - Main menu with summary and options
//! - Issue-by-issue review with edit/ignore/skip actions
//! - Cross-platform terminal input handling

use crate::utils::types::{LintIssue, RunResult, Severity};
use colored::Colorize;
use std::collections::HashSet;
use std::io::{self, BufRead, Write};
use std::path::PathBuf;

use super::ai_fix::{run_ai_fix_all, run_ai_fix_single, AiFixConfig};
use super::editor::{open_in_editor, LineChange};
use super::nolint::{add_nolint_comment, describe_nolint_action, LineDiff, NolintResult};
use super::quickfix::{default_quickfix_path, write_quickfix_file};

/// Action taken for a single issue
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InteractiveAction {
    /// Open file in editor at issue location
    Edit,
    /// Add NOLINT comment to suppress issue
    Ignore,
    /// Skip this issue (do nothing)
    Skip,
    /// Go to previous issue
    Previous,
    /// Go to specific issue number
    GoTo(usize),
    /// Get AI-powered fix suggestion
    AiFix,
    /// Quit interactive mode
    Quit,
}

/// Result of the interactive session
#[derive(Debug, Default)]
pub struct InteractiveResult {
    /// Number of issues opened in editor
    pub edited: usize,
    /// Number of issues ignored (NOLINT added)
    pub ignored: usize,
    /// Number of issues skipped
    pub skipped: usize,
    /// Whether user quit early
    pub quit_early: bool,
    /// Set of files that were modified (for rechecking)
    pub modified_files: HashSet<PathBuf>,
}

/// Run the interactive review mode
///
/// # Arguments
/// * `result` - The lint result to review
///
/// # Returns
/// * `InteractiveResult` with statistics about actions taken
pub fn run_interactive(result: &RunResult) -> InteractiveResult {
    let issues = &result.issues;

    if issues.is_empty() {
        println!("{}", "No issues to review.".green());
        return InteractiveResult::default();
    }

    // Show main menu
    loop {
        match show_main_menu(result) {
            MainMenuChoice::ReviewOneByOne => {
                return run_issue_review(issues);
            }
            MainMenuChoice::OpenInQuickfix => {
                if let Err(e) = open_quickfix(issues) {
                    eprintln!("{}: {}", "Error".red(), e);
                } else {
                    println!("{} Quickfix file created", "".green());
                }
            }
            MainMenuChoice::AiFixAll => {
                let ai_config = AiFixConfig::default();
                let ai_result = run_ai_fix_all(result, &ai_config);
                return InteractiveResult {
                    edited: ai_result.applied,
                    ignored: 0,
                    skipped: ai_result.skipped,
                    quit_early: ai_result.quit_early,
                    modified_files: ai_result.modified_files,
                };
            }
            MainMenuChoice::Exit => {
                return InteractiveResult::default();
            }
        }
    }
}

/// Main menu choices
#[derive(Debug, Clone, Copy)]
enum MainMenuChoice {
    ReviewOneByOne,
    OpenInQuickfix,
    AiFixAll,
    Exit,
}

/// Show the main menu with issue summary
fn show_main_menu(result: &RunResult) -> MainMenuChoice {
    let issues = &result.issues;
    let error_count = issues
        .iter()
        .filter(|i| i.severity == Severity::Error)
        .count();
    let warning_count = issues
        .iter()
        .filter(|i| i.severity == Severity::Warning)
        .count();
    let info_count = issues
        .iter()
        .filter(|i| i.severity == Severity::Info)
        .count();

    println!();
    println!("{}", "".repeat(60).dimmed());
    println!(
        "  Found {} issue{} ({} error{}, {} warning{})",
        issues.len().to_string().bold(),
        if issues.len() == 1 { "" } else { "s" },
        error_count.to_string().red(),
        if error_count == 1 { "" } else { "s" },
        warning_count.to_string().yellow(),
        if warning_count == 1 { "" } else { "s" },
    );
    if info_count > 0 {
        println!("         {} info", info_count.to_string().blue());
    }
    println!("{}", "".repeat(60).dimmed());
    println!();
    println!("  [{}] Review issues one by one (interactive)", "1".cyan());
    println!("  [{}] Open all in editor (vim quickfix)", "2".cyan());
    println!("  [{}] AI Fix - get AI-powered suggestions", "3".cyan());
    println!("  [{}] Exit", "4".cyan());
    println!();
    println!("  {}", "Vim quickfix shortcuts:".dimmed());
    println!(
        "    {} - next issue  {} - previous  {} - list all",
        ":cn".cyan(),
        ":cp".cyan(),
        ":copen".cyan()
    );
    println!();
    print!("  > ");
    io::stdout().flush().ok();

    let choice = read_line().trim().to_lowercase();

    match choice.as_str() {
        "1" => MainMenuChoice::ReviewOneByOne,
        "2" => MainMenuChoice::OpenInQuickfix,
        "3" | "ai" => MainMenuChoice::AiFixAll,
        "4" | "q" | "quit" | "exit" => MainMenuChoice::Exit,
        _ => {
            println!("{}", "Invalid choice, please try again.".yellow());
            show_main_menu(result)
        }
    }
}

/// Run the issue-by-issue review loop
fn run_issue_review(issues: &[LintIssue]) -> InteractiveResult {
    let mut result = InteractiveResult::default();
    let total = issues.len();
    let mut idx: usize = 0;

    // Track which issues have been processed
    let mut processed = vec![false; total];

    while idx < total {
        let issue = &issues[idx];
        let action = show_issue_menu(issue, idx + 1, total);

        match action {
            InteractiveAction::Edit => {
                processed[idx] = true;
                handle_edit_action(issue, &mut result);
                idx += 1;
            }
            InteractiveAction::Ignore => {
                processed[idx] = true;
                handle_ignore_action(issue, &mut result);
                idx += 1;
            }
            InteractiveAction::AiFix => {
                processed[idx] = true;
                handle_ai_fix_action(issue, &mut result);
                idx += 1;
            }
            InteractiveAction::Skip => {
                result.skipped += 1;
                processed[idx] = true;
                idx += 1;
            }
            InteractiveAction::Previous => {
                if idx > 0 {
                    idx -= 1;
                    if processed[idx] {
                        println!("{}", "  (Revisiting previously processed issue)".dimmed());
                    }
                } else {
                    println!("{}", "  Already at first issue".yellow());
                }
            }
            InteractiveAction::GoTo(target) => {
                if target > 0 && target <= total {
                    idx = target - 1;
                    if processed[idx] {
                        println!("{}", "  (Jumping to previously processed issue)".dimmed());
                    }
                } else {
                    println!(
                        "  {} Issue #{} out of range (1-{})",
                        "Invalid:".yellow(),
                        target,
                        total
                    );
                }
            }
            InteractiveAction::Quit => {
                result.quit_early = true;
                for &was_processed in &processed[idx..] {
                    if !was_processed {
                        result.skipped += 1;
                    }
                }
                break;
            }
        }
    }

    print_review_summary(&result);
    result
}

/// Handle the Edit action for a single issue
fn handle_edit_action(issue: &LintIssue, result: &mut InteractiveResult) {
    result.edited += 1;

    let editor_result = open_in_editor(&issue.file_path, issue.line, issue.column);

    if editor_result.success {
        println!();
        if editor_result.changes.is_empty() {
            println!("  {}", "No changes made".dimmed());
        } else {
            print_editor_changes(&editor_result.changes, &issue.file_path);
            result.modified_files.insert(issue.file_path.clone());
        }
    } else if let Some(ref error) = editor_result.error {
        eprintln!("{}: {}", "Failed to open editor".red(), error);
    }
}

/// Handle the Ignore (NOLINT) action for a single issue
fn handle_ignore_action(issue: &LintIssue, result: &mut InteractiveResult) {
    match add_nolint_comment(issue) {
        NolintResult::Success(diffs) => {
            result.ignored += 1;
            println!("{} Added NOLINT comment", "".green());
            println!();
            print_diff(&diffs, &issue.file_path);
            result.modified_files.insert(issue.file_path.clone());
        }
        NolintResult::AlreadyIgnored => {
            println!("{}", "Already has NOLINT comment".yellow());
            result.skipped += 1;
        }
        NolintResult::Error(e) => {
            eprintln!("{}: {}", "Failed to add NOLINT".red(), e);
            result.skipped += 1;
        }
    }
}

/// Handle the AI Fix action for a single issue
fn handle_ai_fix_action(issue: &LintIssue, result: &mut InteractiveResult) {
    let ai_config = AiFixConfig::default();
    match run_ai_fix_single(issue, &ai_config) {
        Ok((applied, modified_files)) => {
            if applied {
                result.edited += 1;
                result.modified_files.extend(modified_files);
            } else {
                result.skipped += 1;
            }
        }
        Err(e) => {
            eprintln!("{}: {}", "AI fix error".red(), e);
            result.skipped += 1;
        }
    }
}

/// Print the interactive review summary
fn print_review_summary(result: &InteractiveResult) {
    println!();
    println!("{}", "".repeat(60).dimmed());
    println!("  {}", "Interactive Review Summary".bold());
    println!("{}", "".repeat(60).dimmed());
    println!("  Edited:  {}", result.edited.to_string().cyan());
    println!("  Ignored: {}", result.ignored.to_string().yellow());
    println!("  Skipped: {}", result.skipped.to_string().dimmed());
    if result.quit_early {
        println!("  {}", "(Quit early)".dimmed());
    }
    println!("{}", "".repeat(60).dimmed());
    println!();
}

/// Show menu for a single issue
fn show_issue_menu(issue: &LintIssue, current: usize, total: usize) -> InteractiveAction {
    display_issue_header(issue, current, total);
    display_issue_actions(issue, current, total);

    let choice = read_line().trim().to_lowercase();

    match choice.as_str() {
        "e" | "edit" => InteractiveAction::Edit,
        "i" | "ignore" => InteractiveAction::Ignore,
        "a" | "ai" | "aifix" | "ai-fix" => InteractiveAction::AiFix,
        "s" | "skip" | "" => InteractiveAction::Skip,
        "p" | "prev" | "previous" => InteractiveAction::Previous,
        "q" | "quit" => InteractiveAction::Quit,
        input if input.starts_with("g") => parse_goto_input(input)
            .unwrap_or_else(|| show_issue_menu(issue, current, total)),
        _ => {
            println!("{}", "Invalid choice. Use: e/i/s/p/g/q".yellow());
            show_issue_menu(issue, current, total)
        }
    }
}

/// Display the issue header with severity, location, code context, and message.
fn display_issue_header(issue: &LintIssue, current: usize, total: usize) {
    println!();
    println!("{}", "".repeat(60).dimmed());

    let severity_badge = match issue.severity {
        Severity::Error => format!("[E{}]", current).red().bold(),
        Severity::Warning => format!("[W{}]", current).yellow().bold(),
        Severity::Info => format!("[I{}]", current).blue(),
    };

    let lang_tag = issue
        .language
        .map(|l| format!("[{}]", format!("{:?}", l).to_lowercase()))
        .unwrap_or_default()
        .dimmed();

    let source_tag = issue
        .source
        .as_ref()
        .map(|s| format!("[{}]", s))
        .unwrap_or_default()
        .dimmed();

    let location = if let Some(col) = issue.column {
        format!("{}:{}:{}", issue.file_path.display(), issue.line, col)
    } else {
        format!("{}:{}", issue.file_path.display(), issue.line)
    };

    let progress = format!("({}/{})", current, total).dimmed();

    println!(
        "  {} {}{} {} {}",
        severity_badge,
        lang_tag,
        source_tag,
        location.white().bold(),
        progress
    );

    print_code_context(issue);

    if let Some(ref code) = issue.code {
        println!("  {} ({})", issue.message, code.cyan());
    } else {
        println!("  {}", issue.message);
    }

    if let Some(ref suggestion) = issue.suggestion {
        println!("  {} {}", "-->".green(), suggestion);
    }
}

/// Display the action menu options for an issue.
fn display_issue_actions(issue: &LintIssue, current: usize, total: usize) {
    println!();
    println!("  {}", format!("Issue {}/{}", current, total).bold().cyan());
    println!();
    let nolint_desc = describe_nolint_action(issue);
    println!("    [{}] Edit - open $EDITOR at this line", "e".cyan());
    println!("    [{}] Ignore - {}", "i".cyan(), nolint_desc.dimmed());
    println!(
        "    [{}] AI fix - get AI suggestion for this issue",
        "a".cyan()
    );
    println!("    [{}] Skip", "s".cyan());
    if current > 1 {
        println!(
            "    [{}] Previous - go back to issue #{}",
            "p".cyan(),
            current - 1
        );
    }
    println!("    [{}] Go to #N - jump to specific issue", "g".cyan());
    println!("    [{}] Quit", "q".cyan());
    println!();
    print!("  > ");
    io::stdout().flush().ok();
}

/// Parse a "goto" input like "g 5" or prompt for a number if just "g".
/// Returns `Some(GoTo(n))` on success, `None` if parsing fails.
fn parse_goto_input(input: &str) -> Option<InteractiveAction> {
    let parts: Vec<&str> = input.split_whitespace().collect();
    if parts.len() >= 2 {
        if let Ok(num) = parts[1].parse::<usize>() {
            return Some(InteractiveAction::GoTo(num));
        }
        println!("{}", "Invalid issue number".yellow());
        return None;
    }
    // Prompt for issue number
    print!("  {} ", "Go to issue #:".cyan());
    io::stdout().flush().ok();
    let num_input = read_line().trim().to_string();
    if let Ok(num) = num_input.parse::<usize>() {
        Some(InteractiveAction::GoTo(num))
    } else {
        println!("{}", "Invalid issue number".yellow());
        None
    }
}

/// Print code context for an issue
pub(crate) fn print_code_context(issue: &LintIssue) {
    // Context before
    for (line_num, content) in &issue.context_before {
        println!(
            "      {} {}",
            format!("{:>5} |", line_num).dimmed(),
            content.dimmed()
        );
    }

    // Issue line (highlighted)
    if let Some(ref code_line) = issue.code_line {
        println!(
            "    {} {} {}",
            ">".red().bold(),
            format!("{:>5} |", issue.line).dimmed(),
            code_line
        );

        // Column indicator
        if let Some(col) = issue.column {
            let padding = " ".repeat(col.saturating_sub(1));
            println!(
                "      {} {}{}",
                "      |".dimmed(),
                padding,
                "^".red().bold()
            );
        }
    }

    // Context after
    for (line_num, content) in &issue.context_after {
        println!(
            "      {} {}",
            format!("{:>5} |", line_num).dimmed(),
            content.dimmed()
        );
    }
}

/// Open all issues in vim quickfix
fn open_quickfix(issues: &[LintIssue]) -> super::InteractiveResult<()> {
    use super::InteractiveError;

    let path = default_quickfix_path();

    // Ensure parent directory exists
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            InteractiveError::FileOperation(format!(
                "Failed to create directory '{}': {}",
                parent.display(),
                e
            ))
        })?;
    }

    write_quickfix_file(issues, &path)?;

    println!(
        "{} Quickfix file written to: {}",
        "".green(),
        path.display()
    );
    println!();

    // Try to detect vim-compatible editor
    let editor = detect_quickfix_editor();

    if let Some(editor_cmd) = editor {
        println!("Opening in {}...", editor_cmd.cyan());
        println!("  Use {} to jump between issues", ":cn / :cp".cyan());
        println!();

        // Launch editor with quickfix
        match launch_quickfix_editor(&editor_cmd, &path) {
            Ok(()) => {
                println!();
                println!("{} Editor closed", "".green());
            }
            Err(e) => {
                eprintln!("{}: {}", "Failed to open editor".red(), e);
                println!();
                show_manual_quickfix_instructions(&path);
            }
        }
    } else {
        // No compatible editor found, show manual instructions
        show_manual_quickfix_instructions(&path);
    }

    Ok(())
}

/// Show manual instructions for opening quickfix
fn show_manual_quickfix_instructions(path: &std::path::Path) {
    println!("To open in vim:");
    println!("  {} {}", "vim -q".cyan(), path.display());
    println!();
    println!("Or load in vim with:");
    println!("  {} {}", ":cfile".cyan(), path.display());
    println!();
    println!("{}", "Quickfix shortcuts in vim:".bold());
    println!("  {} - Jump to next issue", ":cn".cyan());
    println!("  {} - Jump to previous issue", ":cp".cyan());
    println!("  {} - Open quickfix window", ":copen".cyan());
    println!("  {} - Close quickfix window", ":cclose".cyan());
    println!("  {} - Jump to issue #N", ":cc N".cyan());
}

/// Detect a quickfix-compatible editor
fn detect_quickfix_editor() -> Option<String> {
    // Check for vim-compatible editors in order of preference
    let vim_editors = [
        "nvim", // Neovim (best vim compatibility)
        "vim",  // Vim
        "vi",   // Vi (basic but widely available)
    ];

    // Check $EDITOR first if it's a vim variant
    if let Ok(editor) = std::env::var("EDITOR") {
        let editor_lower = editor.to_lowercase();
        if editor_lower.contains("vim")
            || editor_lower.contains("nvim")
            || editor_lower.contains("vi")
        {
            return Some(editor);
        }
    }

    // Try to find a vim-compatible editor
    for editor in &vim_editors {
        if which_exists(editor) {
            return Some(editor.to_string());
        }
    }

    None
}

/// Check if a command exists in PATH
fn which_exists(cmd: &str) -> bool {
    use std::process::{Command, Stdio};

    #[cfg(windows)]
    let which_cmd = "where";
    #[cfg(not(windows))]
    let which_cmd = "which";

    Command::new(which_cmd)
        .arg(cmd)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Launch editor with quickfix file
fn launch_quickfix_editor(editor: &str, path: &std::path::Path) -> super::InteractiveResult<()> {
    use super::InteractiveError;
    use std::process::Command;

    let mut cmd = Command::new(editor);
    cmd.arg("-q").arg(path);

    match cmd.status() {
        Ok(status) => {
            if status.success() {
                Ok(())
            } else {
                Err(InteractiveError::EditorLaunch {
                    editor: editor.to_string(),
                    message: format!("exited with status: {}", status.code().unwrap_or(-1)),
                })
            }
        }
        Err(e) => Err(InteractiveError::EditorLaunch {
            editor: editor.to_string(),
            message: e.to_string(),
        }),
    }
}

/// Print diff information in git-style format (for NOLINT comments)
pub(crate) fn print_diff(diffs: &[LineDiff], _file_path: &PathBuf) {
    println!("  {}", "Changes:".bold());

    for diff in diffs {
        // Show context before (from diff)
        if let Some(ref context_before) = diff.context_before {
            println!(
                "  {} {}",
                format!(" {:>4} |", diff.line_number - 1).dimmed(),
                context_before.dimmed()
            );
        }

        // Show removed line (if not empty, meaning it was a modification)
        if !diff.old_content.is_empty() {
            println!(
                "  {} {}",
                format!("-{:>4} |", diff.line_number).red(),
                diff.old_content.red()
            );
        }

        // Show added/modified line
        println!(
            "  {} {}",
            format!("+{:>4} |", diff.line_number).green(),
            diff.new_content.green()
        );

        // Show context after (from diff)
        if let Some(ref context_after) = diff.context_after {
            println!(
                "  {} {}",
                format!(" {:>4} |", diff.line_number + 1).dimmed(),
                context_after.dimmed()
            );
        }
    }
    println!();
}

/// Print changes made in the editor
fn print_editor_changes(changes: &[LineChange], file_path: &PathBuf) {
    use std::fs;

    println!("  {}", "Changes:".bold());

    // Read file to get context lines
    let file_content = fs::read_to_string(file_path).ok();
    let lines: Vec<String> = file_content
        .as_ref()
        .map(|content| content.lines().map(|s| s.to_string()).collect())
        .unwrap_or_default();

    // Limit the number of changes shown to avoid overwhelming output
    const MAX_CHANGES_SHOWN: usize = 20;
    let changes_to_show = if changes.len() > MAX_CHANGES_SHOWN {
        &changes[..MAX_CHANGES_SHOWN]
    } else {
        changes
    };

    for change in changes_to_show {
        let line_idx = change.line_number.saturating_sub(1);

        // Show context before (one line before)
        if line_idx > 0 && line_idx <= lines.len() {
            if let Some(context_line) = lines.get(line_idx - 1) {
                println!(
                    "  {} {}",
                    format!(" {:>4} |", change.line_number - 1).dimmed(),
                    context_line.dimmed()
                );
            }
        }

        // Show removed line (if not empty, meaning it was a modification)
        if !change.old_content.is_empty() {
            println!(
                "  {} {}",
                format!("-{:>4} |", change.line_number).red(),
                change.old_content.red()
            );
        }

        // Show added/modified line (if not empty)
        if !change.new_content.is_empty() {
            println!(
                "  {} {}",
                format!("+{:>4} |", change.line_number).green(),
                change.new_content.green()
            );
        }

        // Show context after (one line after)
        if line_idx + 1 < lines.len() {
            if let Some(context_line) = lines.get(line_idx + 1) {
                println!(
                    "  {} {}",
                    format!(" {:>4} |", change.line_number + 1).dimmed(),
                    context_line.dimmed()
                );
            }
        }
    }

    if changes.len() > MAX_CHANGES_SHOWN {
        println!(
            "  {} ({} more changes not shown)",
            "...".dimmed(),
            changes.len() - MAX_CHANGES_SHOWN
        );
    }

    println!();
}

/// Read a line from stdin (cross-platform)
fn read_line() -> String {
    let stdin = io::stdin();
    let mut line = String::new();

    // Lock stdin for reading
    let mut handle = stdin.lock();
    handle.read_line(&mut line).ok();

    line
}

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

    #[test]
    fn test_interactive_result_default() {
        let result = InteractiveResult::default();
        assert_eq!(result.edited, 0);
        assert_eq!(result.ignored, 0);
        assert_eq!(result.skipped, 0);
        assert!(!result.quit_early);
    }

    #[test]
    fn test_interactive_action_variants() {
        assert_ne!(InteractiveAction::Edit, InteractiveAction::Skip);
        assert_ne!(InteractiveAction::Ignore, InteractiveAction::Quit);
        assert_ne!(InteractiveAction::Previous, InteractiveAction::Skip);
        assert_ne!(InteractiveAction::AiFix, InteractiveAction::Edit);
    }

    #[test]
    fn test_interactive_action_goto() {
        let goto1 = InteractiveAction::GoTo(1);
        let goto2 = InteractiveAction::GoTo(2);
        assert_ne!(goto1, goto2);
        assert_eq!(goto1, InteractiveAction::GoTo(1));
    }

    #[test]
    fn test_interactive_action_clone() {
        let action = InteractiveAction::GoTo(42);
        let cloned = action.clone();
        assert_eq!(action, cloned);
    }
}