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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
// Ported from Sonarr v4.0.17.2952 (97e85a90):
//   src/NzbDrone.Core/Parser/Parser.cs — ParseTitle + ParseMatchCollection

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

use super::ParsedEpisodeInfo;
use super::regexes;
use crate::normalize;

/// Parse a release title for episode/season information.
/// Returns `None` when no regex matches (mirrors Sonarr returning null).
pub fn parse_title(title: &str) -> Option<ParsedEpisodeInfo> {
    let simple_title = normalize::preprocess_title(title)?;

    for entry in regexes::REPORT_TITLE_REGEXES.iter() {
        if let Some(mut info) = try_regex(entry.index, entry.regex, &simple_title) {
            // Post-cascade: populate release_group from original title
            // (Sonarr Parser.cs:787 — ParseReleaseGroup(releaseTitle))
            info.release_group = crate::release_group::parse_release_group(title);

            // Anime subgroup override: if cascade captured <subgroup>,
            // use it instead (Sonarr Parser.cs:789-793)
            if let Some(caps) = entry.regex.captures(&simple_title)
                && let Some(sg) = caps.name("subgroup")
            {
                let sg_val = sg.as_str().trim();
                if !sg_val.is_empty() {
                    info.release_group = Some(sg_val.to_string());
                }
            }

            return Some(info);
        }
    }

    None
}

/// Sonarr `(?!-[a-z]+)` lookahead emulation.
///
/// Returns true when the byte position `end` in `title` is followed by `-`
/// then one or more ASCII lowercase letters. Used to reject absolute episode
/// captures where the number is part of a token like `300-nen` or `100-jin`
/// rather than a true episode number. Returns false when `end >= title.len()`
/// (no panic — `get` returns `None`, the `unwrap_or(&[])` falls through to an
/// empty slice that fails the slice-pattern match).
fn followed_by_hyphen_lowercase_word(title: &str, end: usize) -> bool {
    let after = title.as_bytes().get(end..).unwrap_or(&[]);
    matches!(after, [b'-', rest @ ..] if rest.first().is_some_and(|c| c.is_ascii_lowercase()))
}

/// Sonarr `.Captures.Last()` emulation for broad absolute regexes.
///
/// Returns true when the byte range `[end, ..)` in `title` has the shape
/// ` <words> - \d+` — i.e. one-or-more space-separated alpha-words, then a
/// space-dash-space, then digits. When this matches, the captured absolute
/// episode is *not* the last episode token in the title; the C# engine
/// would have iterated `+` and captured the trailing digits instead.
fn followed_by_word_chain_then_dash_episode(title: &str, end: usize) -> bool {
    static TAIL_RE: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"^\s+[A-Za-z][A-Za-z'\-]*(?:\s+[A-Za-z][A-Za-z'\-]*)*\s*-\s*\d+")
            .expect("TAIL_RE")
    });
    let after = title.get(end..).unwrap_or("");
    TAIL_RE.is_match(after)
}

/// Mask digit runs at the given byte ranges with ASCII 'X'. Preserves byte
/// lengths so capture positions on the masked string align 1:1 with the
/// original — title-text re-slicing therefore needs no offset bookkeeping.
fn mask_digit_ranges(input: &str, ranges: &[(usize, usize)]) -> String {
    let mut out = String::with_capacity(input.len());
    let mut last = 0;
    for &(s, e) in ranges {
        out.push_str(&input[last..s]);
        out.extend(std::iter::repeat_n('X', e - s));
        last = e;
    }
    out.push_str(&input[last..]);
    out
}

fn try_regex(index: u8, regex: &Regex, title: &str) -> Option<ParsedEpisodeInfo> {
    // Sonarr `(?!-[a-z]+)` lookahead emulation via mask-and-retry.
    //
    // For absolute-pattern indices, when the matched `absoluteepisode` capture
    // is followed by `-[a-z]+` (e.g. "300-nen"), mask those digits in a
    // working copy of the title and re-run the regex. This emulates C#'s
    // engine backtracking the absolute quantifier to a later position when
    // the lookahead fails, yielding the trailing real episode number ("02"
    // in `300-nen, ... 02`). Mask preserves byte lengths, so capture
    // byte-positions on the working string align 1:1 with the original;
    // `series_title` is patched post-hoc by re-slicing from the original.
    //
    // Other indices use `regex.captures(title)` directly — non-absolute
    // patterns don't carry `absoluteepisode` captures so the retry would
    // be a no-op, and we'd rather skip the per-call ownership cost.
    let absolute_index = matches!(
        index,
        7 | 8 | 11..=21 | 26 | 28..=32 | 65..=67 | 77 | 81 | 87..=94
    );
    let working: String;
    let title_for_caps: &str = if absolute_index {
        // Iteratively mask digit runs that fail the `(?!-[a-z]+)` lookahead
        // until the regex either no longer matches or matches with a clean
        // absolute capture. MAX_RETRIES caps work cheaply — each iteration
        // strictly reduces the number of digit runs in the working string.
        const MAX_RETRIES: usize = 8;
        let mut current = std::borrow::Cow::Borrowed(title);
        let mut iters = 0;
        loop {
            let caps = regex.captures(current.as_ref())?;
            let bad_ranges: Vec<(usize, usize)> = ["absoluteepisode", "absoluteepisode2"]
                .iter()
                .filter_map(|name| caps.name(name))
                .filter(|m| {
                    followed_by_hyphen_lowercase_word(current.as_ref(), m.end())
                        || followed_by_word_chain_then_dash_episode(current.as_ref(), m.end())
                })
                .map(|m| (m.start(), m.end()))
                .collect();
            if bad_ranges.is_empty() {
                break;
            }
            iters += 1;
            if iters > MAX_RETRIES {
                return None;
            }
            current = std::borrow::Cow::Owned(mask_digit_ranges(current.as_ref(), &bad_ranges));
        }
        match current {
            std::borrow::Cow::Borrowed(s) => s,
            std::borrow::Cow::Owned(s) => {
                working = s;
                working.as_str()
            }
        }
    } else {
        title
    };
    let caps = regex.captures(title_for_caps)?;
    let full_match = caps.get(0)?.as_str();
    // Capture byte ranges align with both `title_for_caps` (for downstream
    // parser fns that read via `caps.name(...).as_str()`) AND with the
    // original `title` (for post-hoc series_title patching). The `original`
    // alias makes that intent explicit at the patch site.
    let original = title;
    // `title` from here forward is the working/masked variant — caps reference
    // it directly. Retain `original` for post-process series_title patching.
    let title = title_for_caps;

    // m53b: opt-in diagnostic for matching-index discovery. Zero cost in
    // release builds when the env var is unset (one syscall per match in
    // debug builds, used during fixture-gap triage).
    #[cfg(debug_assertions)]
    if std::env::var("AVATARR_DEBUG_REGEX_INDEX").is_ok() {
        eprintln!("regex matched: index={index} title={title:?}");
    }

    // Post-match: backreference validation for patterns using dual sep captures.
    // C# `\k<sep>` requires the same separator character in both positions.
    if matches!(index, 0 | 1)
        && let (Some(s1), Some(s2)) = (caps.name("sep1"), caps.name("sep2"))
        && s1.as_str() != s2.as_str()
    {
        return None;
    }

    // Post-match: for REGEX_01 (daily without title), reject if airday is
    // followed by a digit — replaces C# `(?!\d)`.
    if index == 1
        && let Some(m) = caps.name("airday")
        && m.end() < title.len()
        && title.as_bytes()[m.end()].is_ascii_digit()
    {
        return None;
    }

    // Post-match: reject when ep/season captures are embedded in longer numbers.
    // Skip for fused-digit formats, daily-only patterns, and absolute patterns
    // (which use absoluteepisode, not ep/season).
    if !matches!(
        index,
        0 | 1 | 7 | 8 | 10..=21 | 26 | 28..=32 | 34 | 35
            | 45 | 46 | 49 | 65..=68 | 72 | 73 | 76..=82 | 87..=95
    ) {
        for name in ["ep", "ep1", "ep2", "season", "seasonpart"] {
            if let Some(m) = caps.name(name)
                && !normalize::digit_boundary_ok(title, m.start(), m.end())
            {
                return None;
            }
        }
    }

    // Post-match: multi-season pack 43 — reject when season2 capture is
    // adjacent to digits (C# `(?!\d+)` after season2).
    if index == 43 {
        for name in ["season1", "season2"] {
            if let Some(m) = caps.name(name)
                && !normalize::digit_boundary_ok(title, m.start(), m.end())
            {
                return None;
            }
        }
    }

    // Post-match: season-only patterns 70/71 — reject when season number
    // is followed by optional separator + digits.
    // C# uses `(?![-_. ]?\d+)` which we can't express directly in Rust.
    if matches!(index, 70 | 71)
        && let Some(m) = caps.name("season")
    {
        let after = &title[m.end()..];
        let skip_sep = after
            .strip_prefix(|c: char| "-_. ".contains(c))
            .unwrap_or(after);
        if skip_sep.starts_with(|c: char| c.is_ascii_digit()) {
            return None;
        }
    }

    // Post-match: regex 82 (1103/1113 naming) — reject when the episode
    // capture is followed by `\W\d+` or `\W(e|ep|x)\d+` or `)` or `]`.
    // C# negative lookahead: `(?!p|i|\d+|\)|\]|\W\d+|\W(?:e|ep|x)\d+)`
    if index == 82
        && let Some(m) = caps.name("ep")
    {
        static EP82_REJECT_RE: Lazy<Regex> = Lazy::new(|| {
            Regex::new(r"(?i)^(?:[pi]|\d+|[)\]]|\W\d+|\W(?:ep|e|x)\d+)").expect("EP82_REJECT_RE")
        });
        let after = &title[m.end()..];
        if EP82_REJECT_RE.is_match(after) {
            return None;
        }
    }

    // Post-match: regex 75 (4-digit episode with title) — reject when the
    // character before the season capture is preceded by `\d{1,2}-`.
    // C# `(?<![()\[!]|\d{1,2}-)` on the separator prevents `30-04-2024` from
    // being parsed as season=04, episode=2024.
    if index == 75
        && let Some(m) = caps.name("season")
    {
        let before = &title[..m.start()];
        if let Some(prefix) = before.strip_suffix('-')
            && prefix.ends_with(|c: char| c.is_ascii_digit())
        {
            return None;
        }
    }

    // Post-match: REGEX_10 (anime S+E without absolute) — reject when the
    // trailing `[_. ]` is followed by more digits, since that indicates
    // a trailing absolute episode number which REGEX_13 should handle.
    // C# has `(?:[_. ](?!\d+))` — we check the character after the
    // `[_. ]` separator.
    if index == 10
        && let Some(ep_m) = caps.name("episode")
    {
        let after_ep = &title[ep_m.end()..];
        // Skip one separator char and check if digit follows
        if let Some(rest) = after_ep.strip_prefix(|c: char| "-_. ".contains(c))
            && rest.starts_with(|c: char| c.is_ascii_digit())
        {
            return None;
        }
    }

    // Post-match: boundary-check absoluteepisode captures for absolute patterns.
    // Skip for 4-digit absolute (45/46) where adjacent digits are by design.
    // Skip for index 10 (no absoluteepisode group).
    //
    // The Sonarr `(?!-[a-z]+)` lookahead is emulated up-front by the
    // mask-and-retry loop at the top of `try_regex`, so by the time we reach
    // here every absolute capture is guaranteed to NOT be followed by
    // `-[a-z]+`. Only `digit_boundary_ok` remains as a residual check.
    if matches!(
        index,
        7 | 8 | 11..=21 | 26 | 28..=32 | 65..=67 | 77 | 81 | 87..=94
    ) {
        for name in ["absoluteepisode", "absoluteepisode2"] {
            if let Some(m) = caps.name(name)
                && !normalize::digit_boundary_ok(title, m.start(), m.end())
            {
                return None;
            }
        }
    }

    // Post-match: all absolute patterns — reject when the absolute episode
    // number is followed by `:` (it's part of the title, e.g. "Series 100:
    // Bucket List"), because a colon after digits strongly indicates the
    // number is part of the series title, not an episode number.
    if matches!(
        index,
        7 | 8 | 11..=21 | 26 | 28..=32 | 45 | 46 | 65..=67 | 77 | 81 | 87..=94
    ) && let Some(m) = caps.name("absoluteepisode")
        && m.end() < title.len()
        && title.as_bytes()[m.end()] == b':'
    {
        return None;
    }

    let mut result = match index {
        // -- Daily leading-date patterns --
        0 => parse_daily(&caps),
        1 => parse_daily(&caps),

        // -- Anime pattern with subgroup but season+episode only (no absolute) --
        10 => parse_anime_season_episode(&caps),

        // -- Absolute/anime patterns --
        7 | 8 | 11..=21 | 26 | 28..=32 | 45 | 46 | 65..=67 | 77 | 81 | 87..=94 => {
            parse_absolute(&caps, index, title)
        }

        // -- Daily with decomposed date + season/episode --
        33 | 34 => parse_daily_with_episode(&caps),

        // -- TJET wrestling daily --
        35 => parse_daily(&caps),

        // -- Season-only patterns (no episodes) --
        43 => parse_multi_season(&caps),
        44 => parse_partial_season(&caps),
        69..=71 | 96 => parse_season_only(&caps),

        // -- Daily with part --
        49 => parse_daily_with_part(&caps),

        // -- Mini-series: Part One/Two --
        51 => parse_mini_series_word(&caps),

        // -- Mini-series: XofY, Part N --
        47 | 50 | 52 => parse_mini_series_part(&caps),

        // -- Mini-series: E1-E2 --
        48 => parse_mini_dual(&caps),

        // -- Japanese variety shows: 2-digit year, handled as standard episode --
        // C# treats airYear < 1900 as standard (not daily), defaults season=1.
        68 => parse_generic(&caps, full_match, index, original),

        // -- Spanish Cap.xxx (season+ep fused) --
        72 => parse_spanish_cap(&caps, full_match),

        // -- Short format 103/113 --
        73 => parse_short_format(&caps, full_match),

        // -- Main daily (YYYY.MM.DD) --
        76 => parse_daily(&caps),

        // -- Ambiguous dates --
        78 | 79 => parse_ambiguous_date(&caps),

        // -- Compact YYYYMMDD --
        80 => parse_daily(&caps),

        // -- 4-digit short 1103/1113 --
        82 => parse_four_digit_short(&caps),

        // -- Terrible multi: extant.10708 --
        95 => parse_terrible_multi(&caps),

        // -- Patterns with explicit ep1/ep2 named groups --
        27 | 36..=38 | 64 | 83 => parse_explicit_dual(&caps, index, original),

        // -- Standard patterns using generic extraction --
        _ => parse_generic(&caps, full_match, index, original),
    }?;

    // Mask-and-retry post-process: when the working `title` differs from the
    // `original` (we ran the regex against masked digits), `series_title`
    // contains the masked text. Re-slice the title-capture's byte range from
    // `original` and re-run the same `clean_series_title` normalisation so
    // the masked 'X's are replaced with the real digits the parser saw.
    //
    // Byte positions align across `title` and `original` because masking
    // preserves byte lengths (ASCII digit → ASCII 'X', 1 byte → 1 byte).
    if title.as_ptr() != original.as_ptr()
        && let Some(m) = caps.name("title")
    {
        result.series_title = normalize::clean_series_title(&original[m.start()..m.end()]);
    }
    Some(result)
}

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

fn cap_i32(caps: &regex::Captures, name: &str) -> Option<i32> {
    caps.name(name)?.as_str().parse::<i32>().ok()
}

fn cap_str<'a>(caps: &'a regex::Captures, name: &str) -> Option<&'a str> {
    Some(caps.name(name)?.as_str())
}

fn title_from_caps(caps: &regex::Captures) -> String {
    normalize::clean_series_title(cap_str(caps, "title").unwrap_or(""))
}

fn word_to_number(word: &str) -> Option<i32> {
    match word.to_ascii_lowercase().as_str() {
        "one" => Some(1),
        "two" => Some(2),
        "three" => Some(3),
        "four" => Some(4),
        "five" => Some(5),
        "six" => Some(6),
        "seven" => Some(7),
        "eight" => Some(8),
        "nine" => Some(9),
        _ => None,
    }
}

fn episode_range(first: i32, last: i32) -> Vec<i32> {
    if first > last {
        return Vec::new();
    }
    (first..=last).collect()
}

/// Extract ALL episode numbers from the full regex match string.
static EPISODE_SCAN_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?i)(?:Episode\s+|[Ee][Pp]?|[Xx])(\d{1,5})").expect("EPISODE_SCAN_RE")
});

/// Matches bare numbers after dashes (for range continuations like E03-04-05).
static DASH_CONTINUATION_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"[-_](\d{1,5})").expect("DASH_CONTINUATION_RE"));

fn extract_episodes_from_match(matched: &str) -> Vec<i32> {
    let mut eps: Vec<i32> = Vec::new();
    let mut last_ep_end: usize = 0;

    for cap in EPISODE_SCAN_RE.captures_iter(matched) {
        if let Ok(n) = cap[1].parse::<i32>()
            && !eps.contains(&n)
        {
            eps.push(n);
        }
        if let Some(m) = cap.get(0) {
            last_ep_end = m.end();
        }
    }

    if !eps.is_empty() {
        let mut pos = last_ep_end;
        while pos < matched.len() {
            let remaining = &matched[pos..];
            match DASH_CONTINUATION_RE.find(remaining) {
                Some(dm) if dm.start() == 0 => {
                    if let Some(dcap) = DASH_CONTINUATION_RE.captures(remaining)
                        && let Ok(n) = dcap[1].parse::<i32>()
                        && !eps.contains(&n)
                    {
                        eps.push(n);
                    }
                    pos += dm.end();
                }
                _ => break,
            }
        }
    }

    // Sonarr range expansion: first..=last
    if eps.len() >= 2 {
        let first = eps[0];
        let last = *eps.last().unwrap();
        if last > first && (last - first + 1) as usize > eps.len() && (last - first) < 100 {
            eps = episode_range(first, last);
        }
    }

    eps
}

/// Extract season from matched text, looking for S## or ##x patterns.
static SEASON_SCAN_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?i)(?:S(\d{1,4})|(\d{1,4})x)").expect("SEASON_SCAN_RE"));

fn extract_season_from_match(matched: &str) -> Option<i32> {
    let cap = SEASON_SCAN_RE.captures(matched)?;
    if let Some(m) = cap.get(1) {
        return m.as_str().parse().ok();
    }
    if let Some(m) = cap.get(2) {
        return m.as_str().parse().ok();
    }
    None
}

// ---------------------------------------------------------------------------
// Generic episode extraction
// ---------------------------------------------------------------------------

fn parse_generic(
    caps: &regex::Captures,
    full_match: &str,
    index: u8,
    input: &str,
) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);

    let season = cap_i32(caps, "season");
    let ep = cap_i32(caps, "ep");
    let ep1 = cap_i32(caps, "ep1");
    let ep2 = cap_i32(caps, "ep2");

    let season_number = match season {
        Some(s) => s,
        None => {
            if index <= 6 || index == 97 {
                extract_season_from_match(full_match)?
            } else {
                1
            }
        }
    };

    let episodes = if let Some(e) = ep {
        let re_scanned = extract_episodes_from_match(full_match);
        if re_scanned.len() > 1 {
            re_scanned
        } else {
            vec![e]
        }
    } else if let Some(e1) = ep1 {
        if let Some(e2) = ep2 {
            let range = episode_range(e1, e2);
            if range.is_empty() {
                return None;
            }
            range
        } else {
            vec![e1]
        }
    } else {
        let scanned = extract_episodes_from_match(full_match);
        if scanned.is_empty() {
            return None;
        }
        scanned
    };

    let is_split = cap_str(caps, "splitepisode").is_some();
    let special = cap_str(caps, "special").is_some();

    let mut info = ParsedEpisodeInfo {
        series_title: title,
        season_number,
        episode_numbers: episodes,
        is_split_episode: is_split,
        special,
        ..Default::default()
    };

    // m53b Failure 5: same tail-enrichment as parse_explicit_dual, gated on a
    // multi-episode standard match. Index 25 (the F5 fixture's matching
    // cascade index) routes here via the catch-all `_` arm in try_regex.
    if info.episode_numbers.len() >= 2
        && let Some(scan_start) = absolute_scan_start(caps)
        && let Some(abs_range) =
            enrich_absolute_from_tail(input, scan_start, info.episode_numbers.len())
    {
        info.absolute_episode_numbers = abs_range;
    }

    Some(info)
}

// ---------------------------------------------------------------------------
// Specialized parsers
// ---------------------------------------------------------------------------

fn parse_explicit_dual(
    caps: &regex::Captures,
    index: u8,
    input: &str,
) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let season = cap_i32(caps, "season")?;
    let ep1 = cap_i32(caps, "ep1")?;
    let ep2 = cap_i32(caps, "ep2");

    let episodes = if let Some(e2) = ep2 {
        episode_range(ep1, e2)
    } else {
        vec![ep1]
    };

    if episodes.is_empty() {
        return None;
    }

    let full_season = if index == 36 {
        if let (Some(count), Some(&last)) = (cap_i32(caps, "episodecount"), episodes.last()) {
            last == count
        } else {
            false
        }
    } else {
        false
    };

    let mut info = ParsedEpisodeInfo {
        series_title: title,
        season_number: season,
        episode_numbers: if full_season { vec![] } else { episodes },
        full_season,
        ..Default::default()
    };

    // m53b Failure 5: tail-enrichment when the standard match has multi-episode
    // semantics and the input continues with a length-matched absolute chain.
    // Scan from after the LAST captured ep (ep2 if present, else ep1) so the
    // chain we find is between the standard episode tokens and any trailing
    // brackets/quality.
    if info.episode_numbers.len() >= 2
        && let Some(scan_start) = absolute_scan_start(caps)
        && let Some(abs_range) =
            enrich_absolute_from_tail(input, scan_start, info.episode_numbers.len())
    {
        info.absolute_episode_numbers = abs_range;
    }

    Some(info)
}

fn parse_multi_season(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let s1 = cap_i32(caps, "season1")?;
    let s2 = cap_i32(caps, "season2")?;

    if s1 < 1 || s2 <= s1 {
        return None;
    }

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: s1,
        full_season: true,
        is_multi_season: true,
        ..Default::default()
    })
}

fn parse_partial_season(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let season = cap_i32(caps, "season")?;
    let season_part = cap_i32(caps, "seasonpart").unwrap_or(0);

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: season,
        is_partial_season: true,
        season_part,
        ..Default::default()
    })
}

fn parse_season_only(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let season = cap_i32(caps, "season")?;
    let extras = cap_str(caps, "extras");

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: season,
        full_season: extras.is_none(),
        is_season_extra: extras.is_some(),
        ..Default::default()
    })
}

fn parse_mini_series_part(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let ep = cap_i32(caps, "ep")?;

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: 1,
        episode_numbers: vec![ep],
        ..Default::default()
    })
}

fn parse_mini_series_word(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let word = cap_str(caps, "ep")?;
    let ep = word_to_number(word)?;

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: 1,
        episode_numbers: vec![ep],
        ..Default::default()
    })
}

fn parse_mini_dual(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let ep1 = cap_i32(caps, "ep1")?;
    let ep2 = cap_i32(caps, "ep2");

    let episodes = if let Some(e2) = ep2 {
        episode_range(ep1, e2)
    } else {
        vec![ep1]
    };

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: 1,
        episode_numbers: episodes,
        ..Default::default()
    })
}

fn parse_spanish_cap(caps: &regex::Captures, full_match: &str) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let season = cap_i32(caps, "season")?;
    let ep = cap_i32(caps, "ep")?;

    static CAP_RANGE_RE: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)Cap[_. ]+(\d{1,2})(\d{2})[_](\d{1,2})(\d{2})").expect("CAP_RANGE")
    });

    if let Some(range_caps) = CAP_RANGE_RE.captures(full_match) {
        let s1: i32 = range_caps[1].parse().ok()?;
        let e1: i32 = range_caps[2].parse().ok()?;
        let _s2: i32 = range_caps[3].parse().ok()?;
        let e2: i32 = range_caps[4].parse().ok()?;
        return Some(ParsedEpisodeInfo {
            series_title: title,
            season_number: s1,
            episode_numbers: episode_range(e1, e2),
            ..Default::default()
        });
    }

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: season,
        episode_numbers: vec![ep],
        ..Default::default()
    })
}

static SHORT_FORMAT_SCAN_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"([1-9])([1-9][0-9]|0[1-9])").expect("SHORT_FORMAT_SCAN"));

fn parse_short_format(caps: &regex::Captures, full_match: &str) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let title_end = caps.name("title").map(|m| m.end()).unwrap_or(0);
    let numbers_text = &full_match[title_end..];

    let mut season: Option<i32> = None;
    let mut episodes = Vec::new();

    for scan_cap in SHORT_FORMAT_SCAN_RE.captures_iter(numbers_text) {
        let s: i32 = scan_cap[1].parse().ok()?;
        let e: i32 = scan_cap[2].parse().ok()?;
        if season.is_none() {
            season = Some(s);
        }
        if season == Some(s) && !episodes.contains(&e) {
            episodes.push(e);
        }
    }

    if episodes.is_empty() {
        return None;
    }

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: season?,
        episode_numbers: episodes,
        ..Default::default()
    })
}

fn parse_four_digit_short(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let season = cap_i32(caps, "season")?;
    let ep = cap_i32(caps, "ep")?;

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: season,
        episode_numbers: vec![ep],
        ..Default::default()
    })
}

fn parse_terrible_multi(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let season = cap_i32(caps, "season").unwrap_or(0);
    let ep1 = cap_i32(caps, "ep1")?;
    let ep2 = cap_i32(caps, "ep2")?;

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: season,
        episode_numbers: vec![ep1, ep2],
        ..Default::default()
    })
}

// ---------------------------------------------------------------------------
// Daily episode parsers (m53 Phase 1)
// ---------------------------------------------------------------------------

/// Parse a daily episode with explicit `airyear`, `airmonth`, `airday` groups.
///
/// Sonarr Parser.cs:1196-1201: swaps day and month if month > 12 ("scene fail").
fn parse_daily(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let year = cap_i32(caps, "airyear")?;
    let mut month = cap_i32(caps, "airmonth")?;
    let mut day = cap_i32(caps, "airday")?;

    // Sonarr: swap day and month if month > 12 (scene fail)
    if month > 12 {
        std::mem::swap(&mut month, &mut day);
    }

    Some(ParsedEpisodeInfo {
        series_title: title,
        air_year: year,
        air_month: month,
        air_day: day,
        ..Default::default()
    })
}

/// Parse daily with decomposed airdate AND season/episode captures.
/// Sonarr indices 33 and 34: populate both airdate fields and season/episode.
fn parse_daily_with_episode(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let year = cap_i32(caps, "airyear")?;
    let mut month = cap_i32(caps, "airmonth")?;
    let mut day = cap_i32(caps, "airday")?;
    let season = cap_i32(caps, "season").unwrap_or(0);
    let ep = cap_i32(caps, "ep")
        .or_else(|| cap_i32(caps, "episode"))
        .unwrap_or(0);

    if month > 12 {
        std::mem::swap(&mut month, &mut day);
    }

    Some(ParsedEpisodeInfo {
        series_title: title,
        air_year: year,
        air_month: month,
        air_day: day,
        season_number: season,
        episode_numbers: if ep > 0 { vec![ep] } else { Vec::new() },
        ..Default::default()
    })
}

/// Parse daily with Part number (index 49).
fn parse_daily_with_part(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let year = cap_i32(caps, "airyear")?;
    let mut month = cap_i32(caps, "airmonth")?;
    let mut day = cap_i32(caps, "airday")?;
    let part = cap_i32(caps, "part")?;

    if month > 12 {
        std::mem::swap(&mut month, &mut day);
    }

    Some(ParsedEpisodeInfo {
        series_title: title,
        air_year: year,
        air_month: month,
        air_day: day,
        daily_part: Some(part),
        ..Default::default()
    })
}

/// Parse ambiguous date (index 78 = US MM.DD.YYYY, index 79 = UK DD.MM.YYYY).
///
/// Sonarr disambiguation logic: if BOTH `ambiguousairmonth` and `ambiguousairday`
/// are <= 12, it's truly ambiguous — cannot determine which is month vs day,
/// so return None. If one is > 12, swap to make it valid.
fn parse_ambiguous_date(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let year = cap_i32(caps, "airyear")?;
    let raw_month = cap_i32(caps, "ambiguousairmonth")?;
    let raw_day = cap_i32(caps, "ambiguousairday")?;

    let (month, day) = disambiguate_date(raw_month, raw_day)?;

    Some(ParsedEpisodeInfo {
        series_title: title,
        air_year: year,
        air_month: month,
        air_day: day,
        ..Default::default()
    })
}

/// Sonarr disambiguation: if both values <= 12, it's ambiguous (None).
/// If month > 12, swap — it must be the day.
/// If day > 12, keep as-is — it's definitely a day.
fn disambiguate_date(raw_month: i32, raw_day: i32) -> Option<(i32, i32)> {
    if raw_month > 12 {
        // Month value too large to be a month — must be the day. Swap.
        Some((raw_day, raw_month))
    } else if raw_day > 12 {
        // Day is unambiguously a day, month is unambiguously a month.
        Some((raw_month, raw_day))
    } else {
        // Both <= 12 — truly ambiguous, cannot determine.
        None
    }
}

// ---------------------------------------------------------------------------
// Absolute/anime episode parser (m53)
// ---------------------------------------------------------------------------

/// Parse anime pattern with subgroup, season, and episode but no absolute number (index 10).
fn parse_anime_season_episode(caps: &regex::Captures) -> Option<ParsedEpisodeInfo> {
    let title = title_from_caps(caps);
    let season = cap_i32(caps, "season")?;
    let ep = cap_i32(caps, "episode")?;
    let release_hash = extract_hash(caps);

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number: season,
        episode_numbers: vec![ep],
        release_hash,
        ..Default::default()
    })
}

/// Parse an absolute-episode capture string. Handles decimal episodes:
/// integer -> returns the integer; decimal (07.5) -> truncates, sets special flag.
fn parse_absolute_number(s: &str) -> Option<(i32, bool)> {
    if let Some(dot_pos) = s.find('.') {
        let int_part = &s[..dot_pos];
        let n: i32 = int_part.parse().ok()?;
        Some((n, true))
    } else {
        let n: i32 = s.parse().ok()?;
        Some((n, false))
    }
}

/// Extract release hash from `<hash>` capture. Strips brackets/parens.
fn extract_hash(caps: &regex::Captures) -> Option<String> {
    let raw = cap_str(caps, "hash")?;
    let trimmed = raw
        .trim_start_matches(['[', '('])
        .trim_end_matches([']', ')']);
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Look backward from the `absoluteepisode` capture position in the original
/// input to find the FIRST number in a dash-separated range chain.
///
/// Scans recursively backward through patterns like `NNN-NNN-NNN-` to find
/// the leftmost number, which is the range start. The captured number is
/// the range end.
///
/// Returns `Some(first)` if a valid range start was found, `None` otherwise.
fn find_range_start(caps: &regex::Captures, abs_start: usize, abs_ep: i32) -> Option<i32> {
    let full_match = caps.get(0)?;
    let title_end = caps.name("title").map(|m| m.end()).unwrap_or(0);

    if abs_start <= title_end {
        return None;
    }

    let between = full_match.as_str().get(
        title_end.saturating_sub(full_match.start())..abs_start.saturating_sub(full_match.start()),
    )?;

    // Look for a dash-separated number chain ending at the capture position.
    // The chain must be contiguous: only dash/underscore (or space-dash-space)
    // separators between numbers (no words, parens, or other text). This
    // prevents false matches from "(Season 2) - 33" being treated as a range
    // start.
    //
    // Walk backward from the end of `between` to find the start of the chain.
    static TRAILING_CHAIN_RE: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(?:(\d{1,4})(?:[-_]| - ))+$").expect("TRAILING_CHAIN_RE"));

    // The text must end with "NNN-" (number + dash) to form a range.
    // Extract the FIRST number in the contiguous dash chain.
    let m = TRAILING_CHAIN_RE.find(between)?;
    let chain = &between[m.start()..];

    // Extract all numbers from the chain
    static CHAIN_NUM_RE: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(\d{1,4})").expect("CHAIN_NUM_RE"));

    let mut first: Option<i32> = None;
    for cap in CHAIN_NUM_RE.captures_iter(chain) {
        if let Ok(n) = cap[1].parse::<i32>()
            && n < abs_ep
            && first.is_none()
        {
            first = Some(n);
        }
    }

    first
}

/// Detect a Sonarr-style batch range (`0NN - NNN`) where the first number
/// was absorbed into the title's lazy capture (e.g. REGEX_18's `[^-]+?`
/// consuming `01` in `Some Anime Show 01 - 119`).
///
/// Returns `Some((first, trim_at))` where `first` is the leading episode
/// number and `trim_at` is the byte offset (in the original input) where
/// the title should be truncated.
///
/// Returns `None` when:
/// - The captured title doesn't end with ` 0N` (a leading-zero 2+ digit
///   number after whitespace — the leading zero distinguishes an episode
///   token from a sequel/season number like `Series Title 21`).
/// - The gap between title.end and abs.start isn't exactly ` - `.
///
/// The leading-zero requirement matches Sonarr's
/// `(?<!\b[0]\d+) - ` lookbehind family — without a leading zero on the
/// first number, the engine refuses to treat it as a range start.
fn find_batch_range_in_title(
    caps: &regex::Captures,
    abs_start: usize,
    abs_ep: i32,
    input: &str,
) -> Option<(i32, usize)> {
    let title_match = caps.name("title")?;
    let title_start = title_match.start();
    let title_end = title_match.end();

    // Gap between title.end and abs.start must be exactly ` - ` (the
    // space-dash-space separator marks an explicit batch shape — Sonarr's
    // repeated `(?:[-_. ]?(?P<absoluteepisode>\d{2,3}))+` capturing both
    // numbers via `.First()`/`.Last()`).
    let gap = input.get(title_end..abs_start)?;
    if gap != " - " {
        return None;
    }

    // Title must end with whitespace + leading-zero number (`0N`, `0NN`,
    // `0NNN`). The leading zero is what signals "episode token", not
    // "sequel number" — `Series Title 21 - 101` is title=`Series Title 21`
    // ep=101, not range [21..101].
    static TITLE_TAIL_RE: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(?:^|\s)(0\d{1,3})\s*$").expect("TITLE_TAIL_RE"));
    let title_text = input.get(title_start..title_end)?;
    let m = TITLE_TAIL_RE.captures(title_text)?;
    let num = m.get(1)?;
    let first: i32 = num.as_str().parse().ok()?;
    if first >= abs_ep || first <= 0 {
        return None;
    }
    // Position where the chain head digit begins (relative to input).
    let trim_at = title_start + num.start();
    Some((first, trim_at))
}

/// Look forward from the `absoluteepisode` capture end position in the
/// original input for a dash-separated following number that forms a range
/// end. Scans for patterns like `-NNN` or ` - NNN` immediately after.
fn find_range_end(input: &str, abs_end: usize, _abs_ep: i32) -> Option<i32> {
    if abs_end >= input.len() {
        return None;
    }

    let after = &input[abs_end..];

    // Match: optional whitespace, dash, optional whitespace, digits
    // Also match multiple dash-separated numbers and take the last
    static RANGE_END_RE: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"^(?:[-_. ]+(\d{1,4}))+").expect("RANGE_END_RE"));

    let m = RANGE_END_RE.captures(after)?;
    // The `+` repetition keeps the LAST capture
    let n: i32 = m[1].parse().ok()?;
    Some(n)
}

/// When a broad absolute regex captured `title=X` and `absoluteepisode=N`,
/// check the original `input` for a `<year>` token between the title's end
/// and the absolute's start. Returns `<title> <year>` if exactly one
/// 4-digit year separates them; otherwise returns the title unchanged.
fn reattach_trailing_year(
    caps: &regex::Captures,
    title: String,
    abs_ep: i32,
    input: &str,
) -> String {
    if !(1..=999).contains(&abs_ep) {
        return title;
    }
    let title_end = match caps.name("title") {
        Some(m) => m.end(),
        None => return title,
    };
    let abs_start = match caps.name("absoluteepisode") {
        Some(m) => m.start(),
        None => return title,
    };
    let between = match input.get(title_end..abs_start) {
        Some(s) => s,
        None => return title,
    };
    static YEAR_BETWEEN_RE: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"^[ ._-](?P<year>(?:19|20)\d{2})[ ._-]$").expect("YEAR_BETWEEN_RE")
    });
    match YEAR_BETWEEN_RE.captures(between) {
        Some(c) => format!("{title} {}", &c["year"]),
        None => title,
    }
}

/// Compute the byte offset to start scanning for a trailing absolute
/// chain after a standard match. Prefers the LAST captured ep position
/// (`ep2` if present, else `ep1`, else `ep`) so the scan window starts
/// after the standard episode tokens. Returns None when no episode
/// capture is present (callers should not invoke the post-handler).
fn absolute_scan_start(caps: &regex::Captures) -> Option<usize> {
    if let Some(m) = caps.name("ep2") {
        return Some(m.end());
    }
    if let Some(m) = caps.name("ep1") {
        return Some(m.end());
    }
    if let Some(m) = caps.name("ep") {
        return Some(m.end());
    }
    None
}

/// Post-handler: when a standard regex matched and produced
/// `episode_numbers` of length N, scan the input starting from
/// `scan_start` (typically the position immediately after the standard
/// match's last `ep`-style capture, or after the chain it consumed) for
/// an absolute-range chain. Accept the chain ONLY when its length
/// equals N (the length-match precondition).
///
/// Sonarr-equivalent: composite indices capture both standard and
/// absolute groups simultaneously via repeated named groups in the SAME
/// regex. Where the standard match succeeded against a non-composite
/// regex but the input has a parallel absolute chain, we recover it
/// post-match. The length-match precondition emulates the C# .NET
/// regex behaviour where `(?<absoluteepisode>...)+` and
/// `(?<episode>...)+` repetitions in the same composite regex always
/// yield equal-length capture collections by construction.
///
/// Accepts both parenthesized `(NNN-NNN[-NNN]*)` and dash-prefixed
/// ` - NNN-NNN[-NNN]*` tail shapes — fixtures use both forms.
///
/// Note: regex 25 (`S01E01.+?\[.+?\]`) absorbs through `[RlsGrp]`, so
/// the post-match tail is empty. We instead scan from after the `ep`
/// capture (its trailing chain consumption is bounded by the lazy `.+?`
/// before `\[`), which is guaranteed to lie inside the full match for
/// every dispatched index. The first `(NNN-NNN)` or ` - NNN-NNN` chain
/// encountered in that span is the absolute range; the regex's
/// non-greedy `.+?` ensures at most one such chain appears between the
/// `ep` capture and the closing `\[...]`.
fn enrich_absolute_from_tail(
    input: &str,
    scan_start: usize,
    expected_len: usize,
) -> Option<Vec<i32>> {
    if expected_len < 2 || scan_start >= input.len() {
        return None;
    }
    let tail = &input[scan_start..];

    // Find the FIRST occurrence of a parenthesized or dash-prefixed
    // chain anywhere in the scan window. The lazy `.+?` in the calling
    // regex bounds where this chain can land relative to the literal
    // bracket terminator, so we don't need to worry about picking up a
    // chain after `[RlsGrp]`.
    // Paren form: `(NNN-NNN[-NNN]*)` — closing `)` is its own boundary.
    // Dash form:  ` - NNN-NNN[-NNN]*` — explicit `\b` after the chain
    // prevents picking up partial chains embedded in longer numeric runs.
    static TAIL_RANGE_RE: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
            r"(?:\((?P<paren>\d{1,4}(?:-\d{1,4})+)\)|\s-\s*(?P<dash>\d{1,4}(?:-\d{1,4})+)\b)",
        )
        .expect("TAIL_RANGE_RE")
    });
    let m = TAIL_RANGE_RE.captures(tail)?;
    let chain = m.name("paren").or_else(|| m.name("dash"))?.as_str();

    let nums: Vec<i32> = chain.split('-').filter_map(|s| s.parse().ok()).collect();

    // Length-match precondition: chain must align with the standard match's
    // episode_numbers count. Rejects stray double-pairs in single-episode tails.
    if nums.len() != expected_len {
        return None;
    }

    let lo = *nums.first()?;
    let hi = *nums.last()?;
    if lo <= 0 || hi <= lo || (hi - lo) >= 100 {
        return None;
    }
    Some(episode_range(lo, hi))
}

/// Parse absolute (anime) episode patterns.
fn parse_absolute(caps: &regex::Captures, index: u8, input: &str) -> Option<ParsedEpisodeInfo> {
    let mut title = title_from_caps(caps);

    let abs_str = cap_str(caps, "absoluteepisode")?;
    let (abs_ep, mut is_special) = parse_absolute_number(abs_str)?;

    // Reject episode 0 -- not a valid absolute episode
    if abs_ep <= 0 && !matches!(index, 45 | 46) {
        return None;
    }

    if cap_str(caps, "special").is_some() {
        is_special = true;
    }

    // m53b Failure 1: when the matched broad absolute regex (87..=94) leaves
    // a 4-digit year between the captured title and the captured absolute,
    // re-attach the year as part of the title. C# Sonarr's lazy/greedy
    // interplay handles this implicitly via .Captures iteration; we patch it
    // post-match.
    title = if matches!(index, 87..=94) {
        reattach_trailing_year(caps, title, abs_ep, input)
    } else {
        title
    };

    let mut absolute_episodes = vec![abs_ep];

    // Handle dual absoluteepisode captures (batch ranges)
    if let Some(abs2_str) = cap_str(caps, "absoluteepisode2")
        && let Some((abs_ep2, special2)) = parse_absolute_number(abs2_str)
    {
        if special2 {
            is_special = true;
        }
        if abs_ep2 > abs_ep && (abs_ep2 - abs_ep) < 100 {
            absolute_episodes = episode_range(abs_ep, abs_ep2);

            // Bidirectional chain extension: even with a dual capture, the
            // chain may extend further in either direction. REGEX_90's
            // `(?P<absoluteepisode>\d{1,2})-(?P<absoluteepisode2>\d{1,2})`
            // anchors on only the first two digits of `01-02-03`; the
            // trailing `03` is consumed by `.*?` and lost. Run forward and
            // backward scanners to recover the full chain.
            let abs1_match = caps.name("absoluteepisode");
            let abs2_match = caps.name("absoluteepisode2");
            let backward = abs1_match
                .and_then(|m| find_range_start(caps, m.start(), abs_ep))
                .filter(|&n| n < abs_ep);
            let forward = abs2_match
                .and_then(|m| find_range_end(input, m.end(), abs_ep2))
                .filter(|&n| n > abs_ep2);
            let lo = backward.unwrap_or(abs_ep);
            let hi = forward.unwrap_or(abs_ep2);
            if lo < hi && (hi - lo) < 100 {
                absolute_episodes = episode_range(lo, hi);
            }
        } else if abs_ep2 != abs_ep {
            absolute_episodes.push(abs_ep2);
        }
    } else if absolute_episodes.len() == 1 {
        // No explicit absoluteepisode2: check the original input text for a
        // range pattern (NNN-NNN or NNN - NNN) around the captured absolute
        // episode number. This handles the C# repeating capture semantics
        // where Sonarr takes .First() and .Last() from all repetitions.
        if let Some(abs_match) = caps.name("absoluteepisode") {
            // Run BOTH directional scanners and take the union. The captured
            // absolute may be an interior element of a chain (`01-02-03`
            // captures `02` as the regex repetition's last successful
            // iteration); only running one direction would miss the other
            // half of the chain.
            let backward = find_range_start(caps, abs_match.start(), abs_ep);
            let forward = find_range_end(input, abs_match.end(), abs_ep);
            let backward_ok = backward.filter(|&n| n < abs_ep);
            let forward_ok = forward.filter(|&n| n > abs_ep);

            match (backward_ok, forward_ok) {
                (Some(first), Some(last)) => {
                    // Both directions yielded a chain — union into [first..=last].
                    if (last - first) < 100 {
                        absolute_episodes = episode_range(first, last);
                    }
                }
                (Some(first), None) => {
                    // Backward only — chain `NN-abs` (e.g. `01-02`).
                    if (abs_ep - first) < 100 {
                        absolute_episodes = episode_range(first, abs_ep);
                    }
                }
                (None, Some(last)) => {
                    // Forward only — chain `abs-NN` (e.g. `01-02`).
                    if (last - abs_ep) < 100 {
                        absolute_episodes = episode_range(abs_ep, last);
                    }
                }
                (None, None) => {
                    // Neither directional scan caught a chain — fall back to
                    // Task 3's title-absorbed batch detection. Did the title's
                    // lazy capture absorb the chain head digit (REGEX_18
                    // `[^-]+?` etc.)? Handles batch shapes like
                    // `Title NNN - NNN` where the gap is exactly ` - ` and
                    // the leading number was pulled into title.
                    if let Some((first, trim_at)) =
                        find_batch_range_in_title(caps, abs_match.start(), abs_ep, input)
                    {
                        absolute_episodes = episode_range(first, abs_ep);
                        let title_start = caps.name("title").map(|m| m.start()).unwrap_or(0);
                        title = normalize::clean_series_title(&input[title_start..trim_at]);
                    }
                }
            }
        }
    }

    // Composite patterns carry season+episode alongside absolute
    let season_number = match index {
        7 | 8 | 11..=15 | 26 => cap_i32(caps, "season").unwrap_or(0),
        _ => 0,
    };
    let episode_numbers = match index {
        7 | 8 | 11..=13 | 26 => {
            if let Some(ep) = cap_i32(caps, "episode") {
                vec![ep]
            } else {
                Vec::new()
            }
        }
        _ => Vec::new(),
    };

    let release_hash = extract_hash(caps);

    Some(ParsedEpisodeInfo {
        series_title: title,
        season_number,
        episode_numbers,
        absolute_episode_numbers: absolute_episodes,
        special: is_special,
        release_hash,
        ..Default::default()
    })
}

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

    #[test]
    fn rejects_absolute_capture_followed_by_hyphen_lowercase_word() {
        // Sonarr Parser.cs:138 — `(?!-[a-z]+)` lookahead drops "300-nen" so the
        // cascade falls through to a later regex that captures "02".
        let input =
            "[Chihiro] Anime Title 300-nen, With Even More Title 02 [720p Hi10P AAC][031FA533]";
        let info = parse_title(input).expect("must match a regex");
        assert_eq!(
            info.series_title,
            "Anime Title 300-nen, With Even More Title"
        );
        assert_eq!(info.absolute_episode_numbers, vec![2]);
    }

    #[test]
    fn rejects_absolute_when_later_dash_episode_follows_words() {
        // Sonarr captures both "100" and "01" via repeated (?<absoluteepisode>...)
        // and .Captures.Last() returns "01". Rust regex returns only the last
        // *positional* capture — which is "100" because the engine can't span
        // the words. Reject 100 to let cascade fall through.
        let input = "[SubsPlease] Series Title - 100 Years Quest - 01 (1080p) [1107F3A9].mkv";
        let info = parse_title(input).expect("must match a regex");
        assert_eq!(info.series_title, "Series Title - 100 Years Quest");
        assert_eq!(info.absolute_episode_numbers, vec![1]);
    }

    #[test]
    fn detects_space_dash_space_range_start() {
        // Sonarr's repeated (?<absoluteepisode>...) captures both 01 and 119;
        // .First()/.Last() yield the range. Our find_range_start must accept
        // " - " between the chained numbers, not only "-" or "_".
        let input = "[HorribleSubs] Some Anime Show 01 - 119 [1080p] [Batch]";
        let info = parse_title(input).expect("must match a regex");
        assert_eq!(info.series_title, "Some Anime Show");
        assert_eq!(info.absolute_episode_numbers.first().copied(), Some(1));
        assert_eq!(info.absolute_episode_numbers.last().copied(), Some(119));
    }

    #[test]
    fn extracts_triple_dash_range_to_third_element() {
        // Sonarr captures all three via repeated (?<absoluteepisode>...) and
        // .First()/.Last() yield 1..=3. Our scanner must continue forward past
        // the captured absolute to pick up trailing chain elements when the
        // regex stopped before the final digit.
        let input = "Series Title (2010) - 01-02-03 - Episode Title (1) HDTV-720p";
        let info = parse_title(input).expect("must match a regex");
        assert_eq!(info.series_title, "Series Title (2010)");
        assert_eq!(info.absolute_episode_numbers, vec![1, 2, 3]);
    }

    #[test]
    fn carries_trailing_year_into_title_for_broad_absolute() {
        // 'Series Title 2018' is the canonical title (a year-branded show); '06'
        // is the absolute episode. Broad absolute regexes (87..=94) lazily stop
        // title at "Series Title", capturing 2018 as a discarded preliminary
        // absolute and 06 as the final. Re-attach 2018 to the title when the
        // pattern is "title \d{4} \d{1,3}".
        let input = "Series Title 2018 06 720p x265 AOZ.mp4";
        let info = parse_title(input).expect("must match a regex");
        assert_eq!(info.series_title, "Series Title 2018");
        assert_eq!(info.absolute_episode_numbers, vec![6]);
    }

    #[test]
    fn enriches_standard_match_with_trailing_absolute_range() {
        // m53b Failure 5: composite S+E+absolute. The standard regex matches
        // season=1, episodes=[1,2]; the trailing parenthesized "(001-002)" is
        // the absolute range. C# Sonarr captures both via repeated named
        // groups in the same composite regex; we recover it post-match by
        // scanning the input after the standard match's end for an
        // absolute-range chain whose length matches episode_numbers.len().
        let input =
            "Series Title (2010) - S01E01-02 (001-002) - Episode Title (1) HDTV-720p v2 [RlsGrp]";
        let info = parse_title(input).expect("must match a regex");
        assert_eq!(info.series_title, "Series Title (2010)");
        assert_eq!(info.season_number, 1);
        assert_eq!(info.episode_numbers, vec![1, 2]);
        assert_eq!(info.absolute_episode_numbers.first().copied(), Some(1));
        assert_eq!(info.absolute_episode_numbers.last().copied(), Some(2));
    }
}