avatarr-parser 0.1.0

Release-name parser ported from Sonarr v4.0.17.2952
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
// Ported from Sonarr v4.0.17.2952 (97e85a90):
//   src/NzbDrone.Core/Parser/Parser.cs — ParseReleaseGroup (lines 908-966)
//
// The release-group pipeline runs on the ORIGINAL un-preprocessed title
// (not the cascade-cleaned `simple_title`). It is called post-cascade by
// `parse_title` and returns the release group as an `Option<String>`.
//
// Pipeline order (Sonarr-faithful):
//   1. Trim + strip file extension
//   2. Apply Chinese-fansub PreSubstitutionRegex (first match wins)
//   3. Strip website prefix + torrent tracker suffix
//   4. Try anime [SubGroup] → return subgroup if matched
//   5. Apply clean-suffix strip (after anime check)
//   6. Try exception groups (25 context-bounded + 9 exact) → return if matched
//   7. Try trailing -GROUP extraction (hand-rolled) → return if matched
//   8. Return None

use once_cell::sync::Lazy;
use regex::Regex;

use crate::normalize;

// ---------------------------------------------------------------------------
// Constants: exception release groups (Sonarr Parser.cs line references)
// ---------------------------------------------------------------------------

/// Parser.cs:573 — 25 release groups that appear in parenthesised/bracketed
/// context (e.g. `(Silence)`, `[Joy]`). Requires a boundary char before and
/// a closing `]` or `)` after.
const EXCEPTION_GROUPS: &[&str] = &[
    "Silence",
    "afm72",
    "Panda",
    "Ghost",
    "MONOLITH",
    "Tigole",
    "Joy",
    "ImE",
    "UTR",
    "t3nzin",
    "Anime Time",
    "Project Angel",
    "Hakata Ramen",
    "HONE",
    "Vyndros",
    "SEV",
    "Garshasp",
    "Kappa",
    "Natty",
    "RCVR",
    "SAMPA",
    "YOGI",
    "r00t",
    "EDGE2020",
    "RZeroX",
];

/// Parser.cs:570 — 9 exact-match release groups that may appear anywhere
/// in the title (no context-boundary requirement beyond `\b`).
const EXCEPTION_EXACT_GROUPS: &[&str] = &[
    "D-Z0N3",
    "Fight-BB",
    "VARYG",
    "E.N.D",
    "KRaLiMaRKo",
    "BluDragon",
    "DarQ",
    "KCRT",
    "BEN THE MEN",
];

/// Regex for exact exception groups. `BEN THE MEN` uses flexible separators
/// (C#: `BEN[_. ]THE[_. ]MEN`); all others are literal.
static EXCEPTION_EXACT_REGEX: Lazy<Regex> = Lazy::new(|| {
    let alts: Vec<String> = EXCEPTION_EXACT_GROUPS
        .iter()
        .map(|&g| {
            if g == "BEN THE MEN" {
                r"BEN[_. ]THE[_. ]MEN".to_string()
            } else {
                regex::escape(g)
            }
        })
        .collect();
    let pattern = format!(r"(?i)(?P<releasegroup>{})\b", alts.join("|"));
    Regex::new(&pattern).expect("EXCEPTION_EXACT_REGEX")
});

/// Parser.cs:563 — invalid release groups (season/episode tag or 8-hex hash).
static INVALID_RELEASE_GROUP_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?i)^([se]\d+|[0-9a-f]{8})$").expect("INVALID_RELEASE_GROUP_REGEX"));

// ---------------------------------------------------------------------------
// Pre-processing regexes (release-group-specific)
// ---------------------------------------------------------------------------

/// Parser.cs:20-57 — Chinese fansub normalization regexes.
/// For release-group extraction, these normalise bracketed anime titles so the
/// `[SubGroup]` regex at step 4 can find the subgroup in the first bracket.
/// Order matters: first match wins (break after).
///
/// C# lookaheads (`(?=...)`) are dropped — Rust regex does not support
/// look-around. The remaining pattern constrains matches sufficiently for
/// release-group extraction (we only need the `[subgroup]` bracket).
static PRE_SUB_REGEXES: Lazy<Vec<(Regex, &'static str)>> = Lazy::new(|| {
    vec![
        // [0] Korean series without season number
        (
            Regex::new(r"\.E(\d{2,4})\.\d{6}\.(.*-NEXT)$").expect("PRE_SUB_0"),
            ".S01E$1.$2",
        ),
        // [1] Chinese anime with English + Chinese titles
        (
            Regex::new(
                r"(?i)^\[(?:(?P<subgroup>[^\]]+?)(?:[\x{4e00}-\x{9fcc}]+)?)\]\[(?P<title>[^\]]+?)(?:\s(?P<chinesetitle>[\x{4e00}-\x{9fcc}][^\]]*?))\]\[(?:(?:[\x{4e00}-\x{9fcc}]+?)?(?P<episode>\d{1,4})(?:[\x{4e00}-\x{9fcc}]+?)?)\]",
            )
            .expect("PRE_SUB_1"),
            "[${subgroup}] ${title} - ${episode} - ",
        ),
        // [2] LoliHouse/ZERO/Lilith-Raws/Skymoon-Raws/orion origin
        (
            Regex::new(
                r"(?i)^\[(?P<subgroup>[^\]]*?(?:LoliHouse|ZERO|Lilith-Raws|Skymoon-Raws|orion origin)[^\]]*?)\](?P<title>[^\[\]]+?)(?:\s-\s(?P<episode>[0-9-]+)\s*|\[\x{7b2c}?(?P<episode2>[0-9]+(?:-[0-9]+)?)\x{8bdd}?(?:END|\x{5b8c})?\])\[",
            )
            .expect("PRE_SUB_2"),
            "[${subgroup}][${title}][${episode}${episode2}][",
        ),
        // [3] Chinese with season number (lookahead dropped)
        (
            Regex::new(
                r"(?i)^\[(?P<subgroup>[^\]]+)\](?:\s?\x{2605}[^\[\s-]+\s?)?\[?(?:(?P<chinesetitle>[^\]]*?)(?:\]\[|\s*[_/\x{00b7}]\s*)){0,2}(?P<title>[^\[\]]+?)(?:\s(?:S?(?:(?:0)(?P<season>\d)|(?P<season2>[1-9]\d))))\]?(?:\[\d{4}\])?\[\x{7b2c}?(?P<episode>[0-9]+(?:-[0-9]+)?)\x{8bdd}?\x{96c6}?(?:\s?END|\x{5b8c}|\s?Fin)?\]",
            )
            .expect("PRE_SUB_3"),
            "[${subgroup}] ${title} S${season}${season2} - ${episode} ",
        ),
        // [4] GM-Team releases (lookahead dropped)
        (
            Regex::new(
                r"(?i)^\[(?P<subgroup>[^\]]+)\](?:(?P<chinesub>\[[^\]]*\])+)\[(?P<title>[^\]]+?)\](?P<junk>\[[^\]]+\])*\[(?P<episode>[0-9]+(?:-[0-9]+)?)(?:\sEND|\sFin)?\]",
            )
            .expect("PRE_SUB_4"),
            "[${subgroup}] ${title} - ${episode} ",
        ),
    ]
});

/// Parser.cs:565 — anime release group: leading `[SubGroup]`
static ANIME_RELEASE_GROUP_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"^\[(?P<subgroup>[^\]]+)\]").expect("ANIME_RELEASE_GROUP_REGEX"));

/// Parser.cs:549 — clean suffixes stripped before the trailing-group search.
/// These are indexer/scene tags appended after the real release group.
static CLEAN_RELEASE_GROUP_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(
        r"(?i)(?:-(RP|1|NZBGeek|Obfuscated|Scrambled|sample|Pre|postbot|xpost|Rakuv[a-z0-9]*|WhiteRev|BUYMORE|AsRequested|AlternativeToRequested|GEROV|Z0iDS3N|Chamele0n|4P|4Planet|AlteZachen|RePACKPOST))+$",
    )
    .expect("CLEAN_RELEASE_GROUP_REGEX")
});

/// Resolution tokens. A candidate that IS one of these, or is followed by one
/// anywhere in the remaining title, gets rejected.
const RESOLUTION_TOKENS: &[&str] = &["480p", "576p", "720p", "1080p", "2160p"];

// ---------------------------------------------------------------------------
// Trailing -GROUP extraction (hand-rolled, step 7)
// ---------------------------------------------------------------------------
//
// Sonarr's ReleaseGroupRegex has two branches (ORed with `|`):
//
// Branch A: `-(?<releasegroup>[a-z0-9]+(?<part2>-[a-z0-9]+)?
//            (?!.+?(?:480p|576p|720p|1080p|2160p)))
//            (?<!(?:WEB-DL|Blu-Ray|480p|576p|720p|1080p|2160p|DTS-HD|
//            DTS-X|DTS-MA|DTS-ES|-ES|-EN|-CAT|[ ._]\d{4}-\d{2}|-\d{2})
//            (?:\k<part2>)?)
//            (?:\b|[-._ ]|$)`
//
// Branch B: `[-._ ]\[(?<releasegroup>[a-z0-9]+)\]$`
//
// Since Rust regex doesn't support lookaround or backreferences, we hand-roll
// the matching with explicit checks.

/// Patterns that, when they appear as the full `PREFIX-GROUP` or
/// `PREFIX-GROUP-PART2` match, indicate a codec/format — not a release group.
const BLACKLIST_FULL: &[&str] = &["WEB-DL", "Blu-Ray", "DTS-HD", "DTS-X", "DTS-MA", "DTS-ES"];

/// Suffixes that, when they are the entire candidate (single segment after a
/// dash), indicate a language/format tag — not a release group.
const BLACKLIST_SINGLE_SEGMENT: &[&str] = &["ES", "EN", "CAT"];

/// A trailing-group candidate found by the scanner.
struct TrailingCandidate {
    /// Position of the leading dash in the title.
    dash_pos: usize,
    /// End of the full candidate (after optional `-part2`).
    full_end: usize,
    /// The candidate text (everything after the leading dash).
    group: String,
}

/// Find all `-GROUP` or `-GROUP-PART2` candidates in the title.
fn find_trailing_group_candidates(title: &str) -> Vec<TrailingCandidate> {
    let mut candidates = Vec::new();
    let bytes = title.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        if bytes[i] == b'-' {
            let group_start = i + 1;
            if group_start >= len {
                break;
            }

            // Consume first segment: [a-zA-Z0-9]+
            let mut j = group_start;
            while j < len && bytes[j].is_ascii_alphanumeric() {
                j += 1;
            }
            if j == group_start {
                i += 1;
                continue;
            }

            let first_end = j;

            // Check for optional second segment: -[a-zA-Z0-9]+
            let mut full_end = first_end;
            if j < len && bytes[j] == b'-' {
                let seg2_start = j + 1;
                let mut k = seg2_start;
                while k < len && bytes[k].is_ascii_alphanumeric() {
                    k += 1;
                }
                if k > seg2_start {
                    full_end = k;
                }
            }

            let group_text = title[group_start..full_end].to_string();
            candidates.push(TrailingCandidate {
                dash_pos: i,
                full_end,
                group: group_text,
            });
            i = full_end;
        } else {
            i += 1;
        }
    }

    candidates
}

/// Check if the character(s) after the candidate constitute a valid boundary.
/// Sonarr requires `(?:\b|[-._ ]|$)` after the group.
///
/// The boundary definition mirrors .NET's `\b`: a transition between `\w`
/// (word char) and `\W` (non-word char). Since our candidate scanner only
/// captures ASCII alphanumeric groups, we need the next character to be
/// a non-word char. Unlike simple `!is_ascii_alphanumeric()`, we treat
/// Unicode alphabetic chars (`ë` = `ë`, etc.) as word chars — matching
/// .NET's `\w` class, which includes accented letters.
fn has_valid_boundary(title: &str, end: usize) -> bool {
    if end >= title.len() {
        return true; // end of string = `$`
    }
    // Get the character at `end`. If it's a word char (alphanumeric or
    // Unicode letter/digit), the boundary fails. Explicit separators
    // `[-._ ]` always count as boundaries.
    let remaining = &title[end..];
    if let Some(ch) = remaining.chars().next() {
        // Explicit separators always pass
        if matches!(ch, '-' | '.' | '_' | ' ') {
            return true;
        }
        // Unicode-aware word char check (mirrors .NET \w)
        // Rejects: accented letters (ë, é, etc.), CJK chars, any
        // Unicode alphabetic/numeric that isn't an ASCII separator.
        if ch.is_alphanumeric() {
            return false;
        }
        // Non-alphanumeric, non-separator: comma, bracket, etc.
        true
    } else {
        true // should not happen if end < len, but defensive
    }
}

/// Check if a resolution token appears anywhere after `pos` in the title.
fn resolution_after(title: &str, pos: usize) -> bool {
    if pos >= title.len() {
        return false;
    }
    let rest = &title[pos..];
    let rest_lower = rest.to_ascii_lowercase();
    RESOLUTION_TOKENS.iter().any(|&r| rest_lower.contains(r))
}

/// Check if the candidate itself IS a resolution token.
fn is_resolution(candidate: &str) -> bool {
    RESOLUTION_TOKENS
        .iter()
        .any(|&r| r.eq_ignore_ascii_case(candidate))
}

/// Check if the `PREFIX-CANDIDATE` context (looking backward from the dash)
/// matches a blacklisted full pattern like `WEB-DL`, `DTS-HD`, etc.
fn context_is_blacklisted(title: &str, candidate: &TrailingCandidate) -> bool {
    let dash_pos = candidate.dash_pos;

    // Scan backward from the dash to find the preceding alphanumeric token
    let mut prefix_start = dash_pos;
    while prefix_start > 0 && title.as_bytes()[prefix_start - 1].is_ascii_alphanumeric() {
        prefix_start -= 1;
    }

    if prefix_start < dash_pos {
        let full_token = &title[prefix_start..candidate.full_end];
        for &bl in BLACKLIST_FULL {
            if bl.eq_ignore_ascii_case(full_token) {
                return true;
            }
        }
    }

    // Single-segment candidates against the single-segment blacklist
    // Sonarr: `-ES`, `-EN`, `-CAT`
    if !candidate.group.contains('-') {
        for &bl in BLACKLIST_SINGLE_SEGMENT {
            if bl.eq_ignore_ascii_case(&candidate.group) {
                return true;
            }
        }
    }

    // Date pattern: `[ ._]\d{4}-\d{2}` — reject YYYY-MM at end.
    // Also catches YYYY-MM-DD when the candidate is MM-DD (2-segment).
    static DATE_PATTERN: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"\d{4}-\d{2}$").expect("DATE_PATTERN"));
    if DATE_PATTERN.is_match(&title[..candidate.full_end]) {
        return true;
    }
    // Check if the full span ending at `full_end` is part of a YYYY-MM-DD
    // sequence where our candidate captured the MM-DD portion.
    static FULL_DATE_PATTERN: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"\d{4}-\d{1,2}-\d{2}$").expect("FULL_DATE_PATTERN"));
    if FULL_DATE_PATTERN.is_match(&title[..candidate.full_end]) {
        return true;
    }

    // Reject bare 2-digit candidates (e.g. `-02` from a date)
    // Sonarr: `-\d{2}` in the lookbehind list
    static TWO_DIGIT: Lazy<Regex> = Lazy::new(|| Regex::new(r"^\d{2}$").expect("TWO_DIGIT"));
    if TWO_DIGIT.is_match(&candidate.group) {
        return true;
    }

    false
}

/// Trailing `[group]` at end of title: `[-._ ]\[([A-Za-z0-9]+)\]$`
static TRAILING_BRACKET_GROUP_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"[-._ ]\[(?P<releasegroup>[a-zA-Z0-9]+)\]$").expect("TRAILING_BRACKET_GROUP_REGEX")
});

// ---------------------------------------------------------------------------
// Exception context-bounded search (step 6)
// ---------------------------------------------------------------------------

/// Regex for the 25 exception groups. Sonarr requires:
///   - lookbehind `(?<=[._ \[])` — char before must be `.`, ` `, `_`, or `[`
///   - lookahead `(?=\]|\))` — char after must be `]` or `)`
///
/// We include the preceding char in the match and extract only the named group.
static EXCEPTION_RELEASE_GROUP_REGEX: Lazy<Regex> = Lazy::new(|| {
    let alts: Vec<String> = EXCEPTION_GROUPS.iter().map(|&g| regex::escape(g)).collect();
    let pattern = format!(r"(?i)[._ \[](?P<releasegroup>{})[)\]]", alts.join("|"));
    Regex::new(&pattern).expect("EXCEPTION_RELEASE_GROUP_REGEX")
});

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Extract the release group from a release title.
///
/// This is a standalone post-cascade function — it operates on the ORIGINAL
/// un-preprocessed title, not the `simple_title` from the regex cascade.
///
/// Returns `None` when no release group is found, the group is purely numeric,
/// or the group matches the invalid-group pattern (e.g. `S01`, hex hashes).
pub fn parse_release_group(title: &str) -> Option<String> {
    // Step 1: Trim + strip file extension
    let title = title.trim();
    if title.is_empty() {
        return None;
    }
    let mut title = normalize::remove_file_extension(title);

    // Step 2: Apply Chinese-fansub PreSubstitutionRegex (first match wins)
    for (re, replacement) in PRE_SUB_REGEXES.iter() {
        if re.is_match(&title) {
            title = re.replace(&title, *replacement).into_owned();
            break;
        }
    }

    // Step 3: Strip website prefix + torrent tracker suffix
    title = crate::episode::regexes::WEBSITE_PREFIX_REGEX
        .replace(&title, "")
        .into_owned();
    title = crate::episode::regexes::CLEAN_TORRENT_SUFFIX_REGEX
        .replace(&title, "")
        .into_owned();

    // Step 4: Try anime [SubGroup]
    if let Some(caps) = ANIME_RELEASE_GROUP_REGEX.captures(&title)
        && let Some(m) = caps.name("subgroup")
    {
        let subgroup = m.as_str().trim();
        if !subgroup.is_empty() {
            return Some(subgroup.to_string());
        }
    }

    // Step 5: Apply clean-suffix strip (AFTER anime check)
    title = CLEAN_RELEASE_GROUP_REGEX.replace(&title, "").into_owned();

    // Step 6a: Try exception groups (context-bounded, 25 entries)
    // Last match wins (Sonarr uses `.OfType<Match>().Last()`)
    let mut last_exception: Option<String> = None;
    for caps in EXCEPTION_RELEASE_GROUP_REGEX.captures_iter(&title) {
        if let Some(m) = caps.name("releasegroup") {
            last_exception = Some(m.as_str().to_string());
        }
    }
    if let Some(group) = last_exception {
        return Some(group);
    }

    // Step 6b: Try exact exception groups (9 entries, no context boundary)
    let mut last_exact: Option<String> = None;
    for caps in EXCEPTION_EXACT_REGEX.captures_iter(&title) {
        if let Some(m) = caps.name("releasegroup") {
            last_exact = Some(m.as_str().to_string());
        }
    }
    if let Some(group) = last_exact {
        return Some(group);
    }

    // Step 7: Try trailing -GROUP extraction (hand-rolled)
    //
    // Two sub-strategies (Sonarr ORs them in one regex):
    //   A) `-GROUP` or `-GROUP-PART2` with validation
    //   B) Trailing `[group]` at end of title

    // Strategy A: find all `-GROUP(-PART2)?` candidates
    let candidates = find_trailing_group_candidates(&title);

    // Iterate from last to first (last valid match wins in Sonarr)
    for candidate in candidates.iter().rev() {
        let group = &candidate.group;

        // Must be followed by a valid boundary
        if !has_valid_boundary(&title, candidate.full_end) {
            continue;
        }

        // Reject if resolution appears anywhere after the candidate
        if resolution_after(&title, candidate.full_end) {
            continue;
        }

        // Reject if the candidate itself is a resolution token
        if is_resolution(group) {
            continue;
        }

        // Reject if the prefix-candidate context matches a blacklisted pattern
        if context_is_blacklisted(&title, candidate) {
            continue;
        }

        // Reject pure numeric groups
        if group.parse::<i64>().is_ok() {
            continue;
        }

        // Reject invalid pattern (S01, E15, 8-char hex)
        if INVALID_RELEASE_GROUP_REGEX.is_match(group) {
            continue;
        }

        return Some(group.clone());
    }

    // Strategy B: trailing `[group]` at end of title
    if let Some(caps) = TRAILING_BRACKET_GROUP_REGEX.captures(&title)
        && let Some(m) = caps.name("releasegroup")
    {
        let group = m.as_str();
        if group.parse::<i64>().is_err() && !INVALID_RELEASE_GROUP_REGEX.is_match(group) {
            return Some(group.to_string());
        }
    }

    // Step 8: No group found
    None
}

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

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

    #[test]
    fn trailing_group_candidate_search() {
        let cases = find_trailing_group_candidates("Series.S01E01.720p.HDTV.x264-LOL");
        assert!(
            cases.iter().any(|c| c.group == "LOL"),
            "should find LOL, got: {:?}",
            cases.iter().map(|c| &c.group).collect::<Vec<_>>()
        );

        let cases2 =
            find_trailing_group_candidates("SomeShow S01E168 1080p WEB-DL AAC 2.0 x264-Erai-raws");
        assert!(
            cases2.iter().any(|c| c.group == "Erai-raws"),
            "should find Erai-raws with hyphen, got: {:?}",
            cases2.iter().map(|c| &c.group).collect::<Vec<_>>()
        );
    }

    #[test]
    fn trailing_group_last_match_wins() {
        let candidates =
            find_trailing_group_candidates("Series-Title.S01E01.720p-FIRST.HDTV-SECOND");
        let last = candidates.last().map(|c| c.group.as_str());
        assert_eq!(last, Some("SECOND"), "last match should win");
    }

    #[test]
    fn invalid_release_group_rejection() {
        assert!(
            INVALID_RELEASE_GROUP_REGEX.is_match("S01"),
            "S01 should be invalid"
        );
        assert!(
            INVALID_RELEASE_GROUP_REGEX.is_match("s02"),
            "s02 should be invalid"
        );
        assert!(
            INVALID_RELEASE_GROUP_REGEX.is_match("E15"),
            "E15 should be invalid"
        );
        assert!(
            INVALID_RELEASE_GROUP_REGEX.is_match("6B7FD717"),
            "8-char hex should be invalid"
        );
        assert!(
            INVALID_RELEASE_GROUP_REGEX.is_match("6b7fd717"),
            "lowercase 8-char hex should be invalid"
        );
        assert!(
            !INVALID_RELEASE_GROUP_REGEX.is_match("LOL"),
            "LOL should be valid"
        );
    }

    #[test]
    fn blacklist_rejection() {
        let title = "Series.S01E01.720p.WEB-DL.x264";
        let candidates = find_trailing_group_candidates(title);
        let dl_candidate = candidates.iter().find(|c| c.group == "DL");
        assert!(dl_candidate.is_some(), "should find -DL candidate");
        assert!(
            context_is_blacklisted(title, dl_candidate.expect("dl candidate")),
            "WEB-DL should be context-blacklisted"
        );

        let title2 = "Series.S01E01.DTS-HD.MA.5.1.x264";
        let candidates2 = find_trailing_group_candidates(title2);
        let hd_candidate = candidates2.iter().find(|c| c.group == "HD");
        assert!(hd_candidate.is_some(), "should find -HD candidate");
        assert!(
            context_is_blacklisted(title2, hd_candidate.expect("hd candidate")),
            "DTS-HD should be context-blacklisted"
        );
    }

    #[test]
    fn resolution_suffix_rejection() {
        // "Series.720p.HDTV.x264-LOL.1080p" — position 25 is '.' after LOL
        // From 25 onward: ".1080p" contains "1080p"
        assert!(
            resolution_after("Series.720p.HDTV.x264-LOL.1080p", 25),
            "should detect 1080p after position 25"
        );
        // "Series.720p.HDTV.x264-LOL" — len=25, no content after
        assert!(
            !resolution_after("Series.720p.HDTV.x264-LOL", 25),
            "no resolution after group at end"
        );
        assert!(is_resolution("1080p"), "1080p should be a resolution");
        assert!(is_resolution("720p"), "720p should be a resolution");
        assert!(!is_resolution("LOL"), "LOL should not be a resolution");
    }
}