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
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
// Ported from Sonarr v4.0.17.2952 (97e85a90):
//   src/NzbDrone.Core/Parser/QualityParser.cs

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

/// Source-detection regex constants ported from `QualityParser.cs`.
///
/// These mirror the C# `private static readonly Regex` declarations at lines
/// 17 to 66 of `QualityParser.cs`. The Rust `regex` crate is RE2-based and
/// does not support backreferences or lookarounds; where a C# pattern uses
/// either, the constant here is a relaxed superset and a sibling helper
/// function applies the missing constraint in code post-match. Each such
/// case is documented inline above the affected `Lazy<Regex>` declaration.
pub mod regexes {
    use super::{Lazy, Regex};

    /// Source-class detector. Ported from `QualityParser.cs:17-30`.
    ///
    /// The C# pattern uses three negative lookarounds inside the `bluray` and
    /// `webdl` branches:
    ///
    /// 1. `BD(?!$)` (bluray branch). Bare `BD` only counts when not at end of
    ///    string. Rust workaround: relaxed to `BD`; `match_source` rejects a
    ///    `bluray` match whose entire captured text is `BD` and ends at the
    ///    input boundary.
    /// 2. `(?-i:WEB)$` (webdl branch). Case-sensitive uppercase `WEB` at end
    ///    of input. Rust regex DOES support `(?-i:...)` flag-disable groups,
    ///    so this is ported verbatim.
    /// 3. `(?:AMZN|NF|DP)[. -]WEB[. -](?!Rip)` (webdl branch). Provider tag
    ///    followed by `WEB` and a separator that is not `Rip`. Rust workaround:
    ///    drops the `(?!Rip)` and wraps the provider alternative in a nested
    ///    named sub-capture `(?P<provider_web>...)`. `match_source` then gates
    ///    the post-match `(?!Rip)` filter on `provider_web.is_some()`,
    ///    structurally identifying which alternation branch fired rather than
    ///    relying on alternation order or prefix heuristics.
    ///
    /// Callers reach a fully-correct match through [`super::match_source`];
    /// the raw `SOURCE_REGEX` is exported for tests that want to assert which
    /// branch the alternation hit (named groups: `bluray`, `webdl`, `webrip`,
    /// `hdtv`, `bdrip`, `brrip`, `dvd`, `dsr`, `pdtv`, `sdtv`, `tvrip`).
    pub static SOURCE_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
            r"(?ix)
            \b(?:
                (?P<bluray>BluRay|Blu-Ray|HD-?DVD|BDMux|BD)|
                (?P<webdl>
                    WEB[-_.\x20]DL(?:mux)?|WEBDL|AmazonHD|AmazonSD|iTunesHD|MaxdomeHD|NetflixU?HD|WebHD|HBOMaxHD|DisneyHD|
                    [.\x20]WEB[.\x20](?:[xh][ .]?26[45]|AVC|HEVC|DDP?5[. ]1)|
                    [.\x20](?-i:WEB)$|
                    (?:720|1080|2160)p[-.\x20]WEB[-.\x20]|
                    [-.\x20]WEB[-.\x20](?:720|1080|2160)p|
                    \b\s/\sWEB\s/\s\b|
                    (?P<provider_web>(?:AMZN|NF|DP)[.\x20-]WEB[.\x20-])
                )|
                (?P<webrip>WebRip|Web-Rip|WEBMux)|
                (?P<hdtv>HDTV)|
                (?P<bdrip>BDRip|BDLight)|
                (?P<brrip>BRRip)|
                (?P<dvd>DVD|DVDRip|NTSC|PAL|xvidvd)|
                (?P<dsr>WS[-_.\x20]DSR|DSR)|
                (?P<pdtv>PDTV)|
                (?P<sdtv>SDTV)|
                (?P<tvrip>TVRip)
            )(?:\b|$|[\x20.])",
        )
        .expect("SOURCE_REGEX must compile")
    });

    /// `RawHD` / `Raw-HD` / `Raw_HD` / `Raw.HD` / `Raw HD` detector. Ported
    /// from `QualityParser.cs:32-33`.
    pub static RAW_HD_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)\b(?P<rawhd>RawHD|Raw[-_. ]HD)\b").expect("RAW_HD_REGEX must compile")
    });

    /// `MPEG2` / `MPEG-2` / `MPEG_2` / `MPEG.2` / `MPEG 2` detector. Ported
    /// from `QualityParser.cs:35`. Note: the C# pattern is **case-sensitive**
    /// (no `RegexOptions.IgnoreCase`), so we omit the `(?i)` flag here.
    pub static MPEG2_REGEX: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"\b(?P<mpeg2>MPEG[-_. ]?2)\b").expect("MPEG2_REGEX must compile"));

    /// Remux detector. Ported from `QualityParser.cs:66`.
    ///
    /// The C# pattern declares the same group name `(?<remux>...)` twice in an
    /// alternation. .NET allows that; Rust's `regex` crate rejects duplicate
    /// names within a single pattern. To preserve identical match semantics
    /// while staying compilable, the second branch's group is renamed
    /// `remux_post`. Callers should treat a hit on EITHER `remux` or
    /// `remux_post` as a positive Remux signal; `super::match_remux` exposes
    /// that contract directly.
    pub static REMUX_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
            r"(?i)(?:[_. ]|\d{4}p-|\bHybrid-)(?P<remux>(?:(BD|UHD)[-_. ]?)?Remux)\b|(?P<remux_post>(?:(BD|UHD)[-_. ]?)?Remux[_. ]\d{4}p)",
        )
        .expect("REMUX_REGEX must compile")
    });

    /// Anime-Bluray detector. Ported from `QualityParser.cs:61`.
    ///
    /// The C# pattern uses paired lookarounds for the bare `bd` branch:
    /// `(?<=[-_. (\[])bd(?=[-_. )\]])`. Rust's `regex` crate does not support
    /// lookarounds, so the constant here is the relaxed superset
    /// `bd(?:720|1080|2160)|bd`. Callers must reach a fully-correct match
    /// through [`super::matches_anime_bluray`], which applies the surround
    /// check in code on bare `bd` candidates.
    pub static ANIME_BLURAY_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)bd(?:720|1080|2160)|bd").expect("ANIME_BLURAY_REGEX must compile")
    });

    /// Anime-WEB-DL detector. Ported from `QualityParser.cs:62`.
    pub static ANIME_WEBDL_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)\[WEB\]|[\[(]WEB[ .]").expect("ANIME_WEBDL_REGEX must compile")
    });

    /// Resolution detector. Ported from `QualityParser.cs:49-50`.
    ///
    /// Named groups: `R360p`, `R480p`, `R540p`, `R576p`, `R720p`, `R1080p`,
    /// `R2160p`. Case-insensitive (`IgnoreCase` in C# → `(?i)` flag here).
    ///
    /// Cross-checked against C#: every alternative branch, including the
    /// `4kto1080p` downscaled-UHD token on the `R1080p` branch, is reproduced
    /// verbatim. The one place this port deliberately differs from the m50
    /// plan-spec draft is the `R2160p` branch's 4K alternatives: the plan
    /// drafted `4kto2160p`, but C# actually carries
    /// `4k[-_. ](?:UHD|HEVC|BD|H265)|(?:UHD|HEVC|BD|H265)[-_. ]4k`. C# is
    /// authoritative per the m50 standing rules, so the port mirrors C#.
    /// The Rust `regex` crate accepts the pattern as-is, with every named
    /// group unique and no lookarounds.
    pub static RESOLUTION_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
            r"(?i)\b(?:(?P<R360p>360p)|(?P<R480p>480p|480i|640x480|848x480)|(?P<R540p>540p)|(?P<R576p>576p)|(?P<R720p>720p|1280x720|960p)|(?P<R1080p>1080p|1920x1080|1440p|FHD|1080i|4kto1080p)|(?P<R2160p>2160p|3840x2160|4k[-_. ](?:UHD|HEVC|BD|H265)|(?:UHD|HEVC|BD|H265)[-_. ]4k))\b",
        )
        .expect("RESOLUTION_REGEX must compile")
    });

    /// Alternative resolution detector for releases that omit a numeric
    /// resolution token. Ported from `QualityParser.cs:53-54`.
    ///
    /// The C# pattern declares `(?<R2160p>...)` twice in an alternation
    /// (`(?<R2160p>UHD)\b|(?<R2160p>\[4K\])`). .NET allows duplicate group
    /// names and merges their captures; Rust's `regex` crate rejects this. To
    /// preserve identical match semantics while staying compilable, the second
    /// branch is renamed `R2160p_alt`. Callers should treat a hit on EITHER
    /// `R2160p` or `R2160p_alt` as a positive 2160p signal;
    /// [`super::matches_alternative_resolution`] coalesces both branches into
    /// a single boolean.
    pub static ALTERNATIVE_RESOLUTION_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)\b(?P<R2160p>UHD)\b|(?P<R2160p_alt>\[4K\])")
            .expect("ALTERNATIVE_RESOLUTION_REGEX must compile")
    });

    /// Codec detector. Ported from `QualityParser.cs:56-57`.
    ///
    /// Named groups: `x264`, `h264`, `xvidhd`, `xvid`, `divx`. Case-insensitive
    /// (`IgnoreCase` in C# → `(?i)` flag here). Note that the C# pattern uses
    /// the literal `Xvid` (no hyphen variant), so this port matches `Xvid` and
    /// `xvid` (case-insensitive) but NOT `X-vid`. The plan-spec drafted
    /// `X-?vid`; C# is authoritative per the m50 standing rules, so we keep
    /// the C# form.
    pub static CODEC_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
            r"(?i)\b(?:(?P<x264>x264)|(?P<h264>h264)|(?P<xvidhd>XvidHD)|(?P<xvid>Xvid)|(?P<divx>divx))\b",
        )
        .expect("CODEC_REGEX must compile")
    });

    /// `HD-TV` / `SD-TV` alternative-form detector. Ported from
    /// `QualityParser.cs:59`. Named groups: `hdtv`, `sdtv`. Case-insensitive.
    pub static OTHER_SOURCE_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)(?P<hdtv>HD[-_. ]TV)|(?P<sdtv>SD[-_. ]TV)")
            .expect("OTHER_SOURCE_REGEX must compile")
    });

    /// `hr-ws` (high-def PDTV) detector. Ported from `QualityParser.cs:64`.
    /// Case-insensitive.
    pub static HIGH_DEF_PDTV_REGEX: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(?i)hr[-_. ]ws").expect("HIGH_DEF_PDTV_REGEX must compile"));

    /// PROPER detector. Ported from `QualityParser.cs:37-38`.
    /// Named group: `proper`. Case-insensitive.
    pub static PROPER_REGEX: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(?i)\b(?P<proper>proper)\b").expect("PROPER_REGEX must compile"));

    /// REPACK / RERIP detector. Ported from `QualityParser.cs:40-41`. Matches
    /// `repack`, `repack1`, `repack2`, ..., `rerip`, `rerip1`, `rerip2`, etc.
    /// Named group: `repack`. Case-insensitive.
    pub static REPACK_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)\b(?P<repack>repack\d?|rerip\d?)\b").expect("REPACK_REGEX must compile")
    });

    /// Explicit version-marker detector. Ported from `QualityParser.cs:43-44`.
    ///
    /// The C# pattern declares the same `<version>` named group on FIVE
    /// alternation branches:
    ///
    /// 1. `\d[-._ ]?v(?<version>\d)[-._ ]` (e.g. `1v2.`, `01-v2_`)
    /// 2. `\[v(?<version>\d)\]` (e.g. `[v2]`)
    /// 3. `repack(?<version>\d)` (e.g. `repack2`)
    /// 4. `rerip(?<version>\d)` (e.g. `rerip3`)
    /// 5. `(?:480|576|720|1080|2160)p[._ ]v(?<version>\d)` (e.g. `1080p.v2`)
    ///
    /// .NET allows duplicate names and merges captures; Rust's `regex` crate
    /// rejects them. We rename branches 2-5 to `version2`, `version3`,
    /// `version4`, `version5`. Callers should walk all five names and pick
    /// the first hit:
    ///
    /// ```ignore
    /// caps.name("version")
    ///     .or_else(|| caps.name("version2"))
    ///     .or_else(|| caps.name("version3"))
    ///     .or_else(|| caps.name("version4"))
    ///     .or_else(|| caps.name("version5"))
    /// ```
    ///
    /// T6's modifier cascade owns that walk; the helper is intentionally not
    /// added in T5 because the cascade has additional decision logic that
    /// would be split awkwardly. Case-insensitive (`IgnoreCase` in C# → `(?i)`
    /// flag here).
    pub static VERSION_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
            r"(?i)\d[-._ ]?v(?P<version>\d)[-._ ]|\[v(?P<version2>\d)\]|repack(?P<version3>\d)|rerip(?P<version4>\d)|(?:480|576|720|1080|2160)p[._ ]v(?P<version5>\d)",
        )
        .expect("VERSION_REGEX must compile")
    });

    /// REAL detector. Ported from `QualityParser.cs:46-47`.
    ///
    /// **Case-sensitive intentionally.** The C# pattern carries
    /// `RegexOptions.Compiled` only (no `IgnoreCase`), so only uppercase
    /// `REAL` matches. We omit the `(?i)` flag here to mirror C# faithfully.
    pub static REAL_REGEX: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"\b(?P<real>REAL)\b").expect("REAL_REGEX must compile"));
}

use regexes::*;

/// Source-class signal extracted from a single `SOURCE_REGEX` candidate that
/// has passed all post-match lookaround filters. Carries which named group
/// hit (so callers can route to the correct `Quality` variant) plus the
/// matched substring (for debug logging and round-trip tests).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SourceMatch<'a> {
    pub group: SourceGroup,
    pub matched: &'a str,
}

/// Which named alternative inside `SOURCE_REGEX` matched.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum SourceGroup {
    Bluray,
    Webdl,
    Webrip,
    Hdtv,
    Bdrip,
    Brrip,
    Dvd,
    Dsr,
    Pdtv,
    Sdtv,
    Tvrip,
}

/// Classify a single `SOURCE_REGEX` `Captures` into a `SourceMatch`, or
/// `None` if the capture fails the C# lookaround filters.
///
/// Filters applied (mirroring `QualityParser.cs:17-30`):
///
/// 1. `bluray` branch: a bare `BD` that ends at the input boundary is
///    rejected (`BD(?!$)` in C#).
/// 2. `webdl` branch: an `(?:AMZN|NF|DP)[. -]WEB[. -]` capture that is
///    followed in the input by `Rip` (case-insensitive) is rejected
///    (`(?!Rip)` in C#). Identified structurally via the nested
///    `provider_web` sub-capture rather than a prefix check on the
///    outer match. Robust against future alternation reordering.
fn classify_source_capture<'a>(s: &'a str, caps: &regex::Captures<'a>) -> Option<SourceMatch<'a>> {
    let (group, mat) = if let Some(m) = caps.name("bluray") {
        (SourceGroup::Bluray, m)
    } else if let Some(m) = caps.name("webdl") {
        (SourceGroup::Webdl, m)
    } else if let Some(m) = caps.name("webrip") {
        (SourceGroup::Webrip, m)
    } else if let Some(m) = caps.name("hdtv") {
        (SourceGroup::Hdtv, m)
    } else if let Some(m) = caps.name("bdrip") {
        (SourceGroup::Bdrip, m)
    } else if let Some(m) = caps.name("brrip") {
        (SourceGroup::Brrip, m)
    } else if let Some(m) = caps.name("dvd") {
        (SourceGroup::Dvd, m)
    } else if let Some(m) = caps.name("dsr") {
        (SourceGroup::Dsr, m)
    } else if let Some(m) = caps.name("pdtv") {
        (SourceGroup::Pdtv, m)
    } else if let Some(m) = caps.name("sdtv") {
        (SourceGroup::Sdtv, m)
    } else if let Some(m) = caps.name("tvrip") {
        (SourceGroup::Tvrip, m)
    } else {
        return None;
    };

    // Filter 1: bluray bare-BD-at-end-of-input rejection (C# `BD(?!$)`).
    if group == SourceGroup::Bluray
        && mat.as_str().eq_ignore_ascii_case("BD")
        && mat.end() == s.len()
    {
        return None;
    }

    // Filter 2: webdl provider-tag-followed-by-Rip rejection
    // (C# `(?:AMZN|NF|DP)[. -]WEB[. -](?!Rip)`). Gated on the nested
    // `provider_web` sub-capture so we apply the (?!Rip) filter only when
    // that exact alternation branch fired, independent of alternation
    // order or text-prefix heuristics on the outer match.
    if group == SourceGroup::Webdl && caps.name("provider_web").is_some() {
        let tail = &s[mat.end()..];
        if tail.len() >= 3 && tail.as_bytes()[..3].eq_ignore_ascii_case(b"Rip") {
            // Consumed-iterator pattern: the webdl branch consumed the WEB token,
            // so the webrip branch can never fire. Synthesize the Webrip match
            // to mirror C#'s backtrack semantics.
            return Some(SourceMatch {
                group: SourceGroup::Webrip,
                matched: mat.as_str(),
            });
        }
    }

    Some(SourceMatch {
        group,
        matched: mat.as_str(),
    })
}

/// Find the first source-class match in `s`, applying the lookahead filters
/// that Rust regex cannot express directly. Returns `None` if no candidate
/// satisfies the C# semantics.
///
/// See [`classify_source_capture`] for the filter list.
///
/// Test-only: the production cascade uses [`match_source_last`] (last-wins
/// semantics, see C# `QualityParser.cs:115`). This first-match form exists
/// to pin the C# regex's per-branch alternation behaviour from the test
/// suite without leaking a never-used helper into the production build.
#[cfg(test)]
pub(crate) fn match_source(s: &str) -> Option<SourceMatch<'_>> {
    for caps in SOURCE_REGEX.captures_iter(s) {
        if let Some(m) = classify_source_capture(s, &caps) {
            return Some(m);
        }
    }
    None
}

/// Find the LAST source-class match in `s`, mirroring C#'s
/// `sourceMatches.OfType<Match>().LastOrDefault()` at `QualityParser.cs:115`.
///
/// The cascade uses last-match-wins semantics: a release like
/// `Movie.HDTV.Repack.BluRay.x264` classifies as bluray, not hdtv, because
/// `BluRay` appears AFTER `HDTV` in the string. C# achieves this with
/// `Regex.Matches(...).OfType<Match>().LastOrDefault()`; we mirror it by
/// walking every candidate from `captures_iter` and keeping the last that
/// passes [`classify_source_capture`]'s filters.
///
/// Returns `None` only when no candidate in the entire string satisfies the
/// post-match lookaround filters. A candidate that is rejected by a filter
/// is skipped; an earlier accepted candidate may still be returned if no
/// later candidate passes.
pub(crate) fn match_source_last(s: &str) -> Option<SourceMatch<'_>> {
    let mut last: Option<SourceMatch<'_>> = None;
    for caps in SOURCE_REGEX.captures_iter(s) {
        if let Some(m) = classify_source_capture(s, &caps) {
            last = Some(m);
        }
    }
    last
}

/// Anime-Bluray detection respecting C#'s lookaround semantics.
///
/// The relaxed `ANIME_BLURAY_REGEX` matches `bd720`/`bd1080`/`bd2160`
/// directly, and also matches a bare `bd` anywhere in the input. C# only
/// counts a bare `bd` when it is surrounded by one of `[-_. (\[]` on the left
/// and one of `[-_. )\]]` on the right. This function applies that surround
/// check in code, returning `true` on the first candidate that passes.
///
/// Bare `bd` requires a separator on both sides. Bare `bd` at start- or
/// end-of-input does NOT match, matching C#'s paired
/// `(?<=[-_. (\[])bd(?=[-_. )\]])` lookaround semantics where the
/// lookbehind/lookahead fails at the input boundary.
pub(crate) fn matches_anime_bluray(s: &str) -> bool {
    for m in ANIME_BLURAY_REGEX.find_iter(s) {
        let matched = m.as_str();
        if matched.len() == 2 {
            // Bare `bd`: check the C# surround constraint.
            let bytes = s.as_bytes();
            let start = m.start();
            let end = m.end();
            // Note: `as_bytes().get(start - 1)` returns a single byte at a UTF-8 boundary.
            // For multi-byte chars (e.g. 'é'), the read returns a continuation byte
            // (0x80..=0xBF) which is outside the ASCII separator set, so the surround
            // check correctly rejects non-ASCII surrounds.
            let before_ok = start > 0
                && matches!(
                    bytes.get(start - 1),
                    Some(b'-' | b'_' | b'.' | b' ' | b'(' | b'[')
                );
            let after_ok = end < s.len()
                && matches!(
                    bytes.get(end),
                    Some(b'-' | b'_' | b'.' | b' ' | b')' | b']')
                );
            if before_ok && after_ok {
                return true;
            }
        } else {
            // `bd720` / `bd1080` / `bd2160`: always counts.
            return true;
        }
    }
    false
}

/// Remux detector that merges the two same-named C# capture groups
/// (`remux` and `remux_post` in the Rust port) into a single signal.
///
/// Returns `Some(matched_text)` on the first hit, `None` otherwise. Callers
/// that need positional information can fall back to `REMUX_REGEX` directly;
/// this helper is the canonical "is this a remux release?" gate.
pub(crate) fn match_remux(s: &str) -> Option<&str> {
    for caps in REMUX_REGEX.captures_iter(s) {
        if let Some(m) = caps.name("remux").or_else(|| caps.name("remux_post")) {
            return Some(m.as_str());
        }
    }
    None
}

/// Alternative-resolution detector that merges the two same-named C# capture
/// groups (`R2160p` and `R2160p_alt` in the Rust port) into a single boolean
/// signal.
///
/// Returns `true` if either branch fires, mirroring C#'s
/// `(?<R2160p>UHD)\b|(?<R2160p>\[4K\])` semantics where both alternatives are
/// recorded under the same name.
pub(crate) fn matches_alternative_resolution(s: &str) -> bool {
    ALTERNATIVE_RESOLUTION_REGEX
        .captures_iter(s)
        .any(|caps| caps.name("R2160p").is_some() || caps.name("R2160p_alt").is_some())
}

/// Resolution detector mirroring C#'s `ParseResolution`
/// (`QualityParser.cs:600-651`).
///
/// Walks `RESOLUTION_REGEX`'s named groups in C# evaluation order
/// (R360p, R480p, R540p, R576p, R720p, R1080p, R2160p) and returns the first
/// hit. If no main-regex group fires, falls back to
/// [`matches_alternative_resolution`] to detect the `UHD` / `[4K]` tokens that
/// C#'s `AlternativeResolutionRegex` covers; either alternative-regex branch
/// counts as `R2160p`. Returns `Resolution::Unknown` if neither regex matches.
///
/// **Group-order note.** The C# code checks groups starting from the smallest
/// resolution upward (R360p first, R2160p last). The named groups in
/// `RESOLUTION_REGEX` are mutually exclusive within a single capture (an
/// alternation only fires one branch), so the order does not affect behaviour
/// for any input the regex can match. We mirror the C# walk order verbatim
/// to keep the port reviewable against the source.
fn detect_resolution(name: &str) -> crate::quality::Resolution {
    use crate::quality::Resolution;

    if let Some(caps) = RESOLUTION_REGEX.captures(name) {
        if caps.name("R360p").is_some() {
            return Resolution::R360p;
        }
        if caps.name("R480p").is_some() {
            return Resolution::R480p;
        }
        if caps.name("R540p").is_some() {
            return Resolution::R540p;
        }
        if caps.name("R576p").is_some() {
            return Resolution::R576p;
        }
        if caps.name("R720p").is_some() {
            return Resolution::R720p;
        }
        if caps.name("R1080p").is_some() {
            return Resolution::R1080p;
        }
        if caps.name("R2160p").is_some() {
            return Resolution::R2160p;
        }
    }

    if matches_alternative_resolution(name) {
        return Resolution::R2160p;
    }

    Resolution::Unknown
}

/// `Quality.Source` reverse lookup. Mirrors the C# constructor pairs in
/// `Quality.cs:77-124` where each `Quality` static is paired with a
/// `QualitySource` argument.
///
/// Used by [`parse_quality_name`]'s resolution-only fallback to derive a
/// `QualitySource` from the extension-derived `Quality`, mirroring C#
/// `QualityParser.cs:444` (`source = quality.Source`).
fn quality_source(q: crate::quality::Quality) -> crate::quality::QualitySource {
    use crate::quality::{Quality, QualitySource};
    match q {
        Quality::Unknown => QualitySource::Unknown,
        Quality::Sdtv => QualitySource::Television,
        Quality::Hdtv720p => QualitySource::Television,
        Quality::Hdtv1080p => QualitySource::Television,
        Quality::Hdtv2160p => QualitySource::Television,
        Quality::RawHd => QualitySource::TelevisionRaw,
        Quality::Webdl480p => QualitySource::Web,
        Quality::Webdl720p => QualitySource::Web,
        Quality::Webdl1080p => QualitySource::Web,
        Quality::Webdl2160p => QualitySource::Web,
        Quality::Webrip480p => QualitySource::WebRip,
        Quality::Webrip720p => QualitySource::WebRip,
        Quality::Webrip1080p => QualitySource::WebRip,
        Quality::Webrip2160p => QualitySource::WebRip,
        Quality::Dvd => QualitySource::Dvd,
        Quality::Bluray480p => QualitySource::Bluray,
        Quality::Bluray576p => QualitySource::Bluray,
        Quality::Bluray720p => QualitySource::Bluray,
        Quality::Bluray1080p => QualitySource::Bluray,
        Quality::Bluray2160p => QualitySource::Bluray,
        Quality::Bluray1080pRemux => QualitySource::BlurayRaw,
        Quality::Bluray2160pRemux => QualitySource::BlurayRaw,
    }
}

/// File-extension to `Quality` lookup. Ports
/// `MediaFileExtensions.cs:9-71` + `GetQualityForExtension` (lines 76-84).
///
/// Returns `Quality::Unknown` for any extension not in the table OR an empty
/// extension. The C# wrapper at `QualityParser.cs:82-95` and the inline
/// extension lookup at `:437-451` both use this; the inline path uses Sonarr's
/// `string.GetPathExtension()` (`PathExtensions.cs:74-83`), which is a bare
/// `LastIndexOf('.')` slice (no path-validity checks).
///
/// Comparison is ASCII-case-insensitive to match
/// `StringComparer.OrdinalIgnoreCase` at `MediaFileExtensions.cs:13`.
fn quality_for_extension(extension: &str) -> crate::quality::Quality {
    use crate::quality::Quality;
    // C# MediaFileExtensions.cs:9-71. Pairs are (extension-with-dot, Quality).
    const TABLE: &[(&str, Quality)] = &[
        // Unknown
        (".webm", Quality::Unknown),
        // SDTV
        (".m4v", Quality::Sdtv),
        (".3gp", Quality::Sdtv),
        (".nsv", Quality::Sdtv),
        (".ty", Quality::Sdtv),
        (".strm", Quality::Sdtv),
        (".rm", Quality::Sdtv),
        (".rmvb", Quality::Sdtv),
        (".m3u", Quality::Sdtv),
        (".ifo", Quality::Sdtv),
        (".mov", Quality::Sdtv),
        (".qt", Quality::Sdtv),
        (".divx", Quality::Sdtv),
        (".xvid", Quality::Sdtv),
        (".bivx", Quality::Sdtv),
        (".nrg", Quality::Sdtv),
        (".pva", Quality::Sdtv),
        (".wmv", Quality::Sdtv),
        (".asf", Quality::Sdtv),
        (".asx", Quality::Sdtv),
        (".ogm", Quality::Sdtv),
        (".ogv", Quality::Sdtv),
        (".m2v", Quality::Sdtv),
        (".avi", Quality::Sdtv),
        (".bin", Quality::Sdtv),
        (".dat", Quality::Sdtv),
        (".dvr-ms", Quality::Sdtv),
        (".mpg", Quality::Sdtv),
        (".mpeg", Quality::Sdtv),
        (".mp4", Quality::Sdtv),
        (".avc", Quality::Sdtv),
        (".vp3", Quality::Sdtv),
        (".svq3", Quality::Sdtv),
        (".nuv", Quality::Sdtv),
        (".viv", Quality::Sdtv),
        (".dv", Quality::Sdtv),
        (".fli", Quality::Sdtv),
        (".flv", Quality::Sdtv),
        (".wpl", Quality::Sdtv),
        // DVD
        (".img", Quality::Dvd),
        (".iso", Quality::Dvd),
        (".vob", Quality::Dvd),
        // HD
        (".mkv", Quality::Hdtv720p),
        (".ts", Quality::Hdtv720p),
        (".wtv", Quality::Hdtv720p),
        // Bluray
        (".m2ts", Quality::Bluray720p),
    ];

    if extension.is_empty() {
        return Quality::Unknown;
    }
    for (ext, q) in TABLE {
        if extension.eq_ignore_ascii_case(ext) {
            return *q;
        }
    }
    Quality::Unknown
}

/// Sonarr's `string.GetPathExtension()` from
/// `NzbDrone.Common/Extensions/PathExtensions.cs:74-83`.
///
/// Returns the substring from the LAST `.` to end-of-string, INCLUDING the
/// dot. Returns an empty string if there is no `.` or if the dot is the final
/// character. This is NOT `Path.GetExtension` semantics; it does no path
/// validation, so it picks the trailing token from any string regardless of
/// platform path syntax. The resolution-only fallback at C#
/// `QualityParser.cs:439` calls this helper, which is why a release name like
/// `Movie.2020.1080p.x264.mkv` will yield `.mkv` even though the filename
/// portion has no directory structure.
fn get_path_extension(path: &str) -> &str {
    if let Some(idx) = path.rfind('.')
        && idx + 1 < path.len()
    {
        return &path[idx..];
    }
    ""
}

/// ASCII case-insensitive substring search, mirroring .NET's
/// `string.ContainsIgnoreCase`.
///
/// C#'s `ContainsIgnoreCase` is a culture-aware match by default, but the
/// Sonarr extension method (`Extensions/StringExtensions.cs`) implements it as
/// `IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0`. Ordinal-IgnoreCase
/// folds only the ASCII A-Z / a-z range; non-ASCII code points round-trip
/// unchanged. The Rust port mirrors that contract via
/// [`str::eq_ignore_ascii_case`] on byte-aligned windows.
fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
    let n = needle.len();
    if n == 0 {
        return true;
    }
    let h = haystack.as_bytes();
    if h.len() < n {
        return false;
    }
    h.windows(n)
        .any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
}

/// Quality-cascade entry-point. Ported from `QualityParser.cs:100-598`
/// (`ParseQualityName`).
///
/// **Duties.**
///
/// 1. Normalise: `name.Replace('_', ' ').Trim()` and `name.Trim()` for the raw
///    side, mirroring C#'s twin `Trim()` calls at `QualityParser.cs:77` and
///    `QualityParser.cs:102`.
/// 2. Run `parse_quality_modifiers` against both raw and normalised name to
///    populate `Revision`. Modifiers that fire also set
///    `revision_detection_source = Name`.
/// 3. RawHD short-circuit (C# line 105): return `Quality::RawHd` with
///    `source_detection_source = resolution_detection_source = Name`.
/// 4. Source-to-quality cascade (C# lines 114-318): take the LAST source
///    match, pair with the parsed resolution + codec + remux signals, and
///    route to a concrete `Quality` variant. Branches:
///
///    - `bluray`: codec(xvid|divx) -> 480p, else by-resolution
///      (2160 / 1080 / 576 / {360, 480, 540}); remux+resolution!=720 -> 1080pRemux;
///      else 720p.
///    - `webdl`: by-resolution (2160 / 1080 / 720); raw-name `[WEBDL]` -> 720p;
///      else 480p.
///    - `webrip`: by-resolution (2160 / 1080 / 720); else 480p.
///    - `hdtv`: MPEG2 -> RawHD; else by-resolution; raw-name `[HDTV]` -> 720p;
///      else SDTV.
///    - `bdrip` / `brrip`: by-resolution (720 / 1080 / 2160); else 480p.
///    - `dvd`: DVD always.
///    - `pdtv` / `sdtv` / `dsr` / `tvrip`: 1080p match -> Hdtv1080p;
///      720p match -> Hdtv720p; HighDefPdtv (`hr-ws`) -> Hdtv720p; else SDTV.
///
///    Provenance flags (`source_detection_source`, `resolution_detection_source`)
///    are populated according to the C# rules: `source_detection_source` is set
///    to `Name` whenever a sourceMatch fires; `resolution_detection_source` is
///    set to `Name` when the resolution-regex hit (line 122) or, in the
///    pdtv-cluster branch, when the `ContainsIgnoreCase` substring fallback
///    fires (line 308's `HighDefPdtvRegex` path).
///
/// **Fallthrough cascade (T8).** When no source match fires, the following
/// fallbacks run in C# order, each returning on a hit:
///
/// - **Sourceless remux** (C# 320-347): `remuxMatch && resolution != Unknown`,
///   dispatched per resolution. SourceDetectionSource is explicitly `Unknown`
///   here per C# line 322.
/// - **Anime-bluray** (C# 349-390): `AnimeBlurayRegex` hits, resolution-routed
///   (480/1080/2160/720 defaults). 480p in this branch maps to `Quality::Dvd`
///   per C# line 359.
/// - **Anime-webdl** (C# 392-424): `AnimeWebDlRegex` hits, resolution-routed.
/// - **Resolution-only** (C# 426-497): `resolution != Unknown`. Derives a
///   `QualitySource` from `remuxMatch` (`BlurayRaw`) OR from the file
///   extension via [`quality_for_extension`] + [`quality_source`], then
///   dispatches via `find_by_source_and_resolution`. Unknown source falls
///   back to Television-class defaults (Hdtv2160p / Hdtv1080p / Hdtv720p / Sdtv).
/// - **x264-SDTV** (C# 499-504): bare `x264` with no other signal -> `Sdtv`.
/// - **Pixel-tag fallbacks** (C# 506-560): literal `848x480`, `1280x720`,
///   `1920x1080` substrings, optionally combined with `dvd` / `bluray` markers.
/// - **Bare-bluray-resolution** (C# 562-587): literal `bluray720p` /
///   `bluray1080p` / `bluray2160p` -> `Bluray720p` / `Bluray1080p` / `Bluray2160p`.
/// - **`OtherSourceMatch`** (C# 589-595, 653-672): `OTHER_SOURCE_REGEX` hit
///   (`HD-TV` / `SD-TV` alternative form) -> `Hdtv720p` / `Sdtv`.
///
/// **Most callers want [`parse_quality`] instead.** That wrapper adds the
/// extension-fallback behaviour from `QualityParser.cs:81-95` on top of
/// `parse_quality_name`'s output. Use `parse_quality_name` directly only
/// when you specifically want to bypass the extension lookup (e.g.,
/// text-only parsing, no file path implied). This split mirrors C#'s
/// `ParseQuality` (public) vs `ParseQualityName` (test-seam) shape.
pub fn parse_quality_name(name: &str) -> crate::quality::QualityModel {
    use crate::quality::{
        Quality, QualityDetectionSource, QualityModel, QualitySource, Resolution,
    };

    // C# `QualityParser.cs:77` (`name.Trim()` in ParseQuality, the outer
    // wrapper). The plan delegates this trim to ParseQualityName because the
    // Rust port has only one entry point. Apply to the raw input so the
    // `[WEBDL]` / `[HDTV]` substring checks against `name` see the trimmed
    // string just like C#.
    let raw = name.trim();

    // C# `QualityParser.cs:102`: `name.Replace('_', ' ').Trim()`.
    let normalized = raw.replace('_', " ");
    let normalized = normalized.trim();

    let (revision, revision_detection_source) = parse_quality_modifiers(raw, normalized);

    if RAW_HD_REGEX.is_match(normalized) {
        return QualityModel {
            quality: Quality::RawHd,
            revision,
            source_detection_source: QualityDetectionSource::Name,
            resolution_detection_source: QualityDetectionSource::Name,
            revision_detection_source,
        };
    }

    // C# QualityParser.cs:114-118: gather the per-name signals in one pass.
    // - sourceMatch: LAST sourceMatch wins (line 115's LastOrDefault).
    // - resolution: ParseResolution, our `detect_resolution` helper.
    // - codec_*: x264 / xvid / divx / xvidhd / h264 named groups.
    // - remux_match: REMUX_REGEX hit, gated through `match_remux`.
    let source_match = match_source_last(normalized);
    let resolution = detect_resolution(normalized);
    let codec_caps = CODEC_REGEX.captures(normalized);
    let codec_xvid = codec_caps.as_ref().and_then(|c| c.name("xvid")).is_some();
    let codec_divx = codec_caps.as_ref().and_then(|c| c.name("divx")).is_some();
    let remux_match = match_remux(normalized).is_some();

    // C# QualityParser.cs:120-123: a non-Unknown resolution upgrades the
    // resolution-detection source to Name, regardless of whether any source
    // branch ultimately consumes the resolution value.
    let resolution_detection_source = if resolution != Resolution::Unknown {
        QualityDetectionSource::Name
    } else {
        QualityDetectionSource::Unknown
    };

    // Helper to materialise a final QualityModel with the per-cascade-arm
    // detection-source flips applied. Source detection source is set to Name
    // whenever this helper fires (every caller is inside a sourceMatch arm).
    let mk = |quality: Quality, resolution_source: QualityDetectionSource| QualityModel {
        quality,
        revision,
        source_detection_source: QualityDetectionSource::Name,
        resolution_detection_source: resolution_source,
        revision_detection_source,
    };

    if let Some(sm) = source_match {
        match sm.group {
            // C# QualityParser.cs:129-173. Bluray.
            SourceGroup::Bluray => {
                if codec_xvid || codec_divx {
                    // Line 131-135: codec downgrade.
                    return mk(Quality::Bluray480p, resolution_detection_source);
                }
                match resolution {
                    // Line 137-142: 2160p (with remux variant).
                    Resolution::R2160p => {
                        let q = if remux_match {
                            Quality::Bluray2160pRemux
                        } else {
                            Quality::Bluray2160p
                        };
                        return mk(q, resolution_detection_source);
                    }
                    // Line 144-148: 1080p (with remux variant).
                    Resolution::R1080p => {
                        let q = if remux_match {
                            Quality::Bluray1080pRemux
                        } else {
                            Quality::Bluray1080p
                        };
                        return mk(q, resolution_detection_source);
                    }
                    // Line 150-154: 576p.
                    Resolution::R576p => {
                        return mk(Quality::Bluray576p, resolution_detection_source);
                    }
                    // Line 156-161: 360p / 480p / 540p collapse to 480p.
                    Resolution::R360p | Resolution::R480p | Resolution::R540p => {
                        return mk(Quality::Bluray480p, resolution_detection_source);
                    }
                    // Line 165 explicit comment: "Treat a remux without a
                    // source as 1080p, not 720p. 720p remux should fallback
                    // as 720p BluRay." So the R720p arm ignores `remux_match`
                    // and routes to Bluray720p. The R720p arm in C# is the
                    // implicit fall-through after the resolution checks fail
                    // to match anything except R720p; we make that explicit.
                    Resolution::R720p => {
                        return mk(Quality::Bluray720p, resolution_detection_source);
                    }
                    // Line 165-169 + 171-172: Unknown resolution falls
                    // through to the remux-fallback (1080pRemux) when remux
                    // fired, otherwise the C# implicit default of Bluray720p.
                    Resolution::Unknown => {
                        if remux_match {
                            return mk(Quality::Bluray1080pRemux, resolution_detection_source);
                        }
                        return mk(Quality::Bluray720p, resolution_detection_source);
                    }
                }
            }

            // C# QualityParser.cs:175-203. Webdl.
            SourceGroup::Webdl => match resolution {
                Resolution::R2160p => return mk(Quality::Webdl2160p, resolution_detection_source),
                Resolution::R1080p => return mk(Quality::Webdl1080p, resolution_detection_source),
                Resolution::R720p => return mk(Quality::Webdl720p, resolution_detection_source),
                _ => {
                    // Line 195-199: raw-name `[WEBDL]` substring -> 720p.
                    if raw.contains("[WEBDL]") {
                        return mk(Quality::Webdl720p, resolution_detection_source);
                    }
                    return mk(Quality::Webdl480p, resolution_detection_source);
                }
            },

            // C# QualityParser.cs:205-227. Webrip.
            SourceGroup::Webrip => match resolution {
                Resolution::R2160p => return mk(Quality::Webrip2160p, resolution_detection_source),
                Resolution::R1080p => return mk(Quality::Webrip1080p, resolution_detection_source),
                Resolution::R720p => return mk(Quality::Webrip720p, resolution_detection_source),
                _ => return mk(Quality::Webrip480p, resolution_detection_source),
            },

            // C# QualityParser.cs:229-263. Hdtv.
            SourceGroup::Hdtv => {
                // Line 231-234: MPEG2 short-circuit. C#'s MPEG2_REGEX is
                // case-sensitive (verified at T4) and runs against
                // normalizedName.
                if MPEG2_REGEX.is_match(normalized) {
                    return mk(Quality::RawHd, resolution_detection_source);
                }
                match resolution {
                    Resolution::R2160p => {
                        return mk(Quality::Hdtv2160p, resolution_detection_source);
                    }
                    Resolution::R1080p => {
                        return mk(Quality::Hdtv1080p, resolution_detection_source);
                    }
                    Resolution::R720p => return mk(Quality::Hdtv720p, resolution_detection_source),
                    _ => {
                        // Line 255-259: raw-name `[HDTV]` substring -> 720p.
                        if raw.contains("[HDTV]") {
                            return mk(Quality::Hdtv720p, resolution_detection_source);
                        }
                        return mk(Quality::Sdtv, resolution_detection_source);
                    }
                }
            }

            // C# QualityParser.cs:265-283. BDRip / BRRip.
            SourceGroup::Bdrip | SourceGroup::Brrip => match resolution {
                Resolution::R720p => return mk(Quality::Bluray720p, resolution_detection_source),
                Resolution::R1080p => return mk(Quality::Bluray1080p, resolution_detection_source),
                Resolution::R2160p => return mk(Quality::Bluray2160p, resolution_detection_source),
                _ => return mk(Quality::Bluray480p, resolution_detection_source),
            },

            // C# QualityParser.cs:285-289. DVD source.
            SourceGroup::Dvd => return mk(Quality::Dvd, resolution_detection_source),

            // C# QualityParser.cs:291-317. PDTV / SDTV / DSR / TVRip cluster.
            SourceGroup::Pdtv | SourceGroup::Sdtv | SourceGroup::Dsr | SourceGroup::Tvrip => {
                // Line 296-300: 1080p (regex hit OR substring fallback).
                if resolution == Resolution::R1080p
                    || contains_ignore_ascii_case(normalized, "1080p")
                {
                    return mk(Quality::Hdtv1080p, resolution_detection_source);
                }
                // Line 302-306: 720p (regex hit OR substring fallback).
                if resolution == Resolution::R720p || contains_ignore_ascii_case(normalized, "720p")
                {
                    return mk(Quality::Hdtv720p, resolution_detection_source);
                }
                // Line 308-313: HighDefPdtv (hr-ws). C# explicitly sets
                // ResolutionDetectionSource = Name on this branch even though
                // the resolution regex did NOT fire.
                if HIGH_DEF_PDTV_REGEX.is_match(normalized) {
                    return mk(Quality::Hdtv720p, QualityDetectionSource::Name);
                }
                return mk(Quality::Sdtv, resolution_detection_source);
            }
        }
    }

    // ---------------------------------------------------------------------
    // T8 fallthrough cascade (C# QualityParser.cs:320-595).
    // ---------------------------------------------------------------------
    //
    // From here down, source_match is None (every source-arm above returned).
    // The C# control flow runs the following blocks in order; each returns
    // on a hit. We reuse the modifier+resolution_detection_source values
    // gathered above.

    // Builder for branches that flip source_detection_source to Name (anime,
    // pixel-tag, bare-bluray, OtherSourceMatch). Identical to the T7 `mk`
    // closure; defined here to avoid borrowing the T7 closure across the
    // T8 boundary.
    let mk_named = |quality: Quality, resolution_source: QualityDetectionSource| QualityModel {
        quality,
        revision,
        source_detection_source: QualityDetectionSource::Name,
        resolution_detection_source: resolution_source,
        revision_detection_source,
    };

    // C# QualityParser.cs:320-347: sourceless remux. Explicit C# behaviour
    // (line 322): `result.SourceDetectionSource = QualityDetectionSource.Unknown;`
    // even though we matched a remux signal. Resolutions outside
    // {480p, 720p, 1080p, 2160p} (e.g. 360p, 540p, 576p) fall through to the
    // anime / resolution-only branches.
    if source_match.is_none() && remux_match && resolution != Resolution::Unknown {
        let q = match resolution {
            Resolution::R480p => Some(Quality::Bluray480p),
            Resolution::R720p => Some(Quality::Bluray720p),
            Resolution::R2160p => Some(Quality::Bluray2160pRemux),
            Resolution::R1080p => Some(Quality::Bluray1080pRemux),
            _ => None,
        };
        if let Some(quality) = q {
            return QualityModel {
                quality,
                revision,
                // C# line 322 hard-codes Unknown here.
                source_detection_source: QualityDetectionSource::Unknown,
                resolution_detection_source,
                revision_detection_source,
            };
        }
    }

    // C# QualityParser.cs:349-390: anime-bluray. Matches before the
    // resolution-only fallback because C#'s control flow checks anime
    // detection first (at the same depth as sourceless-remux). NB: the
    // 480p substring path collapses to `Quality::Dvd`, NOT a Bluray480p
    // variant, intentionally per C# line 359.
    if matches_anime_bluray(normalized) {
        // Anime-bluray treats the substring "480p" as equivalent to a 480p
        // resolution token even when the resolution regex didn't fire.
        // The substring path explicitly flips ResolutionDetectionSource to
        // Name (C# lines 358 / 366 / 374).
        let resolution_source_anime = QualityDetectionSource::Name;

        if matches!(
            resolution,
            Resolution::R360p | Resolution::R480p | Resolution::R540p | Resolution::R576p
        ) || contains_ignore_ascii_case(normalized, "480p")
        {
            return mk_named(Quality::Dvd, resolution_source_anime);
        }

        if resolution == Resolution::R1080p || contains_ignore_ascii_case(normalized, "1080p") {
            let q = if remux_match {
                Quality::Bluray1080pRemux
            } else {
                Quality::Bluray1080p
            };
            return mk_named(q, resolution_source_anime);
        }

        if resolution == Resolution::R2160p || contains_ignore_ascii_case(normalized, "2160p") {
            let q = if remux_match {
                Quality::Bluray2160pRemux
            } else {
                Quality::Bluray2160p
            };
            return mk_named(q, resolution_source_anime);
        }

        // C# line 382-386: remux without a 720p resolution (incl. Unknown)
        // collapses to 1080pRemux. R720p with remux falls through to the
        // 720p default below.
        if remux_match && resolution != Resolution::R720p {
            return mk_named(Quality::Bluray1080pRemux, resolution_detection_source);
        }

        // C# line 388: anime-bluray default is 720p. Resolution detection
        // source carries through whatever the regex hit: if R720p fired the
        // regex, it's Name; else Unknown.
        return mk_named(Quality::Bluray720p, resolution_detection_source);
    }

    // C# QualityParser.cs:392-424: anime-webdl. Substring "480p" / "1080p" /
    // "2160p" promotes the resolution-detection source to Name even when the
    // regex itself didn't fire (C# lines 400 / 408 / 416).
    if ANIME_WEBDL_REGEX.is_match(normalized) {
        let resolution_source_anime = QualityDetectionSource::Name;

        if matches!(
            resolution,
            Resolution::R360p | Resolution::R480p | Resolution::R540p | Resolution::R576p
        ) || contains_ignore_ascii_case(normalized, "480p")
        {
            return mk_named(Quality::Webdl480p, resolution_source_anime);
        }

        if resolution == Resolution::R1080p || contains_ignore_ascii_case(normalized, "1080p") {
            return mk_named(Quality::Webdl1080p, resolution_source_anime);
        }

        if resolution == Resolution::R2160p || contains_ignore_ascii_case(normalized, "2160p") {
            return mk_named(Quality::Webdl2160p, resolution_source_anime);
        }

        // C# line 422: anime-webdl default is 720p.
        return mk_named(Quality::Webdl720p, resolution_detection_source);
    }

    // C# QualityParser.cs:426-497: resolution-only fallback. Derives a
    // QualitySource from EITHER remuxMatch (BlurayRaw) OR the file extension
    // via MediaFileExtensions, then uses find_by_source_and_resolution. When
    // the derived source is Unknown, falls back to the Television-class
    // default for each resolution.
    if resolution != Resolution::Unknown {
        // C# line 428 + 432-451. `source` defaults to Unknown; `remuxMatch`
        // sets it to BlurayRaw (and flips SourceDetectionSource to Name);
        // otherwise the extension lookup may set it via the path's last
        // dotted token.
        let mut derived_source = QualitySource::Unknown;
        let mut source_detection = QualityDetectionSource::Unknown;

        if remux_match {
            derived_source = QualitySource::BlurayRaw;
            source_detection = QualityDetectionSource::Name;
        } else {
            // C# line 437-450 calls Sonarr's GetPathExtension
            // (LastIndexOf('.')), distinct from Path.GetExtension. The C#
            // version wraps the call in try/catch over ArgumentException,
            // but our Rust port's get_path_extension is total (no exceptions);
            // we read the extension verbatim and rely on
            // quality_for_extension to return Unknown for empty / unrecognised
            // inputs.
            //
            // C# uses `name` (raw) here, NOT `normalizedName`. For path-like
            // inputs that contain underscores (e.g. extension `.dvr_ms`, but
            // the dictionary actually carries `.dvr-ms`), the `_ -> ` `
            // normalisation could turn extensions into multi-token strings.
            // We mirror C# faithfully and read from `raw`.
            let ext = get_path_extension(raw);
            let from_ext = quality_for_extension(ext);
            if from_ext != Quality::Unknown {
                derived_source = quality_source(from_ext);
                source_detection = QualityDetectionSource::Extension;
            }
        }

        // Build the result with the resolution-arm-specific source/resolution
        // detection-source flips.
        let mk_resfb = |quality: Quality| QualityModel {
            quality,
            revision,
            source_detection_source: source_detection,
            // C# lines 455 / 466 / 477 / 489: ResolutionDetectionSource
            // explicitly set to Name in every resolution-only return.
            resolution_detection_source: QualityDetectionSource::Name,
            revision_detection_source,
        };

        let q = match resolution {
            Resolution::R2160p => {
                if derived_source == QualitySource::Unknown {
                    Quality::Hdtv2160p
                } else {
                    crate::quality::finder::find_by_source_and_resolution(derived_source, 2160)
                }
            }
            Resolution::R1080p => {
                if derived_source == QualitySource::Unknown {
                    Quality::Hdtv1080p
                } else {
                    crate::quality::finder::find_by_source_and_resolution(derived_source, 1080)
                }
            }
            Resolution::R720p => {
                if derived_source == QualitySource::Unknown {
                    Quality::Hdtv720p
                } else {
                    crate::quality::finder::find_by_source_and_resolution(derived_source, 720)
                }
            }
            Resolution::R360p | Resolution::R480p | Resolution::R540p | Resolution::R576p => {
                if derived_source == QualitySource::Unknown {
                    Quality::Sdtv
                } else {
                    crate::quality::finder::find_by_source_and_resolution(derived_source, 480)
                }
            }
            // Resolution::Unknown is excluded by the outer `if`.
            Resolution::Unknown => unreachable!("resolution != Unknown gated by outer if"),
        };

        return mk_resfb(q);
    }

    // C# QualityParser.cs:499-504: x264 codec with no other signal -> SDTV.
    // The codec_caps were already gathered above. This branch does NOT flip
    // any detection source to Name; per C# line 501 only Quality is set.
    if codec_caps.as_ref().and_then(|c| c.name("x264")).is_some() {
        return QualityModel {
            quality: Quality::Sdtv,
            revision,
            source_detection_source: QualityDetectionSource::Unknown,
            resolution_detection_source,
            revision_detection_source,
        };
    }

    // C# QualityParser.cs:506-526: 848x480 pixel tag. NB: C# uses
    // case-sensitive `Contains("dvd")` here (line 510) and case-insensitive
    // `ContainsIgnoreCase("bluray")` (line 515). We mirror that asymmetry.
    if normalized.contains("848x480") {
        if normalized.contains("dvd") {
            return mk_named(Quality::Dvd, QualityDetectionSource::Name);
        }
        if contains_ignore_ascii_case(normalized, "bluray") {
            return mk_named(Quality::Bluray480p, QualityDetectionSource::Name);
        }
        // Bare 848x480 with no source marker: only the resolution detection
        // source flips to Name; the quality is SDTV. C# line 522 doesn't
        // set SourceDetectionSource on this default-arm.
        return QualityModel {
            quality: Quality::Sdtv,
            revision,
            source_detection_source: QualityDetectionSource::Unknown,
            resolution_detection_source: QualityDetectionSource::Name,
            revision_detection_source,
        };
    }

    // C# QualityParser.cs:528-543: 1280x720 pixel tag. Both C# checks are
    // case-insensitive (line 528 + 532).
    if contains_ignore_ascii_case(normalized, "1280x720") {
        if contains_ignore_ascii_case(normalized, "bluray") {
            return mk_named(Quality::Bluray720p, QualityDetectionSource::Name);
        }
        return QualityModel {
            quality: Quality::Hdtv720p,
            revision,
            source_detection_source: QualityDetectionSource::Unknown,
            resolution_detection_source: QualityDetectionSource::Name,
            revision_detection_source,
        };
    }

    // C# QualityParser.cs:545-560: 1920x1080 pixel tag. Same shape as 1280x720.
    if contains_ignore_ascii_case(normalized, "1920x1080") {
        if contains_ignore_ascii_case(normalized, "bluray") {
            return mk_named(Quality::Bluray1080p, QualityDetectionSource::Name);
        }
        return QualityModel {
            quality: Quality::Hdtv1080p,
            revision,
            source_detection_source: QualityDetectionSource::Unknown,
            resolution_detection_source: QualityDetectionSource::Name,
            revision_detection_source,
        };
    }

    // C# QualityParser.cs:562-587: bare bluray-resolution tokens. The literal
    // "bluray720p" / "bluray1080p" / "bluray2160p" without separators bypasses
    // SOURCE_REGEX (which expects word boundaries around `BluRay`).
    if contains_ignore_ascii_case(normalized, "bluray720p") {
        return mk_named(Quality::Bluray720p, QualityDetectionSource::Name);
    }
    if contains_ignore_ascii_case(normalized, "bluray1080p") {
        return mk_named(Quality::Bluray1080p, QualityDetectionSource::Name);
    }
    if contains_ignore_ascii_case(normalized, "bluray2160p") {
        return mk_named(Quality::Bluray2160p, QualityDetectionSource::Name);
    }

    // C# QualityParser.cs:589-595 + 653-672: OtherSourceMatch. HD-TV / SD-TV
    // alternative-form via OTHER_SOURCE_REGEX. Only Quality + source-detection
    // are set; resolution-detection-source carries through from above.
    if let Some(caps) = OTHER_SOURCE_REGEX.captures(normalized) {
        let q = if caps.name("sdtv").is_some() {
            Some(Quality::Sdtv)
        } else if caps.name("hdtv").is_some() {
            Some(Quality::Hdtv720p)
        } else {
            None
        };
        if let Some(quality) = q {
            return QualityModel {
                quality,
                revision,
                source_detection_source: QualityDetectionSource::Name,
                resolution_detection_source,
                revision_detection_source,
            };
        }
    }

    // Carry-out: nothing matched. Return the default with the parsed revision
    // and any resolution-detection-source flag we accumulated.
    QualityModel {
        revision,
        revision_detection_source,
        resolution_detection_source,
        ..Default::default()
    }
}

/// **Canonical entry-point** for parsing a release name into a
/// [`QualityModel`](crate::quality::QualityModel). Ported from
/// `QualityParser.cs:68-98` (`ParseQuality`). Use [`parse_quality_name`]
/// only if you need to bypass the extension lookup.
///
/// Wraps [`parse_quality_name`] with the C# extension fallback at lines
/// 81-95: when the inner cascade returns `Quality::Unknown`, look up the file
/// extension via [`quality_for_extension`] and overlay the result. The C#
/// branch sets `SourceDetectionSource` and `ResolutionDetectionSource` to
/// `Extension` BEFORE inspecting the returned Quality (lines 87-88), so even
/// a recognised-but-`Unknown` extension (e.g. `.webm`) flips both flags.
///
/// C# guards this branch with `!name.ContainsInvalidPathChars()`. The Rust
/// port mirrors that guard via [`contains_invalid_path_chars`], which is the
/// `Path::GetInvalidPathChars()` set: NUL plus the C0 control range
/// `\x00-\x1F`. Cross-platform, no Windows-only chars (matches the C#
/// behaviour where `Path.GetInvalidPathChars` excludes the per-platform
/// "additional" chars like `<>:"/\?*`).
pub fn parse_quality(name: &str) -> crate::quality::QualityModel {
    use crate::quality::{Quality, QualityDetectionSource};

    let trimmed = name.trim();
    let mut result = parse_quality_name(trimmed);

    if result.quality == Quality::Unknown && !contains_invalid_path_chars(trimmed) {
        let ext = get_path_extension(trimmed);
        // C# QualityParser.cs:87-88: detection sources are set BEFORE the
        // dictionary lookup, so even an Unknown-mapped extension (e.g.
        // `.webm`) flips both flags. Mirror that ordering.
        result.source_detection_source = QualityDetectionSource::Extension;
        result.resolution_detection_source = QualityDetectionSource::Extension;
        result.quality = quality_for_extension(ext);
    }

    result
}

/// Mirrors `string.ContainsInvalidPathChars` from
/// `NzbDrone.Common/Extensions/PathExtensions.cs:184-192`. Returns true if
/// the string contains any character that .NET's
/// `Path.GetInvalidPathChars()` lists.
///
/// On both .NET Framework and .NET Core, `Path.GetInvalidPathChars()` returns
/// `{ '\0', '\x01' .. '\x1F' }` (NUL plus the C0 control range). It does NOT
/// include the per-platform "additional" characters (`<>:"/\?*` on Windows)
/// because those are reserved for `Path.GetInvalidFileNameChars()`. Mirroring
/// the C# behaviour means we accept release names containing `:` or `/` etc.
/// even though those would be invalid in a real filesystem path.
fn contains_invalid_path_chars(text: &str) -> bool {
    text.bytes().any(|b| b == 0 || (0x01..=0x1F).contains(&b))
}

/// Modifier-parsing helper. Ported from `QualityParser.cs:675-711`.
///
/// Returns `(revision, revision_detection_source)`. The detection source is
/// `Name` if any of the four C# modifier branches fire (Version, Proper,
/// Repack, Real); otherwise `Unknown`.
///
/// Order of operations (mirrors C#):
///
/// 1. **Version regex** (line 679): on hit, set `version = N`.
/// 2. **Proper regex** (line 687): on hit, set `version = (versionMatch ? N : 1) + 1`.
///    Equivalently: if Version did not fire, version is 2; if it did, version
///    is the captured N + 1. This is **assignment**, not increment, so a
///    second Proper hit does not bump again.
/// 3. **Repack regex** (line 693): on hit, same assignment as Proper, plus
///    `is_repack = true`. If both Proper and Repack fire, the Repack branch
///    overrides the Proper version (both compute the same value, so the
///    practical effect is just the `is_repack` flag).
/// 4. **Real regex** (line 702): set `real = matches.Count` (count, not
///    flag). Uses the **raw** input `name`, not the normalised one. The
///    other three branches use `normalizedName`. This is intentional in C#
///    and we preserve it.
///
/// Plan-spec drift notes (resolved in favour of C#):
///
/// - The plan-spec drafted Proper as `version += 1` (increment). C# uses
///   assignment with a Version-aware fallback. Ported per C#.
/// - The plan-spec ordered the checks Proper -> Repack -> Version -> Real.
///   C# orders them Version -> Proper -> Repack -> Real. Ported per C#.
/// - The plan-spec modelled `Real` as `bool`. C# stores it as `int` with
///   `Matches.Count` semantics. The Rust port carries `Revision.real: u32`;
///   this helper writes the count.
fn parse_quality_modifiers(
    name: &str,
    normalized_name: &str,
) -> (
    crate::quality::Revision,
    crate::quality::QualityDetectionSource,
) {
    use crate::quality::{QualityDetectionSource, Revision};

    let mut rev = Revision::default();
    let mut detection = QualityDetectionSource::Unknown;

    // Step 1: Version regex (C# line 679, run against normalizedName).
    // Walks all 5 named groups (`version` through `version5`) per the
    // VERSION_REGEX doc-comment, picking the first that captured. The captured
    // text is a single ASCII digit, so `parse::<u32>()` cannot widen overflow.
    let version_caps = VERSION_REGEX.captures(normalized_name);
    let version_value: Option<u32> = version_caps.as_ref().and_then(|caps| {
        caps.name("version")
            .or_else(|| caps.name("version2"))
            .or_else(|| caps.name("version3"))
            .or_else(|| caps.name("version4"))
            .or_else(|| caps.name("version5"))
            .and_then(|m| m.as_str().parse().ok())
    });
    if let Some(v) = version_value {
        rev.version = v;
        detection = QualityDetectionSource::Name;
    }

    // Step 2: Proper regex (C# line 687, run against normalizedName).
    // C#: `result.Revision.Version = versionRegexResult.Success ? Convert.ToInt32(...) + 1 : 2;`
    // -- assignment, not increment. The fallback when Version did NOT fire is
    // the literal 2 (NOT the current `rev.version + 1`).
    if PROPER_REGEX.is_match(normalized_name) {
        rev.version = match version_value {
            Some(v) => v + 1,
            None => 2,
        };
        detection = QualityDetectionSource::Name;
    }

    // Step 3: Repack regex (C# line 693, run against normalizedName).
    // Same assignment semantics as Proper, plus IsRepack = true.
    if REPACK_REGEX.is_match(normalized_name) {
        rev.version = match version_value {
            Some(v) => v + 1,
            None => 2,
        };
        rev.is_repack = true;
        detection = QualityDetectionSource::Name;
    }

    // Step 4: Real regex (C# line 702, run against the RAW name -- not
    // normalizedName -- because that is what C# does. Real is case-sensitive
    // (REAL_REGEX has no `(?i)` flag). The C# code uses `Matches(name).Count`,
    // which we mirror via `find_iter().count()`.
    let real_count = REAL_REGEX.find_iter(name).count();
    if real_count > 0 {
        // C# stores the raw count; we cap at `u32::MAX` defensively because
        // `usize` is wider on 64-bit hosts. In practice the count is bounded
        // by input length, which is bounded by Sonarr's release-name limit
        // (well under 4 billion).
        rev.real = u32::try_from(real_count).unwrap_or(u32::MAX);
        detection = QualityDetectionSource::Name;
    }

    (rev, detection)
}

#[cfg(test)]
mod tests {
    use super::regexes::*;
    use super::{
        SourceGroup, detect_resolution, match_remux, match_source, match_source_last,
        matches_alternative_resolution, matches_anime_bluray, parse_quality, parse_quality_name,
    };
    use crate::quality::{Quality, QualityDetectionSource, Resolution};

    // Source-regex direct hits.

    #[test]
    fn source_regex_detects_bluray() {
        let m = SOURCE_REGEX
            .captures("Movie.2020.1080p.BluRay.x264")
            .unwrap();
        assert!(m.name("bluray").is_some());
    }

    #[test]
    fn source_regex_detects_webdl() {
        let m = SOURCE_REGEX
            .captures("Show.S01E01.WEB-DL.AAC.x264")
            .unwrap();
        assert!(m.name("webdl").is_some());
    }

    #[test]
    fn source_regex_detects_webrip() {
        let m = SOURCE_REGEX.captures("Show.S01E01.WEBRip.x264").unwrap();
        assert!(m.name("webrip").is_some());
    }

    #[test]
    fn source_regex_detects_hdtv() {
        let m = SOURCE_REGEX.captures("Show.S01E01.HDTV.x264").unwrap();
        assert!(m.name("hdtv").is_some());
    }

    #[test]
    fn source_regex_detects_dvd() {
        let m = SOURCE_REGEX.captures("Movie.2010.DVDRip.XviD").unwrap();
        assert!(m.name("dvd").is_some());
    }

    // Source helper: lookaround workarounds.

    #[test]
    fn match_source_rejects_bare_bd_at_end_of_string() {
        // C# `BD(?!$)`. Bare `BD` at end of input must NOT match the bluray branch.
        // The release name "Show.BD" should fall through to other branches or yield None.
        // We craft an input where the only `BD`-shaped token is at the very end.
        let result = match_source("Show.S01E01.BD");
        // Either no match or a non-bluray match is acceptable; the bluray reject is the gate.
        if let Some(found) = result {
            assert_ne!(
                found.group,
                SourceGroup::Bluray,
                "bare BD at EOL should not match bluray; got matched={:?}",
                found.matched
            );
        }
    }

    #[test]
    fn match_source_accepts_bd_when_followed_by_more() {
        // `BD` mid-string is fine.
        let m = match_source("Show.BD.x264.somegroup").expect("should match bluray");
        assert_eq!(m.group, SourceGroup::Bluray);
        // Case-exact: input is uppercase BD; assert the regex returned the literal "BD"
        // rather than any normalised text. Catches accidental case-folding regressions.
        assert_eq!(m.matched, "BD");
    }

    #[test]
    fn match_source_accepts_bdmux_at_eol() {
        // `BDMux` is its own alternative and is not constrained by the BD-not-at-EOL rule.
        let m = match_source("Show.BDMux").expect("BDMux at EOL must match bluray");
        assert_eq!(m.group, SourceGroup::Bluray);
    }

    #[test]
    fn match_source_rejects_amzn_web_rip() {
        // C# `(?:AMZN|NF|DP)[. -]WEB[. -](?!Rip)`. AMZN.WEB.Rip must NOT match webdl.
        let result = match_source("Show.S01E01.AMZN.WEB.Rip.x264");
        if let Some(found) = result {
            // Should fall through to webrip, not webdl.
            assert_ne!(
                found.group,
                SourceGroup::Webdl,
                "AMZN.WEB.Rip must not be classified as webdl; got matched={:?}",
                found.matched
            );
        }
    }

    #[test]
    fn match_source_accepts_amzn_web_dl() {
        // AMZN.WEB-DL must classify as webdl. C# semantics: the leftmost-match
        // wins, so on this input the (?:AMZN|NF|DP)[. -]WEB[. -] provider branch
        // fires first (it starts at `AMZN`, earlier than where WEB-DL begins),
        // and its (?!Rip) post-filter passes because the next char after the
        // provider match is `D`, not `R`. The end result (webdl group) is what
        // callers care about; this test pins both.
        let m = match_source("Show.S01E01.AMZN.WEB-DL.x264").expect("AMZN.WEB-DL must match webdl");
        assert_eq!(m.group, SourceGroup::Webdl);
        // Pin which branch fires. If the alternation order or anchoring ever
        // shifts so that WEB[-_. ]DL claims the match instead, this catches it.
        assert_eq!(
            m.matched.to_ascii_uppercase(),
            "AMZN.WEB-",
            "expected provider_web branch (AMZN.WEB-), got `{}`",
            m.matched
        );
    }

    #[test]
    fn match_source_accepts_amzn_web_when_not_followed_by_rip() {
        // AMZN.WEB.h264 must match the (?:AMZN|NF|DP)[. -]WEB[. -] branch since
        // the trailing chars are not Rip.
        let m = match_source("Show.S01E01.AMZN.WEB.h264").expect("AMZN.WEB.h264 must match webdl");
        assert_eq!(m.group, SourceGroup::Webdl);
    }

    #[test]
    fn source_regex_uppercase_web_at_eol_matches_webdl() {
        // The C# `[. ](?-i:WEB)$` branch matches an uppercase `WEB` at end of input.
        // `(?-i:...)` is supported natively by Rust regex, so this is a verbatim port.
        let m = SOURCE_REGEX.captures("Show.S01E01.WEB").unwrap();
        assert!(
            m.name("webdl").is_some(),
            "uppercase WEB at EOL must match webdl"
        );
    }

    #[test]
    fn source_regex_lowercase_web_at_eol_does_not_match_via_eol_branch() {
        // Verifies that `(?-i:WEB)$` is in fact case-sensitive in our port.
        // `Show.S01E01.web` has no other webdl-matching token, so the only path
        // would be the EOL branch, which must reject lowercase.
        let result = SOURCE_REGEX.captures("Show.S01E01.web");
        // Either no match, or a non-webdl branch (none should hit `web` though).
        if let Some(c) = result {
            assert!(
                c.name("webdl").is_none(),
                "lowercase web at EOL must not match webdl"
            );
        }
    }

    // RawHD.

    #[test]
    fn raw_hd_regex_detects_rawhd() {
        assert!(RAW_HD_REGEX.is_match("Show.S01E01.RawHD.MPEG2"));
    }

    #[test]
    fn raw_hd_regex_detects_raw_hyphen_hd() {
        assert!(RAW_HD_REGEX.is_match("Show.S01E01.Raw-HD"));
    }

    #[test]
    fn raw_hd_regex_does_not_match_unrelated() {
        assert!(!RAW_HD_REGEX.is_match("Show.S01E01.RAWisCool"));
    }

    // MPEG2.

    #[test]
    fn mpeg2_regex_detects_mpeg2() {
        assert!(MPEG2_REGEX.is_match("Movie.MPEG2.x264"));
    }

    #[test]
    fn mpeg2_regex_detects_mpeg_dash_2() {
        assert!(MPEG2_REGEX.is_match("Movie.MPEG-2.x264"));
    }

    #[test]
    fn mpeg2_regex_is_case_sensitive() {
        // C# uses no IgnoreCase flag on this pattern, so `mpeg2` (lowercase) must NOT match.
        assert!(!MPEG2_REGEX.is_match("Movie.mpeg2.x264"));
    }

    // Remux.

    #[test]
    fn remux_regex_detects_uhd_remux() {
        assert!(REMUX_REGEX.is_match("Movie.2020.UHD.Remux.2160p"));
    }

    #[test]
    fn remux_regex_detects_bd_remux_prefix() {
        // `_Remux` form: `\d{4}p-Remux` matches via `\d{4}p-` prefix.
        assert!(REMUX_REGEX.is_match("Movie.2020.1080p-Remux"));
    }

    #[test]
    fn remux_regex_detects_remux_then_resolution() {
        // `Remux_2160p` form: matches the second alternative.
        assert!(REMUX_REGEX.is_match("Movie.2020.Remux_2160p"));
    }

    #[test]
    fn match_remux_returns_text() {
        let s = "Movie.2020.UHD.Remux.2160p";
        let got = match_remux(s).expect("must match");
        assert!(got.to_ascii_lowercase().contains("remux"));
    }

    // Anime Bluray (lookaround workaround).

    #[test]
    fn anime_bluray_regex_detects_bd_with_resolution() {
        assert!(matches_anime_bluray("[group] Show - 01 [BD1080p]"));
    }

    #[test]
    fn anime_bluray_regex_detects_bd_in_brackets() {
        // `[BD]` -> bare `bd` surrounded by `[` and `]`.
        assert!(matches_anime_bluray("[group] Show - 01 [BD]"));
    }

    #[test]
    fn anime_bluray_regex_detects_bd_with_space() {
        // `[BD 1080p]` -> bare `bd` surrounded by `[` and ` `.
        assert!(matches_anime_bluray("[group] Show - 01 [BD 1080p]"));
    }

    #[test]
    fn anime_bluray_regex_does_not_match_substring() {
        // Without surround chars, bare `bd` inside a word must not count.
        assert!(!matches_anime_bluray("Some.abdef.movie"));
    }

    #[test]
    fn anime_bluray_regex_does_not_match_bd_then_letter() {
        // `bdrip` has surround `.` left but `r` right, must not match the bare-bd branch.
        assert!(!matches_anime_bluray("Show.bdrip"));
    }

    #[test]
    fn anime_bluray_regex_rejects_bare_bd_at_sol() {
        // C#'s (?<=[-_. (\[])bd... lookbehind cannot match at start-of-input.
        assert!(!matches_anime_bluray("bd"));
        assert!(!matches_anime_bluray("bd.x264"));
    }

    #[test]
    fn anime_bluray_regex_rejects_bare_bd_at_eol() {
        // C#'s ...bd(?=[-_. )\]]) lookahead cannot match at end-of-input.
        assert!(!matches_anime_bluray("show.bd"));
    }

    #[test]
    fn anime_bluray_regex_accepts_bd1080_at_boundaries() {
        // bd720/bd1080/bd2160 are the lookaround-free branch; boundaries are fine.
        assert!(matches_anime_bluray("bd1080"));
        assert!(matches_anime_bluray("bd1080.mkv"));
    }

    // Anime WebDL.

    #[test]
    fn anime_webdl_regex_detects_web_brackets() {
        assert!(ANIME_WEBDL_REGEX.is_match("[group] Show - 01 [WEB] [1080p]"));
    }

    #[test]
    fn anime_webdl_regex_detects_paren_web_dot() {
        assert!(ANIME_WEBDL_REGEX.is_match("(WEB.1080p) Show"));
    }

    #[test]
    fn anime_webdl_regex_does_not_match_bare_web() {
        assert!(!ANIME_WEBDL_REGEX.is_match("Show.WEB.1080p"));
    }

    // Resolution.

    #[test]
    fn resolution_regex_detects_2160p() {
        let m = RESOLUTION_REGEX.captures("Movie.2160p.HDR").unwrap();
        assert!(m.name("R2160p").is_some());
    }

    #[test]
    fn resolution_regex_detects_1280x720_as_720p() {
        let m = RESOLUTION_REGEX
            .captures("[group] Show - 01 (1280x720)")
            .unwrap();
        assert!(m.name("R720p").is_some());
    }

    #[test]
    fn resolution_regex_detects_uhd_4k_form() {
        // C# 4K branch: `(?:UHD|HEVC|BD|H265)[-_. ]4k`. `UHD-4k` must hit R2160p.
        let m = RESOLUTION_REGEX.captures("Movie.2020.UHD-4k.x265").unwrap();
        assert!(m.name("R2160p").is_some());
    }

    #[test]
    fn resolution_regex_detects_4k_uhd_form() {
        // C# 4K branch: `4k[-_. ](?:UHD|HEVC|BD|H265)`. `4k-UHD` must hit R2160p.
        let m = RESOLUTION_REGEX.captures("Movie.2020.4k-UHD.x265").unwrap();
        assert!(m.name("R2160p").is_some());
    }

    #[test]
    fn resolution_regex_detects_480p() {
        let m = RESOLUTION_REGEX.captures("Show.S01E01.480p.x264").unwrap();
        assert!(m.name("R480p").is_some());
    }

    #[test]
    fn resolution_regex_detects_1080p_fhd() {
        let m = RESOLUTION_REGEX.captures("Movie.2020.FHD.x264").unwrap();
        assert!(m.name("R1080p").is_some());
    }

    #[test]
    fn resolution_regex_detects_4kto1080p_form() {
        // C# QualityParser.cs:49 - R1080p group includes `4kto1080p` for
        // downscaled-UHD releases. Regression guard against the T5-original
        // miss that dropped this token while correcting the R2160p 4K branches.
        let m = RESOLUTION_REGEX.captures("Movie.4kto1080p.x264").unwrap();
        assert!(
            m.name("R1080p").is_some(),
            "expected R1080p branch to match `4kto1080p`"
        );
    }

    // Alternative resolution (duplicate-group workaround).

    #[test]
    fn alternative_resolution_regex_matches_uhd() {
        assert!(matches_alternative_resolution("Movie.UHD.Bluray"));
    }

    #[test]
    fn alternative_resolution_regex_matches_bracket_4k() {
        assert!(matches_alternative_resolution("Movie [4K] Bluray"));
    }

    #[test]
    fn alternative_resolution_regex_does_not_match_unrelated() {
        assert!(!matches_alternative_resolution("Movie.1080p.Bluray"));
    }

    #[test]
    fn alternative_resolution_regex_named_groups_are_distinct() {
        // Direct regex assertion: C# uses the same `<R2160p>` name twice; we
        // renamed the second to `R2160p_alt` to satisfy Rust regex's no-dup
        // rule. Confirm both names exist and fire on their respective inputs.
        let uhd = ALTERNATIVE_RESOLUTION_REGEX
            .captures("Movie.UHD.x264")
            .unwrap();
        assert!(uhd.name("R2160p").is_some());
        assert!(uhd.name("R2160p_alt").is_none());

        let four_k = ALTERNATIVE_RESOLUTION_REGEX
            .captures("Movie [4K] x264")
            .unwrap();
        assert!(four_k.name("R2160p").is_none());
        assert!(four_k.name("R2160p_alt").is_some());
    }

    // Codec.

    #[test]
    fn codec_regex_detects_xvid() {
        let m = CODEC_REGEX.captures("Show.S01E01.Xvid.AC3").unwrap();
        assert!(m.name("xvid").is_some());
    }

    #[test]
    fn codec_regex_does_not_match_x_hyphen_vid() {
        // Plan-spec drafted `X-?vid`; C# QualityParser.cs:56-57 is `Xvid`
        // literal. A future relaxation back to the hyphenated form would
        // silently widen matching. Mirror of the resolution_regex_detects_4kto1080p_form
        // regression-guard pattern.
        assert!(CODEC_REGEX.captures("Movie.X-vid.AC3").is_none());
    }

    #[test]
    fn codec_regex_detects_x264() {
        let m = CODEC_REGEX.captures("Movie.1080p.x264.AC3").unwrap();
        assert!(m.name("x264").is_some());
    }

    #[test]
    fn codec_regex_detects_h264_case_insensitive() {
        let m = CODEC_REGEX.captures("Movie.1080p.H264.AC3").unwrap();
        assert!(m.name("h264").is_some());
    }

    #[test]
    fn codec_regex_detects_xvidhd() {
        let m = CODEC_REGEX.captures("Movie.XvidHD.AC3").unwrap();
        // XvidHD must hit the xvidhd group, not xvid (alternation order matters).
        assert!(m.name("xvidhd").is_some());
        assert!(m.name("xvid").is_none());
    }

    #[test]
    fn codec_regex_detects_divx() {
        let m = CODEC_REGEX.captures("Movie.divx.AC3").unwrap();
        assert!(m.name("divx").is_some());
    }

    // Other source.

    #[test]
    fn other_source_regex_detects_hd_tv() {
        let m = OTHER_SOURCE_REGEX.captures("Show.HD-TV.x264").unwrap();
        assert!(m.name("hdtv").is_some());
    }

    #[test]
    fn other_source_regex_detects_sd_tv() {
        let m = OTHER_SOURCE_REGEX.captures("Show.SD.TV.x264").unwrap();
        assert!(m.name("sdtv").is_some());
    }

    // High-def PDTV.

    #[test]
    fn high_def_pdtv_regex_detects_hr_ws() {
        assert!(HIGH_DEF_PDTV_REGEX.is_match("Show.S01E01.hr-ws.x264"));
    }

    #[test]
    fn high_def_pdtv_regex_does_not_match_unrelated() {
        assert!(!HIGH_DEF_PDTV_REGEX.is_match("Show.S01E01.hrws.x264"));
    }

    // Proper.

    #[test]
    fn proper_regex_detects_proper() {
        assert!(PROPER_REGEX.is_match("Show PROPER 720p"));
    }

    #[test]
    fn proper_regex_detects_proper_lowercase() {
        // C# uses IgnoreCase; lowercase must match too.
        assert!(PROPER_REGEX.is_match("Show.proper.720p"));
    }

    // Repack.

    #[test]
    fn repack_regex_detects_repack() {
        assert!(REPACK_REGEX.is_match("Show REPACK2 1080p"));
    }

    #[test]
    fn repack_regex_detects_rerip() {
        assert!(REPACK_REGEX.is_match("Show.RERIP.1080p"));
    }

    #[test]
    fn repack_regex_detects_bare_repack() {
        // No trailing digit is also valid: `repack\d?` makes the digit optional.
        assert!(REPACK_REGEX.is_match("Show.REPACK.1080p"));
    }

    // Version.

    #[test]
    fn version_regex_detects_v2() {
        // Rust regex does not allow duplicate names, so we renamed the C#
        // alternation branches to version/version2/version3/version4/version5.
        // For the `1080p.v2` form, the fifth branch (`version5`) fires.
        let m = VERSION_REGEX.captures("Show 1080p v2").unwrap();
        let version = m
            .name("version")
            .or_else(|| m.name("version2"))
            .or_else(|| m.name("version3"))
            .or_else(|| m.name("version4"))
            .or_else(|| m.name("version5"))
            .expect("at least one named version group must capture");
        assert_eq!(version.as_str(), "2");
    }

    #[test]
    fn version_regex_detects_bracket_v3() {
        // `[v3]` form fires the second branch (version2 in our port).
        let m = VERSION_REGEX.captures("Show [v3] 1080p").unwrap();
        assert!(m.name("version2").is_some());
        assert_eq!(m.name("version2").unwrap().as_str(), "3");
    }

    #[test]
    fn version_regex_detects_repack_with_digit() {
        // `repack2` form fires the third branch (version3 in our port).
        let m = VERSION_REGEX.captures("Show.repack2.1080p").unwrap();
        assert!(m.name("version3").is_some());
        assert_eq!(m.name("version3").unwrap().as_str(), "2");
    }

    #[test]
    fn version_regex_detects_rerip_with_digit() {
        // `rerip3` form fires the fourth branch (version4 in our port).
        let m = VERSION_REGEX.captures("Show.rerip3.1080p").unwrap();
        assert!(m.name("version4").is_some());
        assert_eq!(m.name("version4").unwrap().as_str(), "3");
    }

    #[test]
    fn version_regex_detects_digit_v_digit_form() {
        // `01-v2_` form fires the first branch (version in our port).
        // Pattern: `\d[-._ ]?v(?<version>\d)[-._ ]`.
        let m = VERSION_REGEX.captures("Show 01-v2_1080p").unwrap();
        assert!(m.name("version").is_some());
        assert_eq!(m.name("version").unwrap().as_str(), "2");
    }

    // Real (case-sensitive).

    #[test]
    fn real_regex_detects_real() {
        assert!(REAL_REGEX.is_match("Show REAL PROPER 1080p"));
    }

    #[test]
    fn real_regex_is_case_sensitive() {
        // C# `RealRegex` carries no IgnoreCase flag, so lowercase `real` must
        // NOT match. This gates the absence of the `(?i)` flag in our port.
        assert!(!REAL_REGEX.is_match("show real proper"));
        assert!(!REAL_REGEX.is_match("Show Real Proper"));
    }

    // T6 cascade entry-point + modifier parsing.
    //
    // Cross-checked against `QualityParser.cs:100-112` (ParseQualityName) and
    // `QualityParser.cs:675-711` (ParseQualityModifiers). Plan-spec versus C#
    // discrepancies are noted in `parse_quality_modifiers` itself; the tests
    // below pin C# semantics (the source of truth).

    #[test]
    fn parses_proper_increments_revision() {
        // C# (line 689): proper sets version = match? +1 : 2 (no version match
        // here, so version becomes 2).
        let m = parse_quality_name("Show S01E01 PROPER HDTV XviD");
        assert_eq!(m.revision.version, 2);
    }

    #[test]
    fn parses_repack_sets_is_repack() {
        // C# (line 696): repack sets IsRepack = true. version becomes 2 via the
        // same fallback as proper.
        let m = parse_quality_name("Show.2010.REPACK.1080p.WEB");
        assert!(m.revision.is_repack);
        assert_eq!(m.revision.version, 2);
    }

    #[test]
    fn parses_real_sets_real_flag() {
        // C# (line 706): Real = realRegexResult.Count, so for one REAL match
        // the count is 1. The PROPER on this input bumps version to 2 (the
        // REAL itself does not change version).
        let m = parse_quality_name("Show.REAL.PROPER.1080p");
        assert_eq!(m.revision.real, 1);
        assert_eq!(m.revision.version, 2);
    }

    #[test]
    fn parses_explicit_version_2() {
        // C# (line 683): VersionRegex sets version = N. The 5th VERSION_REGEX
        // branch fires for the `1080p.v2` form.
        let m = parse_quality_name("Show.S01E01.1080p.v2");
        assert_eq!(m.revision.version, 2);
    }

    #[test]
    fn raw_hd_short_circuits() {
        // C# (line 105): if RawHDRegex matches, set Quality = RAWHD and return
        // immediately. The cascade bails before considering source/resolution.
        let m = parse_quality_name("Show.S01E01.RawHD");
        assert_eq!(m.quality, Quality::RawHd);
    }

    // Extra coverage on T6's load-bearing edges.

    #[test]
    fn parse_quality_name_default_when_no_modifiers_or_rawhd() {
        // No modifiers, no RawHD: T6 returns the default QualityModel with
        // version=1 and Quality::Unknown. T7's source-to-quality cascade is
        // what flips Quality based on source/resolution; T6 must not.
        let m = parse_quality_name("Show.S01E01.MysteryFormat");
        assert_eq!(m.quality, Quality::Unknown);
        assert_eq!(m.revision.version, 1);
        assert_eq!(m.revision.real, 0);
        assert!(!m.revision.is_repack);
    }

    #[test]
    fn parse_quality_name_empty_input_returns_default() {
        // C# ParseQuality:72 short-circuits on IsNullOrWhiteSpace. The Rust
        // port handles empty input via natural cascade fallthrough (no source
        // match, no resolution, no modifiers -> default QualityModel).
        // Pins the graceful-empty behaviour against a future "validate
        // input non-empty" change that might panic.
        let m = parse_quality_name("");
        assert_eq!(m.quality, Quality::Unknown);
        assert_eq!(m.revision.version, 1);
        assert_eq!(m.revision.real, 0);
        assert!(!m.revision.is_repack);
    }

    #[test]
    fn parse_quality_name_normalizes_underscores() {
        // C# (line 102): name.Replace('_', ' '). PROPER sandwiched in
        // underscores must still classify as a proper. Our `\b(?<proper>proper)\b`
        // also matches across `_` boundaries (regex `\b` treats underscore as a
        // word char, so `_PROPER_` does NOT have a word boundary), which is
        // exactly why C# normalises first.
        let m = parse_quality_name("Show_S01E01_PROPER_HDTV");
        assert_eq!(m.revision.version, 2);
    }

    #[test]
    fn parse_quality_name_real_uses_raw_input_not_normalized() {
        // C# (line 702): RealRegex.Matches(name). The raw input is used, not
        // normalizedName. Real is case-sensitive uppercase. Underscores around
        // REAL are fine because the regex uses \b boundaries with word-char
        // semantics (`_` is a word char, so `_REAL_` has no \b, but that is
        // NOT a problem here because the literal `REAL` token is bordered by
        // other separators in real-world inputs).
        let m = parse_quality_name("Show.REAL.S01E01.1080p");
        assert_eq!(m.revision.real, 1);
    }

    #[test]
    fn parse_quality_name_real_underscore_bordered_does_not_match() {
        // C# uses RealRegex.Matches(name) on the RAW input. `_REAL_` has no \b
        // boundary on either side because `_` is a word-char in the regex
        // engine. If a future refactor accidentally switched Real to scan the
        // normalized name (` REAL `), the boundary would fire and this would
        // flip from 0 to 1. This test gates that drift; the existing
        // parse_quality_name_real_uses_raw_input_not_normalized test does NOT
        // discriminate (its input produces identical results raw and normalized).
        let m = parse_quality_name("Show_S01E01_REAL_1080p");
        assert_eq!(m.revision.real, 0);
    }

    #[test]
    fn parse_quality_name_real_lowercase_is_ignored() {
        // C# REAL_REGEX is case-sensitive (no IgnoreCase flag). lowercase
        // `real` must not bump the counter.
        let m = parse_quality_name("Show.real.S01E01.1080p");
        assert_eq!(m.revision.real, 0);
    }

    #[test]
    fn parse_quality_name_multi_real_counts() {
        // C# `Real = realRegexResult.Count`. Two REAL tokens => Real = 2.
        // Verifies the u32 vs bool decision: a `bool` would lose this signal.
        let m = parse_quality_name("Show.REAL.REAL.1080p");
        assert_eq!(m.revision.real, 2);
    }

    #[test]
    fn parse_quality_name_repack_with_digit_takes_version() {
        // C# (line 695): when version regex AND repack both match, the version
        // value is `versionRegexResult.Groups["version"].Value + 1`. For
        // `repack2`, the version regex captures "2", and the repack branch
        // sets version = 2 + 1 = 3.
        let m = parse_quality_name("Show.repack2.1080p");
        assert_eq!(m.revision.version, 3);
        assert!(m.revision.is_repack);
    }

    #[test]
    fn parse_quality_name_proper_with_digit_v2_takes_version() {
        // C# (line 689): version=2, proper bumps to 3.
        let m = parse_quality_name("Show.PROPER.1080p.v2");
        assert_eq!(m.revision.version, 3);
    }

    #[test]
    fn raw_hd_short_circuits_populates_detection_sources() {
        // C# (lines 107-109): when RawHD matches, source + resolution detection
        // sources are set to Name. Revision detection source is set if any
        // modifier fired (none here, so it stays Unknown).
        let m = parse_quality_name("Show.S01E01.RawHD");
        assert_eq!(
            m.source_detection_source,
            crate::quality::QualityDetectionSource::Name
        );
        assert_eq!(
            m.resolution_detection_source,
            crate::quality::QualityDetectionSource::Name
        );
        assert_eq!(
            m.revision_detection_source,
            crate::quality::QualityDetectionSource::Unknown
        );
    }

    #[test]
    fn raw_hd_short_circuits_with_proper_sets_revision_detection_source() {
        // C# (line 690): proper sets RevisionDetectionSource = Name. Even
        // through a RawHD short-circuit, the revision-detection source must
        // travel along because ParseQualityModifiers ran first.
        let m = parse_quality_name("Show.RawHD.PROPER");
        assert_eq!(m.quality, Quality::RawHd);
        assert_eq!(m.revision.version, 2);
        assert_eq!(
            m.revision_detection_source,
            crate::quality::QualityDetectionSource::Name
        );
    }

    // T7 detect_resolution helper.

    #[test]
    fn detect_resolution_returns_2160p_for_2160p_token() {
        assert_eq!(
            detect_resolution("Movie.2020.2160p.BluRay"),
            Resolution::R2160p
        );
    }

    #[test]
    fn detect_resolution_returns_2160p_for_uhd_token() {
        // Falls back to ALTERNATIVE_RESOLUTION_REGEX when the main
        // RESOLUTION_REGEX would not capture (no numeric resolution token).
        assert_eq!(
            detect_resolution("Movie.2020.UHD.BluRay"),
            Resolution::R2160p
        );
    }

    #[test]
    fn detect_resolution_returns_2160p_for_bracket_4k() {
        assert_eq!(
            detect_resolution("Movie.2020 [4K] BluRay"),
            Resolution::R2160p
        );
    }

    #[test]
    fn detect_resolution_returns_1080p_for_1080p_token() {
        assert_eq!(
            detect_resolution("Movie.2020.1080p.WEB-DL"),
            Resolution::R1080p
        );
    }

    #[test]
    fn detect_resolution_returns_720p_for_1280x720_token() {
        // C# RESOLUTION_REGEX folds 1280x720 into R720p.
        assert_eq!(detect_resolution("Show.S01E01.1280x720"), Resolution::R720p);
    }

    #[test]
    fn detect_resolution_returns_480p_for_480p_token() {
        assert_eq!(
            detect_resolution("Show.S01E01.480p.HDTV"),
            Resolution::R480p
        );
    }

    #[test]
    fn detect_resolution_returns_540p_for_540p_token() {
        assert_eq!(
            detect_resolution("Show.S01E01.540p.HDTV"),
            Resolution::R540p
        );
    }

    #[test]
    fn detect_resolution_returns_576p_for_576p_token() {
        assert_eq!(
            detect_resolution("Show.S01E01.576p.HDTV"),
            Resolution::R576p
        );
    }

    #[test]
    fn detect_resolution_returns_360p_for_360p_token() {
        assert_eq!(
            detect_resolution("Show.S01E01.360p.HDTV"),
            Resolution::R360p
        );
    }

    #[test]
    fn detect_resolution_returns_unknown_when_no_token() {
        assert_eq!(
            detect_resolution("Show.S01E01.HDTV.x264"),
            Resolution::Unknown
        );
    }

    // T7 match_source_last (LastOrDefault semantics).

    #[test]
    fn match_source_last_returns_last_when_two_distinct_sources() {
        // C# `sourceMatches.OfType<Match>().LastOrDefault()`: HDTV at the
        // start, BluRay at the end -> last match is BluRay.
        let m = match_source_last("Show.HDTV.Repack.1080p.BluRay.x264").expect("BluRay must match");
        assert_eq!(m.group, SourceGroup::Bluray);
    }

    #[test]
    fn match_source_last_returns_first_when_only_one_source() {
        // Single sourceMatch -> first == last; trivially exercised.
        let m = match_source_last("Movie.2020.1080p.BluRay.x264").expect("BluRay must match");
        assert_eq!(m.group, SourceGroup::Bluray);
    }

    #[test]
    fn match_source_last_skips_filtered_candidates() {
        // C# `BD(?!$)` rejects bare BD at end. If the only candidate is
        // filtered, return None.
        assert!(match_source_last("Show.S01E01.BD").is_none());
    }

    // T7 cascade: bluray arm.

    #[test]
    fn bluray_2160p() {
        // Plan-required test #1.
        assert_eq!(
            parse_quality_name("Movie.2020.2160p.BluRay.x265").quality,
            Quality::Bluray2160p
        );
    }

    #[test]
    fn bluray_1080p_remux() {
        // Plan-required test #2.
        assert_eq!(
            parse_quality_name("Movie.2020.1080p.BluRay.Remux.AVC").quality,
            Quality::Bluray1080pRemux
        );
    }

    #[test]
    fn bluray_720p() {
        // Plan-required test #3.
        assert_eq!(
            parse_quality_name("Movie.720p.BluRay.x264").quality,
            Quality::Bluray720p
        );
    }

    #[test]
    fn bluray_576p() {
        // C# QualityParser.cs:150-154 covers 576p as its own bucket.
        assert_eq!(
            parse_quality_name("Movie.576p.BluRay.x264").quality,
            Quality::Bluray576p
        );
    }

    #[test]
    fn bluray_480p_via_xvid_codec() {
        // C# QualityParser.cs:131-135: a bluray release with xvid OR divx
        // codec is downgraded to 480p regardless of resolution.
        assert_eq!(
            parse_quality_name("Movie.2020.BluRay.Xvid.AC3").quality,
            Quality::Bluray480p
        );
    }

    #[test]
    fn bluray_480p_via_divx_codec() {
        // C# QualityParser.cs:131-135: divx co-equal with xvid.
        assert_eq!(
            parse_quality_name("Movie.2020.BluRay.divx.AC3").quality,
            Quality::Bluray480p
        );
    }

    #[test]
    fn bluray_480p_via_low_resolution() {
        // C# QualityParser.cs:156-161: 360p / 480p / 540p collapse to 480p.
        assert_eq!(
            parse_quality_name("Movie.2020.480p.BluRay.x264").quality,
            Quality::Bluray480p
        );
        assert_eq!(
            parse_quality_name("Movie.2020.540p.BluRay.x264").quality,
            Quality::Bluray480p
        );
    }

    #[test]
    fn bluray_2160p_remux_via_2160p_token_and_remux() {
        // C# QualityParser.cs:139.
        assert_eq!(
            parse_quality_name("Movie.2020.2160p.BluRay.Remux.HDR.x265").quality,
            Quality::Bluray2160pRemux
        );
    }

    #[test]
    fn bluray_remux_unknown_resolution_falls_back_to_1080p_remux() {
        // C# QualityParser.cs:165-169: remux without a 720p resolution falls
        // back to 1080pRemux. Unknown resolution + remux + bluray -> 1080pRemux.
        assert_eq!(
            parse_quality_name("Movie.BluRay.Remux.x264").quality,
            Quality::Bluray1080pRemux
        );
    }

    #[test]
    fn bluray_720p_with_remux_stays_720p() {
        // C# QualityParser.cs:165 explicit comment: "720p remux should
        // fallback as 720p BluRay". Pin that the 720p arm ignores the remux
        // signal.
        assert_eq!(
            parse_quality_name("Movie.720p.BluRay.Remux.x264").quality,
            Quality::Bluray720p
        );
    }

    #[test]
    fn bluray_unknown_resolution_no_remux_falls_back_to_720p() {
        // C# QualityParser.cs:171-172: implicit default at the bottom of the
        // bluray arm is Bluray720p when no resolution token, no remux, no
        // codec downgrade hits. Pins the Resolution::Unknown + remux=false
        // -> Bluray720p path. The 720p-with-remux carve-out test
        // (bluray_720p_with_remux_stays_720p) covers the symmetric case;
        // this completes the matrix.
        assert_eq!(
            parse_quality_name("Movie.BluRay.x264").quality,
            Quality::Bluray720p
        );
    }

    // T7 cascade: webdl arm.

    #[test]
    fn webdl_1080p() {
        // Plan-required test #4.
        assert_eq!(
            parse_quality_name("Movie.2020.1080p.WEB-DL.x264").quality,
            Quality::Webdl1080p
        );
    }

    #[test]
    fn webdl_720p_itunes() {
        // Plan-required test #5. iTunesHD is a webdl-branch alternative.
        assert_eq!(
            parse_quality_name("Movie.720p.iTunesHD.AVC").quality,
            Quality::Webdl720p
        );
    }

    #[test]
    fn webdl_2160p() {
        // C# QualityParser.cs:177-180.
        assert_eq!(
            parse_quality_name("Movie.2020.2160p.WEB-DL.x265").quality,
            Quality::Webdl2160p
        );
    }

    #[test]
    fn webdl_480p_default() {
        // C# QualityParser.cs:201-202: any webdl with no R720p / R1080p /
        // R2160p resolution match falls back to 480p.
        assert_eq!(
            parse_quality_name("Movie.2020.WEB-DL.AAC.x264").quality,
            Quality::Webdl480p
        );
    }

    #[test]
    fn webdl_720p_via_bracket_marker() {
        // C# QualityParser.cs:195-199: raw-name `[WEBDL]` substring forces
        // 720p when no resolution match is present. The substring is checked
        // against the RAW input, NOT the normalised name (underscores become
        // spaces in normalised, but the literal bracket text is identical).
        assert_eq!(
            parse_quality_name("Movie.[WEBDL].WEB-DL.AC3").quality,
            Quality::Webdl720p
        );
    }

    // T7 cascade: webrip arm.

    #[test]
    fn webrip_2160p() {
        // Plan-required test #6.
        assert_eq!(
            parse_quality_name("Movie.2160p.WebRip.x265").quality,
            Quality::Webrip2160p
        );
    }

    #[test]
    fn webrip_1080p() {
        // C# QualityParser.cs:213-216.
        assert_eq!(
            parse_quality_name("Movie.2020.1080p.WEBRip.x264").quality,
            Quality::Webrip1080p
        );
    }

    #[test]
    fn webrip_720p() {
        // C# QualityParser.cs:219-222.
        assert_eq!(
            parse_quality_name("Show.S01E01.720p.WEBRip.x264").quality,
            Quality::Webrip720p
        );
    }

    #[test]
    fn webrip_480p_default() {
        // C# QualityParser.cs:225-226: webrip with no resolution match -> 480p.
        assert_eq!(
            parse_quality_name("Show.S01E01.WEBRip.x264").quality,
            Quality::Webrip480p
        );
    }

    // T7 cascade: hdtv arm.

    #[test]
    fn hdtv_720p() {
        // Plan-required test #7.
        assert_eq!(
            parse_quality_name("Show.S01E01.720p.HDTV.x264").quality,
            Quality::Hdtv720p
        );
    }

    #[test]
    fn hdtv_1080p() {
        // Plan-required test #8.
        assert_eq!(
            parse_quality_name("Show.S01E01.1080p.HDTV.x264").quality,
            Quality::Hdtv1080p
        );
    }

    #[test]
    fn hdtv_2160p() {
        // C# QualityParser.cs:237-240.
        assert_eq!(
            parse_quality_name("Show.S01E01.2160p.HDTV.x265").quality,
            Quality::Hdtv2160p
        );
    }

    #[test]
    fn hdtv_mpeg2_short_circuits_to_rawhd() {
        // C# QualityParser.cs:231-234: when the source is HDTV and the
        // normalized name contains MPEG2 (case-sensitive), the cascade
        // short-circuits to RAWHD even with a 1080p token in the input.
        assert_eq!(
            parse_quality_name("Show.S01E01.1080p.HDTV.MPEG2").quality,
            Quality::RawHd
        );
    }

    #[test]
    fn hdtv_mpeg2_lowercase_does_not_short_circuit() {
        // C#'s MPEG2_REGEX is case-sensitive (no IgnoreCase flag): a
        // lowercase `mpeg2` token must NOT trigger the short-circuit.
        // Matches the modifier behaviour pinned at T4 (mpeg2_regex_is_case_sensitive).
        assert_eq!(
            parse_quality_name("Show.S01E01.1080p.HDTV.mpeg2.x264").quality,
            Quality::Hdtv1080p
        );
    }

    #[test]
    fn hdtv_720p_via_bracket_marker() {
        // C# QualityParser.cs:255-259: raw-name `[HDTV]` substring forces
        // 720p when no resolution match is present.
        assert_eq!(
            parse_quality_name("Show.S01E01.[HDTV].x264").quality,
            Quality::Hdtv720p
        );
    }

    // T7 cascade: dvd arm.

    #[test]
    fn dvd() {
        // Plan-required test #9. DVD source always maps to DVD regardless of
        // resolution.
        assert_eq!(
            parse_quality_name("Movie.2010.DVDRip.XviD-AAC").quality,
            Quality::Dvd
        );
    }

    #[test]
    fn dvd_with_explicit_dvd_token() {
        // The bare `DVD` token also fires the dvd branch.
        assert_eq!(
            parse_quality_name("Movie.2010.DVD.XviD-AAC").quality,
            Quality::Dvd
        );
    }

    #[test]
    fn dvd_ntsc_token() {
        // C# QualityParser.cs:25 includes NTSC in the dvd alternation.
        assert_eq!(
            parse_quality_name("Movie.2010.NTSC.XviD-AAC").quality,
            Quality::Dvd
        );
    }

    // T7 cascade: bdrip / brrip (sub-bluray) arms.

    #[test]
    fn bdrip_720p_maps_to_bluray720p() {
        // C# QualityParser.cs:265-272.
        assert_eq!(
            parse_quality_name("Movie.720p.BDRip.x264").quality,
            Quality::Bluray720p
        );
    }

    #[test]
    fn bdrip_1080p_maps_to_bluray1080p() {
        assert_eq!(
            parse_quality_name("Movie.1080p.BDRip.x264").quality,
            Quality::Bluray1080p
        );
    }

    #[test]
    fn bdrip_default_maps_to_bluray480p() {
        // C# QualityParser.cs:280-281: BDRip default is 480p.
        assert_eq!(
            parse_quality_name("Movie.BDRip.x264").quality,
            Quality::Bluray480p
        );
    }

    #[test]
    fn brrip_2160p_maps_to_bluray2160p() {
        // C# QualityParser.cs:276-278.
        assert_eq!(
            parse_quality_name("Movie.2160p.BRRip.x265").quality,
            Quality::Bluray2160p
        );
    }

    // T7 cascade: pdtv / sdtv / dsr / tvrip arm.

    #[test]
    fn sdtv_default() {
        // Plan-required test #10. HDTV with no resolution token -> SDTV.
        // (The hdtv arm hits the no-resolution fallback at C# line 261.)
        assert_eq!(
            parse_quality_name("Show.S01E01.HDTV.x264").quality,
            Quality::Sdtv
        );
    }

    #[test]
    fn pdtv_no_resolution_maps_to_sdtv() {
        // C# QualityParser.cs:315-316.
        assert_eq!(
            parse_quality_name("Show.S01E01.PDTV.x264").quality,
            Quality::Sdtv
        );
    }

    #[test]
    fn pdtv_1080p_maps_to_hdtv1080p() {
        // C# QualityParser.cs:296-300.
        assert_eq!(
            parse_quality_name("Show.S01E01.1080p.PDTV.x264").quality,
            Quality::Hdtv1080p
        );
    }

    #[test]
    fn pdtv_720p_maps_to_hdtv720p() {
        // C# QualityParser.cs:302-306.
        assert_eq!(
            parse_quality_name("Show.S01E01.720p.PDTV.x264").quality,
            Quality::Hdtv720p
        );
    }

    #[test]
    fn pdtv_hr_ws_maps_to_hdtv720p() {
        // C# QualityParser.cs:308-312: HighDefPdtvRegex (`hr-ws`) on a pdtv
        // source promotes to Hdtv720p AND flips the resolution-detection
        // source to Name even though no resolution-regex group fired.
        let m = parse_quality_name("Show.S01E01.PDTV.hr-ws.x264");
        assert_eq!(m.quality, Quality::Hdtv720p);
        assert_eq!(m.resolution_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn sdtv_branch_with_explicit_sdtv_token() {
        // The bare `SDTV` token routes into the pdtv-cluster arm.
        assert_eq!(
            parse_quality_name("Show.S01E01.SDTV.x264").quality,
            Quality::Sdtv
        );
    }

    #[test]
    fn dsr_branch_default_sdtv() {
        // C# QualityParser.cs:293-294: DSR routes through the pdtv-cluster
        // arm and falls back to SDTV without a resolution match.
        assert_eq!(
            parse_quality_name("Show.S01E01.DSR.x264").quality,
            Quality::Sdtv
        );
    }

    #[test]
    fn tvrip_branch_default_sdtv() {
        // C# QualityParser.cs:294: TVRip in the pdtv-cluster arm.
        assert_eq!(
            parse_quality_name("Show.S01E01.TVRip.x264").quality,
            Quality::Sdtv
        );
    }

    // T7 cascade: cross-arm semantics.

    #[test]
    fn cascade_uses_last_source_match() {
        // C# QualityParser.cs:115 LastOrDefault: HDTV appears first, BluRay
        // appears later -> classification is bluray, not hdtv. This is the
        // single most important cross-arm guarantee in the cascade.
        let m = parse_quality_name("Show.HDTV.Repack.1080p.BluRay.x264");
        assert_eq!(m.quality, Quality::Bluray1080p);
    }

    #[test]
    fn cascade_populates_source_detection_when_source_fires() {
        // Any sourceMatch sets source_detection_source = Name (C# line 127).
        let m = parse_quality_name("Movie.1080p.BluRay.x264");
        assert_eq!(m.source_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn cascade_populates_resolution_detection_when_resolution_fires() {
        // C# QualityParser.cs:120-123: a non-Unknown resolution flips
        // resolution_detection_source to Name regardless of source-arm.
        let m = parse_quality_name("Movie.1080p.BluRay.x264");
        assert_eq!(m.resolution_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn cascade_leaves_resolution_detection_unknown_when_no_resolution() {
        // No resolution token -> resolution_detection_source stays Unknown
        // even though the source arm fires.
        let m = parse_quality_name("Movie.WEB-DL.x264");
        assert_eq!(m.source_detection_source, QualityDetectionSource::Name);
        assert_eq!(
            m.resolution_detection_source,
            QualityDetectionSource::Unknown
        );
    }

    #[test]
    fn cascade_falls_back_to_unknown_when_no_source() {
        // A name with no source, no resolution, no anime markers, no codec, no
        // pixel tag, no bare-bluray token, and no OtherSourceMatch hit (no
        // recognised file extension either) returns Quality::Unknown.
        let m = parse_quality_name("Show.S01E01.MysteryFormat");
        assert_eq!(m.quality, Quality::Unknown);
    }

    #[test]
    fn cascade_resolution_only_1080p_maps_to_hdtv1080p() {
        // T8 resolution-only fallback. C# QualityParser.cs:464-473: with no
        // source match, `Movie.2020.1080p.x264` derives source from extension
        // (`.x264` is unknown -> QualitySource::Unknown), then routes via
        // line 468's `source == Unknown` branch to Quality::Hdtv1080p.
        let m = parse_quality_name("Movie.2020.1080p.x264");
        assert_eq!(m.quality, Quality::Hdtv1080p);
        // Resolution detection flips to Name because the resolution regex
        // fired (line 122 + line 466).
        assert_eq!(m.resolution_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn cascade_underscore_normalised_for_source_match() {
        // C# normalises `_` -> ` ` before sourceMatch. A release like
        // `Movie_1080p_BluRay_x264` must classify as bluray-1080p just like
        // its dotted twin.
        let m = parse_quality_name("Movie_2020_1080p_BluRay_x264");
        assert_eq!(m.quality, Quality::Bluray1080p);
    }

    #[test]
    fn cascade_trims_outer_whitespace() {
        // C# QualityParser.cs:77 trims the raw input before the pipeline.
        // Leading/trailing whitespace must NOT change classification.
        let m = parse_quality_name("   Movie.2020.1080p.BluRay.x264   ");
        assert_eq!(m.quality, Quality::Bluray1080p);
    }

    #[test]
    fn cascade_revision_carries_through_arm() {
        // PROPER bumps version to 2; the cascade must preserve the
        // revision through the bluray arm.
        let m = parse_quality_name("Movie.2020.1080p.BluRay.PROPER.x264");
        assert_eq!(m.quality, Quality::Bluray1080p);
        assert_eq!(m.revision.version, 2);
        assert_eq!(m.revision_detection_source, QualityDetectionSource::Name);
    }

    // T8 cascade: sourceless-remux (C# QualityParser.cs:320-347).

    #[test]
    fn sourceless_remux_2160p_maps_to_bluray2160p_remux() {
        // C# QualityParser.cs:336-340: REMUX + 2160p without a source token
        // routes through the sourceless-remux block to Bluray2160pRemux.
        let m = parse_quality_name("Movie.2020.2160p.Remux.HDR.x265");
        assert_eq!(m.quality, Quality::Bluray2160pRemux);
        // Line 322: SourceDetectionSource is explicitly set to Unknown for
        // sourceless remux even though we matched something.
        assert_eq!(m.source_detection_source, QualityDetectionSource::Unknown);
        assert_eq!(m.resolution_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn sourceless_remux_1080p_maps_to_bluray1080p_remux() {
        // C# QualityParser.cs:342-346.
        let m = parse_quality_name("Movie.2020.1080p.Remux.AVC.DTS-HD");
        assert_eq!(m.quality, Quality::Bluray1080pRemux);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Unknown);
    }

    #[test]
    fn sourceless_remux_720p_maps_to_bluray720p() {
        // C# QualityParser.cs:330-334. The 720p remux without source is
        // explicitly Bluray720p, NOT Bluray720pRemux (which doesn't exist).
        let m = parse_quality_name("Movie.2020.720p.Remux.AVC");
        assert_eq!(m.quality, Quality::Bluray720p);
    }

    #[test]
    fn sourceless_remux_480p_maps_to_bluray480p() {
        // C# QualityParser.cs:324-328.
        let m = parse_quality_name("Movie.2020.480p.Remux.x264");
        assert_eq!(m.quality, Quality::Bluray480p);
    }

    // T8 cascade: anime-bluray (C# QualityParser.cs:349-390).

    #[test]
    fn anime_bluray_720p() {
        // Plan-required test #1. C# QualityParser.cs:388: anime-bluray with
        // unknown resolution falls through to default Bluray720p.
        //
        // NB: token form `[BD720p]` (no space) matches ANIME_BLURAY_REGEX's
        // `bd720` branch but NOT SOURCE_REGEX's bluray group (which requires
        // a word-boundary or space/period after `BD`). A name with `[BD 720p]`
        // (with space) would short-circuit through the T7 bluray arm instead.
        let m = parse_quality_name("[group] Show - 01 [BD720p]");
        assert_eq!(m.quality, Quality::Bluray720p);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn anime_bluray_1080p() {
        // C# QualityParser.cs:364-369. Token form `[BD1080p]` matches
        // ANIME_BLURAY_REGEX's `bd1080` branch.
        let m = parse_quality_name("[group] Show - 01 [BD1080p]");
        assert_eq!(m.quality, Quality::Bluray1080p);
    }

    #[test]
    fn anime_bluray_2160p() {
        // C# QualityParser.cs:372-377. Token form `[BD2160p]`.
        let m = parse_quality_name("[group] Show - 01 [BD2160p]");
        assert_eq!(m.quality, Quality::Bluray2160p);
    }

    #[test]
    fn anime_bluray_480p_maps_to_dvd() {
        // C# QualityParser.cs:354-362: anime-bluray at 360p / 480p / 540p /
        // 576p (or substring "480p") is intentionally collapsed to Quality::Dvd.
        //
        // Constructing a name that triggers this branch is delicate. Both
        // `bd720`/`bd1080`/`bd2160` literal forms AND bare `bd` with separator
        // surround can match ANIME_BLURAY_REGEX, but bare-bd with separator
        // surround ALSO matches SOURCE_REGEX's bluray group (because
        // separator chars like `[` `]` `(` `)` `-` `.` ` ` give a `\b` or
        // `[ .]` after `bd`). The only way to fire anime-bluray without
        // SOURCE_REGEX hijacking is via a `bd<digits>` literal (e.g. `bd720`)
        // because no `\b|$|[ .]` follows `bd` in that case (digits are word
        // chars).
        //
        // So we use `bd720` to fire ANIME_BLURAY_REGEX, plus a separate
        // `480p` token to drive the 480p anime-bluray sub-branch. The 720p
        // in `bd720` does NOT register as a resolution because RESOLUTION_REGEX
        // expects `\b720p\b` (and the regex needs `bd` to be separated from
        // `720` by a word boundary, which it isn't).
        let m = parse_quality_name("Show.480p.bd720.AC3");
        assert_eq!(m.quality, Quality::Dvd);
        assert_eq!(m.resolution_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn anime_bluray_remux_no_resolution_falls_back_to_1080p_remux() {
        // C# QualityParser.cs:382-386: anime-bluray + remux + resolution !=
        // R720p (incl. Unknown) -> Bluray1080pRemux. Use the surround-bd
        // form to match anime-bluray without firing SOURCE_REGEX's bluray
        // group.
        let m = parse_quality_name("[group] Show.(bd).Remux");
        assert_eq!(m.quality, Quality::Bluray1080pRemux);
    }

    #[test]
    fn anime_bluray_1080p_remux_combo() {
        // C# QualityParser.cs:367 with remux: Bluray1080pRemux. Use the
        // surround-bd form + a 1080p resolution token.
        let m = parse_quality_name("[group] Show.1080p.(bd).Remux");
        assert_eq!(m.quality, Quality::Bluray1080pRemux);
    }

    #[test]
    fn anime_bluray_unknown_resolution_no_remux_defaults_720p() {
        // C# QualityParser.cs:388: anime-bluray with no resolution and no
        // remux defaults to Bluray720p. Surround-bd form.
        let m = parse_quality_name("[group] Show.(bd).x264");
        assert_eq!(m.quality, Quality::Bluray720p);
    }

    // T8 cascade: anime-webdl (C# QualityParser.cs:392-424).

    #[test]
    fn anime_webdl_1080p() {
        // Plan-required test #2. C# QualityParser.cs:406-411.
        let m = parse_quality_name("[group] Show - 01 [WEB][1080p]");
        assert_eq!(m.quality, Quality::Webdl1080p);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn anime_webdl_2160p() {
        // C# QualityParser.cs:414-420.
        let m = parse_quality_name("[group] Show - 01 [WEB][2160p]");
        assert_eq!(m.quality, Quality::Webdl2160p);
    }

    #[test]
    fn anime_webdl_480p() {
        // C# QualityParser.cs:396-404: 480p / 540p / 576p / substring "480p"
        // -> Webdl480p.
        let m = parse_quality_name("[group] Show - 01 [WEB][480p]");
        assert_eq!(m.quality, Quality::Webdl480p);
    }

    #[test]
    fn anime_webdl_unknown_resolution_defaults_720p() {
        // C# QualityParser.cs:422: anime-webdl with no resolution defaults
        // to Webdl720p.
        let m = parse_quality_name("[group] Show - 01 (WEB.)");
        assert_eq!(m.quality, Quality::Webdl720p);
    }

    // T8 cascade: resolution-only fallback (C# QualityParser.cs:426-497).

    #[test]
    fn resolution_only_2160p_maps_to_hdtv2160p() {
        // C# QualityParser.cs:453-461. No source, 2160p resolution, no remux,
        // unknown extension -> Hdtv2160p.
        let m = parse_quality_name("Movie.2020.2160p.x265");
        assert_eq!(m.quality, Quality::Hdtv2160p);
    }

    #[test]
    fn resolution_only_720p_maps_to_hdtv720p() {
        // C# QualityParser.cs:475-484.
        let m = parse_quality_name("Movie.2020.720p.x264");
        assert_eq!(m.quality, Quality::Hdtv720p);
    }

    #[test]
    fn resolution_only_480p_maps_to_sdtv() {
        // C# QualityParser.cs:486-496. 360 / 480 / 540 / 576 -> SDTV when
        // source is Unknown.
        let m = parse_quality_name("Movie.2020.480p.x264");
        assert_eq!(m.quality, Quality::Sdtv);
    }

    #[test]
    fn resolution_only_with_mkv_extension_promotes_via_television_source() {
        // C# QualityParser.cs:437-451: extension `.mkv` resolves to Quality
        // HDTV720p (Television source). resolution-only at 1080p with
        // Television source returns find_by_source_and_resolution(Television,
        // 1080) = Quality::Hdtv1080p. The detection-source flag is Extension
        // for the source, Name for the resolution.
        let m = parse_quality_name("Movie.2020.1080p.x264.mkv");
        assert_eq!(m.quality, Quality::Hdtv1080p);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Extension);
        assert_eq!(m.resolution_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn resolution_only_with_iso_extension_promotes_to_dvd_at_480p() {
        // `.iso` -> Quality::Dvd (source = Dvd). At 480p, exact match in
        // ALL[] yields Dvd directly.
        let m = parse_quality_name("Movie.2020.480p.x264.iso");
        assert_eq!(m.quality, Quality::Dvd);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Extension);
    }

    // T8 cascade: x264-SDTV fallback (C# QualityParser.cs:499-504).

    #[test]
    fn x264_codec_alone_maps_to_sdtv() {
        // C# QualityParser.cs:499-503: x264 codec with no source, no
        // resolution, no anime, no remux -> SDTV.
        let m = parse_quality_name("Movie.x264.AC3");
        assert_eq!(m.quality, Quality::Sdtv);
    }

    // T8 cascade: pixel-tag fallbacks (C# QualityParser.cs:506-560).
    //
    // RESOLUTION_REGEX already matches 848x480 / 1280x720 / 1920x1080 with
    // word boundaries, so these pixel-tag blocks only fire when the regex
    // boundary check fails. To exercise them, we glue the pixel tag against
    // surrounding text WITHOUT word boundaries.

    #[test]
    fn pixel_tag_848x480_with_dvd_token_no_word_boundary() {
        // C# QualityParser.cs:506-513: literal "848x480" + "dvd" -> DVD,
        // case-sensitive on "dvd" per C# `Contains("dvd")`.
        let m = parse_quality_name("Movie848x480dvd");
        assert_eq!(m.quality, Quality::Dvd);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Name);
        assert_eq!(m.resolution_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn pixel_tag_848x480_with_bluray_token_no_word_boundary() {
        // C# QualityParser.cs:515-519: literal "848x480" + "bluray"
        // (case-insensitive) -> Bluray480p.
        let m = parse_quality_name("Movie848x480bluray");
        assert_eq!(m.quality, Quality::Bluray480p);
    }

    #[test]
    fn pixel_tag_848x480_default_sdtv() {
        // C# QualityParser.cs:520-523: bare "848x480" without dvd/bluray
        // marker -> SDTV.
        let m = parse_quality_name("Movie848x480extra");
        assert_eq!(m.quality, Quality::Sdtv);
    }

    #[test]
    fn pixel_tag_1280x720_default_hdtv720p() {
        // C# QualityParser.cs:528-543: bare "1280x720" without bluray ->
        // Hdtv720p.
        let m = parse_quality_name("Movie1280x720extra");
        assert_eq!(m.quality, Quality::Hdtv720p);
    }

    #[test]
    fn pixel_tag_1280x720_with_bluray_token() {
        // C# QualityParser.cs:532-536.
        let m = parse_quality_name("Movie1280x720bluray");
        assert_eq!(m.quality, Quality::Bluray720p);
    }

    #[test]
    fn pixel_tag_1920x1080_default_hdtv1080p() {
        // C# QualityParser.cs:545-560.
        let m = parse_quality_name("Movie1920x1080extra");
        assert_eq!(m.quality, Quality::Hdtv1080p);
    }

    #[test]
    fn pixel_tag_1920x1080_with_bluray_token() {
        // C# QualityParser.cs:549-553.
        let m = parse_quality_name("Movie1920x1080bluray");
        assert_eq!(m.quality, Quality::Bluray1080p);
    }

    // T8 cascade: bare bluray720p/1080p/2160p tokens (C# QualityParser.cs:562-587).

    #[test]
    fn bare_bluray720p_token() {
        // C# QualityParser.cs:562-569. The literal "bluray720p" without
        // separators bypasses SOURCE_REGEX (which requires `\b|$|[ .]` after
        // `BluRay`) and RESOLUTION_REGEX (which requires `\b...720p\b`).
        // Also avoid any x264/h264 codec token: C# line 499 short-circuits
        // x264 to SDTV BEFORE this branch (`bluray720p` runs at line 562).
        let m = parse_quality_name("Movie.bluray720p.AC3");
        assert_eq!(m.quality, Quality::Bluray720p);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Name);
        assert_eq!(m.resolution_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn bare_bluray1080p_token() {
        // C# QualityParser.cs:571-578. Same x264-gating note as the 720p test.
        let m = parse_quality_name("Movie.bluray1080p.AC3");
        assert_eq!(m.quality, Quality::Bluray1080p);
    }

    #[test]
    fn bare_bluray2160p_token() {
        // C# QualityParser.cs:580-587. Same x264-gating note.
        let m = parse_quality_name("Movie.bluray2160p.AC3");
        assert_eq!(m.quality, Quality::Bluray2160p);
    }

    // T8 cascade: OtherSourceMatch (C# QualityParser.cs:589-595 + 653-672).

    #[test]
    fn other_source_hd_tv_maps_to_hdtv720p() {
        // C# QualityParser.cs:589-594 + 666-670. OTHER_SOURCE_REGEX matches
        // "HD TV" / "HD-TV" / "HD_TV" / "HD.TV" -> Hdtv720p when nothing else
        // matched. Avoid x264 codec because C# line 499 short-circuits to
        // SDTV BEFORE the OtherSourceMatch path.
        let m = parse_quality_name("Show.HD-TV.AC3.foo");
        assert_eq!(m.quality, Quality::Hdtv720p);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Name);
    }

    #[test]
    fn other_source_sd_tv_maps_to_sdtv() {
        // C# QualityParser.cs:589-594 + 661-664. Same x264-gating note.
        let m = parse_quality_name("Show.SD-TV.AC3.foo");
        assert_eq!(m.quality, Quality::Sdtv);
    }

    // T8: extension fallback (C# QualityParser.cs:81-95).

    #[test]
    fn extension_fallback_mkv_to_hdtv720p() {
        // C# QualityParser.cs:81-95: when ParseQualityName returns Unknown,
        // the outer ParseQuality wrapper looks up the file extension. `.mkv`
        // -> HDTV720p in MediaFileExtensions.
        let m = parse_quality("Show.S01E01.mkv");
        assert_eq!(m.quality, Quality::Hdtv720p);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Extension);
        assert_eq!(
            m.resolution_detection_source,
            QualityDetectionSource::Extension
        );
    }

    #[test]
    fn extension_fallback_mp4_to_sdtv() {
        // `.mp4` is mapped to Quality::SDTV in MediaFileExtensions.
        let m = parse_quality("Show.S01E01.mp4");
        assert_eq!(m.quality, Quality::Sdtv);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Extension);
    }

    #[test]
    fn extension_fallback_iso_to_dvd() {
        // `.iso` is mapped to Quality::DVD in MediaFileExtensions.
        let m = parse_quality("Show.S01E01.iso");
        assert_eq!(m.quality, Quality::Dvd);
    }

    #[test]
    fn extension_fallback_m2ts_to_bluray720p() {
        // `.m2ts` is mapped to Quality::Bluray720p in MediaFileExtensions.
        let m = parse_quality("Show.S01E01.m2ts");
        assert_eq!(m.quality, Quality::Bluray720p);
    }

    #[test]
    fn extension_fallback_webm_stays_unknown() {
        // C# MediaFileExtensions.cs:16: `.webm` -> Quality::Unknown. The
        // dictionary contains the key but maps to Unknown. SourceDetectionSource
        // and ResolutionDetectionSource are still flipped to Extension because
        // the C# branch sets them BEFORE inspecting the returned Quality.
        let m = parse_quality("Show.S01E01.webm");
        assert_eq!(m.quality, Quality::Unknown);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Extension);
    }

    #[test]
    fn extension_fallback_unknown_extension_stays_unknown() {
        // C# MediaFileExtensions.cs:76-83: an extension not in the dictionary
        // returns Quality::Unknown but the source/resolution detection
        // sources are still flipped to Extension (line 87-88 set them before
        // `GetQualityForExtension` returns Unknown). Verified against C#.
        let m = parse_quality("Show.S01E01.xyz");
        assert_eq!(m.quality, Quality::Unknown);
        assert_eq!(m.source_detection_source, QualityDetectionSource::Extension);
    }

    #[test]
    fn extension_fallback_does_not_overwrite_resolved_quality() {
        // The extension fallback only fires when ParseQualityName returned
        // Quality::Unknown. A name that already classifies (e.g. has BluRay)
        // must NOT have its quality overwritten by the extension table.
        let m = parse_quality("Movie.2020.1080p.BluRay.x264.mp4");
        assert_eq!(m.quality, Quality::Bluray1080p);
        // Source detection comes from the BluRay regex hit, not the extension.
        assert_eq!(m.source_detection_source, QualityDetectionSource::Name);
    }
}