psyche-subtitle-toolkit 0.4.0

Extract, translate, and mux ASS/SRT/VTT/PGS subtitles in MKV files via pluggable translation providers
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
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tempfile::tempdir;
use tokio::sync::Semaphore;

use crate::error::{Result, SubtitleToolkitError};
use crate::media::mkv::{
    SubtitleFormat, discover_mkv_files, extract_subtitle, inspect_mkv, mux_subtitle_in_place,
    select_subtitle_track,
};
use crate::ocr::{OcrConfig, ocr_pgs_to_srt};
use crate::retry::retry_async;
use crate::subtitles::ass::AssSubtitle;
use crate::subtitles::model::SubtitleDocument;
use crate::subtitles::srt::SrtSubtitle;
use crate::subtitles::structured::{
    apply_translation, chunk_document_with_limits, parse_numbered_text, protect_ass_spans,
    protect_markup_spans, restore_protected_spans, strip_tags, to_numbered_text,
};
use crate::subtitles::vtt::VttSubtitle;
use crate::translation::{TranslationLimits, TranslationRequest, Translator};

#[derive(Debug)]
struct TranslationFileLock(std::fs::File);

impl Drop for TranslationFileLock {
    fn drop(&mut self) {
        let _ = fs2::FileExt::unlock(&self.0);
    }
}

const PROGRESS_VERSION: u32 = 1;
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Options for the [`translate_mkv`] pipeline.
#[derive(Debug, Clone)]
pub struct TranslateMkvOptions {
    /// Path to an MKV file or directory containing MKV files.
    pub input: PathBuf,
    /// Target language code (e.g. `"pt-BR"`, `"en"`, `"ja"`).
    pub target_language: String,
    /// Specific subtitle track ID to translate. If `None`, selects the first ASS track.
    pub track_id: Option<u64>,
    /// If `true`, preserves extracted/translated ASS files alongside the MKV.
    pub keep_temp: bool,
    /// If `true`, shows what would be translated without modifying files.
    pub dry_run: bool,
    /// If `true`, saves progress to a file and skips already-translated files on restart.
    pub resume: bool,
    /// Maximum number of chunks to translate concurrently. Default: 1 (sequential).
    pub max_concurrent: usize,
}

impl TranslateMkvOptions {
    /// Validate option invariants. Called by [`translate_mkv`] before any work.
    pub fn validate(&self) -> Result<()> {
        if self.target_language.trim().is_empty() {
            return Err(SubtitleToolkitError::Translation {
                provider: "options",
                message: "target_language cannot be empty".to_string(),
            });
        }
        if self.target_language != self.target_language.trim() {
            return Err(SubtitleToolkitError::Translation {
                provider: "options",
                message: "target_language cannot contain surrounding whitespace".to_string(),
            });
        }
        if self.max_concurrent == 0 {
            return Err(SubtitleToolkitError::Translation {
                provider: "options",
                message: "max_concurrent must be at least 1".to_string(),
            });
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct ProgressManifest {
    version: u32,
    run: ProgressRun,
    completed: Vec<CompletedFile>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct ProgressRun {
    target_language: String,
    translator: String,
    requested_track_id: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct CompletedFile {
    canonical_path: String,
    fingerprint: FileFingerprint,
    #[serde(default = "completed_by_default")]
    completed: bool,
}

const fn completed_by_default() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct FileFingerprint {
    size: u64,
    modified_unix_nanos: u128,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResumeAction {
    Process,
    Skip,
}

fn resume_action(
    manifest: &ProgressManifest,
    canonical_path: &str,
    fingerprint: &FileFingerprint,
) -> Result<ResumeAction> {
    let Some(entry) = manifest
        .completed
        .iter()
        .find(|entry| entry.canonical_path == canonical_path)
    else {
        return Ok(ResumeAction::Process);
    };

    if entry.completed {
        return Ok(if entry.fingerprint == *fingerprint {
            ResumeAction::Skip
        } else {
            ResumeAction::Process
        });
    }

    if entry.fingerprint == *fingerprint {
        return Ok(ResumeAction::Process);
    }

    Err(SubtitleToolkitError::Progress {
        message: format!(
            "{canonical_path} changed after translation started but before its checkpoint was committed; inspect the MKV before resuming"
        ),
    })
}

/// Translate supported subtitles in MKV file(s) and mux the result back in-place.
///
/// For each MKV file:
/// 1. Inspects tracks and selects ASS, SRT, WebVTT, or PGS
/// 2. Extracts the subtitle to a temporary directory
/// 3. Protects inline formatting spans
/// 4. Chunks cues according to provider item and byte limits
/// 5. Translates each chunk via the provided [`Translator`]
/// 6. Validates and restores protected formatting
/// 7. Builds and validates a replacement MKV while preserving track metadata/order
///
/// If `input` is a directory, processes all `.mkv` files sequentially.
pub async fn translate_mkv(
    options: TranslateMkvOptions,
    translator: Arc<dyn Translator>,
) -> Result<()> {
    options.validate()?;
    let files = discover_mkv_files(&options.input).await?;
    let use_resume = options.resume && !options.dry_run;
    let progress_path = progress_file_path(&options.input);
    let run = ProgressRun {
        target_language: options.target_language.trim().to_string(),
        translator: translator.identifier(),
        requested_track_id: options.track_id,
    };
    let mut manifest = if use_resume && progress_path.exists() {
        load_progress(&progress_path, &run).await?
    } else {
        ProgressManifest {
            version: PROGRESS_VERSION,
            run,
            completed: Vec::new(),
        }
    };

    let total = files.len();
    for (i, file) in files.into_iter().enumerate() {
        let canonical_path = canonical_path_string(&file).await?;
        let fingerprint = file_fingerprint(&file).await?;

        if use_resume
            && resume_action(&manifest, &canonical_path, &fingerprint)? == ResumeAction::Skip
        {
            eprintln!(
                "[resume] skipping ({}/{}): {}",
                i + 1,
                total,
                file.display()
            );
            continue;
        }
        if use_resume {
            manifest
                .completed
                .retain(|entry| entry.canonical_path != canonical_path);
            manifest.completed.push(CompletedFile {
                canonical_path: canonical_path.clone(),
                fingerprint: fingerprint.clone(),
                completed: false,
            });
            save_progress_atomic(&progress_path, &manifest).await?;
        }

        translate_one(file.clone(), &options, translator.clone()).await?;

        if use_resume {
            let completed = manifest
                .completed
                .iter_mut()
                .find(|entry| entry.canonical_path == canonical_path)
                .ok_or_else(|| SubtitleToolkitError::Progress {
                    message: format!("internal progress entry for {} disappeared", file.display()),
                })?;
            completed.fingerprint = file_fingerprint(&file).await?;
            completed.completed = true;
            save_progress_atomic(&progress_path, &manifest).await?;
            eprintln!(
                "[resume] progress saved ({}/{})",
                manifest
                    .completed
                    .iter()
                    .filter(|entry| entry.completed)
                    .count(),
                total
            );
        }
    }

    if use_resume && progress_path.exists() {
        tokio::fs::remove_file(&progress_path).await?;
    }

    Ok(())
}

async fn load_progress(path: &Path, expected_run: &ProgressRun) -> Result<ProgressManifest> {
    let data = tokio::fs::read_to_string(path).await?;
    let manifest: ProgressManifest =
        serde_json::from_str(&data).map_err(|error| SubtitleToolkitError::Progress {
            message: format!(
                "{} is not a valid progress manifest: {error}",
                path.display()
            ),
        })?;
    if manifest.version != PROGRESS_VERSION {
        return Err(SubtitleToolkitError::Progress {
            message: format!(
                "{} uses unsupported version {}; expected {}",
                path.display(),
                manifest.version,
                PROGRESS_VERSION
            ),
        });
    }
    if &manifest.run != expected_run {
        return Err(SubtitleToolkitError::Progress {
            message: format!(
                "{} belongs to a different language, provider/model, or track selection",
                path.display()
            ),
        });
    }
    Ok(manifest)
}

async fn save_progress_atomic(path: &Path, manifest: &ProgressManifest) -> Result<()> {
    let json = serde_json::to_vec_pretty(manifest)?;
    let suffix = unique_suffix();
    let temp_path = path.with_extension(format!("json.tmp-{suffix}"));
    let backup_path = path.with_extension(format!("json.bak-{suffix}"));
    tokio::fs::write(&temp_path, json).await?;

    let had_previous = path.exists();
    if had_previous {
        tokio::fs::rename(path, &backup_path).await?;
    }
    if let Err(error) = tokio::fs::rename(&temp_path, path).await {
        if had_previous {
            let _ = tokio::fs::rename(&backup_path, path).await;
        }
        let _ = tokio::fs::remove_file(&temp_path).await;
        return Err(error.into());
    }
    if had_previous {
        tokio::fs::remove_file(backup_path).await?;
    }
    Ok(())
}

async fn canonical_path_string(path: &Path) -> Result<String> {
    Ok(tokio::fs::canonicalize(path)
        .await?
        .to_string_lossy()
        .into_owned())
}

async fn file_fingerprint(path: &Path) -> Result<FileFingerprint> {
    let metadata = tokio::fs::metadata(path).await?;
    let modified_unix_nanos = metadata
        .modified()?
        .duration_since(UNIX_EPOCH)
        .map_err(|error| SubtitleToolkitError::Progress {
            message: format!(
                "{} has an invalid modification time: {error}",
                path.display()
            ),
        })?
        .as_nanos();
    Ok(FileFingerprint {
        size: metadata.len(),
        modified_unix_nanos,
    })
}

fn unique_suffix() -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| duration.as_nanos());
    let counter = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("{}-{nanos}-{counter}", std::process::id())
}

async fn translate_one(
    file: PathBuf,
    options: &TranslateMkvOptions,
    translator: Arc<dyn Translator>,
) -> Result<()> {
    let _file_lock = acquire_translation_file_lock(&file)?;
    let info = inspect_mkv(&file).await?;
    let (track, format) = select_subtitle_track(&info, options.track_id)
        .ok_or_else(|| SubtitleToolkitError::NoSubtitleTrack { path: file.clone() })?;

    let temp_dir = tempdir()?;

    // PGS requires special handling: extract .sup, OCR to SRT, then translate
    if format == SubtitleFormat::Pgs {
        let sup_path = temp_dir.path().join("source.sup");
        let translated_path = temp_dir.path().join("translated.srt");

        eprintln!("[translate] {} (PGS → OCR)", file.display());
        extract_subtitle(&file, track.id, &sup_path).await?;

        if options.dry_run {
            println!(
                "[dry-run] {}: PGS bitmap subtitle (requires OCR)",
                file.display()
            );
            return Ok(());
        }

        let ocr_config = OcrConfig {
            stream_language: track.properties.language.clone(),
            ..OcrConfig::default()
        };
        let srt_text = ocr_pgs_to_srt(&sup_path, &ocr_config).await?;
        let srt = SrtSubtitle::parse(&srt_text)?;
        let source_cue_count = srt.document().cues.len();

        eprintln!(
            "[translate] OCR extracted {} cues, translating",
            srt.document().cues.len()
        );
        let translated = translate_srt(
            srt,
            &options.target_language,
            options.max_concurrent,
            translator,
        )
        .await?;

        let rendered = translated.render();
        validate_rendered_subtitle(SubtitleFormat::Srt, &rendered, source_cue_count)?;
        tokio::fs::write(&translated_path, rendered).await?;
        if options.keep_temp {
            persist_temp_artifacts(
                &file,
                &[
                    ("source.sup", &sup_path),
                    ("translated.srt", &translated_path),
                ],
            )
            .await?;
        }

        eprintln!("[translate] muxing translated subtitle");
        mux_subtitle_in_place(&file, track.id, &translated_path, &options.target_language).await?;
        eprintln!("[translate] done: {}", file.display());
        return Ok(());
    }

    let ext = match format {
        SubtitleFormat::Ass => "ass",
        SubtitleFormat::Srt => "srt",
        SubtitleFormat::Vtt => "vtt",
        SubtitleFormat::Pgs => unreachable!(),
    };

    let extracted_path = temp_dir.path().join(format!("source.{ext}"));
    let translated_path = temp_dir.path().join(format!("translated.{ext}"));

    let format_label = match format {
        SubtitleFormat::Ass => "ASS",
        SubtitleFormat::Srt => "SRT",
        SubtitleFormat::Vtt => "VTT",
        SubtitleFormat::Pgs => unreachable!(),
    };
    eprintln!("[translate] {} ({})", file.display(), format_label);
    extract_subtitle(&file, track.id, &extracted_path).await?;

    let source = tokio::fs::read_to_string(&extracted_path).await?;

    let (rendered, source_cue_count) = match format {
        SubtitleFormat::Ass => {
            let ass = AssSubtitle::parse(&source)?;
            if options.dry_run {
                let summary = dry_run_summary(ass.document(), &options.target_language);
                println!("[dry-run] {}: {}", file.display(), summary);
                return Ok(());
            }
            let cue_count = ass.document().cues.len();
            let rendered = translate_ass(
                ass,
                &options.target_language,
                options.max_concurrent,
                translator,
            )
            .await?
            .render();
            (rendered, cue_count)
        }
        SubtitleFormat::Srt => {
            let srt = SrtSubtitle::parse(&source)?;
            if options.dry_run {
                let summary = dry_run_summary(srt.document(), &options.target_language);
                println!("[dry-run] {}: {}", file.display(), summary);
                return Ok(());
            }
            let cue_count = srt.document().cues.len();
            let rendered = translate_srt(
                srt,
                &options.target_language,
                options.max_concurrent,
                translator,
            )
            .await?
            .render();
            (rendered, cue_count)
        }
        SubtitleFormat::Vtt => {
            let vtt = VttSubtitle::parse(&source)?;
            if options.dry_run {
                let summary = dry_run_summary(vtt.document(), &options.target_language);
                println!("[dry-run] {}: {}", file.display(), summary);
                return Ok(());
            }
            let cue_count = vtt.document().cues.len();
            let rendered = translate_vtt(
                vtt,
                &options.target_language,
                options.max_concurrent,
                translator,
            )
            .await?
            .render();
            (rendered, cue_count)
        }
        SubtitleFormat::Pgs => unreachable!(),
    };

    validate_rendered_subtitle(format, &rendered, source_cue_count)?;
    tokio::fs::write(&translated_path, &rendered).await?;
    if options.keep_temp {
        persist_temp_artifacts(
            &file,
            &[
                (&format!("source.{ext}"), &extracted_path),
                (&format!("translated.{ext}"), &translated_path),
            ],
        )
        .await?;
    }

    eprintln!("[translate] muxing translated subtitle");
    mux_subtitle_in_place(&file, track.id, &translated_path, &options.target_language).await?;
    eprintln!("[translate] done: {}", file.display());

    Ok(())
}

fn acquire_translation_file_lock(file: &Path) -> Result<TranslationFileLock> {
    let canonical = std::fs::canonicalize(file)?;
    let identity = canonical.to_string_lossy();
    let identity = if cfg!(windows) {
        identity.to_ascii_lowercase()
    } else {
        identity.into_owned()
    };
    let digest = format!("{:x}", Sha256::digest(identity.as_bytes()));
    let lock_dir = std::env::temp_dir().join("psyche-subtitle-toolkit-locks");
    std::fs::create_dir_all(&lock_dir)?;
    let lock_path = lock_dir.join(format!("{digest}.lock"));
    let lock_file = std::fs::OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(&lock_path)?;
    fs2::FileExt::try_lock_exclusive(&lock_file).map_err(|error| {
        SubtitleToolkitError::Io(std::io::Error::other(format!(
            "another translation is already processing {} (lock {}): {error}",
            file.display(),
            lock_path.display()
        )))
    })?;
    Ok(TranslationFileLock(lock_file))
}

async fn persist_temp_artifacts(file: &Path, artifacts: &[(&str, &PathBuf)]) -> Result<()> {
    let persisted = file.with_extension("psyche-subtitle-toolkit-temp");
    tokio::fs::create_dir_all(&persisted).await?;
    for (name, source) in artifacts {
        tokio::fs::copy(source, persisted.join(name)).await?;
    }
    Ok(())
}

fn validate_rendered_subtitle(
    format: SubtitleFormat,
    rendered: &str,
    expected_cues: usize,
) -> Result<()> {
    let actual_cues = match format {
        SubtitleFormat::Ass => AssSubtitle::parse(rendered)?.document().cues.len(),
        SubtitleFormat::Srt => SrtSubtitle::parse(rendered)?.document().cues.len(),
        SubtitleFormat::Vtt => VttSubtitle::parse(rendered)?.document().cues.len(),
        SubtitleFormat::Pgs => unreachable!("PGS is converted to SRT before validation"),
    };
    if expected_cues == 0 || actual_cues != expected_cues {
        return Err(SubtitleToolkitError::InvalidTranslation {
            message: format!(
                "rendered subtitle contains {actual_cues} cues; expected {expected_cues}"
            ),
        });
    }
    Ok(())
}

fn progress_file_path(input: &std::path::Path) -> PathBuf {
    if input.is_dir() {
        input.join(".psyche-subtitle-toolkit-progress.json")
    } else if input.extension().is_some() {
        let parent = input.parent().unwrap_or_else(|| Path::new("."));
        let name = input
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("input.mkv");
        parent.join(format!(".{name}.psyche-subtitle-toolkit-progress.json"))
    } else {
        input.join(".psyche-subtitle-toolkit-progress.json")
    }
}

/// Generate a dry-run summary for a subtitle document: cue count, char count, chunk count.
pub fn dry_run_summary(doc: &SubtitleDocument, target_language: &str) -> String {
    let (clean_doc, _) = strip_tags(doc);
    let limits = TranslationLimits::default();
    let chunks = chunk_document_with_limits(&clean_doc, limits.max_items, limits.max_request_bytes)
        .unwrap_or_default();
    let cue_count = clean_doc.cues.len();
    let total_chars: usize = clean_doc.cues.iter().map(|c| c.text.len()).sum();
    format!(
        "{} cues, {} chars, {} chunk(s) → {}",
        cue_count,
        total_chars,
        chunks.len(),
        target_language,
    )
}

/// Translate an ASS subtitle through the full processing pipeline.
///
/// 1. Protects all ASS override tags, including inline tags
/// 2. Chunks cues according to provider item and byte limits
/// 3. Translates each chunk via the provided [`Translator`]
/// 4. Applies translated text back to the document
/// 5. Validates and restores the original override tags
///
/// Returns the translated [`AssSubtitle`]. Use [`AssSubtitle::render`] to get
/// the final ASS string.
pub async fn translate_ass(
    mut ass: AssSubtitle,
    target_language: &str,
    max_concurrent: usize,
    translator: Arc<dyn Translator>,
) -> Result<AssSubtitle> {
    validate_direct_translation_options(ass.document(), target_language, max_concurrent)?;
    let (mut clean_doc, tag_map) = protect_ass_spans(ass.document());
    clean_doc = translate_document(clean_doc, target_language, max_concurrent, translator).await?;
    restore_protected_spans(&mut clean_doc, &tag_map)?;
    *ass.document_mut() = clean_doc;
    Ok(ass)
}

/// Translate an SRT subtitle through the processing pipeline.
///
/// Protects inline markup, translates provider-sized chunks, then restores markup.
///
/// Returns the translated [`SrtSubtitle`]. Use [`SrtSubtitle::render`] to get
/// the final SRT string.
pub async fn translate_srt(
    mut srt: SrtSubtitle,
    target_language: &str,
    max_concurrent: usize,
    translator: Arc<dyn Translator>,
) -> Result<SrtSubtitle> {
    validate_direct_translation_options(srt.document(), target_language, max_concurrent)?;
    let (clean_doc, tag_map) = protect_markup_spans(srt.document());
    let mut clean_doc =
        translate_document(clean_doc, target_language, max_concurrent, translator).await?;
    restore_protected_spans(&mut clean_doc, &tag_map)?;
    *srt.document_mut() = clean_doc;
    Ok(srt)
}

/// Translate a WebVTT subtitle through the processing pipeline.
///
/// Protects inline markup, translates provider-sized chunks, then restores markup.
///
/// Returns the translated [`VttSubtitle`]. Use [`VttSubtitle::render`] to get
/// the final WebVTT string.
pub async fn translate_vtt(
    mut vtt: VttSubtitle,
    target_language: &str,
    max_concurrent: usize,
    translator: Arc<dyn Translator>,
) -> Result<VttSubtitle> {
    validate_direct_translation_options(vtt.document(), target_language, max_concurrent)?;
    let (clean_doc, tag_map) = protect_markup_spans(vtt.document());
    let mut clean_doc =
        translate_document(clean_doc, target_language, max_concurrent, translator).await?;
    restore_protected_spans(&mut clean_doc, &tag_map)?;
    *vtt.document_mut() = clean_doc;
    Ok(vtt)
}

fn validate_direct_translation_options(
    document: &SubtitleDocument,
    target_language: &str,
    max_concurrent: usize,
) -> Result<()> {
    if target_language.trim().is_empty() {
        return Err(SubtitleToolkitError::Translation {
            provider: "options",
            message: "target_language cannot be empty".into(),
        });
    }
    if target_language != target_language.trim() {
        return Err(SubtitleToolkitError::Translation {
            provider: "options",
            message: "target_language cannot contain surrounding whitespace".into(),
        });
    }
    if max_concurrent == 0 {
        return Err(SubtitleToolkitError::Translation {
            provider: "options",
            message: "max_concurrent must be at least 1".into(),
        });
    }
    if document.cues.is_empty() {
        return Err(SubtitleToolkitError::InvalidTranslation {
            message: "subtitle document contains no cues".into(),
        });
    }
    Ok(())
}

/// Core translation logic shared by ASS, SRT, and VTT pipelines.
async fn translate_document(
    mut doc: SubtitleDocument,
    target_language: &str,
    max_concurrent: usize,
    translator: Arc<dyn Translator>,
) -> Result<SubtitleDocument> {
    let translatable = SubtitleDocument {
        cues: doc
            .cues
            .iter()
            .filter(|cue| !cue.text.trim().is_empty())
            .cloned()
            .collect(),
    };
    if translatable.cues.is_empty() {
        return Ok(doc);
    }

    let limits = translator.limits();
    let chunks =
        chunk_document_with_limits(&translatable, limits.max_items, limits.max_request_bytes)?;
    let chunk_count = chunks.len();
    let cue_count = doc.cues.len();
    let total_chars: usize = doc.cues.iter().map(|c| c.text.len()).sum();
    eprintln!(
        "[translate] {} cues, {} chars, {} chunk(s), {} concurrent",
        cue_count, total_chars, chunk_count, max_concurrent,
    );

    let semaphore = Arc::new(Semaphore::new(max_concurrent));
    let mut join_set = tokio::task::JoinSet::new();

    for (i, chunk) in chunks.into_iter().enumerate() {
        if chunk_count > 1 {
            let chunk_chars: usize = chunk.cues.iter().map(|c| c.text.len()).sum();
            eprintln!(
                "[translate] chunk {}/{}: {} cues, {} chars",
                i + 1,
                chunk_count,
                chunk.cues.len(),
                chunk_chars,
            );
        }
        let numbered = to_numbered_text(&chunk);
        let ids: Vec<usize> = chunk.cues.iter().map(|cue| cue.id).collect();
        let source_chunk = chunk.clone();
        let semaphore = semaphore.clone();
        let translator = translator.clone();
        let target = target_language.to_string();

        join_set.spawn(async move {
            let permit = semaphore.acquire_owned().await.map_err(|error| {
                SubtitleToolkitError::Translation {
                    provider: "pipeline",
                    message: format!("semaphore closed: {error}"),
                }
            });
            let permit = match permit {
                Ok(permit) => permit,
                Err(error) => return (i, Err(error)),
            };
            let _permit = permit;
            let numbered_clone = numbered.clone();
            let ids_clone = ids.clone();
            let source_chunk_clone = source_chunk.clone();
            let result = retry_async(3, || {
                let numbered = numbered_clone.clone();
                let ids = ids_clone.clone();
                let source_chunk = source_chunk_clone.clone();
                let translator = translator.clone();
                let target = target.clone();
                async move {
                    let translated_text = translator
                        .translate(TranslationRequest {
                            source_text: &numbered,
                            target_language: &target,
                        })
                        .await?;
                    let parsed = parse_numbered_text(&translated_text, &ids)?;
                    validate_translated_chunk(&source_chunk, &parsed, limits)?;
                    Ok(parsed)
                }
            })
            .await;
            (i, result)
        });
    }

    let mut ordered_results = BTreeMap::new();
    while let Some(result) = join_set.join_next().await {
        let (i, outcome) = result.map_err(|e| SubtitleToolkitError::Translation {
            provider: "pipeline",
            message: format!("task panicked: {e}"),
        })?;
        match outcome {
            Ok(translated) => {
                ordered_results.insert(i, translated);
            }
            Err(error) => {
                join_set.abort_all();
                while join_set.join_next().await.is_some() {}
                return Err(error);
            }
        }
    }

    let mut all_translated = BTreeMap::new();
    for translated in ordered_results.into_values() {
        all_translated.extend(translated);
    }

    apply_translation(&mut doc, all_translated);
    Ok(doc)
}

fn validate_translated_chunk(
    source: &SubtitleDocument,
    translated: &BTreeMap<usize, String>,
    limits: TranslationLimits,
) -> Result<()> {
    for cue in &source.cues {
        let source_tokens = protected_tokens(&cue.text);
        let translated_tokens = translated
            .get(&cue.id)
            .map_or_else(Vec::new, |value| protected_tokens(value));
        if source_tokens != translated_tokens {
            return Err(SubtitleToolkitError::InvalidTranslation {
                message: format!("protected formatting tokens changed for id <{}>", cue.id),
            });
        }
    }

    if !limits.reject_unchanged_output {
        return Ok(());
    }

    let alphabetic_count: usize = source
        .cues
        .iter()
        .map(|cue| {
            cue.text
                .chars()
                .filter(|character| character.is_alphabetic())
                .count()
        })
        .sum();
    let unchanged = source.cues.iter().all(|cue| {
        translated
            .get(&cue.id)
            .is_some_and(|value| value == &cue.text)
    });
    if unchanged && alphabetic_count >= 12 {
        return Err(SubtitleToolkitError::InvalidTranslation {
            message: "provider returned the source chunk unchanged".into(),
        });
    }
    Ok(())
}

fn protected_tokens(text: &str) -> Vec<&str> {
    let mut tokens = Vec::new();
    let mut remaining = text;
    while let Some(start) = remaining.find("[[PSY_TAG_") {
        let candidate = &remaining[start..];
        let Some(end) = candidate.find("]]") else {
            break;
        };
        let end = end + 2;
        tokens.push(&candidate[..end]);
        remaining = &candidate[end..];
    }
    tokens
}

#[cfg(test)]
mod options_tests {
    use super::*;
    use std::path::PathBuf;

    fn opts(target_language: &str, max_concurrent: usize) -> TranslateMkvOptions {
        TranslateMkvOptions {
            input: PathBuf::from("/tmp/nonexistent.mkv"),
            target_language: target_language.to_string(),
            track_id: None,
            keep_temp: false,
            dry_run: false,
            resume: false,
            max_concurrent,
        }
    }

    #[test]
    fn validate_accepts_minimal_valid_options() {
        assert!(opts("pt-BR", 1).validate().is_ok());
        assert!(opts("en", 8).validate().is_ok());
    }

    #[test]
    fn validate_rejects_empty_target_language() {
        let error = opts("", 1).validate().unwrap_err();
        assert!(matches!(error, SubtitleToolkitError::Translation { .. }));
    }

    #[test]
    fn validate_rejects_whitespace_target_language() {
        assert!(opts("   ", 1).validate().is_err());
    }

    #[test]
    fn validate_rejects_zero_concurrency() {
        let error = opts("pt-BR", 0).validate().unwrap_err();
        assert!(matches!(error, SubtitleToolkitError::Translation { .. }));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::SubtitleToolkitError;
    use crate::subtitles::ass::AssSubtitle;
    use crate::subtitles::srt::SrtSubtitle;
    use crate::subtitles::vtt::VttSubtitle;
    use crate::translation::{TranslationLimits, TranslationRequest, Translator};
    use std::sync::Mutex;

    /// A mock translator for integration tests.
    ///
    /// Records each source text it receives and returns translations from
    /// a pre-configured map. If the map has no entry, returns a default
    /// identity translation (same text back).
    struct FakeTranslator {
        /// Source texts received, in call order.
        received: Mutex<Vec<String>>,
        /// Maps source text → translated text. If missing, returns source unchanged.
        responses: std::collections::HashMap<String, String>,
        /// If set, all calls return this error.
        error: Option<String>,
        /// If set, returns responses in order (first call → first response, etc.).
        /// Used for testing retry on malformed output.
        sequential: Mutex<Vec<String>>,
    }

    impl FakeTranslator {
        fn new(responses: std::collections::HashMap<String, String>) -> Self {
            Self {
                received: Mutex::new(Vec::new()),
                responses,
                error: None,
                sequential: Mutex::new(Vec::new()),
            }
        }

        fn with_error(message: &str) -> Self {
            Self {
                received: Mutex::new(Vec::new()),
                responses: std::collections::HashMap::new(),
                error: Some(message.to_string()),
                sequential: Mutex::new(Vec::new()),
            }
        }

        fn with_sequential_responses(responses: Vec<String>) -> Self {
            Self {
                received: Mutex::new(Vec::new()),
                responses: std::collections::HashMap::new(),
                error: None,
                sequential: Mutex::new(responses),
            }
        }

        fn received_texts(&self) -> Vec<String> {
            self.received.lock().unwrap().clone()
        }
    }

    #[async_trait::async_trait]
    impl Translator for FakeTranslator {
        async fn translate(&self, request: TranslationRequest<'_>) -> crate::error::Result<String> {
            self.received
                .lock()
                .unwrap()
                .push(request.source_text.to_string());

            if let Some(msg) = &self.error {
                return Err(SubtitleToolkitError::Translation {
                    provider: "fake",
                    message: msg.clone(),
                });
            }

            // Sequential mode: pop from front of queue
            {
                let mut seq = self.sequential.lock().unwrap();
                if !seq.is_empty() {
                    return Ok(seq.remove(0));
                }
            }

            Ok(self
                .responses
                .get(request.source_text)
                .cloned()
                .unwrap_or_else(|| request.source_text.to_string()))
        }
    }

    const SIMPLE_ASS: &str = r"[Script Info]
Title: Test
ScriptType: v4.00+

[V4+ Styles]
Format: Name, Fontname, Fontsize
Style: Default,Arial,20

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,Hello world
Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,Goodbye world
";

    const ASS_WITH_TAGS: &str = r"[Script Info]
Title: Test Tags
ScriptType: v4.00+

[V4+ Styles]
Format: Name, Fontname, Fontsize
Style: Default,Arial,20

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\pos(857.6,122.4)}{\an7}Status line
Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,Normal text
";

    #[tokio::test]
    async fn pipeline_translates_dialogue_and_preserves_structure() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();

        let mut responses = std::collections::HashMap::new();
        responses.insert(
            "<1> Hello world\n<2> Goodbye world".to_string(),
            "<1> Olá mundo\n<2> Adeus mundo".to_string(),
        );

        let translator = Arc::new(FakeTranslator::new(responses));
        let result = translate_ass(ass, "pt-BR", 1, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();
        let rendered = result.render();

        assert!(rendered.contains("Olá mundo"));
        assert!(rendered.contains("Adeus mundo"));
        assert!(!rendered.contains("Hello world"));
        assert!(!rendered.contains("Goodbye world"));

        // Headers and styles preserved
        assert!(rendered.contains("[Script Info]"));
        assert!(rendered.contains("[V4+ Styles]"));
        assert!(rendered.contains("[Events]"));
    }

    #[tokio::test]
    async fn pipeline_passes_numbered_text_and_target_language_to_translator() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();

        let mut responses = std::collections::HashMap::new();
        responses.insert(
            "<1> Hello world\n<2> Goodbye world".to_string(),
            "<1> translated1\n<2> translated2".to_string(),
        );

        let translator = Arc::new(FakeTranslator::new(responses));
        translate_ass(ass, "ja", 1, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();

        let texts = translator.received_texts();
        assert_eq!(texts.len(), 1);
        assert_eq!(texts[0], "<1> Hello world\n<2> Goodbye world");
    }

    #[tokio::test]
    async fn pipeline_strips_and_reinjects_override_tags() {
        let ass = AssSubtitle::parse(ASS_WITH_TAGS).unwrap();

        // The translator receives protected tokens instead of raw ASS commands.
        let mut responses = std::collections::HashMap::new();
        responses.insert(
            "<1> [[PSY_TAG_0]][[PSY_TAG_1]]Status line\n<2> Normal text".to_string(),
            "<1> [[PSY_TAG_0]][[PSY_TAG_1]]Linha de status\n<2> Texto normal".to_string(),
        );

        let translator = Arc::new(FakeTranslator::new(responses));
        let result = translate_ass(ass, "pt-BR", 1, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();
        let rendered = result.render();

        // Tags reinjected
        assert!(rendered.contains(r"{\pos(857.6,122.4)}{\an7}Linha de status"));
        // Second line had no tags, stays clean
        assert!(rendered.contains("Texto normal"));
        assert!(!rendered.contains("Normal text"));

        // Verify translator received clean text (no tags)
        let texts = translator.received_texts();
        assert!(!texts[0].contains(r"{\pos"));
        assert!(!texts[0].contains(r"{\an7}"));
        assert!(texts[0].contains("[[PSY_TAG_0]][[PSY_TAG_1]]"));
    }

    #[tokio::test]
    async fn pipeline_chunks_large_documents() {
        // Build an ASS with 300 cues to force multiple chunks at 200 lines/chunk.
        let mut lines = vec![
            "[Script Info]".to_string(),
            "Title: Big".to_string(),
            "ScriptType: v4.00+".to_string(),
            "".to_string(),
            "[V4+ Styles]".to_string(),
            "Format: Name, Fontname, Fontsize".to_string(),
            "Style: Default,Arial,20".to_string(),
            "".to_string(),
            "[Events]".to_string(),
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
                .to_string(),
        ];

        for i in 1..=300 {
            lines.push(format!(
                "Dialogue: 0,0:00:{:02}.00,0:00:{:02}.00,Default,,0,0,0,,subtitle line {i}",
                i,
                i + 1,
            ));
        }

        let ass_content = lines.join("\n");

        // Verify chunking splits at 200 lines
        let ass = AssSubtitle::parse(&ass_content).unwrap();
        let (clean_doc, _) = crate::subtitles::structured::strip_tags(ass.document());
        let chunks = crate::subtitles::structured::chunk_document_by_lines(&clean_doc, 200);
        assert_eq!(
            chunks.len(),
            2,
            "300 cues should produce 2 chunks at 200 lines"
        );
        assert_eq!(chunks[0].cues.len(), 200);
        assert_eq!(chunks[1].cues.len(), 100);

        // Build a FakeTranslator (identity translation)
        let translator = Arc::new(FakeTranslator::new(std::collections::HashMap::new()));

        let ass = AssSubtitle::parse(&ass_content).unwrap();
        let result = translate_ass(ass, "pt-BR", 1, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();
        let rendered = result.render();

        // All 300 cues should be present
        for i in 1..=300 {
            assert!(
                rendered.contains(&format!("subtitle line {i}")),
                "missing cue {i} in rendered output"
            );
        }

        // Translator was called twice (2 chunks)
        let texts = translator.received_texts();
        assert_eq!(texts.len(), 2);

        // All 300 cue IDs accounted for across all calls
        let mut all_ids: Vec<usize> = Vec::new();
        for text in &texts {
            for line in text.lines() {
                if let Some(start) = line.find('<')
                    && let Some(end) = line[start + 1..].find('>')
                    && let Ok(id) = line[start + 1..start + 1 + end].parse::<usize>()
                {
                    all_ids.push(id);
                }
            }
        }
        all_ids.sort();
        assert_eq!(all_ids, (1..=300).collect::<Vec<_>>());
    }

    struct TwoItemTranslator {
        calls: Mutex<Vec<String>>,
    }

    #[async_trait::async_trait]
    impl Translator for TwoItemTranslator {
        async fn translate(&self, request: TranslationRequest<'_>) -> crate::error::Result<String> {
            self.calls
                .lock()
                .unwrap()
                .push(request.source_text.to_string());
            Ok(request.source_text.replace("line", "linha"))
        }

        fn limits(&self) -> TranslationLimits {
            TranslationLimits {
                max_items: 2,
                max_request_bytes: 1_024,
                reject_unchanged_output: false,
            }
        }
    }

    #[tokio::test]
    async fn pipeline_respects_provider_item_limit() {
        let mut ass = SIMPLE_ASS.to_string();
        ass.push_str(
            "Dialogue: 0,0:00:05.00,0:00:06.00,Default,,0,0,0,,third line\n\
             Dialogue: 0,0:00:07.00,0:00:08.00,Default,,0,0,0,,fourth line\n\
             Dialogue: 0,0:00:09.00,0:00:10.00,Default,,0,0,0,,fifth line\n",
        );
        let translator = Arc::new(TwoItemTranslator {
            calls: Mutex::new(Vec::new()),
        });
        translate_ass(
            AssSubtitle::parse(&ass).unwrap(),
            "pt-BR",
            1,
            translator.clone(),
        )
        .await
        .unwrap();

        let calls = translator.calls.lock().unwrap();
        assert_eq!(calls.len(), 3);
        assert!(calls.iter().all(|call| call.lines().count() <= 2));
    }

    #[test]
    fn strict_validation_rejects_nontrivial_identity_output() {
        let source = SubtitleDocument {
            cues: vec![crate::SubtitleCue {
                id: 1,
                text: "This is unchanged dialogue".into(),
            }],
        };
        let translated = BTreeMap::from([(1, "This is unchanged dialogue".into())]);
        let error = validate_translated_chunk(
            &source,
            &translated,
            TranslationLimits {
                reject_unchanged_output: true,
                ..TranslationLimits::default()
            },
        )
        .unwrap_err();
        assert!(error.to_string().contains("unchanged"));
    }

    #[test]
    fn chunk_validation_rejects_changed_protected_tokens() {
        let source = SubtitleDocument {
            cues: vec![crate::SubtitleCue {
                id: 1,
                text: "[[PSY_TAG_0]]Hello[[PSY_TAG_1]]".into(),
            }],
        };
        let translated = BTreeMap::from([(1, "[[PSY_TAG_0]]Olá".into())]);
        let error = validate_translated_chunk(&source, &translated, TranslationLimits::default())
            .unwrap_err();
        assert!(error.to_string().contains("formatting tokens changed"));
    }

    #[tokio::test]
    async fn pipeline_propagates_translator_error() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();
        let translator = FakeTranslator::with_error("rate limit exceeded");

        let err = translate_ass(ass, "pt-BR", 1, Arc::new(translator) as Arc<dyn Translator>)
            .await
            .unwrap_err();

        assert!(err.to_string().contains("fake"));
        assert!(err.to_string().contains("rate limit exceeded"));
    }

    #[tokio::test]
    async fn pipeline_rejects_incomplete_translation() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();

        // Translator returns only one of two expected IDs
        let mut responses = std::collections::HashMap::new();
        responses.insert(
            "<1> Hello world\n<2> Goodbye world".to_string(),
            "<1> Olá mundo".to_string(), // missing <2>
        );

        let translator = FakeTranslator::new(responses);
        let err = translate_ass(ass, "pt-BR", 1, Arc::new(translator) as Arc<dyn Translator>)
            .await
            .unwrap_err();

        assert!(err.to_string().contains("missing id <2>"));
    }

    #[tokio::test]
    async fn pipeline_handles_multiline_cues() {
        let ass_content = r"[Script Info]
Title: Multiline
ScriptType: v4.00+

[V4+ Styles]
Format: Name, Fontname, Fontsize
Style: Default,Arial,20

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,First line\NSecond line
";

        let ass = AssSubtitle::parse(ass_content).unwrap();

        let mut responses = std::collections::HashMap::new();
        responses.insert(
            "<1> First line\\NSecond line".to_string(),
            "<1> Primeira linha\\NSegunda linha".to_string(),
        );

        let translator = Arc::new(FakeTranslator::new(responses));
        let result = translate_ass(ass, "pt-BR", 1, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();
        let rendered = result.render();

        assert!(rendered.contains("Primeira linha"));
        assert!(rendered.contains("Segunda linha"));
        assert!(rendered.contains(r"Primeira linha\NSegunda linha"));
    }

    #[tokio::test]
    async fn srt_pipeline_restores_real_multiline_and_markup() {
        let srt =
            SrtSubtitle::parse("1\r\n00:00:01,000 --> 00:00:02,000\r\n<i>Hello</i>\r\nworld\r\n")
                .unwrap();
        let mut responses = std::collections::HashMap::new();
        responses.insert(
            "<1> [[PSY_TAG_0]]Hello[[PSY_TAG_1]]\\Nworld".into(),
            "<1> [[PSY_TAG_0]]Olá[[PSY_TAG_1]]\\Nmundo".into(),
        );
        let translated = translate_srt(srt, "pt-BR", 1, Arc::new(FakeTranslator::new(responses)))
            .await
            .unwrap();
        let rendered = translated.render();
        assert!(rendered.contains("<i>Olá</i>\nmundo"));
        assert!(!rendered.contains(r"\N"));
    }

    #[tokio::test]
    async fn vtt_pipeline_restores_real_multiline_and_markup() {
        let vtt = VttSubtitle::parse(
            "WEBVTT\r\n\r\n1\r\n00:00:01.000 --> 00:00:02.000\r\n<v Speaker>Hello</v>\r\nworld\r\n",
        )
        .unwrap();
        let mut responses = std::collections::HashMap::new();
        responses.insert(
            "<1> [[PSY_TAG_0]]Hello[[PSY_TAG_1]]\\Nworld".into(),
            "<1> [[PSY_TAG_0]]Olá[[PSY_TAG_1]]\\Nmundo".into(),
        );
        let translated = translate_vtt(vtt, "pt-BR", 1, Arc::new(FakeTranslator::new(responses)))
            .await
            .unwrap();
        let rendered = translated.render();
        assert!(rendered.contains("<v Speaker>Olá</v>\nmundo"));
        assert!(!rendered.contains(r"\N"));
    }

    #[tokio::test]
    async fn direct_pipeline_rejects_zero_concurrency_without_hanging() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();
        let result = tokio::time::timeout(
            std::time::Duration::from_millis(100),
            translate_ass(
                ass,
                "pt-BR",
                0,
                Arc::new(FakeTranslator::new(std::collections::HashMap::new())),
            ),
        )
        .await
        .expect("validation must return without waiting");
        assert!(result.unwrap_err().to_string().contains("max_concurrent"));
    }

    #[tokio::test]
    async fn pipeline_translates_basic_document() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();

        let mut responses = std::collections::HashMap::new();
        responses.insert(
            "<1> Hello world\n<2> Goodbye world".to_string(),
            "<1> translated1\n<2> translated2".to_string(),
        );

        let translator = Arc::new(FakeTranslator::new(responses));
        translate_ass(ass, "pt-BR", 1, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();

        let texts = translator.received_texts();
        assert_eq!(texts.len(), 1);
    }

    #[test]
    fn dry_run_summary_reports_cues_chars_chunks() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();
        let summary = dry_run_summary(ass.document(), "pt-BR");

        assert!(
            summary.contains("2 cues"),
            "expected '2 cues' in: {summary}"
        );
        assert!(
            summary.contains("1 chunk(s)"),
            "expected '1 chunk(s)' in: {summary}"
        );
        assert!(
            summary.contains("→ pt-BR"),
            "expected '→ pt-BR' in: {summary}"
        );
    }

    #[test]
    fn dry_run_summary_counts_chars() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();
        let summary = dry_run_summary(ass.document(), "en");

        // "Hello world" = 11 chars, "Goodbye world" = 13 chars = 24 total
        assert!(
            summary.contains("24 chars"),
            "expected '24 chars' in: {summary}"
        );
    }

    #[test]
    fn dry_run_summary_handles_empty_document() {
        let ass_content = r"[Script Info]
Title: Empty
ScriptType: v4.00+

[V4+ Styles]
Format: Name, Fontname, Fontsize
Style: Default,Arial,20

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
";
        let ass = AssSubtitle::parse(ass_content).unwrap();
        let summary = dry_run_summary(ass.document(), "de");

        assert!(
            summary.contains("0 cues"),
            "expected '0 cues' in: {summary}"
        );
        assert!(
            summary.contains("0 chars"),
            "expected '0 chars' in: {summary}"
        );
        assert!(
            summary.contains("0 chunk(s)"),
            "expected '0 chunk(s)' in: {summary}"
        );
    }

    #[test]
    fn dry_run_summary_splits_large_documents() {
        // Build ASS with 100 cues to force multiple chunks
        let mut lines = vec![
            "[Script Info]".to_string(),
            "Title: Big".to_string(),
            "ScriptType: v4.00+".to_string(),
            "".to_string(),
            "[V4+ Styles]".to_string(),
            "Format: Name, Fontname, Fontsize".to_string(),
            "Style: Default,Arial,20".to_string(),
            "".to_string(),
            "[Events]".to_string(),
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
                .to_string(),
        ];
        for i in 1..=300 {
            lines.push(format!(
                "Dialogue: 0,0:00:{:02}.00,0:00:{:02}.00,Default,,0,0,0,,This is subtitle line number {i} with enough text to fill space",
                i, i + 1,
            ));
        }
        let ass = AssSubtitle::parse(&lines.join("\n")).unwrap();
        let summary = dry_run_summary(ass.document(), "pt-BR");

        assert!(
            summary.contains("300 cues"),
            "expected '300 cues' in: {summary}"
        );
        assert!(
            summary.contains("2 chunk(s)"),
            "expected '2 chunk(s)' in: {summary}"
        );
    }

    #[tokio::test]
    async fn pipeline_retries_chunk_on_malformed_output() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();

        // First call: returns broken output (missing <2>)
        // Second call: returns correct output
        let translator = Arc::new(FakeTranslator::with_sequential_responses(vec![
            "<1> Olá mundo".to_string(),                  // missing <2>
            "<1> Olá mundo\n<2> Adeus mundo".to_string(), // correct
        ]));

        let result = translate_ass(ass, "pt-BR", 1, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();
        let rendered = result.render();

        assert!(rendered.contains("Olá mundo"));
        assert!(rendered.contains("Adeus mundo"));

        // Should have been called twice (1 failed + 1 success)
        let texts = translator.received_texts();
        assert_eq!(texts.len(), 2);
    }

    #[tokio::test]
    async fn pipeline_gives_up_after_repeated_malformed_output() {
        let ass = AssSubtitle::parse(SIMPLE_ASS).unwrap();

        // Always returns broken output (missing <2>)
        let translator = Arc::new(FakeTranslator::with_sequential_responses(vec![
            "<1> Olá mundo".to_string(),
            "<1> Olá mundo".to_string(),
            "<1> Olá mundo".to_string(),
            "<1> Olá mundo".to_string(), // 4 attempts total (1 initial + 3 retries)
        ]));

        let err = translate_ass(ass, "pt-BR", 1, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap_err();

        assert!(err.to_string().contains("missing id <2>"));

        // Should have been called 4 times (1 initial + 3 retries)
        let texts = translator.received_texts();
        assert_eq!(texts.len(), 4);
    }

    #[test]
    fn progress_file_path_for_directory() {
        let path = progress_file_path(std::path::Path::new("/media/anime"));
        assert_eq!(
            path,
            std::path::PathBuf::from("/media/anime/.psyche-subtitle-toolkit-progress.json")
        );
    }

    #[test]
    fn progress_file_path_for_file() {
        let path = progress_file_path(std::path::Path::new("/media/anime/episode.mkv"));
        assert_eq!(
            path,
            std::path::PathBuf::from(
                "/media/anime/.episode.mkv.psyche-subtitle-toolkit-progress.json"
            )
        );
    }

    #[tokio::test]
    async fn progress_file_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let progress_path = dir.path().join(".psyche-subtitle-toolkit-progress.json");
        let run = ProgressRun {
            target_language: "pt-BR".into(),
            translator: "fake:model".into(),
            requested_track_id: Some(2),
        };
        let manifest = ProgressManifest {
            version: PROGRESS_VERSION,
            run: run.clone(),
            completed: vec![CompletedFile {
                canonical_path: "/media/anime/ep1.mkv".into(),
                fingerprint: FileFingerprint {
                    size: 42,
                    modified_unix_nanos: 123,
                },
                completed: true,
            }],
        };

        save_progress_atomic(&progress_path, &manifest)
            .await
            .unwrap();
        let loaded = load_progress(&progress_path, &run).await.unwrap();
        assert_eq!(loaded, manifest);
    }

    #[test]
    fn resume_retries_an_unchanged_pending_file() {
        let fingerprint = FileFingerprint {
            size: 42,
            modified_unix_nanos: 123,
        };
        let manifest = ProgressManifest {
            version: PROGRESS_VERSION,
            run: ProgressRun {
                target_language: "pt-BR".into(),
                translator: "fake:model".into(),
                requested_track_id: None,
            },
            completed: vec![CompletedFile {
                canonical_path: "/media/anime/ep1.mkv".into(),
                fingerprint: fingerprint.clone(),
                completed: false,
            }],
        };

        assert_eq!(
            resume_action(&manifest, "/media/anime/ep1.mkv", &fingerprint).unwrap(),
            ResumeAction::Process
        );
    }

    #[test]
    fn resume_rejects_a_changed_pending_file() {
        let manifest = ProgressManifest {
            version: PROGRESS_VERSION,
            run: ProgressRun {
                target_language: "pt-BR".into(),
                translator: "fake:model".into(),
                requested_track_id: None,
            },
            completed: vec![CompletedFile {
                canonical_path: "/media/anime/ep1.mkv".into(),
                fingerprint: FileFingerprint {
                    size: 42,
                    modified_unix_nanos: 123,
                },
                completed: false,
            }],
        };
        let changed = FileFingerprint {
            size: 84,
            modified_unix_nanos: 456,
        };

        let error = resume_action(&manifest, "/media/anime/ep1.mkv", &changed).unwrap_err();
        assert!(error.to_string().contains("inspect the MKV"));
    }

    #[tokio::test]
    async fn progress_file_handles_missing_file() {
        let dir = tempfile::tempdir().unwrap();
        let progress_path = dir.path().join(".psyche-subtitle-toolkit-progress.json");

        assert!(!progress_path.exists());
    }

    #[tokio::test]
    async fn progress_file_handles_corrupted_json() {
        let dir = tempfile::tempdir().unwrap();
        let progress_path = dir.path().join(".psyche-subtitle-toolkit-progress.json");

        tokio::fs::write(&progress_path, "not valid json")
            .await
            .unwrap();

        let run = ProgressRun {
            target_language: "pt-BR".into(),
            translator: "fake:model".into(),
            requested_track_id: None,
        };
        let error = load_progress(&progress_path, &run).await.unwrap_err();
        assert!(matches!(error, SubtitleToolkitError::Progress { .. }));
    }

    #[tokio::test]
    async fn progress_file_rejects_different_run_configuration() {
        let dir = tempfile::tempdir().unwrap();
        let progress_path = dir.path().join(".psyche-subtitle-toolkit-progress.json");
        let original_run = ProgressRun {
            target_language: "pt-BR".into(),
            translator: "openai:model-a".into(),
            requested_track_id: Some(2),
        };
        let manifest = ProgressManifest {
            version: PROGRESS_VERSION,
            run: original_run,
            completed: Vec::new(),
        };
        save_progress_atomic(&progress_path, &manifest)
            .await
            .unwrap();

        let different_run = ProgressRun {
            target_language: "es".into(),
            translator: "openai:model-b".into(),
            requested_track_id: Some(3),
        };
        let error = load_progress(&progress_path, &different_run)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("different"));
    }

    #[test]
    fn translation_file_lock_rejects_concurrent_writer() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("episode.mkv");
        std::fs::write(&file, b"fixture").unwrap();
        let first = acquire_translation_file_lock(&file).unwrap();
        let error = acquire_translation_file_lock(&file).unwrap_err();
        assert!(error.to_string().contains("already processing"));
        drop(first);
        acquire_translation_file_lock(&file).unwrap();
    }

    #[tokio::test]
    async fn pipeline_translates_concurrently() {
        // Build ASS with 300 cues → 2 chunks at 200 lines/chunk
        let mut lines = vec![
            "[Script Info]".to_string(),
            "Title: Concurrent".to_string(),
            "ScriptType: v4.00+".to_string(),
            "".to_string(),
            "[V4+ Styles]".to_string(),
            "Format: Name, Fontname, Fontsize".to_string(),
            "Style: Default,Arial,20".to_string(),
            "".to_string(),
            "[Events]".to_string(),
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
                .to_string(),
        ];
        for i in 1..=300 {
            lines.push(format!(
                "Dialogue: 0,0:00:{:02}.00,0:00:{:02}.00,Default,,0,0,0,,line {i}",
                i,
                i + 1,
            ));
        }
        let ass = AssSubtitle::parse(&lines.join("\n")).unwrap();
        let translator = Arc::new(FakeTranslator::new(std::collections::HashMap::new()));

        // Translate with max_concurrent=2 (both chunks in parallel)
        let result = translate_ass(ass, "pt-BR", 2, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();

        let rendered = result.render();
        for i in 1..=300 {
            assert!(rendered.contains(&format!("line {i}")), "missing cue {i}");
        }

        // Both chunks should have been translated
        let texts = translator.received_texts();
        assert_eq!(texts.len(), 2);
    }

    #[tokio::test]
    async fn concurrent_translation_preserves_all_cues() {
        // Stress test: 1000 cues, 5 chunks, max_concurrent=5
        let mut lines = vec![
            "[Script Info]".to_string(),
            "Title: Stress".to_string(),
            "ScriptType: v4.00+".to_string(),
            "".to_string(),
            "[V4+ Styles]".to_string(),
            "Format: Name, Fontname, Fontsize".to_string(),
            "Style: Default,Arial,20".to_string(),
            "".to_string(),
            "[Events]".to_string(),
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
                .to_string(),
        ];
        for i in 1..=1000 {
            lines.push(format!(
                "Dialogue: 0,0:00:{:02}.00,0:00:{:02}.00,Default,,0,0,0,,stress line {i}",
                i,
                i + 1,
            ));
        }
        let ass = AssSubtitle::parse(&lines.join("\n")).unwrap();
        let translator = Arc::new(FakeTranslator::new(std::collections::HashMap::new()));

        let result = translate_ass(ass, "pt-BR", 5, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap();

        let rendered = result.render();
        // Every single cue must be present
        for i in 1..=1000 {
            assert!(
                rendered.contains(&format!("stress line {i}")),
                "missing cue {i} under concurrent translation"
            );
        }

        // 1000 cues / 200 lines per chunk = 5 chunks
        let texts = translator.received_texts();
        assert_eq!(
            texts.len(),
            5,
            "expected 5 chunk calls, got {}",
            texts.len()
        );
    }

    #[tokio::test]
    async fn concurrent_translation_output_is_deterministic() {
        // Run the same document through concurrent translation twice.
        // Output must be identical regardless of task scheduling.
        let make_ass = || {
            let mut lines = vec![
                "[Script Info]".to_string(),
                "Title: Deterministic".to_string(),
                "ScriptType: v4.00+".to_string(),
                "".to_string(),
                "[V4+ Styles]".to_string(),
                "Format: Name, Fontname, Fontsize".to_string(),
                "Style: Default,Arial,20".to_string(),
                "".to_string(),
                "[Events]".to_string(),
                "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
                    .to_string(),
            ];
            for i in 1..=500 {
                lines.push(format!(
                    "Dialogue: 0,0:00:{:02}.00,0:00:{:02}.00,Default,,0,0,0,,det line {i}",
                    i,
                    i + 1,
                ));
            }
            AssSubtitle::parse(&lines.join("\n")).unwrap()
        };

        let t1 = Arc::new(FakeTranslator::new(std::collections::HashMap::new()));
        let r1 = translate_ass(make_ass(), "pt-BR", 3, t1.clone() as Arc<dyn Translator>)
            .await
            .unwrap();

        let t2 = Arc::new(FakeTranslator::new(std::collections::HashMap::new()));
        let r2 = translate_ass(make_ass(), "pt-BR", 3, t2.clone() as Arc<dyn Translator>)
            .await
            .unwrap();

        assert_eq!(
            r1.render(),
            r2.render(),
            "concurrent output is non-deterministic"
        );
    }

    #[tokio::test]
    async fn concurrent_error_propagates_correctly() {
        // First chunk succeeds, second chunk always fails.
        // The pipeline should return an error, not silently succeed.
        let mut lines = vec![
            "[Script Info]".to_string(),
            "Title: ErrProp".to_string(),
            "ScriptType: v4.00+".to_string(),
            "".to_string(),
            "[V4+ Styles]".to_string(),
            "Format: Name, Fontname, Fontsize".to_string(),
            "Style: Default,Arial,20".to_string(),
            "".to_string(),
            "[Events]".to_string(),
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
                .to_string(),
        ];
        for i in 1..=400 {
            lines.push(format!(
                "Dialogue: 0,0:00:{:02}.00,0:00:{:02}.00,Default,,0,0,0,,line {i}",
                i,
                i + 1,
            ));
        }
        let ass = AssSubtitle::parse(&lines.join("\n")).unwrap();

        // Always error — all chunks will fail
        struct MixedResultTranslator;

        #[async_trait::async_trait]
        impl Translator for MixedResultTranslator {
            async fn translate(
                &self,
                request: TranslationRequest<'_>,
            ) -> crate::error::Result<String> {
                if request.source_text.starts_with("<201>") {
                    Err(SubtitleToolkitError::Translation {
                        provider: "mixed",
                        message: "provider down on second chunk".into(),
                    })
                } else {
                    Ok(request.source_text.to_string())
                }
            }
        }
        let translator = Arc::new(MixedResultTranslator);

        let err = translate_ass(ass, "pt-BR", 3, translator.clone() as Arc<dyn Translator>)
            .await
            .unwrap_err();

        assert!(err.to_string().contains("second chunk"));
    }

    /// A translator that tracks the maximum number of concurrent translate calls.
    /// Used to verify the semaphore actually bounds concurrency.
    struct ConcurrencyTrackingTranslator {
        active: std::sync::atomic::AtomicU32,
        max_observed: std::sync::atomic::AtomicU32,
        received: Mutex<Vec<String>>,
    }

    impl ConcurrencyTrackingTranslator {
        fn new() -> Self {
            Self {
                active: std::sync::atomic::AtomicU32::new(0),
                max_observed: std::sync::atomic::AtomicU32::new(0),
                received: Mutex::new(Vec::new()),
            }
        }

        fn max_concurrent_calls(&self) -> u32 {
            self.max_observed.load(std::sync::atomic::Ordering::SeqCst)
        }
    }

    #[async_trait::async_trait]
    impl Translator for ConcurrencyTrackingTranslator {
        async fn translate(&self, request: TranslationRequest<'_>) -> crate::error::Result<String> {
            self.received
                .lock()
                .unwrap()
                .push(request.source_text.to_string());

            let current = self
                .active
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
                + 1;
            // Update max_observed
            self.max_observed
                .fetch_max(current, std::sync::atomic::Ordering::SeqCst);

            // Simulate work — yield to let other tasks run
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;

            self.active
                .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);

            // Identity translation
            Ok(request.source_text.to_string())
        }
    }

    #[tokio::test]
    async fn semaphore_bounds_concurrency() {
        // 600 cues → 3 chunks at 200 lines/chunk, max_concurrent=2
        // The semaphore should prevent all 3 from running simultaneously.
        let mut lines = vec![
            "[Script Info]".to_string(),
            "Title: Semaphore".to_string(),
            "ScriptType: v4.00+".to_string(),
            "".to_string(),
            "[V4+ Styles]".to_string(),
            "Format: Name, Fontname, Fontsize".to_string(),
            "Style: Default,Arial,20".to_string(),
            "".to_string(),
            "[Events]".to_string(),
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
                .to_string(),
        ];
        for i in 1..=600 {
            lines.push(format!(
                "Dialogue: 0,0:00:{:02}.00,0:00:{:02}.00,Default,,0,0,0,,sem line {i}",
                i,
                i + 1,
            ));
        }
        let ass = AssSubtitle::parse(&lines.join("\n")).unwrap();
        let translator = Arc::new(ConcurrencyTrackingTranslator::new());

        let result = translate_ass(
            ass,
            "pt-BR",
            2, // max_concurrent=2
            translator.clone() as Arc<dyn Translator>,
        )
        .await
        .unwrap();

        // All 600 cues should be present
        let rendered = result.render();
        for i in 1..=600 {
            assert!(
                rendered.contains(&format!("sem line {i}")),
                "missing cue {i}"
            );
        }

        // The max observed concurrency should be <= 2
        let max = translator.max_concurrent_calls();
        assert_eq!(max, 2, "expected two calls to overlap, observed {max}");

        // All 3 chunks should have been called
        let texts = translator.received.lock().unwrap();
        assert_eq!(texts.len(), 3);
    }

    #[tokio::test]
    async fn sequential_mode_is_deterministic() {
        // With max_concurrent=1, received_texts() must be in spawn order.
        let mut lines = vec![
            "[Script Info]".to_string(),
            "Title: Seq".to_string(),
            "ScriptType: v4.00+".to_string(),
            "".to_string(),
            "[V4+ Styles]".to_string(),
            "Format: Name, Fontname, Fontsize".to_string(),
            "Style: Default,Arial,20".to_string(),
            "".to_string(),
            "[Events]".to_string(),
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
                .to_string(),
        ];
        for i in 1..=500 {
            lines.push(format!(
                "Dialogue: 0,0:00:{:02}.00,0:00:{:02}.00,Default,,0,0,0,,seq line {i}",
                i,
                i + 1,
            ));
        }
        let ass = AssSubtitle::parse(&lines.join("\n")).unwrap();
        let translator = Arc::new(FakeTranslator::new(std::collections::HashMap::new()));

        translate_ass(
            ass,
            "pt-BR",
            1, // sequential
            translator.clone() as Arc<dyn Translator>,
        )
        .await
        .unwrap();

        let texts = translator.received_texts();
        assert_eq!(texts.len(), 3);

        // In sequential mode, chunk 1 should be called before chunk 2, etc.
        // Verify by checking that each text starts with the expected cue ID range.
        assert!(
            texts[0].starts_with("<1> "),
            "first chunk should start with <1>"
        );
        assert!(
            texts[1].starts_with("<201> "),
            "second chunk should start with <201>"
        );
        assert!(
            texts[2].starts_with("<401> "),
            "third chunk should start with <401>"
        );
    }
}