splice 2.6.1

Span-safe refactoring kernel for 7 languages with Magellan code graph integration
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
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
//! Pattern-based search and replace with AST confirmation.
//!
//! This module provides multi-file pattern replacement capabilities
//! using glob patterns for file discovery and tree-sitter for AST
//! confirmation to ensure replacements land on the intended tokens.

use crate::error::{Result, SpliceError};
use crate::symbol::{parser_for_language, Language};
use crate::validate::AnalyzerMode;
use glob::glob;
use serde::Serialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Configuration for pattern-based replacement.
#[derive(Debug, Clone)]
pub struct PatternReplaceConfig {
    /// Glob pattern for matching files.
    pub glob_pattern: String,
    /// Text pattern to find.
    pub find_pattern: String,
    /// Replacement text.
    pub replace_pattern: String,
    /// Optional language hint (auto-detected from file extension if not provided).
    pub language: Option<Language>,
    /// Whether to apply validation gates.
    pub validate: bool,
}

/// A match found during pattern search.
#[derive(Debug, Clone, Serialize)]
pub struct PatternMatch {
    /// File where the match was found.
    pub file: PathBuf,
    /// Byte start of the match.
    pub byte_start: usize,
    /// Byte end of the match.
    pub byte_end: usize,
    /// Line number (1-based).
    pub line: usize,
    /// Column number (0-based).
    pub column: usize,
    /// The matched text.
    pub matched_text: String,

    // Optional: Context fields (populated when requested)
    /// Context lines before the match.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_before: Option<Vec<String>>,

    /// Context lines after the match.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_after: Option<Vec<String>>,
}

/// Result of a pattern replacement operation.
#[derive(Debug, Clone)]
pub struct PatternReplaceResult {
    /// Files that were patched.
    pub files_patched: Vec<PathBuf>,
    /// Number of replacements made.
    pub replacements_count: usize,
    /// Validation errors (if any).
    pub validation_errors: Vec<String>,
}

/// Find all occurrences of a text pattern in files matching a glob pattern.
///
/// This function performs text-based search and uses tree-sitter to confirm
/// that matches are in valid AST nodes (not in comments or strings, unless
/// the pattern specifically targets those).
pub fn find_pattern_in_files(config: &PatternReplaceConfig) -> Result<Vec<PatternMatch>> {
    let mut matches = Vec::new();

    // Use glob to find matching files
    let glob_paths = glob(&config.glob_pattern)
        .map_err(|e| SpliceError::Other(format!("Invalid glob pattern: {}", e)))?;

    for entry in glob_paths {
        let entry =
            entry.map_err(|e| SpliceError::Other(format!("Glob iteration error: {}", e)))?;
        let path = entry;

        // Skip directories
        if path.is_dir() {
            continue;
        }

        // Determine language for this file
        let language = if let Some(lang) = config.language {
            lang
        } else {
            Language::from_path(&path).ok_or_else(|| {
                SpliceError::Other(format!(
                    "Cannot detect language for file: {}",
                    path.display()
                ))
            })?
        };

        // Find matches in this file
        let file_matches = find_pattern_in_file(&path, &config.find_pattern, language)?;
        matches.extend(file_matches);
    }

    Ok(matches)
}

/// Find all occurrences of a text pattern in a single file with AST confirmation.
///
/// Uses tree-sitter to ensure matches are in valid code locations.
fn find_pattern_in_file(
    file_path: &Path,
    pattern: &str,
    language: Language,
) -> Result<Vec<PatternMatch>> {
    let content = std::fs::read_to_string(file_path).map_err(|e| SpliceError::Io {
        path: file_path.to_path_buf(),
        source: e,
    })?;

    // Get parser for the language
    let mut parser = parser_for_language(language)?;

    let tree = parser
        .parse(&content, None)
        .ok_or_else(|| SpliceError::Other("Failed to parse file".to_string()))?;

    let mut matches = Vec::new();

    // Find all text occurrences of the pattern
    let mut start_idx = 0;
    while let Some(idx) = content[start_idx..].find(pattern) {
        let abs_start = start_idx + idx;
        let abs_end = abs_start + pattern.len();

        // Check if this location is in a valid AST node
        let byte_offset = abs_start as usize;
        let node = tree
            .root_node()
            .descendant_for_byte_range(byte_offset, byte_offset);

        if let Some(node) = node {
            // Skip matches in comments unless the pattern starts with '//'
            let node_kind = node.kind();
            let is_comment = node_kind == "comment"
                || node_kind == "line_comment"
                || node_kind == "block_comment"
                || node_kind.ends_with("_comment");

            if !is_comment || pattern.starts_with("//") {
                // Get line and column using ropey
                let rope = ropey::Rope::from_reader(content.as_bytes()).map_err(|e| {
                    crate::SpliceError::Other(format!("Failed to create rope: {}", e))
                })?;
                let line = rope.byte_to_line(abs_start) + 1;
                let line_start_byte = rope.line_to_byte(line - 1);
                let column = abs_start - line_start_byte;

                matches.push(PatternMatch {
                    file: file_path.to_path_buf(),
                    byte_start: abs_start,
                    byte_end: abs_end,
                    line,
                    column,
                    matched_text: pattern.to_string(),
                    context_before: None,
                    context_after: None,
                });
            }
        }

        start_idx = abs_end;
    }

    Ok(matches)
}

/// Apply pattern replacement to files with atomic writes and rollback.
///
/// This function:
/// 1. Finds all pattern matches using AST confirmation
/// 2. Creates backups of all files to be modified
/// 3. Applies replacements using atomic writes (tempfile + persist)
/// 4. On any error, restores all files from backups (atomic rollback)
/// 5. Runs validation gates if requested
pub fn apply_pattern_replace(
    config: &PatternReplaceConfig,
    workspace_dir: &Path,
) -> Result<PatternReplaceResult> {
    use std::io::Write;

    // Find all matches
    let matches = find_pattern_in_files(config)?;

    if matches.is_empty() {
        return Ok(PatternReplaceResult {
            files_patched: Vec::new(),
            replacements_count: 0,
            validation_errors: Vec::new(),
        });
    }

    // Group matches by file and sort by byte offset (descending for replacement)
    let mut matches_by_file: HashMap<PathBuf, Vec<&PatternMatch>> = HashMap::new();
    for m in &matches {
        matches_by_file.entry(m.file.clone()).or_default().push(m);
    }

    for file_matches in matches_by_file.values_mut() {
        file_matches.sort_by_key(|m| std::cmp::Reverse(m.byte_start));
    }

    // Create backup manifest for rollback
    let mut backups: Vec<(PathBuf, String)> = Vec::new();

    // Apply replacements per file with atomic writes
    let mut files_patched = Vec::new();
    let mut replacements_count = 0;

    // First pass: create backups of all files to be modified
    for (file_path, _) in &matches_by_file {
        let replaced = std::fs::read_to_string(file_path).map_err(|e| SpliceError::Io {
            path: file_path.clone(),
            source: e,
        })?;
        backups.push((file_path.clone(), replaced));
    }

    // Second pass: apply replacements using atomic writes
    let apply_result: std::result::Result<(), SpliceError> =
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            for (file_path, file_matches) in &matches_by_file {
                if file_matches.is_empty() {
                    continue;
                }

                // Get original content from backup
                let replaced = backups
                    .iter()
                    .find(|(path, _)| path == file_path)
                    .map(|(_, content)| content.clone())
                    .unwrap();

                // Apply replacements in reverse byte order
                let mut content = replaced.clone();
                for m in &**file_matches {
                    let start_byte = m.byte_start;
                    let end_byte = m.byte_end;

                    // Replace the content
                    content.replace_range(start_byte..end_byte, &config.replace_pattern);
                    replacements_count += 1;
                }

                // Atomic write using tempfile
                let parent_dir = file_path.parent().unwrap_or(Path::new("."));
                let mut temp =
                    tempfile::NamedTempFile::new_in(parent_dir).map_err(|e| SpliceError::Io {
                        path: file_path.clone(),
                        source: e.into(),
                    })?;

                temp.write_all(content.as_bytes())
                    .map_err(|e| SpliceError::Io {
                        path: file_path.clone(),
                        source: e.into(),
                    })?;

                // Persist atomically (replaces original file)
                temp.persist(file_path).map_err(|e| SpliceError::Io {
                    path: file_path.clone(),
                    source: e.into(),
                })?;

                files_patched.push(file_path.clone());
            }

            Ok::<(), SpliceError>(())
        }))
        .map_err(|_| {
            // Panic occurred - convert to SpliceError for rollback
            SpliceError::Other("Panic during pattern replacement".to_string())
        })?;

    // apply_result is now Result<(), SpliceError> after map_err
    // If it's Err, we need to roll back and return the error
    if let Err(rollback_err) = apply_result {
        // Restore all files from backups
        for (file_path, replaced_content) in &backups {
            // Attempt to restore, but continue even if restore fails
            let _ = std::fs::write(file_path, replaced_content);
        }

        return Err(rollback_err);
    }

    // Run validation if requested
    if config.validate {
        // For each patched file, run validation
        for file_path in &files_patched {
            // Determine language
            let lang = config
                .language
                .or_else(|| Language::from_path(file_path))
                .ok_or_else(|| {
                    SpliceError::Other(format!(
                        "Cannot detect language for file: {}",
                        file_path.display()
                    ))
                })?;

            // Run validation gates
            crate::patch::run_validation_gates(file_path, workspace_dir, lang, AnalyzerMode::Off)?;
        }
    }

    Ok(PatternReplaceResult {
        files_patched,
        replacements_count,
        validation_errors: Vec::new(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_find_pattern_in_file() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"
fn foo() {
    let x = 42;
    let y = 42;
    println!("{}", x);
}
"#,
        )
        .expect("Failed to write test file");

        let matches =
            find_pattern_in_file(&test_file, "42", Language::Rust).expect("Failed to find pattern");

        assert_eq!(matches.len(), 2, "Should find 2 occurrences of '42'");
    }

    #[test]
    fn test_apply_pattern_replace() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.py");
        fs::write(
            &test_file,
            r#"
def foo():
    x = 10
    y = 10
    return x + y
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.py")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "10".to_string(),
            replace_pattern: "20".to_string(),
            language: Some(Language::Python),
            validate: false,
        };

        let result = apply_pattern_replace(&config, workspace_root)
            .expect("Failed to apply pattern replace");

        assert_eq!(result.files_patched.len(), 1);
        assert_eq!(result.replacements_count, 2);

        let content = fs::read_to_string(&test_file).expect("Failed to read file");
        assert!(content.contains("20"), "Should contain replaced value");
    }

    #[test]
    fn test_search_command_rust() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"
fn search_function() {
    let value = "test";
    println!("{}", value);
}

fn another_function() {
    let other = "another";
}
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "function".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 2, "Should find 2 occurrences of 'function'");
        assert_eq!(matches[0].file, test_file);
        assert_eq!(matches[0].line, 2);
    }

    #[test]
    fn test_search_command_python() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.py");
        fs::write(
            &test_file,
            r#"
def search_function():
    value = "test"
    print(value)

def another_function():
    other = "another"
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.py")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "function".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Python),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 2, "Should find 2 occurrences of 'function'");
        assert_eq!(matches[0].file, test_file);
    }

    #[test]
    fn test_search_command_multiple_files() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file1 = workspace_root.join("file1.rs");
        fs::write(
            &test_file1,
            r#"
fn first() {
    let target = 1;
}
"#,
        )
        .expect("Failed to write test file");

        let test_file2 = workspace_root.join("file2.rs");
        fs::write(
            &test_file2,
            r#"
fn second() {
    let target = 2;
}
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "target".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 2, "Should find 2 occurrences across files");
        assert_eq!(matches[0].file, test_file1);
        assert_eq!(matches[1].file, test_file2);
    }

    #[test]
    fn test_search_command_no_matches() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"
fn example() {
    let x = 42;
}
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "nonexistent".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 0, "Should find no occurrences");
    }

    #[test]
    fn test_search_glob_rust_only() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create nested directory structure
        let src_dir = workspace_root.join("src");
        fs::create_dir(&src_dir).expect("Failed to create src dir");

        let tests_dir = workspace_root.join("tests");
        fs::create_dir(&tests_dir).expect("Failed to create tests dir");

        // Create Rust files in src/
        let rust_file = src_dir.join("main.rs");
        fs::write(
            &rust_file,
            r#"
fn main() {
    let rust_unique_pattern = 42;
}
"#,
        )
        .expect("Failed to write test file");

        // Create Python file in tests/
        let python_file = tests_dir.join("test.py");
        fs::write(
            &python_file,
            r#"
def test():
    python_unique_pattern = 24
"#,
        )
        .expect("Failed to write test file");

        // Search only .rs files
        let config = PatternReplaceConfig {
            glob_pattern: src_dir
                .join("**/*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "rust_unique_pattern".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(
            matches.len(),
            1,
            "Should find 1 occurrence in .rs file only"
        );
        assert_eq!(matches[0].file, rust_file, "Should match the Rust file");
    }

    #[test]
    fn test_search_glob_python_only() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create nested directory structure
        let src_dir = workspace_root.join("src");
        fs::create_dir(&src_dir).expect("Failed to create src dir");

        let tests_dir = workspace_root.join("tests");
        fs::create_dir(&tests_dir).expect("Failed to create tests dir");

        // Create Python file in tests/
        let python_file = tests_dir.join("test.py");
        fs::write(
            &python_file,
            r#"
def test_function():
    python_unique_pattern = 42
"#,
        )
        .expect("Failed to write test file");

        // Create Rust file in src/
        let rust_file = src_dir.join("main.rs");
        fs::write(
            &rust_file,
            r#"
fn main() {
    let rust_unique_pattern = 24
}
"#,
        )
        .expect("Failed to write test file");

        // Search only .py files
        let config = PatternReplaceConfig {
            glob_pattern: tests_dir
                .join("**/*.py")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "python_unique_pattern".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Python),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(
            matches.len(),
            1,
            "Should find 1 occurrence in .py file only"
        );
        assert_eq!(matches[0].file, python_file, "Should match the Python file");
    }

    #[test]
    fn test_search_glob_multi_extension() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create Rust file
        let rust_file = workspace_root.join("test.rs");
        fs::write(
            &rust_file,
            r#"
fn rust_function() {
    let target = 1;
}
"#,
        )
        .expect("Failed to write test file");

        // Create Python file
        let python_file = workspace_root.join("test.py");
        fs::write(
            &python_file,
            r#"
def python_function():
    target = 2
"#,
        )
        .expect("Failed to write test file");

        // Create C file (should not match)
        let c_file = workspace_root.join("test.c");
        fs::write(
            &c_file,
            r#"
void c_function() {
    int target = 3;
}
"#,
        )
        .expect("Failed to write test file");

        // Search for .rs files first
        let config_rs = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "target".to_string(),
            replace_pattern: String::new(),
            language: None,
            validate: false,
        };

        let matches_rs =
            find_pattern_in_files(&config_rs).expect("Failed to search for pattern in .rs files");

        // Search for .py files next
        let config_py = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.py")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "target".to_string(),
            replace_pattern: String::new(),
            language: None,
            validate: false,
        };

        let matches_py =
            find_pattern_in_files(&config_py).expect("Failed to search for pattern in .py files");

        // Total matches across both extensions
        let total_matches = matches_rs.len() + matches_py.len();

        assert_eq!(
            total_matches, 2,
            "Should find 2 occurrences total in .rs and .py files"
        );
        assert_eq!(matches_rs.len(), 1, "Should find 1 occurrence in .rs file");
        assert_eq!(matches_py.len(), 1, "Should find 1 occurrence in .py file");
    }

    #[test]
    fn test_search_glob_recursive() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create nested directory structure
        let level1 = workspace_root.join("level1");
        fs::create_dir(&level1).expect("Failed to create level1 dir");

        let level2 = level1.join("level2");
        fs::create_dir(&level2).expect("Failed to create level2 dir");

        // Create files at each level
        let root_file = workspace_root.join("root.rs");
        fs::write(
            &root_file,
            r#"
fn root() {
    let search_target = 1;
}
"#,
        )
        .expect("Failed to write test file");

        let level1_file = level1.join("level1.rs");
        fs::write(
            &level1_file,
            r#"
fn level1() {
    let search_target = 2;
}
"#,
        )
        .expect("Failed to write test file");

        let level2_file = level2.join("level2.rs");
        fs::write(
            &level2_file,
            r#"
fn level2() {
    let search_target = 3;
}
"#,
        )
        .expect("Failed to write test file");

        // Search recursively with **/*.rs pattern
        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("**/*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "search_target".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(
            matches.len(),
            3,
            "Should find 3 occurrences across all nested directories"
        );

        // Verify files are in correct order
        let file_names: Vec<_> = matches
            .iter()
            .map(|m| {
                m.file
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or_default()
                    .to_string()
            })
            .collect();
        assert!(file_names.contains(&"root.rs".to_string()));
        assert!(file_names.contains(&"level1.rs".to_string()));
        assert!(file_names.contains(&"level2.rs".to_string()));
    }

    #[test]
    fn test_search_glob_no_matches() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create directory with no matching files
        let empty_dir = workspace_root.join("empty");
        fs::create_dir(&empty_dir).expect("Failed to create empty dir");

        // Create a file that doesn't match the pattern
        let other_file = empty_dir.join("readme.txt");
        fs::write(
            &other_file,
            r#"
This is a text file with no code.
"#,
        )
        .expect("Failed to write test file");

        // Search for .rs files in directory that has none
        let config = PatternReplaceConfig {
            glob_pattern: empty_dir
                .join("**/*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "anything".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(
            matches.len(),
            0,
            "Should find no occurrences when pattern doesn't match any files"
        );
    }

    #[test]
    fn test_search_with_context() {
        use crate::context::extract_context_asymmetric;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create test file with multiple lines
        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"line 1
line 2
line 3
line 4
line 5
"#,
        )
        .expect("Failed to write test file");

        // Search for "line 3" with context
        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "line 3".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 1, "Should find one occurrence of 'line 3'");

        // Extract context with 1 line before and after
        let m = &matches[0];
        let context = extract_context_asymmetric(
            &m.file,
            m.byte_start,
            m.byte_end,
            1, // context_before
            1, // context_after
        )
        .expect("Failed to extract context");

        // Verify context
        assert_eq!(context.before.len(), 1, "Should have 1 line before");
        assert_eq!(context.selected.len(), 1, "Should have 1 selected line");
        assert_eq!(context.after.len(), 1, "Should have 1 line after");
        assert!(context.before[0].contains("line 2"));
        assert!(context.selected[0].contains("line 3"));
        assert!(context.after[0].contains("line 4"));
    }

    #[test]
    fn test_search_context_asymmetric() {
        use crate::context::extract_context_asymmetric;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create test file with multiple lines
        let test_file = workspace_root.join("test.py");
        fs::write(
            &test_file,
            r#"line 1
line 2
line 3
line 4
line 5
line 6
"#,
        )
        .expect("Failed to write test file");

        // Search for "line 4" with asymmetric context
        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.py")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "line 4".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Python),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 1, "Should find one occurrence of 'line 4'");

        // Extract asymmetric context: 2 lines before, 1 line after
        let m = &matches[0];
        let context = extract_context_asymmetric(
            &m.file,
            m.byte_start,
            m.byte_end,
            2, // context_before
            1, // context_after
        )
        .expect("Failed to extract context");

        // Verify asymmetric context
        assert_eq!(context.before.len(), 2, "Should have 2 lines before");
        assert_eq!(context.after.len(), 1, "Should have 1 line after");
        assert!(context.before[0].contains("line 2"));
        assert!(context.before[1].contains("line 3"));
        assert!(context.after[0].contains("line 5"));
    }

    #[test]
    fn test_search_no_context() {
        use crate::context::extract_context_asymmetric;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create test file
        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"line 1
line 2
line 3
"#,
        )
        .expect("Failed to write test file");

        // Search for "line 2" with no context
        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "line 2".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 1, "Should find one occurrence of 'line 2'");

        // Extract context with 0 lines before and after
        let m = &matches[0];
        let context = extract_context_asymmetric(
            &m.file,
            m.byte_start,
            m.byte_end,
            0, // context_before
            0, // context_after
        )
        .expect("Failed to extract context");

        // Verify no context
        assert_eq!(context.before.len(), 0, "Should have 0 lines before");
        assert_eq!(context.after.len(), 0, "Should have 0 lines after");
        assert_eq!(context.selected.len(), 1, "Should have 1 selected line");
    }

    #[test]
    fn test_search_context_in_json() {
        use crate::context::extract_context_asymmetric;
        use serde_json::json;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        // Create test file with multiple lines
        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"line 1
line 2
line 3
line 4
"#,
        )
        .expect("Failed to write test file");

        // Search for "line 3" with context
        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "line 3".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 1, "Should find one occurrence of 'line 3'");

        // Build JSON structure like execute_search does
        let m = &matches[0];
        let context = extract_context_asymmetric(
            &m.file,
            m.byte_start,
            m.byte_end,
            1, // context_before
            1, // context_after
        )
        .expect("Failed to extract context");

        let json_result = json!({
            "file": m.file.to_str().unwrap_or("<invalid-utf-8>").to_string(),
            "byte_start": m.byte_start,
            "byte_end": m.byte_end,
            "line": m.line,
            "column": m.column,
            "matched_text": m.matched_text,
            "context_before": context.before,
            "context_selected": context.selected,
            "context_after": context.after,
        });

        // Verify JSON structure
        assert!(json_result["file"].is_string());
        assert!(json_result["byte_start"].is_number());
        assert!(json_result["line"].is_number());
        assert!(json_result["matched_text"].is_string());
        assert!(json_result["context_before"].is_array());
        assert!(json_result["context_selected"].is_array());
        assert!(json_result["context_after"].is_array());

        // Verify context arrays have correct length
        assert_eq!(json_result["context_before"].as_array().unwrap().len(), 1);
        assert_eq!(json_result["context_selected"].as_array().unwrap().len(), 1);
        assert_eq!(json_result["context_after"].as_array().unwrap().len(), 1);

        // Verify context content
        let before_str = json_result["context_before"][0].as_str().unwrap();
        let selected_str = json_result["context_selected"][0].as_str().unwrap();
        let after_str = json_result["context_after"][0].as_str().unwrap();

        assert!(before_str.contains("line 2"));
        assert!(selected_str.contains("line 3"));
        assert!(after_str.contains("line 4"));
    }

    #[test]
    fn test_search_json_output_format() {
        use serde_json::json;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.rs");
        fs::write(&test_file, r#"fn test() { let x = 42; }"#).expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "42".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        // Build full JSON output structure like execute_search does
        let results: Vec<Value> = matches
            .into_iter()
            .map(|m| {
                json!({
                    "file": m.file.to_str().unwrap_or("<invalid-utf-8>").to_string(),
                    "byte_start": m.byte_start,
                    "byte_end": m.byte_end,
                    "line": m.line,
                    "column": m.column,
                    "matched_text": m.matched_text,
                })
            })
            .collect();

        let output = json!({
            "status": "ok",
            "message": format!("Found {} occurrence(s) of '42'", results.len()),
            "matches": results,
            "pattern": "42",
            "count": results.len(),
        });

        // Verify top-level structure
        assert_eq!(output["status"], "ok");
        assert!(output["message"].is_string());
        assert!(output["matches"].is_array());
        assert_eq!(output["pattern"], "42");
        assert_eq!(output["count"], 1);
    }

    #[test]
    fn test_search_json_with_context() {
        use crate::context::extract_context_asymmetric;
        use serde_json::json;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"line 1
line 2
line 3
line 4
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "line 3".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        assert_eq!(matches.len(), 1);

        let m = &matches[0];
        let context = extract_context_asymmetric(
            &m.file,
            m.byte_start,
            m.byte_end,
            1, // context_before
            1, // context_after
        )
        .expect("Failed to extract context");

        // Build JSON with context
        let mut match_json = json!({
            "file": m.file.to_str().unwrap_or("<invalid-utf-8>").to_string(),
            "byte_start": m.byte_start,
            "byte_end": m.byte_end,
            "line": m.line,
            "column": m.column,
            "matched_text": m.matched_text,
        });

        if let Some(obj) = match_json.as_object_mut() {
            obj.insert("context_before".to_string(), json!(context.before));
            obj.insert("context_selected".to_string(), json!(context.selected));
            obj.insert("context_after".to_string(), json!(context.after));
        }

        // Verify context fields are present
        assert!(match_json.get("context_before").is_some());
        assert!(match_json.get("context_selected").is_some());
        assert!(match_json.get("context_after").is_some());
        assert!(match_json["context_before"].is_array());
        assert!(match_json["context_selected"].is_array());
        assert!(match_json["context_after"].is_array());
    }

    #[test]
    fn test_search_json_parseable() {
        use serde_json::json;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.py");
        fs::write(
            &test_file,
            r#"def foo():
    x = 10
    return x"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.py")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "x".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Python),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        // Build JSON output
        let results: Vec<Value> = matches
            .into_iter()
            .map(|m| {
                json!({
                    "file": m.file.to_str().unwrap_or("<invalid-utf-8>").to_string(),
                    "byte_start": m.byte_start,
                    "byte_end": m.byte_end,
                    "line": m.line,
                    "column": m.column,
                    "matched_text": m.matched_text,
                })
            })
            .collect();

        let output = json!({
            "status": "ok",
            "message": format!("Found {} occurrence(s) of 'x'", results.len()),
            "matches": results,
            "pattern": "x",
            "count": results.len(),
        });

        // Verify it can be serialized and deserialized
        let json_string = serde_json::to_string(&output).expect("Failed to serialize JSON");
        let parsed: Value = serde_json::from_str(&json_string).expect("Failed to parse JSON");

        assert_eq!(parsed, output);
    }

    #[test]
    fn test_search_json_no_context() {
        use serde_json::json;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.rs");
        fs::write(&test_file, r#"fn test() { let x = 42; }"#).expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "42".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        // Build JSON without context (no context flags specified)
        let results: Vec<Value> = matches
            .into_iter()
            .map(|m| {
                json!({
                    "file": m.file.to_str().unwrap_or("<invalid-utf-8>").to_string(),
                    "byte_start": m.byte_start,
                    "byte_end": m.byte_end,
                    "line": m.line,
                    "column": m.column,
                    "matched_text": m.matched_text,
                })
            })
            .collect();

        // Verify context fields are not present when not requested
        let first_match = &results[0];
        assert!(first_match.get("context_before").is_none());
        assert!(first_match.get("context_selected").is_none());
        assert!(first_match.get("context_after").is_none());
    }

    #[test]
    fn test_search_json_all_metadata() {
        use serde_json::json;
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"fn example() {
    let value = 100;
}"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "100".to_string(),
            replace_pattern: String::new(),
            language: Some(Language::Rust),
            validate: false,
        };

        let matches = find_pattern_in_files(&config).expect("Failed to search for pattern");

        // Build JSON output with all metadata
        let results: Vec<Value> = matches
            .into_iter()
            .map(|m| {
                json!({
                    "file": m.file.to_str().unwrap_or("<invalid-utf-8>").to_string(),
                    "byte_start": m.byte_start,
                    "byte_end": m.byte_end,
                    "line": m.line,
                    "column": m.column,
                    "matched_text": m.matched_text,
                })
            })
            .collect();

        let output = json!({
            "status": "ok",
            "message": format!("Found {} occurrence(s) of '100'", results.len()),
            "matches": results,
            "pattern": "100",
            "count": results.len(),
        });

        // Verify all top-level fields
        assert!(output.get("status").is_some());
        assert!(output.get("message").is_some());
        assert!(output.get("matches").is_some());
        assert!(output.get("pattern").is_some());
        assert!(output.get("count").is_some());

        // Verify all match metadata fields
        let first_match = &output["matches"][0];
        assert!(first_match.get("file").is_some());
        assert!(first_match.get("byte_start").is_some());
        assert!(first_match.get("byte_end").is_some());
        assert!(first_match.get("line").is_some());
        assert!(first_match.get("column").is_some());
        assert!(first_match.get("matched_text").is_some());

        // Verify field types
        assert!(first_match["file"].is_string());
        assert!(first_match["byte_start"].is_number());
        assert!(first_match["byte_end"].is_number());
        assert!(first_match["line"].is_number());
        assert!(first_match["column"].is_number());
        assert!(first_match["matched_text"].is_string());
    }

    #[test]
    fn test_apply_replace_single_file() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.rs");
        fs::write(
            &test_file,
            r#"
fn foo() {
    let x = 42;
    let y = 42;
    println!("{}", x);
}
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "42".to_string(),
            replace_pattern: "100".to_string(),
            language: Some(Language::Rust),
            validate: false,
        };

        let result = apply_pattern_replace(&config, workspace_root)
            .expect("Failed to apply pattern replace");

        assert_eq!(result.files_patched.len(), 1);
        assert_eq!(result.replacements_count, 2);

        let content = fs::read_to_string(&test_file).expect("Failed to read file");
        assert!(content.contains("100"), "Should contain replaced value");
        assert!(!content.contains("42"), "Should not contain replaced value");
    }

    #[test]
    fn test_apply_replace_multiple_files() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file1 = workspace_root.join("file1.rs");
        fs::write(
            &test_file1,
            r#"
fn first() {
    let target = 1;
}
"#,
        )
        .expect("Failed to write test file");

        let test_file2 = workspace_root.join("file2.rs");
        fs::write(
            &test_file2,
            r#"
fn second() {
    let target = 2;
}
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "target".to_string(),
            replace_pattern: "replaced".to_string(),
            language: Some(Language::Rust),
            validate: false,
        };

        let result = apply_pattern_replace(&config, workspace_root)
            .expect("Failed to apply pattern replace");

        assert_eq!(result.files_patched.len(), 2);
        assert_eq!(result.replacements_count, 2);

        let content1 = fs::read_to_string(&test_file1).expect("Failed to read file1");
        assert!(content1.contains("replaced"));

        let content2 = fs::read_to_string(&test_file2).expect("Failed to read file2");
        assert!(content2.contains("replaced"));
    }

    #[test]
    fn test_apply_replace_rollback_on_error() {
        // Test atomic multi-file replacement - all files succeed or none do
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file1 = workspace_root.join("file1.rs");
        fs::write(
            &test_file1,
            r#"
fn first() {
    let target = 1;
}
"#,
        )
        .expect("Failed to write test file");

        let test_file2 = workspace_root.join("file2.rs");
        fs::write(
            &test_file2,
            r#"
fn second() {
    let target = 2;
}
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "target".to_string(),
            replace_pattern: "modified".to_string(),
            language: Some(Language::Rust),
            validate: false,
        };

        // Apply should succeed atomically (both files replaced)
        let result = apply_pattern_replace(&config, workspace_root)
            .expect("Failed to apply pattern replace");

        assert_eq!(result.files_patched.len(), 2);
        assert_eq!(result.replacements_count, 2);

        // Verify both files were modified
        let content1 = fs::read_to_string(&test_file1).expect("Failed to read file1");
        let content2 = fs::read_to_string(&test_file2).expect("Failed to read file2");

        assert!(
            content1.contains("modified"),
            "file1 should contain replaced text"
        );
        assert!(
            !content1.contains("target"),
            "file1 should not contain original text"
        );
        assert!(
            content2.contains("modified"),
            "file2 should contain replaced text"
        );
        assert!(
            !content2.contains("target"),
            "file2 should not contain original text"
        );

        // Test edge case: no matches found (should succeed without modifying files)
        let workspace2 = TempDir::new().expect("Failed to create temp dir 2");
        let workspace_root2 = workspace2.path();

        let test_file3 = workspace_root2.join("file3.rs");
        fs::write(&test_file3, "fn test() { let x = 42; }").expect("Failed to write test file");

        let original_content3 =
            fs::read_to_string(&test_file3).expect("Failed to read original file3");

        let config2 = PatternReplaceConfig {
            glob_pattern: workspace_root2
                .join("*.rs")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "nonexistent_pattern_xyz".to_string(),
            replace_pattern: "replacement".to_string(),
            language: Some(Language::Rust),
            validate: false,
        };

        // Should succeed with no replacements (atomic behavior preserved)
        let result2 = apply_pattern_replace(&config2, workspace_root2)
            .expect("Should succeed even with no matches");

        assert_eq!(result2.files_patched.len(), 0);
        assert_eq!(result2.replacements_count, 0);

        // Verify file was not modified (atomicity preserved)
        let content3_after = fs::read_to_string(&test_file3).expect("Failed to read file3 after");
        assert_eq!(
            content3_after, original_content3,
            "file3 should be unchanged when no matches found"
        );
    }

    #[test]
    fn test_apply_replace_with_validation() {
        let workspace = TempDir::new().expect("Failed to create temp dir");
        let workspace_root = workspace.path();

        let test_file = workspace_root.join("test.py");
        fs::write(
            &test_file,
            r#"
def foo():
    x = 10
    y = 10
    return x + y
"#,
        )
        .expect("Failed to write test file");

        let config = PatternReplaceConfig {
            glob_pattern: workspace_root
                .join("*.py")
                .to_str()
                .expect("Invalid UTF-8 path")
                .to_string(),
            find_pattern: "10".to_string(),
            replace_pattern: "20".to_string(),
            language: Some(Language::Python),
            validate: false, // Set to true to enable validation gates
        };

        let result = apply_pattern_replace(&config, workspace_root)
            .expect("Failed to apply pattern replace");

        assert_eq!(result.files_patched.len(), 1);
        assert_eq!(result.replacements_count, 2);

        let content = fs::read_to_string(&test_file).expect("Failed to read file");
        assert!(content.contains("20"), "Should contain replaced value");
    }
}