subx-cli 1.6.0

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
//! Task definition and utilities for parallel processing
use crate::core::fs_util::{atomic_create_file, validate_write_target};
use async_trait::async_trait;
use std::fmt;
use std::fs::File;
use std::io;
use std::path::Path;

/// Returns true if the given I/O error indicates a cross-device link failure,
/// which is the signal to fall back from `rename` to copy+delete.
fn is_cross_device_error(err: &io::Error) -> bool {
    #[cfg(unix)]
    {
        // EXDEV == 18 on Linux and most Unixes
        if err.raw_os_error() == Some(18) {
            return true;
        }
    }
    // Fallback check: some platforms report cross-device via a message or kind.
    matches!(err.kind(), io::ErrorKind::Unsupported)
}

/// Resolve filename conflicts by atomically creating the target.
///
/// Returns the resolved path together with the open file handle. Callers
/// should write through this handle to avoid TOCTOU races between conflict
/// resolution and file creation.
fn resolve_filename_conflict(
    target: std::path::PathBuf,
) -> Result<(std::path::PathBuf, File), Box<dyn std::error::Error + Send + Sync>> {
    match atomic_create_file(&target) {
        Ok(f) => return Ok((target, f)),
        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
        Err(e) => return Err(e.into()),
    }

    let file_stem = target
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("file");
    let extension = target.extension().and_then(|s| s.to_str()).unwrap_or("");
    let parent = target.parent().unwrap_or_else(|| std::path::Path::new("."));

    for i in 1..1000 {
        let new_name = if extension.is_empty() {
            format!("{}.{}", file_stem, i)
        } else {
            format!("{}.{}.{}", file_stem, i, extension)
        };
        let new_path = parent.join(new_name);
        match atomic_create_file(&new_path) {
            Ok(f) => return Ok((new_path, f)),
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e.into()),
        }
    }

    Err("Could not resolve filename conflict".into())
}

/// Trait defining a unit of work that can be executed asynchronously.
///
/// All tasks in the parallel processing system must implement this trait
/// to provide execution logic and metadata.
#[async_trait]
pub trait Task: Send + Sync {
    /// Executes the task and returns the result.
    async fn execute(&self) -> TaskResult;
    /// Returns the type identifier for this task.
    fn task_type(&self) -> &'static str;
    /// Returns a unique identifier for this specific task instance.
    fn task_id(&self) -> String;
    /// Returns an estimated duration for the task execution.
    fn estimated_duration(&self) -> Option<std::time::Duration> {
        None
    }
    /// Returns a human-readable description of the task.
    fn description(&self) -> String {
        format!("{} task", self.task_type())
    }
}

/// Result of task execution indicating success, failure, or partial completion.
///
/// Provides detailed information about the outcome of a task execution,
/// including success/failure status and descriptive messages.
#[derive(Debug, Clone)]
pub enum TaskResult {
    /// Task completed successfully with a result message
    Success(String),
    /// Task failed with an error message
    Failed(String),
    /// Task was cancelled before completion
    Cancelled,
    /// Task partially completed with success and failure messages
    PartialSuccess(String, String),
}

/// Current execution status of a task in the system.
///
/// Tracks the lifecycle of a task from initial queuing through completion
/// or failure, providing detailed status information.
#[derive(Debug, Clone)]
pub enum TaskStatus {
    /// Task is queued and waiting for execution
    Pending,
    /// Task is currently being executed
    Running,
    /// Task completed successfully or with partial success
    Completed(TaskResult),
    /// Task failed during execution
    Failed(String),
    /// Task was cancelled before or during execution
    Cancelled,
}

impl fmt::Display for TaskResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TaskResult::Success(msg) => write!(f, "✓ {}", msg),
            TaskResult::Failed(msg) => write!(f, "✗ {}", msg),
            TaskResult::Cancelled => write!(f, "âš  Task cancelled"),
            TaskResult::PartialSuccess(success, warn) => {
                write!(f, "âš  {} (warning: {})", success, warn)
            }
        }
    }
}

impl fmt::Display for TaskStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TaskStatus::Pending => write!(f, "Pending"),
            TaskStatus::Running => write!(f, "Running"),
            TaskStatus::Completed(result) => write!(f, "Completed: {}", result),
            TaskStatus::Failed(msg) => write!(f, "Failed: {}", msg),
            TaskStatus::Cancelled => write!(f, "Cancelled"),
        }
    }
}

/// Task for processing files (convert, sync, match, validate).
///
/// Represents a file processing operation that can be executed
/// asynchronously in the parallel processing system.
pub struct FileProcessingTask {
    /// Path to the input file to be processed
    pub input_path: std::path::PathBuf,
    /// Optional output path for the processed file
    pub output_path: Option<std::path::PathBuf>,
    /// The specific operation to perform on the file
    pub operation: ProcessingOperation,
}

/// Supported operations for file processing tasks.
///
/// Defines the different types of operations that can be performed
/// on subtitle and video files in the processing system.
#[derive(Debug, Clone)]
pub enum ProcessingOperation {
    /// Convert subtitle format from one type to another
    ConvertFormat {
        /// Source format (e.g., "srt", "ass")
        from: String,
        /// Target format (e.g., "srt", "ass")
        to: String,
    },
    /// Synchronize subtitle timing with audio
    SyncSubtitle {
        /// Path to the audio file for synchronization
        audio_path: std::path::PathBuf,
    },
    /// Match subtitle files with video files
    MatchFiles {
        /// Whether to search recursively in subdirectories
        recursive: bool,
    },
    /// Validate subtitle file format and structure
    ValidateFormat,
    /// Copy subtitle file to video folder
    CopyToVideoFolder {
        /// Path to the source subtitle file to be copied
        source: std::path::PathBuf,
        /// Path to the target video folder where the subtitle will be copied
        target: std::path::PathBuf,
    },
    /// Move subtitle file to video folder
    MoveToVideoFolder {
        /// Path to the source subtitle file to be moved
        source: std::path::PathBuf,
        /// Path to the target video folder where the subtitle will be moved
        target: std::path::PathBuf,
    },
    /// Copy a file with a new name (local copy)
    CopyWithRename {
        /// Source file path
        source: std::path::PathBuf,
        /// Target file path
        target: std::path::PathBuf,
    },
    /// Create a backup of a file
    CreateBackup {
        /// Original file path
        source: std::path::PathBuf,
        /// Backup file path
        backup: std::path::PathBuf,
    },
    /// Rename (move) a file
    RenameFile {
        /// Original file path
        source: std::path::PathBuf,
        /// New file path after rename
        target: std::path::PathBuf,
    },
}

#[async_trait]
impl Task for FileProcessingTask {
    async fn execute(&self) -> TaskResult {
        match &self.operation {
            ProcessingOperation::ConvertFormat { from, to } => {
                match self.convert_format(from, to).await {
                    Ok(path) => TaskResult::Success(format!(
                        "Successfully converted {} -> {}: {}",
                        from,
                        to,
                        path.display()
                    )),
                    Err(e) => TaskResult::Failed(format!(
                        "Conversion failed {}: {}",
                        self.input_path.display(),
                        e
                    )),
                }
            }
            ProcessingOperation::SyncSubtitle { .. } => {
                // Sync not supported in parallel tasks
                TaskResult::Failed("Sync functionality not implemented".to_string())
            }
            ProcessingOperation::MatchFiles { recursive } => {
                match self.match_files(*recursive).await {
                    Ok(m) => TaskResult::Success(format!(
                        "File matching completed: found {} matches",
                        m.len()
                    )),
                    Err(e) => TaskResult::Failed(format!("Matching failed: {}", e)),
                }
            }
            ProcessingOperation::ValidateFormat => match self.validate_format().await {
                Ok(true) => TaskResult::Success(format!(
                    "Format validation passed: {}",
                    self.input_path.display()
                )),
                Ok(false) => TaskResult::Failed(format!(
                    "Format validation failed: {}",
                    self.input_path.display()
                )),
                Err(e) => TaskResult::Failed(format!("Validation error: {}", e)),
            },
            ProcessingOperation::CopyToVideoFolder { source, target } => {
                match self.execute_copy_operation(source, target).await {
                    Ok(_) => TaskResult::Success(format!(
                        "Copied: {} -> {}",
                        source.display(),
                        target.display()
                    )),
                    Err(e) => TaskResult::Failed(format!("Copy failed: {}", e)),
                }
            }
            ProcessingOperation::MoveToVideoFolder { source, target } => {
                match self.execute_move_operation(source, target).await {
                    Ok(_) => TaskResult::Success(format!(
                        "Moved: {} -> {}",
                        source.display(),
                        target.display()
                    )),
                    Err(e) => TaskResult::Failed(format!("Move failed: {}", e)),
                }
            }
            ProcessingOperation::CopyWithRename { source, target } => {
                match self
                    .execute_copy_with_rename_operation(source, target)
                    .await
                {
                    Ok(_) => TaskResult::Success(format!(
                        "Copied: {} -> {}",
                        source.display(),
                        target.display()
                    )),
                    Err(e) => TaskResult::Failed(format!("Copy failed: {}", e)),
                }
            }
            ProcessingOperation::CreateBackup { source, backup } => {
                match self.execute_create_backup_operation(source, backup).await {
                    Ok(_) => TaskResult::Success(format!(
                        "Backup created: {} -> {}",
                        source.display(),
                        backup.display()
                    )),
                    Err(e) => TaskResult::Failed(format!("Backup failed: {}", e)),
                }
            }
            ProcessingOperation::RenameFile { source, target } => {
                match self.execute_rename_file_operation(source, target).await {
                    Ok(_) => TaskResult::Success(format!(
                        "Renamed: {} -> {}",
                        source.display(),
                        target.display()
                    )),
                    Err(e) => TaskResult::Failed(format!("Rename failed: {}", e)),
                }
            }
        }
    }

    fn task_type(&self) -> &'static str {
        match &self.operation {
            ProcessingOperation::ConvertFormat { .. } => "convert",
            ProcessingOperation::SyncSubtitle { .. } => "sync",
            ProcessingOperation::MatchFiles { .. } => "match",
            ProcessingOperation::ValidateFormat => "validate",
            ProcessingOperation::CopyToVideoFolder { .. } => "copy_to_video_folder",
            ProcessingOperation::MoveToVideoFolder { .. } => "move_to_video_folder",
            ProcessingOperation::CopyWithRename { .. } => "copy_with_rename",
            ProcessingOperation::CreateBackup { .. } => "create_backup",
            ProcessingOperation::RenameFile { .. } => "rename_file",
        }
    }

    fn task_id(&self) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        self.input_path.hash(&mut hasher);
        self.operation.hash(&mut hasher);
        format!("{}_{:x}", self.task_type(), hasher.finish())
    }

    fn estimated_duration(&self) -> Option<std::time::Duration> {
        if let Ok(meta) = std::fs::metadata(&self.input_path) {
            let size_mb = meta.len() as f64 / 1_048_576.0;
            let secs = match &self.operation {
                ProcessingOperation::ConvertFormat { .. } => size_mb * 0.1,
                ProcessingOperation::SyncSubtitle { .. } => size_mb * 0.5,
                ProcessingOperation::MatchFiles { .. } => 2.0,
                ProcessingOperation::ValidateFormat => size_mb * 0.05,
                ProcessingOperation::CopyToVideoFolder { .. } => size_mb * 0.01, // Fast copy
                ProcessingOperation::MoveToVideoFolder { .. } => size_mb * 0.005, // Even faster move
                ProcessingOperation::CopyWithRename { .. } => size_mb * 0.01,
                ProcessingOperation::CreateBackup { .. } => size_mb * 0.01,
                ProcessingOperation::RenameFile { .. } => size_mb * 0.005,
            };
            Some(std::time::Duration::from_secs_f64(secs))
        } else {
            None
        }
    }

    fn description(&self) -> String {
        match &self.operation {
            ProcessingOperation::ConvertFormat { from, to } => {
                format!(
                    "Convert {} from {} to {}",
                    self.input_path.display(),
                    from,
                    to
                )
            }
            ProcessingOperation::SyncSubtitle { audio_path } => format!(
                "Sync subtitle {} with audio {}",
                self.input_path.display(),
                audio_path.display()
            ),
            ProcessingOperation::MatchFiles { recursive } => format!(
                "Match files in {}{}",
                self.input_path.display(),
                if *recursive { " (recursive)" } else { "" }
            ),
            ProcessingOperation::ValidateFormat => {
                format!("Validate format of {}", self.input_path.display())
            }
            ProcessingOperation::CopyToVideoFolder { source, target } => {
                format!("Copy {} to {}", source.display(), target.display())
            }
            ProcessingOperation::MoveToVideoFolder { source, target } => {
                format!("Move {} to {}", source.display(), target.display())
            }
            ProcessingOperation::CopyWithRename { source, target } => {
                format!(
                    "CopyWithRename {} to {}",
                    source.display(),
                    target.display()
                )
            }
            ProcessingOperation::CreateBackup { source, backup } => {
                format!("CreateBackup {} to {}", source.display(), backup.display())
            }
            ProcessingOperation::RenameFile { source, target } => {
                format!("Rename {} to {}", source.display(), target.display())
            }
        }
    }
}

impl FileProcessingTask {
    /// Create a new file processing task with operation
    pub fn new(
        input_path: std::path::PathBuf,
        output_path: Option<std::path::PathBuf>,
        operation: ProcessingOperation,
    ) -> Self {
        FileProcessingTask {
            input_path,
            output_path,
            operation,
        }
    }

    /// Execute copy operation for file relocation
    async fn execute_copy_operation(
        &self,
        source: &Path,
        target: &Path,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let source = source.to_path_buf();
        let target = target.to_path_buf();
        tokio::task::spawn_blocking(
            move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                // Create target directory if it doesn't exist
                if let Some(parent) = target.parent() {
                    std::fs::create_dir_all(parent)?;
                }

                // Atomically resolve filename conflicts and obtain an open file handle.
                let (final_target, mut file) = resolve_filename_conflict(target)?;

                if let Some(parent) = final_target.parent() {
                    validate_write_target(&final_target, parent)?;
                }

                // Stream the source file contents through the exclusive handle.
                let mut src = std::fs::File::open(&source)?;
                std::io::copy(&mut src, &mut file)?;
                Ok(())
            },
        )
        .await?
    }

    /// Execute move operation for file relocation
    async fn execute_move_operation(
        &self,
        source: &Path,
        target: &Path,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let source = source.to_path_buf();
        let target = target.to_path_buf();
        tokio::task::spawn_blocking(
            move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                // Create target directory if it doesn't exist
                if let Some(parent) = target.parent() {
                    std::fs::create_dir_all(parent)?;
                }

                // Try a fast in-filesystem rename first; fall back to copy+delete otherwise.
                if !target.exists() {
                    match std::fs::rename(&source, &target) {
                        Ok(_) => return Ok(()),
                        Err(e) if is_cross_device_error(&e) => {}
                        Err(_) => { /* fall through to copy+delete path */ }
                    }
                }

                let (final_target, mut file) = resolve_filename_conflict(target)?;

                if let Some(parent) = final_target.parent() {
                    validate_write_target(&final_target, parent)?;
                }

                let mut src = std::fs::File::open(&source)?;
                std::io::copy(&mut src, &mut file)?;
                file.sync_all()?;
                drop(file);
                std::fs::remove_file(&source)?;
                Ok(())
            },
        )
        .await?
    }

    /// Execute a copy with rename operation (local copy) using CIFS-safe copy
    async fn execute_copy_with_rename_operation(
        &self,
        source: &Path,
        target: &Path,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let source = source.to_path_buf();
        let target = target.to_path_buf();
        tokio::task::spawn_blocking(
            move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                if let Some(parent) = target.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                crate::core::fs_util::copy_file_cifs_safe(&source, &target)?;
                Ok(())
            },
        )
        .await?
    }

    /// Execute a create backup operation using an atomically created destination.
    async fn execute_create_backup_operation(
        &self,
        source: &Path,
        backup: &Path,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let source = source.to_path_buf();
        let backup = backup.to_path_buf();
        tokio::task::spawn_blocking(
            move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                if let Some(parent) = backup.parent() {
                    std::fs::create_dir_all(parent)?;
                }

                let (final_target, mut file) = resolve_filename_conflict(backup)?;

                if let Some(parent) = final_target.parent() {
                    validate_write_target(&final_target, parent)?;
                }

                let mut src = std::fs::File::open(&source)?;
                std::io::copy(&mut src, &mut file)?;
                Ok(())
            },
        )
        .await?
    }

    /// Execute a file rename operation
    async fn execute_rename_file_operation(
        &self,
        source: &Path,
        target: &Path,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let source = source.to_path_buf();
        let target = target.to_path_buf();
        tokio::task::spawn_blocking(
            move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                if let Some(parent) = target.parent() {
                    std::fs::create_dir_all(parent)?;
                }

                if !target.exists() {
                    match std::fs::rename(&source, &target) {
                        Ok(_) => return Ok(()),
                        Err(e) if is_cross_device_error(&e) => {}
                        Err(_) => { /* fall through to copy+delete path */ }
                    }
                }

                let (final_target, mut file) = resolve_filename_conflict(target)?;

                if let Some(parent) = final_target.parent() {
                    validate_write_target(&final_target, parent)?;
                }

                let mut src = std::fs::File::open(&source)?;
                std::io::copy(&mut src, &mut file)?;
                file.sync_all()?;
                drop(file);
                std::fs::remove_file(&source)?;
                Ok(())
            },
        )
        .await?
    }

    async fn convert_format(&self, _from: &str, _to: &str) -> crate::Result<std::path::PathBuf> {
        // Stub convert: simply return input path
        Ok(self.input_path.clone())
    }

    async fn sync_subtitle(
        &self,
        _audio_path: &std::path::Path,
    ) -> crate::Result<crate::core::sync::SyncResult> {
        // Stub implementation: sync not available
        Err(crate::error::SubXError::parallel_processing(
            "sync_subtitle not implemented".to_string(),
        ))
    }

    async fn match_files(&self, _recursive: bool) -> crate::Result<Vec<()>> {
        // Stub implementation: no actual matching
        Ok(Vec::new())
    }

    async fn validate_format(&self) -> crate::Result<bool> {
        // Stub validate: always succeed
        Ok(true)
    }
}

// impl Hash for ProcessingOperation to support task_id generation
impl std::hash::Hash for ProcessingOperation {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            ProcessingOperation::ConvertFormat { from, to } => {
                "convert".hash(state);
                from.hash(state);
                to.hash(state);
            }
            ProcessingOperation::SyncSubtitle { audio_path } => {
                "sync".hash(state);
                audio_path.hash(state);
            }
            ProcessingOperation::MatchFiles { recursive } => {
                "match".hash(state);
                recursive.hash(state);
            }
            ProcessingOperation::ValidateFormat => {
                "validate".hash(state);
            }
            ProcessingOperation::CopyToVideoFolder { source, target } => {
                "copy_to_video_folder".hash(state);
                source.hash(state);
                target.hash(state);
            }
            ProcessingOperation::MoveToVideoFolder { source, target } => {
                "move_to_video_folder".hash(state);
                source.hash(state);
                target.hash(state);
            }
            ProcessingOperation::CopyWithRename { source, target } => {
                "copy_with_rename".hash(state);
                source.hash(state);
                target.hash(state);
            }
            ProcessingOperation::CreateBackup { source, backup } => {
                "create_backup".hash(state);
                source.hash(state);
                backup.hash(state);
            }
            ProcessingOperation::RenameFile { source, target } => {
                "rename_file".hash(state);
                source.hash(state);
                target.hash(state);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_file_processing_task_validate_format() {
        let tmp = TempDir::new().unwrap();
        let test_file = tmp.path().join("test.srt");
        tokio::fs::write(&test_file, "1\n00:00:01,000 --> 00:00:02,000\nTest\n")
            .await
            .unwrap();
        let task = FileProcessingTask {
            input_path: test_file.clone(),
            output_path: None,
            operation: ProcessingOperation::ValidateFormat,
        };
        let result = task.execute().await;
        assert!(matches!(result, TaskResult::Success(_)));
    }

    #[tokio::test]
    async fn test_file_processing_task_copy_with_rename() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("orig.txt");
        let dst = tmp.path().join("copy.txt");
        tokio::fs::write(&src, b"hello").await.unwrap();
        let task = FileProcessingTask::new(
            src.clone(),
            Some(dst.clone()),
            ProcessingOperation::CopyWithRename {
                source: src.clone(),
                target: dst.clone(),
            },
        );
        let result = task.execute().await;
        assert!(matches!(result, TaskResult::Success(_)));
        let data = tokio::fs::read(&dst).await.unwrap();
        assert_eq!(data, b"hello");
    }

    #[tokio::test]
    async fn test_file_processing_task_create_backup() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("orig.txt");
        let backup = tmp.path().join("orig.txt.bak");
        tokio::fs::write(&src, b"backup").await.unwrap();
        let task = FileProcessingTask::new(
            src.clone(),
            Some(backup.clone()),
            ProcessingOperation::CreateBackup {
                source: src.clone(),
                backup: backup.clone(),
            },
        );
        let result = task.execute().await;
        assert!(matches!(result, TaskResult::Success(_)));
        let data = tokio::fs::read(&backup).await.unwrap();
        assert_eq!(data, b"backup");
    }

    #[tokio::test]
    async fn test_file_processing_task_rename_file() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("a.txt");
        let dst = tmp.path().join("b.txt");
        tokio::fs::write(&src, b"rename").await.unwrap();
        let task = FileProcessingTask::new(
            src.clone(),
            Some(dst.clone()),
            ProcessingOperation::RenameFile {
                source: src.clone(),
                target: dst.clone(),
            },
        );
        let result = task.execute().await;
        assert!(matches!(result, TaskResult::Success(_)));
        assert!(tokio::fs::metadata(&src).await.is_err());
        let data = tokio::fs::read(&dst).await.unwrap();
        assert_eq!(data, b"rename");
    }

    /// Test task lifecycle and status transitions
    #[tokio::test]
    async fn test_task_lifecycle() {
        let tmp = TempDir::new().unwrap();
        let test_file = tmp.path().join("lifecycle.srt");
        tokio::fs::write(
            &test_file,
            "1\n00:00:01,000 --> 00:00:02,000\nLifecycle test\n",
        )
        .await
        .unwrap();

        let task = FileProcessingTask {
            input_path: test_file.clone(),
            output_path: None,
            operation: ProcessingOperation::ValidateFormat,
        };

        // Test initial task properties
        assert_eq!(task.task_type(), "validate");
        assert!(!task.task_id().is_empty());
        assert!(task.description().contains("Validate format"));
        assert!(task.description().contains("lifecycle.srt"));
        assert!(
            task.estimated_duration().is_some(),
            "Should estimate duration for existing file"
        );

        // Test execution
        let result = task.execute().await;
        assert!(matches!(result, TaskResult::Success(_)));
    }

    /// Test task result serialization and display
    #[test]
    fn test_task_result_display() {
        let success = TaskResult::Success("Operation completed".to_string());
        let failed = TaskResult::Failed("Operation failed".to_string());
        let cancelled = TaskResult::Cancelled;
        let partial =
            TaskResult::PartialSuccess("Mostly worked".to_string(), "Minor issue".to_string());

        assert_eq!(format!("{}", success), "✓ Operation completed");
        assert_eq!(format!("{}", failed), "✗ Operation failed");
        assert_eq!(format!("{}", cancelled), "âš  Task cancelled");
        assert_eq!(
            format!("{}", partial),
            "âš  Mostly worked (warning: Minor issue)"
        );
    }

    /// Test task status display
    #[test]
    fn test_task_status_display() {
        let pending = TaskStatus::Pending;
        let running = TaskStatus::Running;
        let completed = TaskStatus::Completed(TaskResult::Success("Done".to_string()));
        let failed = TaskStatus::Failed("Error occurred".to_string());
        let cancelled = TaskStatus::Cancelled;

        assert_eq!(format!("{}", pending), "Pending");
        assert_eq!(format!("{}", running), "Running");
        assert_eq!(format!("{}", completed), "Completed: ✓ Done");
        assert_eq!(format!("{}", failed), "Failed: Error occurred");
        assert_eq!(format!("{}", cancelled), "Cancelled");
    }

    /// Test format conversion task
    #[tokio::test]
    async fn test_format_conversion_task() {
        let tmp = TempDir::new().unwrap();
        let input_file = tmp.path().join("input.srt");
        let output_file = tmp.path().join("output.ass");

        // Create valid SRT content
        let srt_content = r#"1
00:00:01,000 --> 00:00:03,000
First subtitle

2
00:00:04,000 --> 00:00:06,000
Second subtitle
"#;

        tokio::fs::write(&input_file, srt_content).await.unwrap();

        let task = FileProcessingTask {
            input_path: input_file.clone(),
            output_path: Some(output_file.clone()),
            operation: ProcessingOperation::ConvertFormat {
                from: "srt".to_string(),
                to: "ass".to_string(),
            },
        };

        let result = task.execute().await;
        assert!(matches!(result, TaskResult::Success(_)));

        // Note: The convert_format method is a stub that returns the input path
        // In a real implementation, this would create an actual output file
        assert!(tokio::fs::metadata(&input_file).await.is_ok());
    }

    /// Test file matching task
    #[tokio::test]
    async fn test_file_matching_task() {
        let tmp = TempDir::new().unwrap();
        let video_file = tmp.path().join("movie.mkv");
        let subtitle_file = tmp.path().join("movie.srt");

        // Create test files
        tokio::fs::write(&video_file, b"fake video content")
            .await
            .unwrap();
        tokio::fs::write(&subtitle_file, "1\n00:00:01,000 --> 00:00:02,000\nTest\n")
            .await
            .unwrap();

        let task = FileProcessingTask {
            input_path: tmp.path().to_path_buf(),
            output_path: None,
            operation: ProcessingOperation::MatchFiles { recursive: false },
        };

        let result = task.execute().await;
        assert!(matches!(result, TaskResult::Success(_)));
    }

    /// Test sync subtitle task (expected to fail)
    #[tokio::test]
    async fn test_sync_subtitle_task() {
        let tmp = TempDir::new().unwrap();
        let audio_file = tmp.path().join("audio.wav");
        let subtitle_file = tmp.path().join("subtitle.srt");

        tokio::fs::write(&audio_file, b"fake audio content")
            .await
            .unwrap();
        tokio::fs::write(&subtitle_file, "1\n00:00:01,000 --> 00:00:02,000\nTest\n")
            .await
            .unwrap();

        let task = FileProcessingTask {
            input_path: subtitle_file.clone(),
            output_path: None,
            operation: ProcessingOperation::SyncSubtitle {
                audio_path: audio_file,
            },
        };

        let result = task.execute().await;
        // Sync is not implemented, so should fail
        assert!(matches!(result, TaskResult::Failed(_)));
    }

    /// Test task error handling
    #[tokio::test]
    async fn test_task_error_handling() {
        // Test with sync operation which always fails in stub implementation
        let tmp = TempDir::new().unwrap();
        let test_file = tmp.path().join("test.srt");

        let task = FileProcessingTask {
            input_path: test_file,
            output_path: None,
            operation: ProcessingOperation::SyncSubtitle {
                audio_path: tmp.path().join("audio.wav"),
            },
        };

        let result = task.execute().await;
        assert!(matches!(result, TaskResult::Failed(_)));
    }

    /// Test task timeout handling
    #[tokio::test]
    async fn test_task_timeout() {
        use async_trait::async_trait;

        struct SlowTask {
            duration: Duration,
        }

        #[async_trait]
        impl Task for SlowTask {
            async fn execute(&self) -> TaskResult {
                tokio::time::sleep(self.duration).await;
                TaskResult::Success("Slow task completed".to_string())
            }
            fn task_type(&self) -> &'static str {
                "slow"
            }
            fn task_id(&self) -> String {
                "slow_task_1".to_string()
            }
            fn estimated_duration(&self) -> Option<Duration> {
                Some(self.duration)
            }
        }

        let slow_task = SlowTask {
            duration: Duration::from_millis(100),
        };

        // Test estimated duration
        assert_eq!(
            slow_task.estimated_duration(),
            Some(Duration::from_millis(100))
        );

        // Test execution
        let start = std::time::Instant::now();
        let result = slow_task.execute().await;
        let elapsed = start.elapsed();

        assert!(matches!(result, TaskResult::Success(_)));
        assert!(elapsed >= Duration::from_millis(90)); // Allow some variance
    }

    /// Test processing operation variants
    #[test]
    fn test_processing_operation_variants() {
        let convert_op = ProcessingOperation::ConvertFormat {
            from: "srt".to_string(),
            to: "ass".to_string(),
        };

        let sync_op = ProcessingOperation::SyncSubtitle {
            audio_path: std::path::PathBuf::from("audio.wav"),
        };

        let match_op = ProcessingOperation::MatchFiles { recursive: true };
        let validate_op = ProcessingOperation::ValidateFormat;

        // Test debug formatting
        assert!(format!("{:?}", convert_op).contains("ConvertFormat"));
        assert!(format!("{:?}", sync_op).contains("SyncSubtitle"));
        assert!(format!("{:?}", match_op).contains("MatchFiles"));
        assert!(format!("{:?}", validate_op).contains("ValidateFormat"));

        // Test cloning
        let convert_clone = convert_op.clone();
        assert!(format!("{:?}", convert_clone).contains("ConvertFormat"));
    }

    /// Test custom task implementation
    #[tokio::test]
    async fn test_custom_task_implementation() {
        use async_trait::async_trait;

        struct CustomTask {
            id: String,
            should_succeed: bool,
        }

        #[async_trait]
        impl Task for CustomTask {
            async fn execute(&self) -> TaskResult {
                if self.should_succeed {
                    TaskResult::Success(format!("Custom task {} succeeded", self.id))
                } else {
                    TaskResult::Failed(format!("Custom task {} failed", self.id))
                }
            }

            fn task_type(&self) -> &'static str {
                "custom"
            }

            fn task_id(&self) -> String {
                self.id.clone()
            }

            fn description(&self) -> String {
                format!("Custom task with ID: {}", self.id)
            }

            fn estimated_duration(&self) -> Option<Duration> {
                Some(Duration::from_millis(1))
            }
        }

        // Test successful custom task
        let success_task = CustomTask {
            id: "success_1".to_string(),
            should_succeed: true,
        };

        assert_eq!(success_task.task_type(), "custom");
        assert_eq!(success_task.task_id(), "success_1");
        assert_eq!(success_task.description(), "Custom task with ID: success_1");
        assert_eq!(
            success_task.estimated_duration(),
            Some(Duration::from_millis(1))
        );

        let result = success_task.execute().await;
        assert!(matches!(result, TaskResult::Success(_)));

        // Test failing custom task
        let fail_task = CustomTask {
            id: "fail_1".to_string(),
            should_succeed: false,
        };

        let result = fail_task.execute().await;
        assert!(matches!(result, TaskResult::Failed(_)));
    }

    #[tokio::test]
    async fn test_resolve_filename_conflict_sequential_suffixes() {
        let tmp = TempDir::new().unwrap();
        let base = tmp.path().join("x.txt");
        tokio::fs::write(&base, b"first").await.unwrap();

        let (p1, f1) = resolve_filename_conflict(base.clone()).unwrap();
        assert_eq!(p1.file_name().unwrap(), "x.1.txt");
        drop(f1);

        let (p2, _f2) = resolve_filename_conflict(base.clone()).unwrap();
        assert_eq!(p2.file_name().unwrap(), "x.2.txt");
    }

    #[tokio::test]
    async fn test_execute_copy_operation_atomic() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("src.txt");
        let dst = tmp.path().join("dst.txt");
        tokio::fs::write(&src, b"payload").await.unwrap();

        let task = FileProcessingTask {
            input_path: src.clone(),
            output_path: None,
            operation: ProcessingOperation::ValidateFormat,
        };
        task.execute_copy_operation(&src, &dst).await.unwrap();
        assert_eq!(tokio::fs::read(&dst).await.unwrap(), b"payload");
    }

    #[tokio::test]
    async fn test_execute_move_operation_deletes_source() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("from.txt");
        let dst = tmp.path().join("to.txt");
        tokio::fs::write(&src, b"moved").await.unwrap();

        let task = FileProcessingTask {
            input_path: src.clone(),
            output_path: None,
            operation: ProcessingOperation::ValidateFormat,
        };
        task.execute_move_operation(&src, &dst).await.unwrap();
        assert!(tokio::fs::metadata(&src).await.is_err());
        assert_eq!(tokio::fs::read(&dst).await.unwrap(), b"moved");
    }
}