hunch 2.0.2

A media filename parser for movies, TV, and anime — built in Rust, inspired by guessit
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
//! Cross-file invariance analysis for year and episode disambiguation.
//!
//! Extends the basic title invariance detection in `context.rs` with
//! number classification: year-like numbers that stay the same across
//! siblings are title content, numbers that vary are metadata (episodes,
//! years). Sequential variant numbers provide episode evidence.
//!
//! See `InvarianceReport` for the unified result, and DESIGN.md
//! (Cross-file context) for the architectural rationale.

use std::sync::LazyLock;

use super::context::{
    SEPS, TRIM_CHARS, UnclaimedGap, find_invariant_text, find_unclaimed_gaps, strip_extension_pos,
};
use crate::matcher::span::{MatchSpan, Property};

// ── InvarianceReport: unified cross-file analysis ─────────────────────────
// Phase 1 of #52/#53: structs + analysis logic.
// Wired into the pipeline in Phase 2.

/// Unified cross-file analysis result.
///
/// Produced by [`analyze_invariance`] from a target file + siblings.
/// Each field is independently optional — partial results are fine.
#[derive(Debug, Clone, Default)]
pub(crate) struct InvarianceReport {
    /// Invariant title text (existing functionality from `find_invariant_text`).
    pub title: Option<String>,
    /// Byte offset where the invariant title starts in the target input.
    pub title_start: Option<usize>,
    /// Year signals: which year-like numbers are invariant (title) vs variant.
    pub year_signals: Vec<YearSignal>,
    /// Episode signals: which bare numbers form sequences across siblings.
    pub episode_signals: Vec<EpisodeSignal>,
}

/// A year-like number classified by cross-file analysis.
#[derive(Debug, Clone)]
pub(crate) struct YearSignal {
    /// Byte offset in the target file.
    pub start: usize,
    /// Byte offset end (exclusive) in the target file.
    pub end: usize,
    /// The 4-digit value.
    pub value: u32,
    /// `true` if this number is the same across all siblings at this position.
    /// Invariant → title content. Variant → release year or other metadata.
    pub is_invariant: bool,
}

/// A bare number classified by cross-file analysis.
#[derive(Debug, Clone)]
pub(crate) struct EpisodeSignal {
    /// Byte offset in the target file.
    pub start: usize,
    /// Byte offset end (exclusive) in the target file.
    pub end: usize,
    /// The numeric value in the target file.
    pub value: u32,
    /// Whether sibling values at this position form a sequence (e.g., 3,4,5).
    pub is_sequential: bool,
    /// Number of digits (helps distinguish 3-digit decomposition from absolute).
    pub digit_count: usize,
}

/// A bare number found in an unclaimed gap.
#[derive(Debug, Clone)]
struct NumberInGap {
    /// Byte offset in the original input string.
    start: usize,
    /// Byte offset end (exclusive).
    end: usize,
    /// The numeric value.
    value: u32,
    /// Number of digits in the original string.
    digit_count: usize,
    /// Which gap index this number was found in.
    gap_idx: usize,
    /// Position within the gap (for alignment across siblings).
    idx_within_gap: usize,
}

/// Input bundle for a single file's Pass 1 results.
pub(crate) struct FileAnalysis<'a> {
    /// The raw input string.
    pub input: &'a str,
    /// Resolved matches from Pass 1.
    pub matches: &'a [MatchSpan],
}

/// Regex for finding bare numbers in gap text.
static GAP_NUMBER: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(r"\d+").expect("GAP_NUMBER regex is valid"));

/// Perform unified cross-file invariance analysis.
///
/// Analyzes the target file against siblings to produce:
/// - Title (invariant text)
/// - Year signals (invariant vs variant year-like numbers)
/// - Episode signals (sequential variant numbers)
///
/// Falls back gracefully: if no siblings, returns an empty report.
pub(crate) fn analyze_invariance(
    target: &FileAnalysis<'_>,
    siblings: &[FileAnalysis<'_>],
) -> InvarianceReport {
    if siblings.is_empty() {
        return InvarianceReport::default();
    }

    // 1. Compute unclaimed gaps for all files.
    let target_gaps = find_unclaimed_gaps(target.input, target.matches);
    let sibling_gaps: Vec<Vec<UnclaimedGap>> = siblings
        .iter()
        .map(|s| find_unclaimed_gaps(s.input, s.matches))
        .collect();

    // 2. Title: invariant text in *pre-anchor* gaps only.
    //
    //    A gap qualifies as a title candidate only when it precedes the
    //    first content anchor (Season/Episode/Year) in the filename.
    //    Rationale: titles structurally appear *before* the
    //    season/episode/year identifier; text that's invariant *after*
    //    that identifier is per-episode-title commonality, not show
    //    title. Without this filter, files like
    //    `Show/S01E10 - Pups Save Ryder's Robot.mkv` and
    //    `Show/S01E11 - Pups and the Ghost Pirate.mkv` would yield an
    //    invariance title of `"Pups"` (the common prefix of two
    //    episode-title strings) and clobber the correct `"Show"` from
    //    the parent directory. (#244 follow-up bug A)
    let target_pre = title_candidate_gaps(&target_gaps, target.input, target.matches);
    let sibling_pre: Vec<Vec<UnclaimedGap>> = siblings
        .iter()
        .zip(&sibling_gaps)
        .map(|(s, gaps)| title_candidate_gaps(gaps, s.input, s.matches))
        .collect();
    let all_gap_refs: Vec<&[UnclaimedGap]> = std::iter::once(target_pre.as_slice())
        .chain(sibling_pre.iter().map(|v| v.as_slice()))
        .collect();
    let (title, title_start) = match find_invariant_text(&all_gap_refs) {
        Some((start, text)) => (Some(text), Some(start)),
        None => (None, None),
    };

    // 3. Extract bare numbers from unclaimed gaps for each file.
    let target_numbers = extract_numbers_from_gaps(target.input, &target_gaps);
    let sibling_numbers: Vec<Vec<NumberInGap>> = siblings
        .iter()
        .zip(&sibling_gaps)
        .map(|(s, gaps)| extract_numbers_from_gaps(s.input, gaps))
        .collect();

    // 4. Classify numbers by cross-file comparison.
    let mut year_signals = classify_year_signals(&target_numbers, &sibling_numbers);
    let mut episode_signals = classify_episode_signals(&target_numbers, &sibling_numbers);

    // 5. Also check Year matches claimed by Pass 1 — they're not in unclaimed
    //    gaps, so classify_year_signals misses them. If a Year match has the
    //    same value across all siblings, it's invariant (title content).
    let claimed_year_signals = classify_claimed_year_signals(target, siblings);
    year_signals.extend(claimed_year_signals);

    // 5b. Also check Season+Episode from digit decomposition.
    //     Pass 1 may decompose "501" → S5E01, claiming the span.
    //     If raw values (501, 502, 503) form a sequence across siblings,
    //     create an episode signal with the raw (undecomposed) value.
    let claimed_ep_signals = classify_claimed_decomposed_episodes(target, siblings);
    episode_signals.extend(claimed_ep_signals);

    // 6. Expand title to include adjacent invariant years.
    //    E.g., "2001.A.Space.Odyssey" → title="A Space Odyssey", but "2001" is
    //    an invariant year at position 0..4. If it's immediately before the
    //    title position in the input, prepend it.
    let (title, title_start) =
        expand_title_with_invariant_years(target.input, title, title_start, &year_signals);

    InvarianceReport {
        title,
        title_start,
        year_signals,
        episode_signals,
    }
}

/// Filter `gaps` to those eligible to contribute a title via invariance.
///
/// A gap qualifies when it ends **at or before** the start of the first
/// content anchor (Season / Episode / Year) in the filename. Anything
/// after the first such anchor is post-title territory — release-group
/// noise, episode titles, language tags, etc. — where cross-file
/// commonality reflects naming convention, not show identity.
///
/// Files with **no** content anchor in the filename pass all gaps
/// through unchanged: the whole filename body is title territory (e.g.
/// `Movie.Name.2020.mkv` only has a Year, but `Movie.Name.mkv` has none
/// and the entire stem is fair game).
///
/// Path-prefix gaps were already excluded structurally by
/// [`find_unclaimed_gaps`].
fn title_candidate_gaps(
    gaps: &[UnclaimedGap],
    input: &str,
    matches: &[MatchSpan],
) -> Vec<UnclaimedGap> {
    let fn_start = crate::filename_start(input);
    let first_anchor = matches
        .iter()
        .filter(|m| {
            m.start >= fn_start
                && matches!(
                    m.property,
                    Property::Season | Property::Episode | Property::Year
                )
        })
        .map(|m| m.start)
        .min();

    match first_anchor {
        Some(anchor) => gaps
            .iter()
            .filter(|g| find_gap_end_in_input(input, g) <= anchor)
            .cloned()
            .collect(),
        None => gaps.to_vec(),
    }
}

/// Expand the title to include adjacent invariant year-like numbers.
///
/// When a year like "2001" is invariant (title content), it may have been
/// claimed by Pass 1's year matcher and thus excluded from unclaimed gaps.
/// This function checks if any invariant year is immediately before or after
/// the title text in the input, and expands the title to include it.
fn expand_title_with_invariant_years(
    input: &str,
    title: Option<String>,
    title_start: Option<usize>,
    year_signals: &[YearSignal],
) -> (Option<String>, Option<usize>) {
    let title_text = match title.as_deref() {
        Some(t) => t,
        None => return (title, title_start),
    };

    // Use the pre-computed title position instead of searching with input.find(),
    // which can match the wrong occurrence for short or repeated title strings.
    let title_start_pos = match title_start {
        Some(s) => s,
        None => return (title, title_start),
    };
    let title_end = find_title_end_in_input(input, title_start_pos, title_text);

    let mut expanded_start = title_start_pos;
    let mut expanded_end = title_end;

    // Sort invariant year signals by position to ensure stable expansion
    // when multiple years appear on the same side of the title.
    let mut sorted_signals: Vec<&YearSignal> =
        year_signals.iter().filter(|ys| ys.is_invariant).collect();
    sorted_signals.sort_by_key(|ys| ys.start);

    for ys in sorted_signals {
        // Check if this invariant year is immediately before the title
        // (separated only by separators/whitespace).
        if ys.end <= expanded_start {
            let between = &input[ys.end..expanded_start];
            if between.chars().all(|c| SEPS.contains(&c)) {
                expanded_start = ys.start;
            }
        }

        // Check if this invariant year is immediately after the title.
        if ys.start >= expanded_end {
            let between = &input[expanded_end..ys.start];
            if between.chars().all(|c| SEPS.contains(&c)) {
                expanded_end = ys.end;
            }
        }
    }

    if expanded_start == title_start_pos && expanded_end == title_end {
        return (Some(title_text.to_string()), Some(expanded_start));
    }

    // Rebuild the title from the expanded range, normalizing separators.
    let raw = &input[expanded_start..expanded_end];
    let normalized: String = raw
        .chars()
        .map(|c| if SEPS.contains(&c) { ' ' } else { c })
        .collect();
    (Some(normalized.trim().to_string()), Some(expanded_start))
}

/// Find the end byte offset of the title text within the original input.
///
/// Since the title text is normalized (separators → spaces), we scan forward
/// from `title_start`, matching non-separator content characters.
fn find_title_end_in_input(input: &str, title_start: usize, title_text: &str) -> usize {
    let mut pos = title_start;
    let mut title_chars = title_text.chars().filter(|c| !c.is_whitespace()).peekable();

    for ch in input[title_start..].chars() {
        if title_chars.peek().is_none() {
            break;
        }
        pos += ch.len_utf8();
        if !SEPS.contains(&ch) && !TRIM_CHARS.contains(&ch) {
            title_chars.next();
        }
    }
    pos
}
/// Extract bare numbers from unclaimed gaps in an input string.
fn extract_numbers_from_gaps(input: &str, gaps: &[UnclaimedGap]) -> Vec<NumberInGap> {
    let mut numbers = Vec::new();

    for (gap_idx, gap) in gaps.iter().enumerate() {
        let gap_end = find_gap_end_in_input(input, gap);
        let gap_slice = &input[gap.start..gap_end];

        let mut idx_within_gap = 0;
        for m in GAP_NUMBER.find_iter(gap_slice) {
            let abs_start = gap.start + m.start();
            let abs_end = gap.start + m.end();
            let digit_str = m.as_str();

            // Skip codec-like numbers (shared constant avoids DRY violation).
            if let Ok(n) = digit_str.parse::<u32>() {
                if crate::CODEC_NUMBERS.contains(&n) {
                    continue;
                }
            } else {
                continue;
            }

            // value is already parsed above via the codec check.
            let value: u32 = digit_str.parse().expect("already validated as numeric");
            numbers.push(NumberInGap {
                start: abs_start,
                end: abs_end,
                value,
                digit_count: digit_str.len(),
                gap_idx,
                idx_within_gap,
            });
            idx_within_gap += 1;
        }
    }

    numbers
}

/// Find the end byte offset of a gap in the original input.
fn find_gap_end_in_input(input: &str, gap: &UnclaimedGap) -> usize {
    let scan_end = strip_extension_pos(input);
    let mut pos = gap.start;
    let mut content_chars = 0;
    let target_chars = gap.text.chars().filter(|c| !c.is_whitespace()).count();

    for ch in input[gap.start..scan_end].chars() {
        pos += ch.len_utf8();
        if !SEPS.contains(&ch) && !TRIM_CHARS.contains(&ch) {
            content_chars += 1;
        }
        if content_chars >= target_chars {
            break;
        }
    }
    pos
}

/// Classify year-like numbers as invariant (title) or variant (metadata).
fn classify_year_signals(
    target_numbers: &[NumberInGap],
    sibling_numbers: &[Vec<NumberInGap>],
) -> Vec<YearSignal> {
    let mut signals = Vec::new();

    for tn in target_numbers {
        if tn.digit_count != 4 || !(1920..=2039).contains(&tn.value) {
            continue;
        }

        let mut all_same = true;
        let mut found_in_all = true;

        for sib_nums in sibling_numbers {
            let aligned = sib_nums
                .iter()
                .find(|sn| sn.gap_idx == tn.gap_idx && sn.idx_within_gap == tn.idx_within_gap);
            match aligned {
                Some(sn) => {
                    if sn.value != tn.value {
                        all_same = false;
                    }
                }
                None => {
                    found_in_all = false;
                    break;
                }
            }
        }

        if found_in_all {
            signals.push(YearSignal {
                start: tn.start,
                end: tn.end,
                value: tn.value,
                is_invariant: all_same,
            });
        }
    }

    signals
}

/// Classify Year matches from Pass 1 that are invariant across siblings.
///
/// This catches year-like numbers that Pass 1 already claimed (e.g., "2001"
/// matched as Year by the year matcher). If every sibling has a Year match
/// with the same value, this year is title content, not release metadata.
fn classify_claimed_year_signals(
    target: &FileAnalysis<'_>,
    siblings: &[FileAnalysis<'_>],
) -> Vec<YearSignal> {
    use crate::matcher::span::Property;

    let mut signals = Vec::new();

    // Find all Year matches in the target.
    for tm in target.matches {
        if tm.property != Property::Year {
            continue;
        }
        let target_value: u32 = match tm.value.parse() {
            Ok(v) => v,
            Err(_) => continue,
        };

        // Check if every sibling has a Year match with the same value.
        let mut all_same = true;
        let mut found_in_all = true;

        for sib in siblings {
            let sib_year = sib.matches.iter().find(|m| m.property == Property::Year);
            match sib_year {
                Some(sy) => {
                    if let Ok(sv) = sy.value.parse::<u32>() {
                        if sv != target_value {
                            all_same = false;
                        }
                    } else {
                        found_in_all = false;
                        break;
                    }
                }
                None => {
                    found_in_all = false;
                    break;
                }
            }
        }

        if found_in_all {
            signals.push(YearSignal {
                start: tm.start,
                end: tm.end,
                value: target_value,
                is_invariant: all_same,
            });
        }
    }

    signals
}

/// Detect 3-digit digit decomposition matches that should be absolute episodes.
///
/// Pass 1 decomposes "501" → Season=5+Episode=01 at the same span. If the raw
/// numbers (501, 502, 503) form a sequence across siblings, this is really an
/// absolute episode, not a season+episode decomposition.
fn classify_claimed_decomposed_episodes(
    target: &FileAnalysis<'_>,
    siblings: &[FileAnalysis<'_>],
) -> Vec<EpisodeSignal> {
    use crate::matcher::span::Property;

    let mut signals = Vec::new();

    // Find Season+Episode pairs from decomposition (same span, priority ≤0).
    for tm in target.matches {
        if tm.property != Property::Season || tm.priority > 0 {
            continue;
        }
        // Find the corresponding Episode match at the same span.
        let ep_match = target.matches.iter().find(|m| {
            m.property == Property::Episode
                && m.start == tm.start
                && m.end == tm.end
                && m.priority <= 0
        });
        let ep_match = match ep_match {
            Some(m) => m,
            None => continue,
        };

        // Reconstruct the raw number: season * 100 + episode.
        let season: u32 = match tm.value.parse() {
            Ok(v) => v,
            Err(_) => continue,
        };
        let episode: u32 = match ep_match.value.parse() {
            Ok(v) => v,
            Err(_) => continue,
        };
        let raw_value = season * 100 + episode;

        // Collect raw values from siblings at similar decomposition positions.
        let mut values: Vec<u32> = vec![raw_value];
        let mut found_in_all = true;

        for sib in siblings {
            // Find a Season+Episode decomposition pair in the sibling.
            let sib_season = sib
                .matches
                .iter()
                .find(|m| m.property == Property::Season && m.priority <= 0);
            let sib_season = match sib_season {
                Some(s) => s,
                None => {
                    found_in_all = false;
                    break;
                }
            };
            let sib_ep = sib.matches.iter().find(|m| {
                m.property == Property::Episode
                    && m.start == sib_season.start
                    && m.end == sib_season.end
                    && m.priority <= 0
            });
            let sib_ep = match sib_ep {
                Some(e) => e,
                None => {
                    found_in_all = false;
                    break;
                }
            };

            let ss: u32 = match sib_season.value.parse() {
                Ok(v) => v,
                Err(_) => {
                    found_in_all = false;
                    break;
                }
            };
            let se: u32 = match sib_ep.value.parse() {
                Ok(v) => v,
                Err(_) => {
                    found_in_all = false;
                    break;
                }
            };
            values.push(ss * 100 + se);
        }

        if !found_in_all {
            continue;
        }

        // Check if values vary and form a sequence.
        let all_same = values.iter().all(|v| *v == values[0]);
        if all_same {
            continue;
        }

        let is_sequential = is_sequential_set(&values);
        if is_sequential {
            signals.push(EpisodeSignal {
                start: tm.start,
                end: tm.end,
                value: raw_value,
                is_sequential: true,
                digit_count: 3,
            });
        }
    }

    signals
}

/// Classify bare numbers as episode signals based on cross-file patterns.
fn classify_episode_signals(
    target_numbers: &[NumberInGap],
    sibling_numbers: &[Vec<NumberInGap>],
) -> Vec<EpisodeSignal> {
    let mut signals = Vec::new();

    for tn in target_numbers {
        if tn.digit_count == 4 && (1920..=2039).contains(&tn.value) {
            continue;
        }

        let mut values: Vec<u32> = vec![tn.value];
        let mut found_in_all = true;

        for sib_nums in sibling_numbers {
            let aligned = sib_nums
                .iter()
                .find(|sn| sn.gap_idx == tn.gap_idx && sn.idx_within_gap == tn.idx_within_gap);
            match aligned {
                Some(sn) => values.push(sn.value),
                None => {
                    found_in_all = false;
                    break;
                }
            }
        }

        if !found_in_all {
            continue;
        }

        let all_same = values.iter().all(|v| *v == values[0]);
        if all_same {
            continue;
        }

        let is_sequential = is_sequential_set(&values);

        signals.push(EpisodeSignal {
            start: tn.start,
            end: tn.end,
            value: tn.value,
            is_sequential,
            digit_count: tn.digit_count,
        });
    }

    signals
}

/// Check if a set of values forms a sequential pattern.
fn is_sequential_set(values: &[u32]) -> bool {
    if values.len() < 2 {
        return false;
    }
    let mut sorted: Vec<u32> = values.to_vec();
    sorted.sort_unstable();
    sorted.dedup();
    if sorted.len() < 2 {
        return false;
    }
    let min = sorted[0];
    let max = sorted[sorted.len() - 1];
    (max - min + 1) as usize == sorted.len()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::matcher::span::Property;

    fn make_match_at(start: usize, end: usize, property: Property, value: &str) -> MatchSpan {
        MatchSpan::new(start, end, property, value)
    }

    #[test]
    fn is_sequential_basic() {
        assert!(is_sequential_set(&[3, 4, 5]));
        assert!(is_sequential_set(&[1, 2]));
        assert!(is_sequential_set(&[501, 502, 503]));
    }

    #[test]
    fn is_sequential_out_of_order() {
        assert!(is_sequential_set(&[5, 3, 4]));
    }

    #[test]
    fn is_sequential_gaps_not_sequential() {
        assert!(!is_sequential_set(&[1, 3, 5]));
        assert!(!is_sequential_set(&[1, 10]));
    }

    #[test]
    fn is_sequential_single_value() {
        assert!(!is_sequential_set(&[5]));
    }

    #[test]
    fn is_sequential_all_same() {
        assert!(!is_sequential_set(&[5, 5, 5]));
    }

    #[test]
    fn year_invariant_detected() {
        let target_input = "2001.A.Space.Odyssey.1080p.mkv";
        let sib_input = "2001.A.Space.Odyssey.720p.mkv";

        let target_matches = vec![make_match_at(21, 26, Property::ScreenSize, "1080p")];
        let sib_matches = vec![make_match_at(21, 25, Property::ScreenSize, "720p")];

        let report = analyze_invariance(
            &FileAnalysis {
                input: target_input,
                matches: &target_matches,
            },
            &[FileAnalysis {
                input: sib_input,
                matches: &sib_matches,
            }],
        );

        let year_2001: Vec<_> = report
            .year_signals
            .iter()
            .filter(|y| y.value == 2001)
            .collect();
        assert!(!year_2001.is_empty(), "should detect 2001 as year signal");
        assert!(
            year_2001[0].is_invariant,
            "2001 should be invariant (title content)"
        );
    }

    #[test]
    fn year_variant_detected() {
        let target_input = "Movie.2023.1080p.mkv";
        let sib_input = "Movie.2024.1080p.mkv";

        let target_matches = vec![make_match_at(11, 16, Property::ScreenSize, "1080p")];
        let sib_matches = vec![make_match_at(11, 16, Property::ScreenSize, "1080p")];

        let report = analyze_invariance(
            &FileAnalysis {
                input: target_input,
                matches: &target_matches,
            },
            &[FileAnalysis {
                input: sib_input,
                matches: &sib_matches,
            }],
        );

        let year_signals: Vec<_> = report
            .year_signals
            .iter()
            .filter(|y| (2023..=2024).contains(&y.value))
            .collect();
        assert!(!year_signals.is_empty(), "should detect year signal");
        assert!(
            !year_signals[0].is_invariant,
            "year should be variant (metadata)"
        );
    }

    #[test]
    fn episode_sequential_detected() {
        let target = "Show.03.720p.mkv";
        let sib = "Show.04.720p.mkv";

        let target_matches = vec![make_match_at(9, 13, Property::ScreenSize, "720p")];
        let sib_matches = vec![make_match_at(9, 13, Property::ScreenSize, "720p")];

        let report = analyze_invariance(
            &FileAnalysis {
                input: target,
                matches: &target_matches,
            },
            &[FileAnalysis {
                input: sib,
                matches: &sib_matches,
            }],
        );

        assert!(
            !report.episode_signals.is_empty(),
            "should detect episode signal"
        );
        let ep = &report.episode_signals[0];
        assert_eq!(ep.value, 3);
        assert!(ep.is_sequential, "episodes should be sequential");
        assert_eq!(ep.digit_count, 2);
    }

    #[test]
    fn episode_three_digit_sequential() {
        let target = "Show.501.720p.mkv";
        let sib1 = "Show.502.720p.mkv";
        let sib2 = "Show.503.720p.mkv";

        let target_matches = vec![make_match_at(9, 13, Property::ScreenSize, "720p")];
        let sib1_matches = vec![make_match_at(9, 13, Property::ScreenSize, "720p")];
        let sib2_matches = vec![make_match_at(9, 13, Property::ScreenSize, "720p")];

        let report = analyze_invariance(
            &FileAnalysis {
                input: target,
                matches: &target_matches,
            },
            &[
                FileAnalysis {
                    input: sib1,
                    matches: &sib1_matches,
                },
                FileAnalysis {
                    input: sib2,
                    matches: &sib2_matches,
                },
            ],
        );

        assert!(
            !report.episode_signals.is_empty(),
            "should detect 3-digit episode"
        );
        let ep = &report.episode_signals[0];
        assert_eq!(ep.value, 501);
        assert!(ep.is_sequential);
        assert_eq!(ep.digit_count, 3);
    }

    #[test]
    fn no_siblings_empty_report() {
        let target = "Movie.2024.1080p.mkv";
        let matches = vec![make_match_at(11, 16, Property::ScreenSize, "1080p")];

        let report = analyze_invariance(
            &FileAnalysis {
                input: target,
                matches: &matches,
            },
            &[],
        );

        assert!(report.title.is_none());
        assert!(report.year_signals.is_empty());
        assert!(report.episode_signals.is_empty());
    }

    #[test]
    fn invariant_number_not_episode() {
        let target = "Show.42.720p.mkv";
        let sib = "Show.42.1080p.mkv";

        let target_matches = vec![make_match_at(8, 12, Property::ScreenSize, "720p")];
        let sib_matches = vec![make_match_at(8, 13, Property::ScreenSize, "1080p")];

        let report = analyze_invariance(
            &FileAnalysis {
                input: target,
                matches: &target_matches,
            },
            &[FileAnalysis {
                input: sib,
                matches: &sib_matches,
            }],
        );

        assert!(
            report.episode_signals.is_empty(),
            "invariant number should not produce episode signal, got: {:?}",
            report.episode_signals
        );
    }
}