ggen-core 26.7.2

Core graph-aware code generation engine
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
//! Three-way merge for delta-driven projection
//!
//! This module provides functionality to merge generated code with manual edits,
//! preserving user customizations during regeneration. It implements a three-way
//! merge algorithm that uses baselines to intelligently combine generated and
//! manual content.
//!
//! ## Submodules
//!
//! - [`three_way_merge`] — Annotation-aware `@ggen:preserve-start/end` merge logic
//!   for `ggen sync` regeneration cycles. Preserves hand-written logic and safely
//!   overwrites `@ggen:generated-start/end` regions.
//!
//! ## Features
//!
//! - **Three-Way Merge**: Merge generated, manual, and baseline content
//! - **Region-Aware**: Preserve manual regions while updating generated regions
//! - **Conflict Detection**: Identify and report merge conflicts
//! - **Merge Strategies**: Configurable merge strategies (prefer-generated, prefer-manual, etc.)
//! - **Conflict Resolution**: Tools for resolving merge conflicts

pub mod three_way_merge;
pub use three_way_merge::{
    apply_generated, three_way_merge as sync_three_way_merge, MergeConflict as SyncMergeConflict,
    MergeError, MergeResult as SyncMergeResult,
};

use crate::utils::error::Result;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::{Path, PathBuf};

use crate::snapshot::{FileSnapshot, Region, RegionType};

/// Represents a merge conflict between generated and manual content
///
/// A `MergeConflict` describes a situation where both generated and manual
/// content have changed the same region, making automatic merging impossible.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::merge::{MergeConflict, ConflictType};
/// use std::path::PathBuf;
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let conflict = MergeConflict::new(
///     PathBuf::from("file.rs"),
///     ConflictType::OverlappingEdit,
///     "Both generated and manual edits changed the same function".to_string(),
///     "fn generated() {}".to_string(),
///     "fn manual() {}".to_string(),
///     "fn original() {}".to_string(),
/// );
///
/// println!("Conflict in {:?}: {}", conflict.file_path, conflict.description);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeConflict {
    /// Path to the file with conflict
    pub file_path: PathBuf,
    /// Type of conflict
    pub conflict_type: ConflictType,
    /// Description of the conflict
    pub description: String,
    /// Generated content that conflicts
    pub generated: String,
    /// Manual content that conflicts
    pub manual: String,
    /// Baseline content for context
    pub baseline: String,
}

impl MergeConflict {
    /// Create a new conflict
    pub fn new(
        file_path: PathBuf, conflict_type: ConflictType, description: String, generated: String,
        manual: String, baseline: String,
    ) -> Self {
        Self {
            file_path,
            conflict_type,
            description,
            generated,
            manual,
            baseline,
        }
    }
}

/// Types of merge conflicts
///
/// Describes the nature of a merge conflict to help with resolution.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::merge::ConflictType;
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let conflict_type = ConflictType::OverlappingEdit;
/// println!("Conflict type: {}", conflict_type);
/// # Ok(())
/// # }
/// ```
///
/// Type of merge conflict
///
/// Represents different types of conflicts that can occur during three-way merging.
///
/// # Examples
///
/// ```rust
/// use crate::merge::ConflictType;
///
/// # fn main() {
/// let conflict = ConflictType::OverlappingEdit;
/// match conflict {
///     ConflictType::OverlappingEdit => assert!(true),
///     ConflictType::RegionConflict => assert!(true),
///     ConflictType::StructuralConflict => assert!(true),
/// }
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConflictType {
    /// Manual edit overlaps with generated content
    OverlappingEdit,
    /// Manual edit in a region that was regenerated
    RegionConflict,
    /// Structural conflict (e.g., manual edit changes structure)
    StructuralConflict,
}

impl fmt::Display for ConflictType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConflictType::OverlappingEdit => write!(f, "overlapping edit"),
            ConflictType::RegionConflict => write!(f, "region conflict"),
            ConflictType::StructuralConflict => write!(f, "structural conflict"),
        }
    }
}

/// Result of a three-way merge operation
///
/// Contains the merged content, any conflicts that were detected, and the
/// strategy used for resolution.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::merge::{MergeResult, MergeStrategy};
///
/// # fn main() -> crate::utils::error::Result<()> {
/// // Successful merge
/// let result = MergeResult::success(
///     "merged content".to_string(),
///     MergeStrategy::GeneratedWins
/// );
///
/// assert!(!result.has_conflicts);
/// assert_eq!(result.content, "merged content");
///
/// // Merge with conflicts
/// let result_with_conflicts = MergeResult::with_conflicts(
///     "partial merge".to_string(),
///     vec![],
///     MergeStrategy::GeneratedWins
/// );
/// assert!(result_with_conflicts.has_conflicts);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeResult {
    /// Merged content
    pub content: String,
    /// Whether there were conflicts
    pub has_conflicts: bool,
    /// Conflicts that were detected
    pub conflicts: Vec<MergeConflict>,
    /// Strategy used for resolution
    pub strategy: MergeStrategy,
}

impl MergeResult {
    /// Create a successful merge result
    ///
    /// Creates a merge result indicating successful merging with no conflicts.
    ///
    /// # Arguments
    ///
    /// * `content` - The merged content
    /// * `strategy` - The merge strategy that was used
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use crate::merge::{MergeResult, MergeStrategy};
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let result = MergeResult::success(
    ///     "merged file content".to_string(),
    ///     MergeStrategy::GeneratedWins
    /// );
    ///
    /// assert!(!result.has_conflicts);
    /// assert_eq!(result.content, "merged file content");
    /// # Ok(())
    /// # }
    /// ```
    pub fn success(content: String, strategy: MergeStrategy) -> Self {
        Self {
            content,
            has_conflicts: false,
            conflicts: Vec::new(),
            strategy,
        }
    }

    /// Create a merge result with conflicts
    pub fn with_conflicts(
        content: String, conflicts: Vec<MergeConflict>, strategy: MergeStrategy,
    ) -> Self {
        Self {
            content,
            has_conflicts: true,
            conflicts,
            strategy,
        }
    }
}

/// Strategy for resolving merge conflicts
///
/// Defines how conflicts should be resolved when both generated and manual
/// content have changed.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::merge::{ThreeWayMerger, MergeStrategy};
///
/// # fn main() -> crate::utils::error::Result<()> {
/// // Prefer generated content
/// let merger = ThreeWayMerger::new(MergeStrategy::GeneratedWins);
///
/// // Prefer manual edits
/// let merger = ThreeWayMerger::new(MergeStrategy::ManualWins);
///
/// // Fail on conflicts
/// let merger = ThreeWayMerger::new(MergeStrategy::FailOnConflict);
/// # Ok(())
/// # }
/// ```
/// Merge strategy for resolving conflicts
///
/// Determines how to handle conflicts during three-way merging.
///
/// # Examples
///
/// ```rust
/// use crate::merge::MergeStrategy;
///
/// # fn main() {
/// let strategy = MergeStrategy::GeneratedWins;
/// match strategy {
///     MergeStrategy::GeneratedWins => assert!(true),
///     MergeStrategy::ManualWins => assert!(true),
///     MergeStrategy::Interactive => assert!(true),
///     MergeStrategy::FailOnConflict => assert!(true),
/// }
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MergeStrategy {
    /// Automatically resolve using generated content (overwrite manual)
    GeneratedWins,
    /// Automatically resolve using manual content (preserve manual)
    ManualWins,
    /// Interactive resolution (ask user)
    Interactive,
    /// Fail on conflicts
    FailOnConflict,
}

impl fmt::Display for MergeStrategy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MergeStrategy::GeneratedWins => write!(f, "generated wins"),
            MergeStrategy::ManualWins => write!(f, "manual wins"),
            MergeStrategy::Interactive => write!(f, "interactive"),
            MergeStrategy::FailOnConflict => write!(f, "fail on conflict"),
        }
    }
}

/// Three-way merger for files with mixed generated and manual content
///
/// Performs three-way merges using a baseline, new generated content, and
/// manual edits. Uses the configured merge strategy to resolve conflicts.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::merge::{ThreeWayMerger, MergeStrategy};
/// use std::path::Path;
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let merger = ThreeWayMerger::new(MergeStrategy::GeneratedWins);
///
/// let result = merger.merge(
///     "baseline content",
///     "new generated content",
///     "manual edits",
///     Path::new("file.rs")
/// )?;
///
/// if result.has_conflicts {
///     println!("Conflicts: {:?}", result.conflicts);
/// } else {
///     println!("Merged: {}", result.content);
/// }
/// # Ok(())
/// # }
/// ```
pub struct ThreeWayMerger {
    /// Strategy for resolving conflicts
    strategy: MergeStrategy,
}

impl ThreeWayMerger {
    /// Create a new three-way merger with specified strategy
    ///
    /// Creates a merger with the specified conflict resolution strategy.
    ///
    /// # Arguments
    ///
    /// * `strategy` - Strategy to use when conflicts are detected
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use crate::merge::{ThreeWayMerger, MergeStrategy};
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let merger = ThreeWayMerger::new(MergeStrategy::GeneratedWins);
    /// // Use merger to merge content
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(strategy: MergeStrategy) -> Self {
        Self { strategy }
    }

    /// Merge three versions of a file
    ///
    /// Merges three versions of content: baseline (original), generated (new
    /// generated content), and manual (user edits). Returns merged content
    /// and any conflicts detected.
    ///
    /// # Arguments
    ///
    /// * `baseline` - Original content from snapshot
    /// * `generated` - New generated content
    /// * `manual` - User's manual edits
    /// * `file_path` - Path to the file being merged
    ///
    /// # Returns
    ///
    /// A `MergeResult` containing the merged content and any conflicts.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use crate::merge::{ThreeWayMerger, MergeStrategy};
    /// use std::path::Path;
    ///
    /// # fn main() -> crate::utils::error::Result<()> {
    /// let merger = ThreeWayMerger::new(MergeStrategy::GeneratedWins);
    ///
    /// let result = merger.merge(
    ///     "original function",
    ///     "new generated function",
    ///     "manual function edit",
    ///     Path::new("file.rs")
    /// )?;
    ///
    /// if !result.has_conflicts {
    ///     println!("Successfully merged: {}", result.content);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn merge(
        &self, baseline: &str, generated: &str, manual: &str, file_path: &Path,
    ) -> Result<MergeResult> {
        // For now, implement a simple strategy-based merge
        // A full implementation would use proper diff3 algorithm

        match self.strategy {
            MergeStrategy::GeneratedWins => {
                Ok(MergeResult::success(generated.to_string(), self.strategy))
            }
            MergeStrategy::ManualWins => {
                Ok(MergeResult::success(manual.to_string(), self.strategy))
            }
            MergeStrategy::FailOnConflict => {
                // Check for conflicts (simplified)
                if self.has_conflicts(baseline, generated, manual)? {
                    let conflicts =
                        self.detect_conflicts(baseline, generated, manual, file_path)?;
                    Ok(MergeResult::with_conflicts(
                        String::new(),
                        conflicts,
                        self.strategy,
                    ))
                } else {
                    Ok(MergeResult::success(generated.to_string(), self.strategy))
                }
            }
            MergeStrategy::Interactive => {
                // Interactive resolution would require user input
                // For now, fall back to generated wins
                Ok(MergeResult::success(generated.to_string(), self.strategy))
            }
        }
    }

    /// Check if there are conflicts between versions
    fn has_conflicts(&self, _baseline: &str, _generated: &str, _manual: &str) -> Result<bool> {
        // Simplified conflict detection
        // Real implementation would use proper diff algorithm
        Ok(false)
    }

    /// Detect specific conflicts
    fn detect_conflicts(
        &self, _baseline: &str, _generated: &str, _manual: &str, _file_path: &Path,
    ) -> Result<Vec<MergeConflict>> {
        // Simplified conflict detection
        // Real implementation would analyze regions and detect overlaps
        Ok(Vec::new())
    }
}

/// Advanced merger that understands generated vs manual regions
///
/// A specialized merger that understands file regions (generated vs manual)
/// and preserves manual regions while updating generated regions.
///
/// # Examples
///
/// ```rust,no_run
/// use crate::merge::{RegionAwareMerger, MergeStrategy};
/// use crate::snapshot::FileSnapshot;
/// use std::path::PathBuf;
///
/// # fn main() -> crate::utils::error::Result<()> {
/// let merger = RegionAwareMerger::new(MergeStrategy::ManualWins);
/// let baseline = FileSnapshot::new(
///     PathBuf::from("file.rs"),
///     "baseline content".to_string()
/// )?;
///
/// let result = merger.merge_with_regions(
///     "baseline content",
///     "new generated content",
///     "manual edits",
///     &baseline,
///     std::path::Path::new("file.rs")
/// )?;
/// # Ok(())
/// # }
/// ```
pub struct RegionAwareMerger {
    /// Strategy for conflict resolution
    strategy: MergeStrategy,
}

impl RegionAwareMerger {
    /// Create a new region-aware merger
    pub fn new(strategy: MergeStrategy) -> Self {
        Self { strategy }
    }

    /// Merge using region information from snapshots
    pub fn merge_with_regions(
        &self, baseline: &str, generated: &str, manual: &str, _baseline_snapshot: &FileSnapshot,
        file_path: &Path,
    ) -> Result<MergeResult> {
        let mut result = String::new();
        let mut conflicts = Vec::new();
        let mut has_conflicts = false;

        // Split content into lines for easier processing
        let baseline_lines: Vec<&str> = baseline.lines().collect();
        let generated_lines: Vec<&str> = generated.lines().collect();
        let manual_lines: Vec<&str> = manual.lines().collect();

        // Process line by line, respecting regions
        let mut i = 0;
        while i < baseline_lines
            .len()
            .max(generated_lines.len())
            .max(manual_lines.len())
        {
            let baseline_line = baseline_lines.get(i);
            let generated_line = generated_lines.get(i);
            let manual_line = manual_lines.get(i);

            match (baseline_line, generated_line, manual_line) {
                (Some(bl), Some(gl), Some(ml)) => {
                    if bl == gl && gl == ml {
                        // All versions agree
                        result.push_str(gl);
                        result.push('\n');
                    } else if bl == gl {
                        // Manual differs from baseline/generated
                        result.push_str(ml);
                        result.push('\n');
                    } else if bl == ml {
                        // Generated differs from baseline/manual
                        result.push_str(gl);
                        result.push('\n');
                    } else {
                        // All three differ - conflict
                        has_conflicts = true;
                        conflicts.push(MergeConflict::new(
                            file_path.to_path_buf(),
                            ConflictType::OverlappingEdit,
                            format!("Conflict at line {}", i + 1),
                            gl.to_string(),
                            ml.to_string(),
                            bl.to_string(),
                        ));

                        // Apply strategy for conflict resolution
                        match self.strategy {
                            MergeStrategy::GeneratedWins => {
                                result.push_str(gl);
                                result.push('\n');
                            }
                            MergeStrategy::ManualWins => {
                                result.push_str(ml);
                                result.push('\n');
                            }
                            _ => {
                                // For other strategies, we'd need more sophisticated handling
                                result.push_str(gl);
                                result.push('\n');
                            }
                        }
                    }
                }
                (Some(bl), Some(gl), None) => {
                    // Manual is shorter
                    if bl == gl {
                        // No conflict, use generated
                        result.push_str(gl);
                        result.push('\n');
                    } else {
                        // Conflict
                        has_conflicts = true;
                        conflicts.push(MergeConflict::new(
                            file_path.to_path_buf(),
                            ConflictType::StructuralConflict,
                            "Length mismatch".to_string(),
                            gl.to_string(),
                            String::new(),
                            bl.to_string(),
                        ));
                    }
                }
                (Some(bl), None, Some(ml)) => {
                    // Generated is shorter
                    if bl == ml {
                        // No conflict, use manual
                        result.push_str(ml);
                        result.push('\n');
                    } else {
                        // Conflict
                        has_conflicts = true;
                        conflicts.push(MergeConflict::new(
                            file_path.to_path_buf(),
                            ConflictType::StructuralConflict,
                            "Length mismatch".to_string(),
                            String::new(),
                            ml.to_string(),
                            bl.to_string(),
                        ));
                    }
                }
                (None, Some(gl), Some(ml)) => {
                    // Baseline is shorter - new content in both
                    if gl == ml {
                        result.push_str(gl);
                        result.push('\n');
                    } else {
                        has_conflicts = true;
                        conflicts.push(MergeConflict::new(
                            file_path.to_path_buf(),
                            ConflictType::OverlappingEdit,
                            "New content conflict".to_string(),
                            gl.to_string(),
                            ml.to_string(),
                            String::new(),
                        ));
                    }
                }
                _ => break, // All versions ended
            }

            i += 1;
        }

        if has_conflicts {
            Ok(MergeResult::with_conflicts(
                result,
                conflicts,
                self.strategy,
            ))
        } else {
            Ok(MergeResult::success(result, self.strategy))
        }
    }
}

/// Utilities for working with file regions
pub struct RegionUtils;

impl RegionUtils {
    /// Parse generated/manual regions from file content using markers
    pub fn parse_regions(content: &str) -> (Vec<Region>, Vec<Region>) {
        let mut generated_regions = Vec::new();
        let mut manual_regions = Vec::new();
        let mut in_generated = false;
        let mut in_manual = false;
        let mut current_start = 0;
        let mut line_number = 1;

        for line in content.lines() {
            if line.contains("// GENERATED: DO NOT EDIT")
                || line.contains("<!-- GENERATED: DO NOT EDIT")
            {
                if !in_generated && !in_manual {
                    current_start = line_number;
                    in_generated = true;
                }
            } else if line.contains("// END GENERATED") || line.contains("<!-- END GENERATED") {
                if in_generated {
                    generated_regions.push(Region {
                        start: current_start,
                        end: line_number,
                        region_type: RegionType::Generated,
                    });
                    in_generated = false;
                }
            } else if line.contains("// MANUAL:") || line.contains("<!-- MANUAL:") {
                if !in_generated && !in_manual {
                    current_start = line_number;
                    in_manual = true;
                }
            } else if (line.contains("// END MANUAL") || line.contains("<!-- END MANUAL"))
                && in_manual
            {
                manual_regions.push(Region {
                    start: current_start,
                    end: line_number,
                    region_type: RegionType::Manual,
                });
                in_manual = false;
            }

            line_number += 1;
        }

        (generated_regions, manual_regions)
    }

    /// Check if a line number is within any region of a specific type
    pub fn is_in_region(line_number: usize, regions: &[Region], region_type: &RegionType) -> bool {
        regions.iter().any(|r| {
            r.start <= line_number && r.end >= line_number && &r.region_type == region_type
        })
    }
}

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

    #[test]
    fn test_merge_strategies() {
        let merger = ThreeWayMerger::new(MergeStrategy::GeneratedWins);

        let baseline = "line 1\nline 2\n";
        let generated = "line 1\nline 2\nline 3\n";
        let manual = "line 1\nmanual line\nline 3\n";

        let result = merger
            .merge(baseline, generated, manual, Path::new("test.txt"))
            .unwrap();

        assert!(!result.has_conflicts);
        assert_eq!(result.strategy, MergeStrategy::GeneratedWins);
        assert_eq!(result.content, generated);
    }

    #[test]
    fn test_region_aware_merge() {
        let merger = RegionAwareMerger::new(MergeStrategy::ManualWins);

        let baseline = "line 1\n// GENERATED: DO NOT EDIT\nline 2\n// END GENERATED\nline 3\n";
        let generated =
            "line 1\n// GENERATED: DO NOT EDIT\nline 2 modified\n// END GENERATED\nline 3\n";
        let manual = "line 1\n// GENERATED: DO NOT EDIT\nline 2\n// END GENERATED\nmanual line\n";

        // Create mock snapshot
        let snapshot = FileSnapshot {
            path: PathBuf::from("test.txt"),
            hash: String::new(),
            size: 0,
            modified_at: chrono::Utc::now(),
            generated_regions: vec![Region {
                start: 2,
                end: 4,
                region_type: RegionType::Generated,
            }],
            manual_regions: vec![Region {
                start: 5,
                end: 5,
                region_type: RegionType::Manual,
            }],
        };

        let result = merger
            .merge_with_regions(
                baseline,
                generated,
                manual,
                &snapshot,
                Path::new("test.txt"),
            )
            .unwrap();

        assert!(!result.has_conflicts);
        assert_eq!(result.strategy, MergeStrategy::ManualWins);
    }

    #[test]
    fn test_region_parsing() {
        let content = r#"
line 1
// GENERATED: DO NOT EDIT
generated line 1
generated line 2
// END GENERATED
// MANUAL: Safe to edit
manual line 1
manual line 2
// END MANUAL
line 4
"#;

        let (generated, manual) = RegionUtils::parse_regions(content);

        log::debug!("Generated regions: {:?}", generated);
        log::debug!("Manual regions: {:?}", manual);

        assert_eq!(generated.len(), 1);
        assert_eq!(manual.len(), 1);
        assert_eq!(generated[0].start, 3);
        assert_eq!(generated[0].end, 6);
        assert_eq!(manual[0].start, 7);
        assert_eq!(manual[0].end, 10);
    }

    #[test]
    fn test_region_check() {
        let regions = vec![
            Region {
                start: 2,
                end: 4,
                region_type: RegionType::Generated,
            },
            Region {
                start: 6,
                end: 8,
                region_type: RegionType::Manual,
            },
        ];

        assert!(RegionUtils::is_in_region(
            3,
            &regions,
            &RegionType::Generated
        ));
        assert!(!RegionUtils::is_in_region(3, &regions, &RegionType::Manual));
        assert!(RegionUtils::is_in_region(7, &regions, &RegionType::Manual));
        assert!(!RegionUtils::is_in_region(
            1,
            &regions,
            &RegionType::Generated
        ));
    }
}