subx-cli 1.7.4

AI subtitle processing CLI tool, which automatically matches, renames, and converts subtitle files.
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
//! Refactored sync command CLI argument definitions.
//!
//! Supports multiple synchronization methods: OpenAI Whisper API, local VAD,
//! automatic selection, and manual offset. Provides fine-grained parameter
//! control and intelligent defaults.
//!
//! # Synchronization Methods
//!
//! ## OpenAI Whisper API
//! Cloud transcription service providing high-precision speech detection.
//!
//! ## Local VAD
//! Voice Activity Detection using local processing for privacy and speed.
//!
//! ## Manual Offset
//! Direct time offset specification for precise manual synchronization.

/// Synchronization method selection for CLI arguments.
#[derive(Debug, Clone, ValueEnum, PartialEq)]
pub enum SyncMethodArg {
    /// Use local voice activity detection only
    Vad,
    /// Apply manual offset (requires --offset parameter)
    Manual,
}

impl From<SyncMethodArg> for crate::core::sync::SyncMethod {
    fn from(arg: SyncMethodArg) -> Self {
        match arg {
            SyncMethodArg::Vad => Self::LocalVad,
            SyncMethodArg::Manual => Self::Manual,
        }
    }
}

use crate::cli::InputPathHandler;
use crate::error::{SubXError, SubXResult};
use clap::{Args, ValueEnum};
use std::path::{Path, PathBuf};

/// Refactored sync command arguments supporting multiple sync methods.
#[derive(Args, Debug, Clone)]
pub struct SyncArgs {
    /// Positional file or directory paths to process. Can include video, subtitle, or directories.
    #[arg(value_name = "PATH", num_args = 0..)]
    pub positional_paths: Vec<PathBuf>,

    /// Video file path (optional if using positional paths or manual offset).
    #[arg(
        short = 'v',
        long = "video",
        value_name = "VIDEO",
        help = "Video file path (optional if using positional or manual offset)"
    )]
    pub video: Option<PathBuf>,

    /// Subtitle file path (optional if using positional paths or manual offset).
    #[arg(
        short = 's',
        long = "subtitle",
        value_name = "SUBTITLE",
        help = "Subtitle file path (optional if using positional or manual offset)"
    )]
    pub subtitle: Option<PathBuf>,
    /// Specify file or directory paths to process (via -i), can be used multiple times
    #[arg(short = 'i', long = "input", value_name = "PATH")]
    pub input_paths: Vec<PathBuf>,

    /// Recursively process subdirectories (new parameter)
    #[arg(short, long)]
    pub recursive: bool,

    /// Manual time offset in seconds (positive delays subtitles, negative advances them).
    #[arg(
        long,
        value_name = "SECONDS",
        help = "Manual offset in seconds (positive delays subtitles, negative advances them)"
    )]
    pub offset: Option<f32>,

    /// Sync method selection.
    #[arg(short, long, value_enum, help = "Synchronization method")]
    pub method: Option<SyncMethodArg>,

    /// Analysis time window in seconds.
    #[arg(
        short = 'w',
        long,
        value_name = "SECONDS",
        default_value = "30",
        help = "Time window around first subtitle for analysis (seconds)"
    )]
    pub window: u32,

    // === VAD Options ===
    /// VAD sensitivity threshold.
    #[arg(
        long,
        value_name = "SENSITIVITY",
        help = "VAD sensitivity threshold (0.0-1.0)"
    )]
    pub vad_sensitivity: Option<f32>,

    // === Output Options ===
    /// Output file path.
    #[arg(
        short = 'o',
        long,
        value_name = "PATH",
        help = "Output file path (default: input_synced.ext)"
    )]
    pub output: Option<PathBuf>,

    /// Verbose output.
    #[arg(
        long,
        help = "Enable verbose output with detailed progress information"
    )]
    pub verbose: bool,

    /// Dry run mode.
    #[arg(long, help = "Analyze and display results but don't save output file")]
    pub dry_run: bool,

    /// Force overwrite existing output file.
    #[arg(long, help = "Overwrite existing output file without confirmation")]
    pub force: bool,

    /// Enable batch processing mode. Can optionally specify a directory path.
    #[arg(
        short = 'b',
        long = "batch",
        value_name = "DIRECTORY",
        help = "Enable batch processing mode. Can optionally specify a directory path.",
        num_args = 0..=1,
        require_equals = false
    )]
    pub batch: Option<Option<PathBuf>>,

    /// Disable automatic archive extraction for `-i` inputs
    #[arg(long, default_value_t = false)]
    pub no_extract: bool,
    // === Legacy/Hidden Options (Deprecated) ===
}

/// Sync method enumeration (backward compatible).
#[derive(Debug, Clone, PartialEq)]
pub enum SyncMethod {
    /// Automatic sync using audio analysis.
    Auto,
    /// Manual sync using specified time offset.
    Manual,
}

impl SyncArgs {
    /// Validate parameter combination validity.
    pub fn validate(&self) -> Result<(), String> {
        // Check manual mode parameter combination
        if let Some(SyncMethodArg::Manual) = &self.method {
            if self.offset.is_none() {
                return Err("Manual method requires --offset parameter.".to_string());
            }
        }

        // In batch mode, check if we have some input source
        if self.batch.is_some() {
            let has_input_paths = !self.input_paths.is_empty();
            let has_positional = !self.positional_paths.is_empty();
            let has_video_or_subtitle = self.video.is_some() || self.subtitle.is_some();
            let has_batch_directory = matches!(&self.batch, Some(Some(_)));

            // Batch mode needs at least one input source
            if has_input_paths || has_positional || has_video_or_subtitle || has_batch_directory {
                return Ok(());
            }

            return Err("Batch mode requires at least one input source.\n\n\
Usage:\n\
• Batch with directory: subx sync -b <directory>\n\
• Batch with input paths: subx sync -b -i <path>\n\
• Batch with positional: subx sync -b <path>\n\n\
Need help? Run: subx sync --help"
                .to_string());
        }

        // For single file mode, check if we have enough information
        let has_video = self.video.is_some();
        let has_subtitle = self.subtitle.is_some();
        let has_positional = !self.positional_paths.is_empty();
        let is_manual = self.offset.is_some();

        // Manual mode only requires subtitle (can be provided via positional args)
        if is_manual {
            if has_subtitle || has_positional {
                return Ok(());
            }
            return Err("Manual sync mode requires subtitle file.\n\n\
Usage:\n\
• Manual sync: subx sync --offset <seconds> <subtitle>\n\
• Manual sync: subx sync --offset <seconds> -s <subtitle>\n\n\
Need help? Run: subx sync --help"
                .to_string());
        }

        // Auto mode: needs video, or positional args
        if has_video || has_positional {
            // Check VAD sensitivity option only used with VAD method
            if self.vad_sensitivity.is_some() {
                if let Some(SyncMethodArg::Manual) = &self.method {
                    return Err("VAD options can only be used with --method vad.".to_string());
                }
            }
            return Ok(());
        }

        Err("Auto sync mode requires video file or positional path.\n\n\
Usage:\n\
• Auto sync: subx sync <video> <subtitle> or subx sync <video_path>\n\
• Auto sync: subx sync -v <video> -s <subtitle>\n\
• Manual sync: subx sync --offset <seconds> <subtitle>\n\
• Batch mode: subx sync -b [directory]\n\n\
Need help? Run: subx sync --help"
            .to_string())
    }

    /// Get output file path.
    pub fn get_output_path(&self) -> Option<PathBuf> {
        if let Some(ref output) = self.output {
            Some(output.clone())
        } else {
            self.subtitle
                .as_ref()
                .map(|subtitle| create_default_output_path(subtitle))
        }
    }

    /// Check if in manual mode.
    pub fn is_manual_mode(&self) -> bool {
        self.offset.is_some() || matches!(self.method, Some(SyncMethodArg::Manual))
    }

    /// Determine sync method (backward compatible).
    pub fn sync_method(&self) -> SyncMethod {
        if self.offset.is_some() {
            SyncMethod::Manual
        } else {
            SyncMethod::Auto
        }
    }

    /// Validate parameters (backward compatible method).
    pub fn validate_compat(&self) -> SubXResult<()> {
        // Allow positional path for auto sync without explicit video
        if self.offset.is_none() && self.video.is_none() && !self.positional_paths.is_empty() {
            return Ok(());
        }
        match (self.offset.is_some(), self.video.is_some()) {
            // Manual mode: offset provided, video optional
            (true, _) => Ok(()),
            // Auto mode: no offset, video required
            (false, true) => Ok(()),
            // Auto mode without video: invalid
            (false, false) => Err(SubXError::CommandExecution(
                "Auto sync mode requires video file.\n\n\
Usage:\n\
• Auto sync: subx sync <video> <subtitle>\n\
• Manual sync: subx sync --offset <seconds> <subtitle>\n\n\
Need help? Run: subx sync --help"
                    .to_string(),
            )),
        }
    }

    /// Return whether video file is required (auto sync).
    #[allow(dead_code)]
    pub fn requires_video(&self) -> bool {
        self.offset.is_none()
    }

    /// Get all input paths, combining video, subtitle and input_paths parameters
    /// Note: For sync command, both video and subtitle are valid input paths
    pub fn get_input_handler(&self) -> Result<InputPathHandler, SubXError> {
        let optional_paths = vec![self.video.clone(), self.subtitle.clone()];
        let string_paths: Vec<String> = self
            .positional_paths
            .iter()
            .map(|p| p.to_string_lossy().to_string())
            .collect();
        let merged_paths = InputPathHandler::merge_paths_from_multiple_sources(
            &optional_paths,
            &self.input_paths,
            &string_paths,
        )?;

        Ok(InputPathHandler::from_args(&merged_paths, self.recursive)?
            .with_extensions(&["mp4", "mkv", "avi", "mov", "srt", "ass", "vtt", "sub"])
            .with_no_extract(self.no_extract))
    }

    /// Get sync mode: single file or batch
    pub fn get_sync_mode(&self) -> Result<SyncMode, SubXError> {
        // Batch mode: process directories or multiple inputs when -b, -i, or directory positional used
        if self.batch.is_some()
            || !self.input_paths.is_empty()
            || self
                .positional_paths
                .iter()
                .any(|p| p.extension().is_none())
        {
            let mut paths = Vec::new();

            // Include batch directory argument if provided
            if let Some(Some(batch_dir)) = &self.batch {
                paths.push(batch_dir.clone());
            }

            // Include input paths (-i) and any positional paths
            paths.extend(self.input_paths.clone());
            paths.extend(self.positional_paths.clone());

            // If still no paths, use current directory
            if paths.is_empty() {
                paths.push(PathBuf::from("."));
            }

            let handler = InputPathHandler::from_args(&paths, self.recursive)?
                .with_extensions(&["mp4", "mkv", "avi", "mov", "srt", "ass", "vtt", "sub"])
                .with_no_extract(self.no_extract);

            return Ok(SyncMode::Batch(handler));
        }

        // Single file positional mode: auto-infer video/subtitle pairing
        if !self.positional_paths.is_empty() {
            if self.positional_paths.len() == 1 {
                let path = &self.positional_paths[0];
                let ext = path
                    .extension()
                    .and_then(|s| s.to_str())
                    .unwrap_or("")
                    .to_lowercase();
                let mut video = None;
                let mut subtitle = None;
                match ext.as_str() {
                    "mp4" | "mkv" | "avi" | "mov" => {
                        video = Some(path.clone());
                        if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                            let dir = path.parent().unwrap_or_else(|| Path::new("."));
                            for sub_ext in &["srt", "ass", "vtt", "sub"] {
                                let cand = dir.join(format!("{stem}.{sub_ext}"));
                                if cand.exists() {
                                    subtitle = Some(cand);
                                    break;
                                }
                            }
                        }
                    }
                    "srt" | "ass" | "vtt" | "sub" => {
                        subtitle = Some(path.clone());
                        if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                            let dir = path.parent().unwrap_or_else(|| Path::new("."));
                            for vid_ext in &["mp4", "mkv", "avi", "mov"] {
                                let cand = dir.join(format!("{stem}.{vid_ext}"));
                                if cand.exists() {
                                    video = Some(cand);
                                    break;
                                }
                            }
                        }
                    }
                    _ => {}
                }
                // For manual mode, we don't need video file if we have subtitle
                if self.is_manual_mode() {
                    if let Some(subtitle_path) = subtitle {
                        return Ok(SyncMode::Single {
                            video: PathBuf::new(), // Empty video path for manual mode
                            subtitle: subtitle_path,
                        });
                    }
                }
                if let (Some(v), Some(s)) = (video, subtitle) {
                    return Ok(SyncMode::Single {
                        video: v,
                        subtitle: s,
                    });
                }
                return Err(SubXError::InvalidSyncConfiguration);
            } else if self.positional_paths.len() == 2 {
                let mut video = None;
                let mut subtitle = None;
                for p in &self.positional_paths {
                    if let Some(ext) = p
                        .extension()
                        .and_then(|s| s.to_str())
                        .map(|s| s.to_lowercase())
                    {
                        if ["mp4", "mkv", "avi", "mov"].contains(&ext.as_str()) {
                            video = Some(p.clone());
                        }
                        if ["srt", "ass", "vtt", "sub"].contains(&ext.as_str()) {
                            subtitle = Some(p.clone());
                        }
                    }
                }
                if let (Some(v), Some(s)) = (video, subtitle) {
                    return Ok(SyncMode::Single {
                        video: v,
                        subtitle: s,
                    });
                }
                return Err(SubXError::InvalidSyncConfiguration);
            }
        }

        // Explicit mode: video and subtitle options
        if let (Some(video), Some(subtitle)) = (self.video.as_ref(), self.subtitle.as_ref()) {
            Ok(SyncMode::Single {
                video: video.clone(),
                subtitle: subtitle.clone(),
            })
        } else if self.is_manual_mode() {
            if let Some(subtitle) = self.subtitle.as_ref() {
                // Manual mode only requires subtitle file
                Ok(SyncMode::Single {
                    video: PathBuf::new(), // Empty video path for manual mode
                    subtitle: subtitle.clone(),
                })
            } else {
                Err(SubXError::InvalidSyncConfiguration)
            }
        } else {
            Err(SubXError::InvalidSyncConfiguration)
        }
    }
}

/// Sync mode: single file or batch
#[derive(Debug)]
pub enum SyncMode {
    /// Single file sync mode, specify video and subtitle files
    Single {
        /// Video file path
        video: PathBuf,
        /// Subtitle file path
        subtitle: PathBuf,
    },
    /// Batch sync mode, using InputPathHandler to process multiple paths
    Batch(InputPathHandler),
}

// Helper functions

/// Creates a default output path by appending `_synced` to the file stem.
pub fn create_default_output_path(input: &Path) -> PathBuf {
    let mut output = input.to_path_buf();

    if let Some(stem) = input.file_stem().and_then(|s| s.to_str()) {
        if let Some(extension) = input.extension().and_then(|s| s.to_str()) {
            let new_filename = format!("{stem}_synced.{extension}");
            output.set_file_name(new_filename);
        }
    }

    output
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::{Cli, Commands};
    use clap::Parser;
    use std::path::PathBuf;
    use tempfile::TempDir;

    // ── helpers ──────────────────────────────────────────────────────────────

    fn default_args() -> SyncArgs {
        SyncArgs {
            positional_paths: Vec::new(),
            video: None,
            subtitle: None,
            input_paths: Vec::new(),
            recursive: false,
            offset: None,
            method: None,
            window: 30,
            vad_sensitivity: None,
            output: None,
            verbose: false,
            dry_run: false,
            force: false,
            batch: None,
            no_extract: false,
        }
    }

    // ── SyncMethodArg / From conversion ──────────────────────────────────────

    #[test]
    fn test_sync_method_selection_manual() {
        let args = SyncArgs {
            video: Some(PathBuf::from("video.mp4")),
            subtitle: Some(PathBuf::from("subtitle.srt")),
            offset: Some(2.5),
            ..default_args()
        };
        assert_eq!(args.sync_method(), SyncMethod::Manual);
    }

    #[test]
    fn test_sync_method_selection_auto() {
        let args = SyncArgs {
            video: Some(PathBuf::from("video.mp4")),
            subtitle: Some(PathBuf::from("subtitle.srt")),
            ..default_args()
        };
        assert_eq!(args.sync_method(), SyncMethod::Auto);
    }

    #[test]
    fn test_method_arg_conversion() {
        assert_eq!(
            crate::core::sync::SyncMethod::from(SyncMethodArg::Vad),
            crate::core::sync::SyncMethod::LocalVad
        );
        assert_eq!(
            crate::core::sync::SyncMethod::from(SyncMethodArg::Manual),
            crate::core::sync::SyncMethod::Manual
        );
    }

    #[test]
    fn test_sync_method_arg_debug_clone() {
        let m = SyncMethodArg::Vad;
        let c = m.clone();
        assert_eq!(m, c);
        assert_eq!(format!("{c:?}"), "Vad");
        let m2 = SyncMethodArg::Manual;
        assert_eq!(format!("{m2:?}"), "Manual");
    }

    // ── SyncMethod enum ───────────────────────────────────────────────────────

    #[test]
    fn test_sync_method_enum_debug_clone() {
        let m = SyncMethod::Auto;
        let c = m.clone();
        assert_eq!(m, c);
        assert_eq!(format!("{c:?}"), "Auto");
        let m2 = SyncMethod::Manual;
        assert_eq!(format!("{m2:?}"), "Manual");
    }

    // ── is_manual_mode ────────────────────────────────────────────────────────

    #[test]
    fn test_is_manual_mode_with_offset() {
        let args = SyncArgs {
            offset: Some(1.0),
            ..default_args()
        };
        assert!(args.is_manual_mode());
    }

    #[test]
    fn test_is_manual_mode_with_method_manual() {
        let args = SyncArgs {
            method: Some(SyncMethodArg::Manual),
            ..default_args()
        };
        assert!(args.is_manual_mode());
    }

    #[test]
    fn test_is_manual_mode_false() {
        let args = default_args();
        assert!(!args.is_manual_mode());
    }

    #[test]
    fn test_is_manual_mode_false_with_vad_method() {
        let args = SyncArgs {
            method: Some(SyncMethodArg::Vad),
            ..default_args()
        };
        assert!(!args.is_manual_mode());
    }

    // ── requires_video ────────────────────────────────────────────────────────

    #[test]
    fn test_requires_video_true_without_offset() {
        let args = default_args();
        assert!(args.requires_video());
    }

    #[test]
    fn test_requires_video_false_with_offset() {
        let args = SyncArgs {
            offset: Some(-1.5),
            ..default_args()
        };
        assert!(!args.requires_video());
    }

    // ── get_output_path ───────────────────────────────────────────────────────

    #[test]
    fn test_get_output_path_explicit() {
        let args = SyncArgs {
            output: Some(PathBuf::from("out.srt")),
            subtitle: Some(PathBuf::from("sub.srt")),
            ..default_args()
        };
        assert_eq!(args.get_output_path(), Some(PathBuf::from("out.srt")));
    }

    #[test]
    fn test_get_output_path_default_from_subtitle() {
        let args = SyncArgs {
            subtitle: Some(PathBuf::from("movie.srt")),
            ..default_args()
        };
        let out = args.get_output_path().unwrap();
        assert_eq!(out.file_name().unwrap(), "movie_synced.srt");
    }

    #[test]
    fn test_get_output_path_none_without_subtitle() {
        let args = default_args();
        assert_eq!(args.get_output_path(), None);
    }

    // ── validate ──────────────────────────────────────────────────────────────

    #[test]
    fn test_validate_manual_method_requires_offset() {
        let args = SyncArgs {
            method: Some(SyncMethodArg::Manual),
            video: Some(PathBuf::from("v.mp4")),
            ..default_args()
        };
        let result = args.validate();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .contains("Manual method requires --offset")
        );
    }

    #[test]
    fn test_validate_manual_method_with_offset_ok() {
        let args = SyncArgs {
            method: Some(SyncMethodArg::Manual),
            offset: Some(1.0),
            subtitle: Some(PathBuf::from("sub.srt")),
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_batch_with_input_paths_ok() {
        let args = SyncArgs {
            batch: Some(None),
            input_paths: vec![PathBuf::from("dir")],
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_batch_with_positional_ok() {
        let args = SyncArgs {
            batch: Some(None),
            positional_paths: vec![PathBuf::from("dir")],
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_batch_with_video_ok() {
        let args = SyncArgs {
            batch: Some(None),
            video: Some(PathBuf::from("v.mp4")),
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_batch_with_subtitle_ok() {
        let args = SyncArgs {
            batch: Some(None),
            subtitle: Some(PathBuf::from("s.srt")),
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_batch_with_directory_ok() {
        let args = SyncArgs {
            batch: Some(Some(PathBuf::from("mydir"))),
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_batch_no_inputs_err() {
        let args = SyncArgs {
            batch: Some(None),
            ..default_args()
        };
        let result = args.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Batch mode requires"));
    }

    #[test]
    fn test_validate_manual_offset_with_subtitle_ok() {
        let args = SyncArgs {
            offset: Some(2.0),
            subtitle: Some(PathBuf::from("sub.srt")),
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_manual_offset_with_positional_ok() {
        let args = SyncArgs {
            offset: Some(2.0),
            positional_paths: vec![PathBuf::from("sub.srt")],
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_manual_offset_without_subtitle_err() {
        let args = SyncArgs {
            offset: Some(2.0),
            ..default_args()
        };
        let result = args.validate();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .contains("Manual sync mode requires subtitle")
        );
    }

    #[test]
    fn test_validate_auto_with_video_ok() {
        let args = SyncArgs {
            video: Some(PathBuf::from("v.mp4")),
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_auto_with_positional_ok() {
        let args = SyncArgs {
            positional_paths: vec![PathBuf::from("v.mp4")],
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_auto_vad_sensitivity_with_manual_method_err() {
        // manual method check fires first (offset required) - this path
        // tests the vad_sensitivity guard, which requires the auto method
        // *and* a video to be set.
        let args2 = SyncArgs {
            video: Some(PathBuf::from("v.mp4")),
            method: Some(SyncMethodArg::Manual),
            vad_sensitivity: Some(0.5),
            offset: None, // manual without offset → first error fires
            ..default_args()
        };
        assert!(args2.validate().is_err());
    }

    #[test]
    fn test_validate_vad_sensitivity_with_vad_method_and_video_ok() {
        // vad_sensitivity is fine when method is Vad (or None)
        let args = SyncArgs {
            video: Some(PathBuf::from("v.mp4")),
            method: Some(SyncMethodArg::Vad),
            vad_sensitivity: Some(0.7),
            ..default_args()
        };
        assert!(args.validate().is_ok());
    }

    #[test]
    fn test_validate_auto_no_inputs_err() {
        let args = default_args();
        let result = args.validate();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .contains("Auto sync mode requires video file")
        );
    }

    // ── validate_compat ───────────────────────────────────────────────────────

    #[test]
    fn test_validate_compat_with_positional_no_video_no_offset_ok() {
        let args = SyncArgs {
            positional_paths: vec![PathBuf::from("movie.mp4")],
            ..default_args()
        };
        assert!(args.validate_compat().is_ok());
    }

    #[test]
    fn test_validate_compat_with_offset_ok() {
        let args = SyncArgs {
            offset: Some(1.0),
            ..default_args()
        };
        assert!(args.validate_compat().is_ok());
    }

    #[test]
    fn test_validate_compat_with_video_ok() {
        let args = SyncArgs {
            video: Some(PathBuf::from("v.mp4")),
            ..default_args()
        };
        assert!(args.validate_compat().is_ok());
    }

    #[test]
    fn test_validate_compat_no_offset_no_video_no_positional_err() {
        let args = default_args();
        assert!(args.validate_compat().is_err());
    }

    #[test]
    fn test_validate_compat_with_offset_and_video_ok() {
        let args = SyncArgs {
            offset: Some(2.5),
            video: Some(PathBuf::from("v.mp4")),
            ..default_args()
        };
        assert!(args.validate_compat().is_ok());
    }

    // ── get_sync_mode ─────────────────────────────────────────────────────────

    #[test]
    fn test_get_sync_mode_batch_explicit_batch_flag() {
        let tmp = TempDir::new().unwrap();
        let args = SyncArgs {
            batch: Some(None),
            input_paths: vec![tmp.path().to_path_buf()],
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        assert!(matches!(mode, SyncMode::Batch(_)));
    }

    #[test]
    fn test_get_sync_mode_batch_with_directory() {
        let tmp = TempDir::new().unwrap();
        let args = SyncArgs {
            batch: Some(Some(tmp.path().to_path_buf())),
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        assert!(matches!(mode, SyncMode::Batch(_)));
    }

    #[test]
    fn test_get_sync_mode_batch_from_input_paths() {
        let tmp = TempDir::new().unwrap();
        let args = SyncArgs {
            input_paths: vec![tmp.path().to_path_buf()],
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        assert!(matches!(mode, SyncMode::Batch(_)));
    }

    #[test]
    fn test_get_sync_mode_batch_uses_current_dir_when_no_paths() {
        let args = SyncArgs {
            batch: Some(None),
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        assert!(matches!(mode, SyncMode::Batch(_)));
    }

    #[test]
    fn test_get_sync_mode_single_from_two_positionals() {
        let args = SyncArgs {
            positional_paths: vec![PathBuf::from("movie.mp4"), PathBuf::from("movie.srt")],
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        match mode {
            SyncMode::Single { video, subtitle } => {
                assert_eq!(video, PathBuf::from("movie.mp4"));
                assert_eq!(subtitle, PathBuf::from("movie.srt"));
            }
            _ => panic!("Expected Single mode"),
        }
    }

    #[test]
    fn test_get_sync_mode_single_two_positionals_wrong_extensions_err() {
        let args = SyncArgs {
            positional_paths: vec![PathBuf::from("file1.txt"), PathBuf::from("file2.doc")],
            ..default_args()
        };
        assert!(args.get_sync_mode().is_err());
    }

    #[test]
    fn test_get_sync_mode_single_one_positional_no_extension_is_batch() {
        // A directory path (no extension) is treated as batch mode
        let tmp = TempDir::new().unwrap();
        let args = SyncArgs {
            positional_paths: vec![tmp.path().to_path_buf()],
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        assert!(matches!(mode, SyncMode::Batch(_)));
    }

    #[test]
    fn test_get_sync_mode_single_positional_video_no_subtitle_err() {
        // File has video extension but no matching subtitle on disk
        let args = SyncArgs {
            positional_paths: vec![PathBuf::from("nonexistent_movie.mp4")],
            ..default_args()
        };
        assert!(args.get_sync_mode().is_err());
    }

    #[test]
    fn test_get_sync_mode_single_positional_subtitle_finds_video() {
        let tmp = TempDir::new().unwrap();
        let video_path = tmp.path().join("clip.mp4");
        let sub_path = tmp.path().join("clip.srt");
        std::fs::write(&video_path, b"fake video").unwrap();
        std::fs::write(&sub_path, b"1\n00:00:01,000 --> 00:00:02,000\nHello\n").unwrap();

        let args = SyncArgs {
            positional_paths: vec![sub_path.clone()],
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        match mode {
            SyncMode::Single { video, subtitle } => {
                assert_eq!(video, video_path);
                assert_eq!(subtitle, sub_path);
            }
            _ => panic!("Expected Single mode"),
        }
    }

    #[test]
    fn test_get_sync_mode_single_positional_video_finds_subtitle() {
        let tmp = TempDir::new().unwrap();
        let video_path = tmp.path().join("film.mkv");
        let sub_path = tmp.path().join("film.ass");
        std::fs::write(&video_path, b"fake video").unwrap();
        std::fs::write(&sub_path, b"[Script Info]\n").unwrap();

        let args = SyncArgs {
            positional_paths: vec![video_path.clone()],
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        match mode {
            SyncMode::Single { video, subtitle } => {
                assert_eq!(video, video_path);
                assert_eq!(subtitle, sub_path);
            }
            _ => panic!("Expected Single mode"),
        }
    }

    #[test]
    fn test_get_sync_mode_single_positional_manual_mode_subtitle_only() {
        let tmp = TempDir::new().unwrap();
        let sub_path = tmp.path().join("orphan.srt");
        std::fs::write(&sub_path, b"1\n00:00:01,000 --> 00:00:02,000\nHi\n").unwrap();

        let args = SyncArgs {
            positional_paths: vec![sub_path.clone()],
            offset: Some(-0.5),
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        match mode {
            SyncMode::Single { video, subtitle } => {
                assert_eq!(video, PathBuf::new());
                assert_eq!(subtitle, sub_path);
            }
            _ => panic!("Expected Single mode"),
        }
    }

    #[test]
    fn test_get_sync_mode_explicit_video_and_subtitle() {
        let args = SyncArgs {
            video: Some(PathBuf::from("v.mp4")),
            subtitle: Some(PathBuf::from("s.srt")),
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        match mode {
            SyncMode::Single { video, subtitle } => {
                assert_eq!(video, PathBuf::from("v.mp4"));
                assert_eq!(subtitle, PathBuf::from("s.srt"));
            }
            _ => panic!("Expected Single mode"),
        }
    }

    #[test]
    fn test_get_sync_mode_manual_explicit_subtitle_only() {
        let args = SyncArgs {
            offset: Some(1.0),
            subtitle: Some(PathBuf::from("s.srt")),
            ..default_args()
        };
        let mode = args.get_sync_mode().unwrap();
        match mode {
            SyncMode::Single { video, subtitle } => {
                assert_eq!(video, PathBuf::new());
                assert_eq!(subtitle, PathBuf::from("s.srt"));
            }
            _ => panic!("Expected Single mode"),
        }
    }

    #[test]
    fn test_get_sync_mode_manual_no_subtitle_err() {
        let args = SyncArgs {
            offset: Some(1.0),
            ..default_args()
        };
        assert!(args.get_sync_mode().is_err());
    }

    #[test]
    fn test_get_sync_mode_no_inputs_err() {
        let args = default_args();
        assert!(args.get_sync_mode().is_err());
    }

    // ── create_default_output_path ────────────────────────────────────────────

    #[test]
    fn test_create_default_output_path_srt() {
        let input = PathBuf::from("test.srt");
        let output = create_default_output_path(&input);
        assert_eq!(output.file_name().unwrap(), "test_synced.srt");
    }

    #[test]
    fn test_create_default_output_path_with_prefix() {
        let input = PathBuf::from("/path/to/movie.ass");
        let output = create_default_output_path(&input);
        assert_eq!(output.file_name().unwrap(), "movie_synced.ass");
        assert_eq!(output.parent().unwrap(), std::path::Path::new("/path/to"));
    }

    #[test]
    fn test_create_default_output_path_vtt() {
        let input = PathBuf::from("episode.vtt");
        let output = create_default_output_path(&input);
        assert_eq!(output.file_name().unwrap(), "episode_synced.vtt");
    }

    #[test]
    fn test_create_default_output_path_no_extension() {
        // File without extension: stem exists but extension does not; path returned unchanged
        let input = PathBuf::from("noextension");
        let output = create_default_output_path(&input);
        assert_eq!(output, PathBuf::from("noextension"));
    }

    // ── CLI parsing ───────────────────────────────────────────────────────────

    #[test]
    fn test_sync_args_batch_input() {
        let cli = Cli::try_parse_from([
            "subx-cli",
            "sync",
            "-i",
            "dir",
            "--batch",
            "--recursive",
            "--video",
            "video.mp4",
        ])
        .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.input_paths, vec![PathBuf::from("dir")]);
        assert!(args.batch.is_some());
        assert!(args.recursive);
        assert_eq!(args.video, Some(PathBuf::from("video.mp4")));
    }

    #[test]
    fn test_sync_args_invalid_combinations() {
        let cli = Cli::try_parse_from(["subx-cli", "sync", "--batch", "-i", "dir"]).unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert!(args.validate().is_ok());

        let args_invalid = SyncArgs {
            batch: Some(None),
            ..default_args()
        };
        assert!(args_invalid.validate().is_err());
    }

    #[test]
    fn test_cli_parse_offset_and_subtitle() {
        let cli = Cli::try_parse_from([
            "subx-cli",
            "sync",
            "--offset",
            "3.5",
            "--subtitle",
            "sub.srt",
        ])
        .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.offset, Some(3.5));
        assert_eq!(args.subtitle, Some(PathBuf::from("sub.srt")));
    }

    #[test]
    fn test_cli_parse_negative_offset() {
        let cli =
            Cli::try_parse_from(["subx-cli", "sync", "--offset=-2.0", "-s", "sub.srt"]).unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.offset, Some(-2.0));
    }

    #[test]
    fn test_cli_parse_method_vad() {
        let cli = Cli::try_parse_from(["subx-cli", "sync", "--method", "vad", "--video", "v.mp4"])
            .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.method, Some(SyncMethodArg::Vad));
    }

    #[test]
    fn test_cli_parse_method_manual() {
        let cli = Cli::try_parse_from([
            "subx-cli",
            "sync",
            "--method",
            "manual",
            "--offset",
            "1.0",
            "--subtitle",
            "sub.srt",
        ])
        .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.method, Some(SyncMethodArg::Manual));
    }

    #[test]
    fn test_cli_parse_default_window() {
        let cli = Cli::try_parse_from(["subx-cli", "sync", "--video", "v.mp4"]).unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.window, 30);
    }

    #[test]
    fn test_cli_parse_custom_window() {
        let cli = Cli::try_parse_from(["subx-cli", "sync", "--video", "v.mp4", "--window", "60"])
            .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.window, 60);
    }

    #[test]
    fn test_cli_parse_flags_verbose_dry_run_force() {
        let cli = Cli::try_parse_from([
            "subx-cli",
            "sync",
            "--video",
            "v.mp4",
            "--verbose",
            "--dry-run",
            "--force",
        ])
        .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert!(args.verbose);
        assert!(args.dry_run);
        assert!(args.force);
    }

    #[test]
    fn test_cli_parse_no_extract_flag() {
        let cli =
            Cli::try_parse_from(["subx-cli", "sync", "--video", "v.mp4", "--no-extract"]).unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert!(args.no_extract);
    }

    #[test]
    fn test_cli_parse_output_path() {
        let cli = Cli::try_parse_from([
            "subx-cli",
            "sync",
            "--video",
            "v.mp4",
            "--output",
            "result.srt",
        ])
        .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.output, Some(PathBuf::from("result.srt")));
    }

    #[test]
    fn test_cli_parse_vad_sensitivity() {
        let cli = Cli::try_parse_from([
            "subx-cli",
            "sync",
            "--video",
            "v.mp4",
            "--vad-sensitivity",
            "0.8",
        ])
        .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.vad_sensitivity, Some(0.8));
    }

    #[test]
    fn test_cli_parse_batch_with_directory() {
        let cli = Cli::try_parse_from(["subx-cli", "sync", "--batch", "mydir"]).unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.batch, Some(Some(PathBuf::from("mydir"))));
    }

    #[test]
    fn test_cli_parse_positional_paths() {
        let cli = Cli::try_parse_from(["subx-cli", "sync", "video.mp4", "subtitle.srt"]).unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(
            args.positional_paths,
            vec![PathBuf::from("video.mp4"), PathBuf::from("subtitle.srt")]
        );
    }

    #[test]
    fn test_cli_parse_short_flags() {
        let cli = Cli::try_parse_from([
            "subx-cli",
            "sync",
            "-v",
            "video.mp4",
            "-s",
            "sub.srt",
            "-r",
            "-b",
        ])
        .unwrap();
        let args = match cli.command {
            Commands::Sync(a) => a,
            _ => panic!("Expected Sync command"),
        };
        assert_eq!(args.video, Some(PathBuf::from("video.mp4")));
        assert_eq!(args.subtitle, Some(PathBuf::from("sub.srt")));
        assert!(args.recursive);
        assert!(args.batch.is_some());
    }
}