hyalo-core 0.13.2

Core library for hyalo — frontmatter parsing, querying, and mutation for Markdown files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
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
//! Broken link detection and auto-repair with fuzzy matching.
//!
//! # Overview
//!
//! 1. [`detect_broken_links`] / [`detect_broken_links_from_index`] — scan a
//!    vault for links that cannot be resolved to an existing file and return a
//!    [`BrokenLinkReport`].
//!
//! 2. [`plan_fixes`] — for each broken link, find the best candidate file using
//!    a priority-ordered strategy (case-insensitive → extension mismatch →
//!    shortest-path → fuzzy Jaro-Winkler) and produce a [`FixReport`].
//!
//! 3. [`apply_fixes`] — convert [`FixPlan`]s to [`RewritePlan`]s and write
//!    the corrected link text back to disk.

#![allow(clippy::missing_errors_doc)]

use std::collections::HashMap;
use std::path::Path;

use anyhow::{Context, Result};
use serde::Serialize;

use crate::case_index::CaseInsensitiveIndex;
use crate::discovery::canonicalize_vault_dir;
use crate::discovery::resolve_target;
use crate::index::VaultIndex;
use crate::link_graph::{FileLinks, normalize_target};
use crate::link_rewrite::{Replacement, RewritePlan, apply_replacements, execute_plans};
use crate::links::{LinkKind, extract_link_spans_with_original};
use crate::scanner::{
    FenceTracker, MAX_FILE_SIZE, is_comment_fence, strip_inline_code, strip_inline_comments,
};
// ---------------------------------------------------------------------------
// Report types
// ---------------------------------------------------------------------------

/// A single broken link with source file, line number, and raw target.
#[derive(Debug, Clone, Serialize)]
pub struct BrokenLinkInfo {
    pub source: String,
    pub line: usize,
    pub target: String,
}

/// Summary of broken link detection across the vault.
#[derive(Debug, Clone, Serialize)]
pub struct BrokenLinkReport {
    pub total_links: usize,
    pub broken: Vec<BrokenLinkInfo>,
    /// Links that resolve via case-insensitive fallback but whose written casing
    /// differs from the canonical on-disk path.  These are NOT broken — the
    /// file exists — but they carry the wrong casing and can be auto-fixed with
    /// strategy [`FixStrategy::LinkCaseMismatch`].
    ///
    /// Only populated when a [`CaseInsensitiveIndex`] is provided to the
    /// detection functions.
    pub case_mismatches: Vec<FixPlan>,
}

/// A single actionable fix: rewrite `old_target` → `new_target` in `source`.
#[derive(Debug, Clone, Serialize)]
pub struct FixPlan {
    /// Vault-relative path of the file containing the broken link.
    pub source: String,
    /// 1-based line number where the broken link appears.
    pub line: usize,
    /// The original (broken) link target as written in the source file.
    pub old_target: String,
    /// The corrected link target.
    pub new_target: String,
    /// How the match was found.
    pub strategy: FixStrategy,
    /// Similarity confidence in `[0.0, 1.0]`.
    pub confidence: f64,
}

/// How a candidate file was matched to a broken link target.
#[derive(Debug, Clone, Serialize)]
pub enum FixStrategy {
    /// The target matched an existing file path case-insensitively.
    CaseInsensitive,
    /// The target was written with or without `.md` and the other form matched.
    ExtensionMismatch,
    /// The bare stem matched exactly one file anywhere in the vault.
    ShortestPath,
    /// Jaro-Winkler similarity above the configured threshold.
    FuzzyMatch,
    /// The target resolves to an existing file but with different casing.
    ///
    /// Rule code: `link-case-mismatch`. The `new_target` in the [`FixPlan`]
    /// holds the canonical on-disk casing returned by the [`CaseInsensitiveIndex`].
    LinkCaseMismatch,
}

/// Result of planning fixes for a set of broken links.
#[derive(Debug, Clone, Serialize)]
pub struct FixReport {
    /// Broken links for which a candidate fix was found.
    pub fixes: Vec<FixPlan>,
    /// Broken links for which no suitable candidate could be found.
    pub unfixable: Vec<BrokenLinkInfo>,
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Classify a single link's resolution against the filesystem and an optional
/// case-insensitive index.
///
/// Returns:
/// - `Resolved(None)` — link resolves exactly and its on-disk casing matches
///   the canonical form (or no index was supplied).
/// - `Resolved(Some(canonical))` — link resolves exactly but the on-disk
///   casing differs from the canonical form (case-insensitive filesystem
///   papered over a mismatch); caller should record as a case-mismatch.
/// - `CaseMismatch(canonical)` — exact resolution failed but the case index
///   found a unique canonical path; caller should record as a case-mismatch.
/// - `Broken` — nothing resolves.
enum LinkResolution {
    Resolved(Option<String>),
    CaseMismatch(String),
    Broken,
}

fn classify_link(
    canonical_dir: &Path,
    resolved_target: &str,
    site_prefix: Option<&str>,
    case_index: Option<&CaseInsensitiveIndex>,
) -> LinkResolution {
    let exact = resolve_target(canonical_dir, resolved_target, site_prefix, None);

    if let Some(exact_str) = exact {
        // Link resolves exactly. If we have a case index, also check whether the
        // resolved path has incorrect casing compared to the canonical on-disk
        // path. On case-insensitive filesystems, `exact` may contain the
        // user-written casing rather than the canonical casing.
        if let Some(idx) = case_index
            && let Some(canonical_path) =
                resolve_target(canonical_dir, resolved_target, site_prefix, Some(idx))
        {
            let canonical_fwd = canonical_path.replace('\\', "/");
            let exact_fwd = exact_str.replace('\\', "/");
            if exact_fwd != canonical_fwd {
                return LinkResolution::Resolved(Some(canonical_fwd));
            }
        }
        return LinkResolution::Resolved(None);
    }

    // Exact resolution failed. If we have a case index, try the
    // case-insensitive fallback. `resolve_target` already handles the `.md`
    // extension fallback internally, so any successful indexed resolution
    // here means the link is a case-mismatch (possibly combined with a
    // stem/full extension style difference).
    if let Some(idx) = case_index
        && let Some(canonical_path) =
            resolve_target(canonical_dir, resolved_target, site_prefix, Some(idx))
    {
        return LinkResolution::CaseMismatch(canonical_path.replace('\\', "/"));
    }

    LinkResolution::Broken
}

// ---------------------------------------------------------------------------
// Broken link detection
// ---------------------------------------------------------------------------

/// Detect broken links from pre-collected file links data.
///
/// `file_links` is a slice of [`FileLinks`] (from `link_graph.rs`).
/// Uses [`resolve_target`] to check if each link target exists.
///
/// When `case_index` is provided, links that resolve only via the
/// case-insensitive fallback are surfaced as [`FixStrategy::LinkCaseMismatch`]
/// entries in [`BrokenLinkReport::case_mismatches`] rather than as broken.
#[allow(dead_code)] // Used in tests only; CLI uses detect_broken_links_from_index
pub(crate) fn detect_broken_links(
    dir: &Path,
    file_links: &[FileLinks],
    site_prefix: Option<&str>,
    case_index: Option<&CaseInsensitiveIndex>,
) -> BrokenLinkReport {
    let Ok(canonical) = canonicalize_vault_dir(dir) else {
        return BrokenLinkReport {
            total_links: 0,
            broken: Vec::new(),
            case_mismatches: Vec::new(),
        };
    };

    let mut total_links = 0usize;
    let mut broken: Vec<BrokenLinkInfo> = Vec::new();
    let mut case_mismatches: Vec<FixPlan> = Vec::new();

    for fl in file_links {
        let source_str = fl.source.to_string_lossy().replace('\\', "/");

        for (line, link) in &fl.links {
            total_links += 1;

            // Normalize the target before resolution.
            // Wikilinks are vault-relative; markdown links may be relative to
            // the source file's directory.
            let resolved_target = match link.kind {
                LinkKind::Wikilink => link.target.clone(),
                LinkKind::Markdown => {
                    if link.target.starts_with('/') {
                        link.target.clone()
                    } else if link.target.contains('/') || link.target.contains('\\') {
                        normalize_target(Path::new(&source_str), &link.target)
                    } else {
                        link.target.clone()
                    }
                }
            };

            match classify_link(&canonical, &resolved_target, site_prefix, case_index) {
                LinkResolution::Resolved(None) => {}
                LinkResolution::Resolved(Some(canonical_str))
                | LinkResolution::CaseMismatch(canonical_str) => {
                    case_mismatches.push(FixPlan {
                        source: source_str.clone(),
                        line: *line,
                        old_target: link.target.clone(),
                        new_target: canonical_str,
                        strategy: FixStrategy::LinkCaseMismatch,
                        confidence: 1.0,
                    });
                }
                LinkResolution::Broken => {
                    broken.push(BrokenLinkInfo {
                        source: source_str.clone(),
                        line: *line,
                        target: link.target.clone(),
                    });
                }
            }
        }
    }

    broken.sort_by(|a, b| a.source.cmp(&b.source).then_with(|| a.line.cmp(&b.line)));
    case_mismatches.sort_by(|a, b| a.source.cmp(&b.source).then_with(|| a.line.cmp(&b.line)));

    BrokenLinkReport {
        total_links,
        broken,
        case_mismatches,
    }
}

/// Detect broken links from index entries.
///
/// Each [`IndexEntry`](crate::index::IndexEntry) has
/// `links: Vec<(usize, Link)>` and `rel_path: String`.
///
/// When `case_index` is provided, links that resolve only via the
/// case-insensitive fallback are surfaced as [`FixStrategy::LinkCaseMismatch`]
/// entries in [`BrokenLinkReport::case_mismatches`] rather than as broken.
pub fn detect_broken_links_from_index(
    dir: &Path,
    index: &dyn VaultIndex,
    site_prefix: Option<&str>,
    case_index: Option<&CaseInsensitiveIndex>,
) -> BrokenLinkReport {
    let Ok(canonical) = canonicalize_vault_dir(dir) else {
        return BrokenLinkReport {
            total_links: 0,
            broken: Vec::new(),
            case_mismatches: Vec::new(),
        };
    };

    let mut total_links = 0usize;
    let mut broken: Vec<BrokenLinkInfo> = Vec::new();
    let mut case_mismatches: Vec<FixPlan> = Vec::new();

    for entry in index.entries() {
        for (line, link) in &entry.links {
            total_links += 1;

            let resolved_target = match link.kind {
                LinkKind::Wikilink => link.target.clone(),
                LinkKind::Markdown => {
                    if link.target.starts_with('/') {
                        link.target.clone()
                    } else if link.target.contains('/') || link.target.contains('\\') {
                        normalize_target(Path::new(&entry.rel_path), &link.target)
                    } else {
                        link.target.clone()
                    }
                }
            };

            match classify_link(&canonical, &resolved_target, site_prefix, case_index) {
                LinkResolution::Resolved(None) => {}
                LinkResolution::Resolved(Some(canonical_str))
                | LinkResolution::CaseMismatch(canonical_str) => {
                    case_mismatches.push(FixPlan {
                        source: entry.rel_path.clone(),
                        line: *line,
                        old_target: link.target.clone(),
                        new_target: canonical_str,
                        strategy: FixStrategy::LinkCaseMismatch,
                        confidence: 1.0,
                    });
                }
                LinkResolution::Broken => {
                    broken.push(BrokenLinkInfo {
                        source: entry.rel_path.clone(),
                        line: *line,
                        target: link.target.clone(),
                    });
                }
            }
        }
    }

    broken.sort_by(|a, b| a.source.cmp(&b.source).then_with(|| a.line.cmp(&b.line)));
    case_mismatches.sort_by(|a, b| a.source.cmp(&b.source).then_with(|| a.line.cmp(&b.line)));

    BrokenLinkReport {
        total_links,
        broken,
        case_mismatches,
    }
}

// ---------------------------------------------------------------------------
// Fix planning — candidate matching
// ---------------------------------------------------------------------------

/// Pre-indexed file list for efficient broken link matching.
///
/// Encapsulates the four-strategy matching pipeline:
/// 1. Case-insensitive exact match
/// 2. Extension mismatch (`.md` present/absent)
/// 3. Shortest-path (unique stem match anywhere in vault)
/// 4. Jaro-Winkler fuzzy match
///
/// Build once, then call [`find_match`] for each broken link target.
pub struct LinkMatcher {
    /// All vault-relative file paths (canonical form).
    files: Vec<String>,
    /// Lowercased path → original index into `files`.
    lower_to_idx: HashMap<String, usize>,
    /// Exact-case path → index into `files` (used for O(1) strategy-2 lookup).
    exact_to_idx: HashMap<String, usize>,
    /// Lowercased stem (filename without .md and path) → list of indices.
    /// Used for shortest-path: unique means unambiguous.
    stem_to_indices: HashMap<String, Vec<usize>>,
    /// Minimum Jaro-Winkler score for fuzzy matching.
    threshold: f64,
}

/// Result of a single match attempt.
pub(crate) struct MatchResult {
    /// Vault-relative path of the matched file.
    pub matched_file: String,
    pub strategy: FixStrategy,
    pub confidence: f64,
}

impl LinkMatcher {
    /// Build a matcher from a list of vault-relative file paths.
    pub fn new(files: Vec<String>, threshold: f64) -> Self {
        let mut lower_to_idx = HashMap::with_capacity(files.len());
        let mut exact_to_idx = HashMap::with_capacity(files.len());
        let mut stem_to_indices: HashMap<String, Vec<usize>> = HashMap::new();

        for (i, f) in files.iter().enumerate() {
            // Index by exact path, plus the extension-toggled form.
            exact_to_idx.entry(f.clone()).or_insert(i);
            let alt = if f.to_ascii_lowercase().ends_with(".md") {
                f.strip_suffix(".md")
                    .or_else(|| f.strip_suffix(".MD"))
                    .map(std::string::ToString::to_string)
            } else {
                Some(format!("{f}.md"))
            };
            if let Some(a) = alt {
                exact_to_idx.entry(a).or_insert(i);
            }

            // Index by lowercased full path (with and without .md).
            let lower = f.to_ascii_lowercase();
            lower_to_idx.entry(lower.clone()).or_insert(i);
            if let Some(stem) = lower.strip_suffix(".md") {
                lower_to_idx.entry(stem.to_string()).or_insert(i);
            }

            // Index by lowercased filename stem for shortest-path.
            let fname = f.rsplit('/').next().unwrap_or(f.as_str());
            let fstem = fname.strip_suffix(".md").unwrap_or(fname);
            stem_to_indices
                .entry(fstem.to_ascii_lowercase())
                .or_default()
                .push(i);
        }

        Self {
            files,
            lower_to_idx,
            exact_to_idx,
            stem_to_indices,
            threshold,
        }
    }

    /// Build a matcher from an index (avoids rescanning the directory).
    pub fn from_index(index: &dyn VaultIndex, threshold: f64) -> Self {
        let files: Vec<String> = index.entries().iter().map(|e| e.rel_path.clone()).collect();
        Self::new(files, threshold)
    }

    /// Returns `true` if `candidate` (vault-relative) refers to the same file
    /// as `source`, ignoring `.md` suffix and ASCII case.
    fn is_self_link(source: &str, candidate: &str) -> bool {
        fn strip_md(s: &str) -> &str {
            if s.len() >= 3 && s[s.len() - 3..].eq_ignore_ascii_case(".md") {
                &s[..s.len() - 3]
            } else {
                s
            }
        }
        strip_md(source).eq_ignore_ascii_case(strip_md(candidate))
    }

    /// Try to find a matching file for a broken link target.
    ///
    /// `source` is the vault-relative path of the file that contains the
    /// broken link.  Candidates that resolve back to `source` are skipped so
    /// the matcher never proposes a self-referential fix.
    ///
    /// Returns `None` if no match is found above the configured threshold.
    pub(crate) fn find_match(&self, raw_target: &str, source: &str) -> Option<MatchResult> {
        // Minimum score difference to avoid ambiguous fuzzy matches.
        const TIE_DELTA: f64 = 0.01;

        let target_filename = raw_target.rsplit('/').next().unwrap_or(raw_target);
        let target_stem = target_filename
            .strip_suffix(".md")
            .unwrap_or(target_filename);

        // --- Strategy 1: Case-insensitive exact match ---
        // `target_lower` is also used for the exact-case alt computation below.
        let target_lower = raw_target.to_ascii_lowercase();

        // Precompute the exact-case alt form so strategy 1 doesn't steal strategy 2 hits.
        // Check the .md suffix on the lowercased form to avoid a case-sensitive comparison.
        let exact_alt = if std::path::Path::new(&target_lower)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
        {
            // Strip the original suffix (preserving the non-suffix casing).
            raw_target[..raw_target.len() - 3].to_string()
        } else {
            format!("{raw_target}.md")
        };

        if let Some(&idx) = self.lower_to_idx.get(&target_lower) {
            let candidate = &self.files[idx];
            // Only report as case-insensitive if it's not an exact-case extension mismatch
            // and not the source file itself.
            if *candidate != exact_alt && !Self::is_self_link(source, candidate) {
                return Some(MatchResult {
                    matched_file: candidate.clone(),
                    strategy: FixStrategy::CaseInsensitive,
                    confidence: 1.0,
                });
            }
        }

        // --- Strategy 2: Extension mismatch (exact case, only extension differs) ---
        // Use the pre-built exact_to_idx for O(1) lookup instead of a linear scan.
        if let Some(&idx) = self.exact_to_idx.get(&exact_alt)
            && !Self::is_self_link(source, &self.files[idx])
        {
            return Some(MatchResult {
                matched_file: self.files[idx].clone(),
                strategy: FixStrategy::ExtensionMismatch,
                confidence: 1.0,
            });
        }

        // --- Strategy 3: Shortest-path (unique stem match) ---
        let target_stem_lower = target_stem.to_ascii_lowercase();
        if let Some(indices) = self.stem_to_indices.get(&target_stem_lower)
            && indices.len() == 1
            && !Self::is_self_link(source, &self.files[indices[0]])
        {
            return Some(MatchResult {
                matched_file: self.files[indices[0]].clone(),
                strategy: FixStrategy::ShortestPath,
                confidence: 0.95,
            });
        }

        // --- Strategy 4: Fuzzy match (Jaro-Winkler on filename stem) ---
        // Track the top-two scores to detect ties: if two candidates score within
        // TIE_DELTA of each other the match is ambiguous and we return None rather
        // than silently picking the first.
        let mut best_score = self.threshold;
        let mut second_score = 0.0_f64;
        let mut best_idx: Option<usize> = None;

        for (i, candidate) in self.files.iter().enumerate() {
            if Self::is_self_link(source, candidate) {
                continue;
            }
            let fname = candidate.rsplit('/').next().unwrap_or(candidate.as_str());
            let fstem = fname.strip_suffix(".md").unwrap_or(fname);
            let score = strsim::jaro_winkler(target_stem, fstem);
            if score > best_score {
                second_score = best_score;
                best_score = score;
                best_idx = Some(i);
            } else if score > second_score {
                second_score = score;
            }
        }

        // If the runner-up is within TIE_DELTA of the winner the match is
        // ambiguous — decline rather than guessing.
        if best_score - second_score <= TIE_DELTA {
            return None;
        }

        best_idx.map(|idx| MatchResult {
            matched_file: self.files[idx].clone(),
            strategy: FixStrategy::FuzzyMatch,
            confidence: best_score,
        })
    }
}

/// Plan fixes for broken links.
///
/// For each broken link, attempts to find the best matching file using
/// the [`LinkMatcher`] priority-ordered strategy.
///
/// `threshold` is the minimum Jaro-Winkler score (0.0–1.0) for fuzzy matching.
pub fn plan_fixes(broken: &[BrokenLinkInfo], matcher: &LinkMatcher) -> FixReport {
    let mut fixes = Vec::new();
    let mut unfixable = Vec::new();

    for info in broken {
        if let Some(result) = matcher.find_match(&info.target, &info.source) {
            fixes.push(FixPlan {
                source: info.source.clone(),
                line: info.line,
                old_target: info.target.clone(),
                new_target: result.matched_file,
                strategy: result.strategy,
                confidence: result.confidence,
            });
        } else {
            unfixable.push(info.clone());
        }
    }

    FixReport { fixes, unfixable }
}

// ---------------------------------------------------------------------------
// Fix application
// ---------------------------------------------------------------------------

/// Convert fix plans to [`RewritePlan`]s and apply them to disk.
///
/// Groups fixes by source file, reads each file once, builds [`Replacement`]s
/// for every fix in that file, applies them via [`apply_replacements`], and
/// writes back via [`execute_plans`].
///
/// Returns the list of [`RewritePlan`]s for reporting.
pub fn apply_fixes(
    dir: &Path,
    fixes: &[FixPlan],
    site_prefix: Option<&str>,
) -> Result<Vec<RewritePlan>> {
    // Group fixes by source file.
    let mut by_source: HashMap<&str, Vec<&FixPlan>> = HashMap::new();
    for fix in fixes {
        by_source.entry(fix.source.as_str()).or_default().push(fix);
    }

    let mut plans: Vec<RewritePlan> = Vec::new();

    for (source_rel, file_fixes) in &by_source {
        let abs_path = dir.join(source_rel.replace('\\', "/"));
        let meta = std::fs::metadata(&abs_path)
            .with_context(|| format!("failed to stat {}", abs_path.display()))?;
        let file_size = meta.len();
        if file_size > MAX_FILE_SIZE {
            eprintln!(
                "warning: skipping {} ({} MiB exceeds {} MiB limit)",
                abs_path.display(),
                file_size / (1024 * 1024),
                MAX_FILE_SIZE / (1024 * 1024)
            );
            continue;
        }
        let file_mtime = meta
            .modified()
            .with_context(|| format!("failed to read mtime for {}", abs_path.display()))
            .map(|t| (t, file_size))
            .ok();
        let content = std::fs::read_to_string(&abs_path)
            .with_context(|| format!("reading {}", abs_path.display()))?;

        let replacements =
            build_replacements_for_file(&content, source_rel, file_fixes, site_prefix);

        if !replacements.is_empty() {
            let rewritten_content = apply_replacements(&content, &replacements);
            plans.push(RewritePlan {
                path: abs_path,
                rel_path: source_rel.to_string(),
                replacements,
                rewritten_content,
                mtime: file_mtime,
            });
        }
    }

    execute_plans(dir, &plans)?;

    Ok(plans)
}

/// Walk `content` line by line (skipping frontmatter, code fences, comment
/// fences) and build [`Replacement`]s for all link fixes that apply to this
/// file.
fn build_replacements_for_file(
    content: &str,
    source_rel: &str,
    fixes: &[&FixPlan],
    _site_prefix: Option<&str>,
) -> Vec<Replacement> {
    // Index fixes by line number for O(1) lookup during the scan.
    let mut fixes_by_line: HashMap<usize, Vec<&FixPlan>> = HashMap::new();
    for fix in fixes {
        fixes_by_line.entry(fix.line).or_default().push(fix);
    }

    let mut replacements = Vec::new();
    let mut fence = FenceTracker::new();
    let mut in_comment_fence = false;
    let mut in_frontmatter = false;
    let mut frontmatter_done = false;
    let mut line_num = 0usize;

    for line in content.split('\n') {
        line_num += 1;

        // --- Frontmatter ---
        if !frontmatter_done {
            if line_num == 1 && line.trim() == "---" {
                in_frontmatter = true;
                continue;
            }
            if in_frontmatter {
                if line.trim() == "---" {
                    in_frontmatter = false;
                    frontmatter_done = true;
                }
                continue;
            }
            frontmatter_done = true;
        }

        // --- Comment fence (Obsidian %% blocks) ---
        if is_comment_fence(line) {
            in_comment_fence = !in_comment_fence;
            continue;
        }
        if in_comment_fence {
            continue;
        }

        // --- Fenced code block ---
        if fence.process_line(line) {
            continue;
        }

        // If there are no fixes on this line, skip expensive span extraction.
        let Some(line_fixes) = fixes_by_line.get(&line_num) else {
            continue;
        };

        // Extract link spans (skipping inline code and comments).
        let stripped_code = strip_inline_code(line);
        let cleaned = strip_inline_comments(stripped_code.as_ref());
        let spans = extract_link_spans_with_original(&cleaned, line);

        for span in &spans {
            // Normalize the span's target the same way detection does, so we
            // can match it against each fix's old_target.
            let normalized_span_target = match span.kind {
                LinkKind::Wikilink => span.link.target.clone(),
                LinkKind::Markdown => {
                    if span.link.target.starts_with('/') {
                        span.link.target.clone()
                    } else if span.link.target.contains('/') || span.link.target.contains('\\') {
                        normalize_target(Path::new(source_rel), &span.link.target)
                    } else {
                        span.link.target.clone()
                    }
                }
            };

            // Find the fix for this particular span.
            let Some(fix) = line_fixes.iter().find(|f| {
                f.old_target == normalized_span_target || f.old_target == span.link.target
            }) else {
                continue;
            };

            // Compute new target text based on link kind.
            let new_target_text = match span.kind {
                LinkKind::Wikilink => {
                    // Use stem (without .md) for wikilinks.
                    fix.new_target
                        .strip_suffix(".md")
                        .unwrap_or(&fix.new_target)
                        .to_string()
                }
                LinkKind::Markdown => {
                    // Preserve the original `.md` presence/absence in the link.
                    // If the original target had no `.md` suffix, strip it from
                    // the new target too so the style is unchanged.
                    let orig_had_md = fix.old_target.to_ascii_lowercase().ends_with(".md");
                    if orig_had_md {
                        fix.new_target.clone()
                    } else {
                        fix.new_target
                            .strip_suffix(".md")
                            .unwrap_or(&fix.new_target)
                            .to_string()
                    }
                }
            };

            // Build old_text / new_text from the ORIGINAL line bytes.
            let old_text = line[span.full_start..span.full_end].to_string();
            let new_text = format!(
                "{}{}{}",
                &line[span.full_start..span.target_start],
                new_target_text,
                &line[span.target_end..span.full_end],
            );

            if old_text != new_text {
                replacements.push(Replacement {
                    line: line_num,
                    byte_offset: span.full_start,
                    old_text,
                    new_text,
                });
            }
        }
    }

    replacements
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

    // --- Fuzzy matching helpers ---

    fn make_files(names: &[&str]) -> Vec<String> {
        names.iter().map(std::string::ToString::to_string).collect()
    }

    fn broken(source: &str, line: usize, target: &str) -> BrokenLinkInfo {
        BrokenLinkInfo {
            source: source.to_string(),
            line,
            target: target.to_string(),
        }
    }

    fn vault_with_files(files: &[(&str, &str)]) -> TempDir {
        let dir = TempDir::new().unwrap();
        for (rel, content) in files {
            let path = dir
                .path()
                .join(rel.replace('/', std::path::MAIN_SEPARATOR_STR));
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(&path, content).unwrap();
        }
        dir
    }

    // --- LinkMatcher unit tests ---

    #[test]
    fn matcher_case_insensitive() {
        let matcher = LinkMatcher::new(make_files(&["Auth.md"]), 0.8);
        let result = matcher.find_match("auth", "__test__").unwrap();
        assert_eq!(result.matched_file, "Auth.md");
        assert!(matches!(result.strategy, FixStrategy::CaseInsensitive));
        assert!((result.confidence - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn matcher_extension_mismatch_add_md() {
        let matcher = LinkMatcher::new(make_files(&["notes/foo.md"]), 0.8);
        let result = matcher.find_match("notes/foo", "__test__").unwrap();
        assert_eq!(result.matched_file, "notes/foo.md");
        assert!(matches!(result.strategy, FixStrategy::ExtensionMismatch));
    }

    #[test]
    fn matcher_extension_mismatch_strip_md() {
        let matcher = LinkMatcher::new(make_files(&["foo"]), 0.8);
        let result = matcher.find_match("foo.md", "__test__").unwrap();
        assert_eq!(result.matched_file, "foo");
        assert!(matches!(result.strategy, FixStrategy::ExtensionMismatch));
    }

    #[test]
    fn matcher_shortest_path_unique_stem() {
        let matcher = LinkMatcher::new(make_files(&["sub/deep/bar.md"]), 0.8);
        let result = matcher.find_match("bar", "__test__").unwrap();
        assert_eq!(result.matched_file, "sub/deep/bar.md");
        assert!(matches!(result.strategy, FixStrategy::ShortestPath));
        assert!((result.confidence - 0.95).abs() < f64::EPSILON);
    }

    #[test]
    fn matcher_shortest_path_ambiguous_skipped() {
        let matcher = LinkMatcher::new(make_files(&["a/bar.md", "b/bar.md"]), 0.99);
        let result = matcher.find_match("bar", "__test__");
        // Both stem-match so shortest-path doesn't fire; fuzzy threshold is
        // very high (0.99) but "bar" vs "bar" scores 1.0, so fuzzy wins.
        if let Some(r) = result {
            assert!(!matches!(r.strategy, FixStrategy::ShortestPath));
        }
    }

    #[test]
    fn matcher_fuzzy_match() {
        let matcher = LinkMatcher::new(make_files(&["authentication.md"]), 0.7);
        // "authentcation" is a typo of "authentication"
        let result = matcher.find_match("authentcation", "__test__").unwrap();
        assert_eq!(result.matched_file, "authentication.md");
        assert!(matches!(result.strategy, FixStrategy::FuzzyMatch));
        assert!(result.confidence >= 0.7);
    }

    #[test]
    fn matcher_no_match() {
        let matcher = LinkMatcher::new(make_files(&["completely-unrelated.md"]), 0.95);
        assert!(matcher.find_match("xyz-abc-notexist", "__test__").is_none());
    }

    // --- Self-link guard ---

    #[test]
    fn matcher_rejects_self_link_fuzzy() {
        // When the only fuzzy candidate is the source file itself, return None.
        let matcher = LinkMatcher::new(make_files(&["sort-by-property-value.md"]), 0.7);
        assert!(
            matcher
                .find_match("sort-reverse", "sort-by-property-value.md")
                .is_none(),
            "should not match source file via fuzzy"
        );
    }

    #[test]
    fn matcher_rejects_self_link_picks_next_best() {
        // When the best fuzzy candidate is the source, the runner-up should win.
        let matcher = LinkMatcher::new(
            make_files(&["sort-by-property-value.md", "sort-reverse.md"]),
            0.7,
        );
        let result = matcher
            .find_match("sort-reverse", "sort-by-property-value.md")
            .unwrap();
        assert_eq!(result.matched_file, "sort-reverse.md");
    }

    #[test]
    fn matcher_rejects_self_link_case_insensitive() {
        // The only case-insensitive match is the source file — should return None.
        let matcher = LinkMatcher::new(make_files(&["Auth.md"]), 0.8);
        assert!(matcher.find_match("auth", "Auth.md").is_none());
    }

    #[test]
    fn matcher_rejects_self_link_extension_mismatch() {
        // Source without .md suffix; only candidate is the .md form — should be blocked.
        let matcher = LinkMatcher::new(make_files(&["notes/foo.md"]), 0.8);
        assert!(matcher.find_match("notes/foo.md", "notes/foo").is_none());
    }

    #[test]
    fn matcher_rejects_self_link_shortest_path() {
        // Unique stem match that resolves to the source file — should return None.
        let matcher = LinkMatcher::new(make_files(&["sub/bar.md"]), 0.8);
        assert!(matcher.find_match("bar", "sub/bar.md").is_none());
    }

    #[test]
    fn matcher_self_link_among_ambiguous_stems_picks_other() {
        // Two files share a stem; source is one of them — matcher should pick the other.
        let matcher = LinkMatcher::new(make_files(&["a/bar.md", "b/bar.md"]), 0.8);
        let result = matcher.find_match("bar", "a/bar.md").unwrap();
        assert_eq!(result.matched_file, "b/bar.md");
    }

    #[test]
    fn plan_fixes_self_link_is_unfixable() {
        let matcher = LinkMatcher::new(make_files(&["sort-by-property-value.md"]), 0.7);
        let broken_links = vec![broken("sort-by-property-value.md", 10, "sort-reverse")];
        let report = plan_fixes(&broken_links, &matcher);
        assert!(report.fixes.is_empty(), "self-link should not be a fix");
        assert_eq!(report.unfixable.len(), 1);
    }

    // --- plan_fixes integration ---

    #[test]
    fn plan_fixes_produces_fix_and_unfixable() {
        let matcher = LinkMatcher::new(make_files(&["Auth.md"]), 0.95);
        let broken_links = vec![
            broken("index.md", 1, "auth"),
            broken("index.md", 5, "totally-nonexistent"),
        ];
        let report = plan_fixes(&broken_links, &matcher);
        assert_eq!(report.fixes.len(), 1);
        assert_eq!(report.fixes[0].new_target, "Auth.md");
        assert_eq!(report.unfixable.len(), 1);
    }

    // --- detect_broken_links: basic ---

    #[test]
    fn detect_broken_links_finds_missing() {
        use crate::link_graph::FileLinks;
        use crate::links::{Link, LinkKind};

        let tmp = vault_with_files(&[("index.md", "[[existing]]"), ("existing.md", "")]);

        let file_links = vec![FileLinks {
            source: PathBuf::from("index.md"),
            links: vec![
                (
                    1,
                    Link {
                        target: "existing".to_string(),
                        label: None,
                        kind: LinkKind::Wikilink,
                    },
                ),
                (
                    2,
                    Link {
                        target: "missing".to_string(),
                        label: None,
                        kind: LinkKind::Wikilink,
                    },
                ),
            ],
        }];

        let report = detect_broken_links(tmp.path(), &file_links, None, None);

        assert_eq!(report.total_links, 2);
        assert_eq!(report.broken.len(), 1);
        assert_eq!(report.broken[0].target, "missing");
    }

    // --- detect_broken_links: sorted output ---

    #[test]
    fn detect_broken_links_sorted() {
        use crate::link_graph::FileLinks;
        use crate::links::{Link, LinkKind};

        let tmp = vault_with_files(&[("a.md", ""), ("b.md", "")]);

        let file_links = vec![
            FileLinks {
                source: PathBuf::from("b.md"),
                links: vec![(
                    3,
                    Link {
                        target: "gone".to_string(),
                        label: None,
                        kind: LinkKind::Wikilink,
                    },
                )],
            },
            FileLinks {
                source: PathBuf::from("a.md"),
                links: vec![
                    (
                        5,
                        Link {
                            target: "also-gone".to_string(),
                            label: None,
                            kind: LinkKind::Wikilink,
                        },
                    ),
                    (
                        1,
                        Link {
                            target: "nope".to_string(),
                            label: None,
                            kind: LinkKind::Wikilink,
                        },
                    ),
                ],
            },
        ];

        let report = detect_broken_links(tmp.path(), &file_links, None, None);

        assert_eq!(report.broken.len(), 3);
        // Sorted by (source, line)
        assert_eq!(report.broken[0].source, "a.md");
        assert_eq!(report.broken[0].line, 1);
        assert_eq!(report.broken[1].source, "a.md");
        assert_eq!(report.broken[1].line, 5);
        assert_eq!(report.broken[2].source, "b.md");
        assert_eq!(report.broken[2].line, 3);
    }

    // --- apply_fixes: wikilink rewrite ---

    #[test]
    fn apply_fixes_rewrites_wikilink() {
        let tmp = vault_with_files(&[
            ("index.md", "See [[wrongname]] for details.\n"),
            ("correct-name.md", ""),
        ]);

        let fixes = vec![FixPlan {
            source: "index.md".to_string(),
            line: 1,
            old_target: "wrongname".to_string(),
            new_target: "correct-name.md".to_string(),
            strategy: FixStrategy::FuzzyMatch,
            confidence: 0.9,
        }];

        let plans = apply_fixes(tmp.path(), &fixes, None).unwrap();

        assert_eq!(plans.len(), 1);
        let written = fs::read_to_string(tmp.path().join("index.md")).unwrap();
        assert!(
            written.contains("[[correct-name]]"),
            "expected wikilink stem, got: {written}"
        );
    }

    // --- apply_fixes: markdown link rewrite ---

    #[test]
    fn apply_fixes_rewrites_markdown_link() {
        let tmp = vault_with_files(&[
            ("index.md", "See [text](wrong.md) for details.\n"),
            ("correct.md", ""),
        ]);

        let fixes = vec![FixPlan {
            source: "index.md".to_string(),
            line: 1,
            old_target: "wrong.md".to_string(),
            new_target: "correct.md".to_string(),
            strategy: FixStrategy::CaseInsensitive,
            confidence: 1.0,
        }];

        let plans = apply_fixes(tmp.path(), &fixes, None).unwrap();

        assert_eq!(plans.len(), 1);
        let written = fs::read_to_string(tmp.path().join("index.md")).unwrap();
        assert!(
            written.contains("[text](correct.md)"),
            "expected rewritten link, got: {written}"
        );
    }

    // ---------------------------------------------------------------------------
    // Case-mismatch detection tests
    // ---------------------------------------------------------------------------

    #[test]
    fn detect_broken_links_emits_case_mismatch_with_index() {
        use crate::case_index::CaseInsensitiveIndex;
        use crate::link_graph::FileLinks;
        use crate::links::{Link, LinkKind};

        // On-disk: `web/foo.md` (lowercase). Link written as `Web/Foo` (PascalCase).
        let tmp = vault_with_files(&[("web/foo.md", ""), ("source.md", "[[Web/Foo]]")]);

        // Build a case index containing the real path.
        let mut idx = CaseInsensitiveIndex::new();
        idx.insert("web/foo.md");

        let file_links = vec![FileLinks {
            source: PathBuf::from("source.md"),
            links: vec![(
                1,
                Link {
                    target: "Web/Foo".to_string(),
                    label: None,
                    kind: LinkKind::Wikilink,
                },
            )],
        }];

        // Without index: case_mismatches is always empty regardless of FS type.
        // The link may resolve exactly on case-insensitive FS (macOS) or be broken
        // on case-sensitive FS (Linux) — but no case_mismatches either way.
        let report_no_idx = detect_broken_links(tmp.path(), &file_links, None, None);
        assert_eq!(report_no_idx.total_links, 1);
        assert!(
            report_no_idx.case_mismatches.is_empty(),
            "case_mismatches must always be empty when no index is provided"
        );

        // With index: total_links is still 1 and accounting is consistent.
        // On case-insensitive FS the exact check resolves successfully (both lists empty).
        // On case-sensitive FS the link is reported as a case_mismatch (not broken).
        let report_with_idx = detect_broken_links(tmp.path(), &file_links, None, Some(&idx));
        assert_eq!(report_with_idx.total_links, 1);
        let total_classified = report_with_idx.broken.len() + report_with_idx.case_mismatches.len();
        assert!(
            total_classified <= 1,
            "each link must appear at most once across broken + case_mismatches"
        );
    }

    #[test]
    fn detect_broken_links_case_mismatch_has_correct_strategy() {
        use crate::case_index::CaseInsensitiveIndex;
        use crate::link_graph::FileLinks;
        use crate::links::{Link, LinkKind};

        // Build a case-sensitive vault setup by checking the actual FS behavior.
        let tmp = vault_with_files(&[("web/foo.md", ""), ("source.md", "")]);

        let mut idx = CaseInsensitiveIndex::new();
        idx.insert("web/foo.md");

        let file_links = vec![FileLinks {
            source: PathBuf::from("source.md"),
            links: vec![(
                1,
                Link {
                    target: "Web/Foo".to_string(),
                    label: None,
                    kind: LinkKind::Wikilink,
                },
            )],
        }];

        let report = detect_broken_links(tmp.path(), &file_links, None, Some(&idx));

        // Regardless of FS case sensitivity: if there are case_mismatches,
        // they must use the LinkCaseMismatch strategy and confidence 1.0.
        for fix in &report.case_mismatches {
            assert!(
                matches!(fix.strategy, FixStrategy::LinkCaseMismatch),
                "strategy should be LinkCaseMismatch, got: {:?}",
                fix.strategy
            );
            assert!(
                (fix.confidence - 1.0).abs() < f64::EPSILON,
                "confidence should be 1.0"
            );
            assert_eq!(
                fix.old_target, "Web/Foo",
                "old_target should preserve original casing"
            );
        }
    }

    #[test]
    fn detect_broken_links_no_index_no_case_mismatches() {
        use crate::link_graph::FileLinks;
        use crate::links::{Link, LinkKind};

        let tmp = vault_with_files(&[("web/foo.md", ""), ("source.md", "")]);

        let file_links = vec![FileLinks {
            source: PathBuf::from("source.md"),
            links: vec![(
                1,
                Link {
                    target: "Web/Foo".to_string(),
                    label: None,
                    kind: LinkKind::Wikilink,
                },
            )],
        }];

        // Without case index: case_mismatches must always be empty.
        let report = detect_broken_links(tmp.path(), &file_links, None, None);
        assert!(
            report.case_mismatches.is_empty(),
            "case_mismatches must be empty when no index is provided"
        );
    }
}