linthis 0.17.1

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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
// 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.

//! Cpplint auto-fixer for C/C++ files.
//!
//! Fixes common cpplint issues by parsing cpplint output:
//! - `build/header_guard`: Fixes header guard naming based on cpplint suggestion
//! - `readability/todo`: Adds username to TODO comments
//! - `legal/copyright`: Inserts copyright header

use std::env;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Mutex;

use regex::Regex;

// Installation state: 0 = not checked, 1 = installing, 2 = installed, 3 = failed
static CPPLINT_INSTALL_STATE: AtomicU8 = AtomicU8::new(0);
static INSTALL_LOCK: Mutex<()> = Mutex::new(());

/// Configuration for cpplint fixes
#[derive(Debug, Clone)]
pub struct CpplintFixerConfig {
    /// How to fix header guards: "fix_name" or "pragma_once"
    pub header_guard_mode: HeaderGuardMode,
    /// Username for TODO comments (default: git user or $USER)
    pub todo_username: Option<String>,
    /// Copyright template (with {year} placeholder)
    pub copyright_template: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum HeaderGuardMode {
    /// Fix the header guard name based on cpplint suggestion
    FixName,
    /// Convert to #pragma once
    PragmaOnce,
    /// Don't fix header guards
    Disabled,
}

impl Default for CpplintFixerConfig {
    fn default() -> Self {
        Self {
            header_guard_mode: HeaderGuardMode::FixName,
            todo_username: None,
            copyright_template: None,
        }
    }
}

/// Parsed cpplint error
#[derive(Debug, Clone)]
struct CpplintError {
    line: usize,
    message: String,
    category: String,
}

/// Cpplint auto-fixer
pub struct CpplintFixer {
    config: CpplintFixerConfig,
    /// Cached username
    cached_username: Option<String>,
    /// Whether the current file is Objective-C (skip unsafe fixes)
    is_objc: bool,
}

impl CpplintFixer {
    pub fn new() -> Self {
        Self {
            config: CpplintFixerConfig::default(),
            cached_username: None,
            is_objc: false,
        }
    }

    pub fn with_config(config: CpplintFixerConfig) -> Self {
        Self {
            config,
            cached_username: None,
            is_objc: false,
        }
    }

    /// Set whether the current file is Objective-C
    /// This will skip unsafe fix categories (like readability/casting)
    pub fn set_is_objc(&mut self, is_objc: bool) {
        self.is_objc = is_objc;
    }

    /// Check if cpplint is available
    fn has_cpplint() -> bool {
        Command::new("cpplint")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    /// Try to auto-install cpplint using pip
    fn try_install_cpplint() -> bool {
        let _lock = INSTALL_LOCK.lock().unwrap();

        let state = CPPLINT_INSTALL_STATE.load(Ordering::SeqCst);
        if state != 0 {
            return state == 2;
        }

        CPPLINT_INSTALL_STATE.store(1, Ordering::SeqCst);
        eprintln!("\n📦 cpplint not found, attempting to install...");

        let install_commands = Self::detect_install_commands();

        for (cmd_name, args) in &install_commands {
            if Self::try_run_installer(cmd_name, args) {
                CPPLINT_INSTALL_STATE.store(2, Ordering::SeqCst);
                return true;
            }
        }

        let hint = crate::python_tool_install_hint("cpplint");
        eprintln!("   ❌ Auto-installation failed. Please install manually:");
        eprintln!("      {}\n", hint);

        CPPLINT_INSTALL_STATE.store(3, Ordering::SeqCst);
        false
    }

    /// Detect available Python tool installer: uv > pipx > pip/pip3.
    fn detect_install_commands() -> Vec<(&'static str, Vec<&'static str>)> {
        let has = |cmd: &str| {
            Command::new(cmd)
                .arg("--version")
                .output()
                .map(|o| o.status.success())
                .unwrap_or(false)
        };
        if has("uv") {
            vec![("uv", vec!["tool", "install", "cpplint"])]
        } else if has("pipx") {
            vec![("pipx", vec!["install", "cpplint"])]
        } else {
            vec![
                ("pip", vec!["install", "cpplint", "--upgrade"]),
                ("pip3", vec!["install", "cpplint", "--upgrade"]),
            ]
        }
    }

    /// Try to run an installer command. Returns true if cpplint is available after.
    fn try_run_installer(cmd_name: &str, args: &[&str]) -> bool {
        if !Command::new(cmd_name)
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
        {
            return false;
        }

        eprintln!("   Using {} to install cpplint...", cmd_name);

        let mut child = match Command::new(cmd_name)
            .args(args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
        {
            Ok(child) => child,
            Err(e) => {
                eprintln!("   ❌ Failed to start {}: {}", cmd_name, e);
                return false;
            }
        };

        if let Some(stderr) = child.stderr.take() {
            let reader = BufReader::new(stderr);
            for line in reader.lines().map_while(Result::ok) {
                if line.contains("Collecting")
                    || line.contains("Downloading")
                    || line.contains("Installing")
                    || line.contains("Successfully")
                {
                    eprintln!("   {}", line);
                }
            }
        }

        match child.wait() {
            Ok(status) if status.success() => {
                if Self::has_cpplint() {
                    eprintln!("   ✓ cpplint installed successfully!\n");
                    return true;
                }
                eprintln!("   ⚠️  Installation completed but cpplint not found in PATH");
                eprintln!("   You may need to restart your terminal or add Python's bin directory to PATH\n");
            }
            Ok(status) => {
                eprintln!("   ❌ Installation failed with exit code: {}", status);
            }
            Err(e) => {
                eprintln!("   ❌ Failed to wait for {}: {}", cmd_name, e);
            }
        }
        false
    }

    /// Run cpplint and get errors
    fn run_cpplint(path: &Path, is_objc: bool) -> Vec<CpplintError> {
        // Check if cpplint is available
        if !Self::has_cpplint() {
            let state = CPPLINT_INSTALL_STATE.load(Ordering::SeqCst);

            match state {
                0 => {
                    // First time detection - try to auto-install
                    if Self::try_install_cpplint() {
                        // Installation successful, continue
                    } else {
                        // Installation failed, skip cpplint
                        return Vec::new();
                    }
                }
                1 => {
                    // Installation in progress (another thread), skip for now
                    return Vec::new();
                }
                2 => {
                    // Should have been installed, but still not found
                    // This shouldn't happen, but skip silently
                    return Vec::new();
                }
                3 => {
                    // Installation failed previously, skip silently
                    return Vec::new();
                }
                _ => {
                    return Vec::new();
                }
            }
        }

        let mut cmd = Command::new("cpplint");

        // Add extensions for Objective-C files
        if is_objc {
            cmd.arg("--extensions=m,mm,h");
            cmd.arg("--linelength=150");
        } else {
            cmd.arg("--linelength=120");
        }

        cmd.arg(path);
        let output = cmd.output();

        let output = match output {
            Ok(o) => o,
            Err(e) => {
                eprintln!("[cpplint-fixer] Failed to run cpplint: {}", e);
                return Vec::new();
            }
        };

        // cpplint outputs to stderr
        let stderr = String::from_utf8_lossy(&output.stderr);
        let errors = Self::parse_cpplint_output(&stderr);

        if std::env::var("LINTHIS_DEBUG").is_ok() {
            eprintln!(
                "[cpplint-fixer] {} cpplint stderr:\n{}",
                path.display(),
                stderr
            );
            eprintln!("[cpplint-fixer] Parsed {} errors", errors.len());
            for e in &errors {
                eprintln!(
                    "[cpplint-fixer]   line {}: {} [{}]",
                    e.line, e.message, e.category
                );
            }
        }

        errors
    }

    /// Parse cpplint output into structured errors
    fn parse_cpplint_output(output: &str) -> Vec<CpplintError> {
        let mut errors = Vec::new();

        // Format: file:line: message [category] [confidence]
        // Example: test.h:8: #ifndef header guard has wrong style, please use: FOO_H_ [build/header_guard] [5]
        // Note: use greedy `.+` for message to skip past any [...] in the message body
        // (e.g., copyright messages contain "[year]") and match the last [category] [confidence]
        let re = Regex::new(r"^([^:]+):(\d+):\s*(.+)\s+\[([^\]]+)\]\s*\[\d+\]\s*$").unwrap();

        for line in output.lines() {
            if let Some(caps) = re.captures(line) {
                let file_path = &caps[1];

                // Skip errors from system paths (SDK, frameworks, system includes)
                if file_path.starts_with("/Library/Developer/")
                    || file_path.starts_with("/System/Library/")
                    || file_path.starts_with("/usr/include/")
                    || file_path.starts_with("/usr/local/include/")
                    || file_path.contains("/SDKs/")
                    || file_path.contains(".framework/")
                {
                    continue;
                }

                if let Ok(line_num) = caps[2].parse::<usize>() {
                    errors.push(CpplintError {
                        line: line_num,
                        message: caps[3].to_string(),
                        category: caps[4].to_string(),
                    });
                }
            }
        }

        errors
    }

    /// Get the username for TODO comments
    fn get_username(&mut self) -> String {
        if let Some(ref username) = self.cached_username {
            return username.clone();
        }

        // 1. Use configured username if set
        if let Some(ref username) = self.config.todo_username {
            self.cached_username = Some(username.clone());
            return username.clone();
        }

        // 2. Try git config user.name
        if let Ok(output) = Command::new("git").args(["config", "user.name"]).output() {
            if output.status.success() {
                let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if !name.is_empty() {
                    // Convert to lowercase and replace spaces with underscores
                    let username = name.to_lowercase().replace(' ', "_");
                    self.cached_username = Some(username.clone());
                    return username;
                }
            }
        }

        // 3. Fall back to $USER environment variable
        if let Ok(user) = env::var("USER") {
            self.cached_username = Some(user.clone());
            return user;
        }

        // 4. Ultimate fallback
        "unknown".to_string()
    }

    /// Fix all cpplint issues in a file
    pub fn fix_file(&mut self, path: &Path) -> Result<bool, String> {
        if !path.exists() {
            return Err(format!("File not found: {}", path.display()));
        }

        let debug = std::env::var("LINTHIS_DEBUG").is_ok();

        // Run cpplint to get errors (pass is_objc flag for correct options)
        let errors = Self::run_cpplint(path, self.is_objc);
        if errors.is_empty() {
            if debug {
                eprintln!("[cpplint-fixer] No errors found for {}", path.display());
            }
            return Ok(false);
        }

        if debug {
            eprintln!(
                "[cpplint-fixer] Processing {} errors for {}",
                errors.len(),
                path.display()
            );
        }

        let content =
            fs::read_to_string(path).map_err(|e| format!("Failed to read file: {}", e))?;

        let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
        let mut modified = false;

        // Process errors
        for error in &errors {
            if self.fix_single_error(&mut lines, error, debug) {
                modified = true;
            }
        }

        if modified {
            if debug {
                eprintln!("[cpplint-fixer] Lines before write:");
                for (i, line) in lines.iter().enumerate() {
                    eprintln!("[cpplint-fixer]   [{}] {:?}", i, line);
                }
            }
            let new_content = lines.join("\n") + if content.ends_with('\n') { "\n" } else { "" };
            fs::write(path, new_content).map_err(|e| format!("Failed to write file: {}", e))?;
        }

        Ok(modified)
    }

    /// Fix a single cpplint error by category. Returns true if a fix was applied.
    fn fix_single_error(
        &mut self,
        lines: &mut Vec<String>,
        error: &CpplintError,
        debug: bool,
    ) -> bool {
        // Skip OC-incompatible categories early
        let skip_for_objc = matches!(
            error.category.as_str(),
            "build/header_guard" | "readability/casting" | "whitespace/operators"
        );
        if self.is_objc && skip_for_objc {
            if debug {
                eprintln!("[cpplint-fixer] Skipping {} for OC file", error.category);
            }
            return false;
        }

        let fixed = match error.category.as_str() {
            "build/header_guard" if self.config.header_guard_mode == HeaderGuardMode::FixName => {
                self.fix_header_guard_from_error(lines, error)
            }
            "build/header_guard"
                if self.config.header_guard_mode == HeaderGuardMode::PragmaOnce =>
            {
                self.convert_to_pragma_once(lines)
            }
            "build/header_guard" => false,
            "readability/todo" => self.fix_todo_from_error(lines, error),
            "legal/copyright" => self.fix_copyright_from_error(lines),
            "readability/casting" => self.fix_c_style_cast(lines, error),
            "readability/check" => self.fix_assert_check(lines, error),
            "whitespace/comments" => self.fix_comment_spacing(lines, error),
            "whitespace/semicolon" => self.fix_empty_semicolon(lines, error),
            "whitespace/comma" => self.fix_comma_spacing(lines, error),
            "whitespace/operators" => self.fix_operator_spacing(lines, error),
            _ => {
                if debug {
                    eprintln!(
                        "[cpplint-fixer] Skipping unsupported category: {}",
                        error.category
                    );
                }
                return false;
            }
        };

        if fixed && debug {
            eprintln!(
                "[cpplint-fixer] Fixed {} at line {}",
                error.category, error.line
            );
        }
        fixed
    }

    /// Fix header guard based on cpplint error message
    fn fix_header_guard_from_error(&self, lines: &mut Vec<String>, error: &CpplintError) -> bool {
        let debug = std::env::var("LINTHIS_DEBUG").is_ok();

        if debug {
            eprintln!(
                "[cpplint-fixer] fix_header_guard_from_error: line={}, msg={}",
                error.line, error.message
            );
        }

        let suggested_guard = match Self::extract_guard_name(&error.message) {
            Some(g) => g,
            None => return false,
        };

        // Handle missing header guard (line 0 means no guard at all)
        if error.line == 0 || error.message.contains("No #ifndef header guard found") {
            return self.insert_header_guard(lines, &suggested_guard);
        }

        let line_idx = error.line.saturating_sub(1);
        if line_idx >= lines.len() {
            return false;
        }

        let line = &lines[line_idx];

        // Fix #ifndef line
        if line.trim().starts_with("#ifndef") {
            lines[line_idx] = format!("#ifndef {}", suggested_guard);
            // Also fix the #define on the next line
            if line_idx + 1 < lines.len() && lines[line_idx + 1].trim().starts_with("#define") {
                lines[line_idx + 1] = format!("#define {}", suggested_guard);
            }
            return true;
        }

        // Fix #endif line
        if line.trim().starts_with("#endif") {
            lines[line_idx] = format!("#endif  // {}", suggested_guard);
            return true;
        }

        false
    }

    /// Extract the suggested guard name from a cpplint error message.
    fn extract_guard_name(message: &str) -> Option<String> {
        if message.contains("please use:") {
            message.split("please use:").nth(1).map(|s| s.trim().to_string())
        } else if message.contains("#endif line should be") {
            Regex::new(r#"#endif\s+//\s+(\w+)"#)
                .ok()
                .and_then(|re| re.captures(message))
                .and_then(|caps| caps.get(1))
                .map(|m| m.as_str().to_string())
        } else if message.contains("suggested CPP variable is:") {
            message
                .split("suggested CPP variable is:")
                .nth(1)
                .map(|s| s.trim().to_string())
        } else {
            None
        }
    }

    /// Insert header guard when none exists
    fn insert_header_guard(&self, lines: &mut Vec<String>, guard_name: &str) -> bool {
        // Find the insertion point (after copyright/license comments)
        let mut insert_idx = 0;
        let mut in_block_comment = false;

        for (i, line) in lines.iter().enumerate() {
            let trimmed = line.trim();

            // Track block comments
            if trimmed.starts_with("/*") {
                in_block_comment = true;
            }
            if in_block_comment {
                if trimmed.contains("*/") {
                    in_block_comment = false;
                }
                insert_idx = i + 1;
                continue;
            }

            // Skip line comments at the start (copyright headers)
            if trimmed.starts_with("//") {
                insert_idx = i + 1;
                continue;
            }

            // Skip empty lines after comments
            if trimmed.is_empty() && insert_idx > 0 {
                insert_idx = i + 1;
                continue;
            }

            // Found first real content
            break;
        }

        // Check if already has #ifndef (shouldn't happen, but be safe)
        if lines.iter().any(|l| l.trim().starts_with("#ifndef")) {
            return false;
        }

        // Insert header guard at the found position
        // Add empty line before if not at start and previous line isn't empty
        if insert_idx > 0 && !lines[insert_idx - 1].trim().is_empty() {
            lines.insert(insert_idx, String::new());
            insert_idx += 1;
        }

        lines.insert(insert_idx, format!("#ifndef {}", guard_name));
        lines.insert(insert_idx + 1, format!("#define {}", guard_name));
        lines.insert(insert_idx + 2, String::new());

        // Add #endif at the end
        // Ensure there's an empty line before #endif
        if !lines.last().is_none_or(|l| l.trim().is_empty()) {
            lines.push(String::new());
        }
        lines.push(format!("#endif  // {}", guard_name));

        true
    }

    /// Convert header guards to #pragma once
    fn convert_to_pragma_once(&self, lines: &mut Vec<String>) -> bool {
        // Find #ifndef, #define, #endif pattern
        let mut ifndef_idx: Option<usize> = None;
        let mut define_idx: Option<usize> = None;
        let mut endif_idx: Option<usize> = None;

        for (i, line) in lines.iter().enumerate() {
            let trimmed = line.trim();
            if ifndef_idx.is_none() && trimmed.starts_with("#ifndef") {
                ifndef_idx = Some(i);
            } else if ifndef_idx.is_some() && define_idx.is_none() && trimmed.starts_with("#define")
            {
                define_idx = Some(i);
            } else if trimmed.starts_with("#endif") {
                endif_idx = Some(i);
            }
        }

        let (ifndef_idx, define_idx, endif_idx) = match (ifndef_idx, define_idx, endif_idx) {
            (Some(a), Some(b), Some(c)) => (a, b, c),
            _ => return false,
        };

        // Verify structure
        if define_idx != ifndef_idx + 1 {
            return false;
        }

        // Check if already using #pragma once
        if lines.iter().any(|l| l.trim() == "#pragma once") {
            return false;
        }

        // Remove old guards and add #pragma once
        lines[ifndef_idx] = "#pragma once".to_string();
        lines[define_idx] = String::new();
        lines[endif_idx] = String::new();

        // Clean up empty lines
        lines.retain(|l| !l.is_empty() || l.trim() != "");

        true
    }

    /// Fix TODO comment based on cpplint error
    fn fix_todo_from_error(&mut self, lines: &mut [String], error: &CpplintError) -> bool {
        // Message: "Missing username in TODO; it should look like "// TODO(my_username): Stuff.""
        if !error.message.contains("Missing username in TODO") {
            return false;
        }

        let line_idx = error.line.saturating_sub(1);
        if line_idx >= lines.len() {
            return false;
        }

        let line = &lines[line_idx];
        let username = self.get_username();

        // Find TODO and add username
        if let Some(todo_pos) = line.find("TODO") {
            let prefix = &line[..todo_pos];
            let after_todo = &line[todo_pos + 4..];

            // Check if already has username
            if after_todo.trim_start().starts_with('(') {
                return false;
            }

            // Extract the rest of the TODO message
            let rest = after_todo.trim_start_matches([':', ' ']).trim();

            lines[line_idx] = if rest.is_empty() {
                format!("{}TODO({}): ", prefix, username)
            } else {
                format!("{}TODO({}): {}", prefix, username, rest)
            };

            return true;
        }

        false
    }

    /// Fix copyright based on cpplint error
    fn fix_copyright_from_error(&self, lines: &mut Vec<String>) -> bool {
        // Check if copyright already exists
        let first_lines: String = lines
            .iter()
            .take(10)
            .cloned()
            .collect::<Vec<_>>()
            .join("\n");
        if first_lines.to_lowercase().contains("copyright") {
            return false;
        }

        // Get copyright template
        let template = match &self.config.copyright_template {
            Some(t) => t.clone(),
            None => return false,
        };

        // Replace {year} with current year
        let year = chrono::Utc::now().format("%Y").to_string();
        let copyright = template.replace("{year}", &year);

        // Insert at the beginning
        let copyright_lines: Vec<String> = copyright.lines().map(|s| s.to_string()).collect();

        // Insert copyright lines at the beginning
        for (i, cline) in copyright_lines.into_iter().enumerate() {
            lines.insert(i, cline);
        }
        lines.insert(copyright.lines().count(), String::new()); // Add empty line after copyright

        true
    }

    /// Fix C-style cast to C++ style cast
    /// E.g., `(void*)0` -> `nullptr`, `(Type*)expr` -> `reinterpret_cast<Type*>(expr)`
    fn fix_c_style_cast(&self, lines: &mut [String], error: &CpplintError) -> bool {
        let line_idx = error.line.saturating_sub(1);
        if line_idx >= lines.len() {
            return false;
        }

        let line = &lines[line_idx];

        // Pattern 1: (void*)0 or ((void*)0) -> nullptr
        let nullptr_re = Regex::new(r"\(\(void\s*\*\)\s*0\)|\(void\s*\*\)\s*0").ok();
        if let Some(re) = nullptr_re {
            if re.is_match(line) {
                lines[line_idx] = re.replace_all(line, "nullptr").to_string();
                return true;
            }
        }

        // Pattern 2: (Type*)expr -> reinterpret_cast<Type*>(expr)
        // This is more complex and risky, so we only handle simple cases
        let cast_re = Regex::new(r"\((\w+\s*\*+)\)\s*(\w+)").ok();
        if let Some(re) = cast_re {
            if let Some(caps) = re.captures(line) {
                let cast_type = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                let expr = caps.get(2).map(|m| m.as_str()).unwrap_or("");
                if !cast_type.is_empty() && !expr.is_empty() {
                    let replacement = format!("reinterpret_cast<{}>({})", cast_type, expr);
                    lines[line_idx] = re.replace(line, replacement.as_str()).to_string();
                    return true;
                }
            }
        }

        false
    }

    /// Fix comment spacing: "//comment" -> "// comment"
    /// NOTE: This only modifies actual comments, not `//` inside string literals
    /// Uses the same detection logic as cpplint's IsCppString function
    fn fix_comment_spacing(&self, lines: &mut [String], error: &CpplintError) -> bool {
        let line_idx = error.line.saturating_sub(1);
        if line_idx >= lines.len() {
            return false;
        }

        let line = &lines[line_idx];
        let fixed = Self::fix_comment_spacing_line(line);

        if fixed != *line {
            lines[line_idx] = fixed;
            true
        } else {
            false
        }
    }

    /// Fix comment spacing for a single line
    fn fix_comment_spacing_line(line: &str) -> String {
        // Find the real comment position (not inside a string)
        let Some(comment_pos) = Self::find_real_comment_pos(line) else {
            return line.to_string();
        };

        let before_comment = &line[..comment_pos];
        let comment_part = &line[comment_pos..];

        // Count consecutive slashes
        let slash_count = comment_part.chars().take_while(|&c| c == '/').count();
        let after_slashes = &comment_part[slash_count..];

        // Check if space is needed
        if !after_slashes.is_empty() {
            let first_char = after_slashes.chars().next().unwrap();
            if first_char != ' ' && first_char != '\n' && first_char != '\r' {
                // Need to add space
                return format!(
                    "{}{} {}",
                    before_comment,
                    "/".repeat(slash_count),
                    after_slashes
                );
            }
        }

        line.to_string()
    }

    /// Find the position of the first real // comment (not inside a string)
    fn find_real_comment_pos(line: &str) -> Option<usize> {
        let mut search_start = 0;

        loop {
            // Find next // starting from search_start
            let rest = &line[search_start..];
            let rel_pos = rest.find("//")?;

            let abs_pos = search_start + rel_pos;
            let before_comment = &line[..abs_pos];

            // Check if this // is inside a string
            if !Self::is_in_cpp_string(before_comment) {
                // This is a real comment
                return Some(abs_pos);
            }

            // This // is inside a string, continue searching after it
            search_start = abs_pos + 2;
        }
    }

    /// Check if the line ends inside a string constant (cpplint's IsCppString logic)
    fn is_in_cpp_string(line: &str) -> bool {
        // Replace \\ with XX to handle escaped backslashes
        let line = line.replace("\\\\", "XX");

        // Count quotes: total " minus escaped \" minus '"' (quote in char literal)
        let total_quotes = line.matches('"').count();
        let escaped_quotes = line.matches("\\\"").count();
        let char_literal_quotes = line.matches("'\"'").count();

        let effective_quotes = total_quotes - escaped_quotes - char_literal_quotes;

        // If odd number of quotes, we're inside a string
        (effective_quotes & 1) == 1
    }

    /// Fix ASSERT_TRUE(a == b) -> ASSERT_EQ(a, b)
    /// And ASSERT_TRUE(a != b) -> ASSERT_NE(a, b)
    fn fix_assert_check(&self, lines: &mut [String], error: &CpplintError) -> bool {
        if !error.message.contains("Consider using ASSERT_") {
            return false;
        }

        let line_idx = error.line.saturating_sub(1);
        if line_idx >= lines.len() {
            return false;
        }

        // (pattern, replacement_macro) pairs
        let replacements = [
            (r"ASSERT_TRUE\s*\(\s*(.+?)\s*==\s*(.+?)\s*\)", "ASSERT_EQ"),
            (r"ASSERT_TRUE\s*\(\s*(.+?)\s*!=\s*(.+?)\s*\)", "ASSERT_NE"),
            (r"ASSERT_FALSE\s*\(\s*(.+?)\s*==\s*(.+?)\s*\)", "ASSERT_NE"),
        ];

        for (pattern, macro_name) in &replacements {
            if Self::try_replace_assert(&mut lines[line_idx], pattern, macro_name) {
                return true;
            }
        }

        false
    }

    /// Try to apply a single assert replacement. Returns true if replaced.
    fn try_replace_assert(line: &mut String, pattern: &str, macro_name: &str) -> bool {
        let re = match Regex::new(pattern) {
            Ok(r) => r,
            Err(_) => return false,
        };
        let Some(caps) = re.captures(line) else {
            return false;
        };
        let lhs = caps.get(1).map(|m| m.as_str().trim()).unwrap_or("");
        let rhs = caps.get(2).map(|m| m.as_str().trim()).unwrap_or("");
        if lhs.is_empty() || rhs.is_empty() {
            return false;
        }
        let replacement = format!("{}({}, {})", macro_name, lhs, rhs);
        *line = re.replace(line.as_str(), replacement.as_str()).to_string();
        true
    }

    /// Fix empty semicolon: replace lone `;` with `{}`
    /// Example: "    ;  // comment" -> "    {}  // comment"
    fn fix_empty_semicolon(&self, lines: &mut [String], error: &CpplintError) -> bool {
        if !error.message.contains("Line contains only semicolon") {
            return false;
        }

        let line_idx = error.line.saturating_sub(1);
        if line_idx >= lines.len() {
            return false;
        }

        let line = &lines[line_idx];

        // Find the position of the lone semicolon (only whitespace before it)
        // Pattern: start with whitespace, then a semicolon, optionally followed by comment or whitespace
        if let Ok(re) = Regex::new(r"^(\s*);(\s*(?://.*)?)?$") {
            if let Some(caps) = re.captures(line) {
                let indent = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                let suffix = caps.get(2).map(|m| m.as_str()).unwrap_or("");
                lines[line_idx] = format!("{}{}{}", indent, "{}", suffix);
                return true;
            }
        }

        false
    }

    /// Fix comma spacing: add space after comma
    /// Example: "foo(a,b)" -> "foo(a, b)"
    /// Skips #pragma mark lines
    fn fix_comma_spacing(&self, lines: &mut [String], error: &CpplintError) -> bool {
        if !error.message.contains("Missing space after ,") {
            return false;
        }

        let line_idx = error.line.saturating_sub(1);
        if line_idx >= lines.len() {
            return false;
        }

        let line = &lines[line_idx];

        // Skip #pragma mark lines - they contain descriptive text where comma is part of content
        if line.trim_start().starts_with("#pragma mark") {
            return false;
        }

        // Add space after comma (but not if already followed by space or end of string)
        // Be careful not to modify strings - use simple approach for now
        let mut result = String::with_capacity(line.len() + 10);
        let mut chars = line.chars().peekable();
        let mut modified = false;

        while let Some(c) = chars.next() {
            result.push(c);
            if c == ',' {
                if let Some(&next) = chars.peek() {
                    if next != ' ' && next != '\n' && next != '\r' {
                        result.push(' ');
                        modified = true;
                    }
                }
            }
        }

        if modified {
            lines[line_idx] = result;
            true
        } else {
            false
        }
    }

    /// Fix operator spacing: add spaces around =
    /// Example: "int x=1" -> "int x = 1"
    fn fix_operator_spacing(&self, lines: &mut [String], error: &CpplintError) -> bool {
        if !error.message.contains("Missing spaces around =") {
            return false;
        }

        let line_idx = error.line.saturating_sub(1);
        if line_idx >= lines.len() {
            return false;
        }

        let line = &lines[line_idx];

        // Use regex to find = without proper spacing
        // Match: not preceded by space + = + not followed by space or =
        // But avoid ==, !=, <=, >=, +=, -=, etc.
        if let Ok(re) = Regex::new(r"([^\s=!<>+\-*/%&|^])=([^=\s])") {
            let result = re.replace_all(line, "$1 = $2").to_string();
            if result != *line {
                lines[line_idx] = result;
                return true;
            }
        }

        false
    }
}

impl Default for CpplintFixer {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parse_cpplint_output() {
        let output = r##"test.h:8:  #ifndef header guard has wrong style, please use: FOO_BAR_H_  [build/header_guard] [5]
test.h:76:  #endif line should be "#endif  // FOO_BAR_H_"  [build/header_guard] [5]
test.cc:17:  Missing username in TODO; it should look like "// TODO(my_username): Stuff."  [readability/todo] [2]
"##;

        let errors = CpplintFixer::parse_cpplint_output(output);
        assert_eq!(errors.len(), 3);

        assert_eq!(errors[0].line, 8);
        assert_eq!(errors[0].category, "build/header_guard");
        assert!(errors[0].message.contains("please use: FOO_BAR_H_"));

        assert_eq!(errors[1].line, 76);
        assert_eq!(errors[1].category, "build/header_guard");

        assert_eq!(errors[2].line, 17);
        assert_eq!(errors[2].category, "readability/todo");
    }

    #[test]
    fn test_parse_missing_header_guard() {
        // Test parsing "No #ifndef header guard found" error (line 0)
        let output = r##"test.h:0:  No #ifndef header guard found, suggested CPP variable is: TEST_H_  [build/header_guard] [5]
"##;

        let errors = CpplintFixer::parse_cpplint_output(output);
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].line, 0);
        assert_eq!(errors[0].category, "build/header_guard");
        assert!(errors[0]
            .message
            .contains("suggested CPP variable is: TEST_H_"));
    }

    #[test]
    fn test_insert_missing_header_guard() {
        let fixer = CpplintFixer::new();

        // File without header guard
        let mut lines = vec![
            "// Copyright notice".to_string(),
            "".to_string(),
            "#include <stdio.h>".to_string(),
            "".to_string(),
            "void foo();".to_string(),
        ];

        let error = CpplintError {
            line: 0,
            message: "No #ifndef header guard found, suggested CPP variable is: TEST_H_"
                .to_string(),
            category: "build/header_guard".to_string(),
        };

        assert!(fixer.fix_header_guard_from_error(&mut lines, &error));

        // Check that header guard was inserted after copyright
        assert!(lines.iter().any(|l| l.contains("#ifndef TEST_H_")));
        assert!(lines.iter().any(|l| l.contains("#define TEST_H_")));
        assert!(lines.iter().any(|l| l.contains("#endif  // TEST_H_")));
    }

    #[test]
    fn test_fix_header_guard_from_error() {
        let fixer = CpplintFixer::new();

        let mut lines = vec![
            "#ifndef OLD_GUARD".to_string(),
            "#define OLD_GUARD".to_string(),
            "// content".to_string(),
            "#endif".to_string(),
        ];

        let error = CpplintError {
            line: 1,
            message: "#ifndef header guard has wrong style, please use: NEW_GUARD_H_".to_string(),
            category: "build/header_guard".to_string(),
        };

        assert!(fixer.fix_header_guard_from_error(&mut lines, &error));
        assert_eq!(lines[0], "#ifndef NEW_GUARD_H_");
        assert_eq!(lines[1], "#define NEW_GUARD_H_");
    }

    #[test]
    fn test_fix_todo_from_error() {
        let mut fixer = CpplintFixer::new();
        fixer.cached_username = Some("testuser".to_string());

        let mut lines = vec![
            "// TODO: fix this".to_string(),
            "// TODO(existing): keep this".to_string(),
        ];

        let error = CpplintError {
            line: 1,
            message:
                r#"Missing username in TODO; it should look like "// TODO(my_username): Stuff.""#
                    .to_string(),
            category: "readability/todo".to_string(),
        };

        assert!(fixer.fix_todo_from_error(&mut lines, &error));
        assert_eq!(lines[0], "// TODO(testuser): fix this");
        assert_eq!(lines[1], "// TODO(existing): keep this");
    }

    #[test]
    fn test_fix_endif_line() {
        let fixer = CpplintFixer::new();

        let mut lines = vec![
            "#ifndef GUARD_H_".to_string(),
            "#define GUARD_H_".to_string(),
            "// content".to_string(),
            "#endif".to_string(),
        ];

        let error = CpplintError {
            line: 4,
            message: r##"#endif line should be "#endif  // GUARD_H_""##.to_string(),
            category: "build/header_guard".to_string(),
        };

        assert!(fixer.fix_header_guard_from_error(&mut lines, &error));
        assert_eq!(lines[3], "#endif  // GUARD_H_");
    }

    #[test]
    fn test_fix_comment_spacing_cpplint() {
        let fixer = CpplintFixer::new();

        let mut lines = vec![
            "int x = 1; //comment".to_string(),
            "int y = 2; // already spaced".to_string(),
        ];

        let error = CpplintError {
            line: 1,
            message: "Should have a space between // and comment".to_string(),
            category: "whitespace/comments".to_string(),
        };

        assert!(fixer.fix_comment_spacing(&mut lines, &error));
        assert_eq!(lines[0], "int x = 1; // comment");
        assert_eq!(lines[1], "int y = 2; // already spaced");
    }

    #[test]
    fn test_fix_comment_spacing_triple_slash() {
        let fixer = CpplintFixer::new();

        let mut lines = vec!["///doc comment".to_string()];

        let error = CpplintError {
            line: 1,
            message: "Should have a space between // and comment".to_string(),
            category: "whitespace/comments".to_string(),
        };

        assert!(fixer.fix_comment_spacing(&mut lines, &error));
        assert_eq!(lines[0], "/// doc comment");
    }

    #[test]
    fn test_fix_comment_spacing_preserves_url() {
        let fixer = CpplintFixer::new();

        // URLs like https:// should NOT be modified
        let mut lines = vec!["return @\"https://example.com\";".to_string()];

        let error = CpplintError {
            line: 1,
            message: "Should have a space between // and comment".to_string(),
            category: "whitespace/comments".to_string(),
        };

        // Should not modify URL
        assert!(!fixer.fix_comment_spacing(&mut lines, &error));
        assert_eq!(lines[0], "return @\"https://example.com\";");
    }

    #[test]
    fn test_fix_comment_spacing_url_and_comment() {
        let fixer = CpplintFixer::new();

        // Should preserve URL but fix comment
        let mut lines = vec!["NSString *url = @\"https://example.com\"; //comment".to_string()];

        let error = CpplintError {
            line: 1,
            message: "Should have a space between // and comment".to_string(),
            category: "whitespace/comments".to_string(),
        };

        assert!(fixer.fix_comment_spacing(&mut lines, &error));
        assert_eq!(
            lines[0],
            "NSString *url = @\"https://example.com\"; // comment"
        );
    }

    #[test]
    fn test_insert_header_guard_after_block_comment() {
        let fixer = CpplintFixer::new();

        let mut lines = vec![
            "/*".to_string(),
            " * Copyright 2024".to_string(),
            " */".to_string(),
            "".to_string(),
            "#include <stdio.h>".to_string(),
        ];

        let error = CpplintError {
            line: 0,
            message: "No #ifndef header guard found, suggested CPP variable is: TEST_H_"
                .to_string(),
            category: "build/header_guard".to_string(),
        };

        assert!(fixer.fix_header_guard_from_error(&mut lines, &error));

        // Find positions
        let ifndef_pos = lines
            .iter()
            .position(|l| l.contains("#ifndef TEST_H_"))
            .unwrap();
        let block_end_pos = lines.iter().position(|l| l.contains("*/")).unwrap();

        // Header guard should be after block comment
        assert!(ifndef_pos > block_end_pos);
    }

    #[test]
    fn test_parse_whitespace_comments_error() {
        let output = r##"test.cc:5:  Should have a space between // and comment  [whitespace/comments] [4]
"##;

        let errors = CpplintFixer::parse_cpplint_output(output);
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].line, 5);
        assert_eq!(errors[0].category, "whitespace/comments");
    }
}