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
//! SubX: Intelligent Subtitle Processing Library
//!
//! SubX is a comprehensive Rust library for intelligent subtitle file processing,
//! featuring AI-powered matching, format conversion, audio synchronization,
//! and advanced encoding detection capabilities.
//!
//! # Key Features
//!
//! - **AI-Powered Matching**: Intelligent subtitle file matching and renaming
//! - **Format Conversion**: Support for multiple subtitle formats (SRT, ASS, VTT, etc.)
//! - **Audio Synchronization**: Advanced audio-subtitle timing adjustment
//! - **Encoding Detection**: Automatic character encoding detection and conversion
//! - **Parallel Processing**: High-performance batch operations
//! - **Configuration Management**: Flexible multi-source configuration system
//!
//! # Architecture Overview
//!
//! The library is organized into several key modules:
//!
//! - [`cli`] - Command-line interface and argument parsing
//! - [`commands`] - Implementation of all SubX commands
//! - [`config`] - Configuration management and validation
//! - [`core`] - Core processing engines (formats, matching, sync)
//! - [`error`] - Comprehensive error handling system
//! - [`services`] - External service integrations (AI, audio processing)
//!
//! # Quick Start
//!
//! ```rust,no_run
//! use subx_cli::config::{TestConfigService, ConfigService};
//!
//! // Create a configuration service
//! let config_service = TestConfigService::with_defaults();
//! let config = config_service.config();
//!
//! // Use the configuration for processing...
//! ```
//!
//! # Error Handling
//!
//! All operations return a [`Result<T>`] type that wraps [`error::SubXError`]:
//!
//! ```rust
//! use subx_cli::{Result, error::SubXError};
//!
//! fn example_operation() -> Result<String> {
//!     // This could fail with various error types
//!     Err(SubXError::config("Missing configuration"))
//! }
//! ```
//!
//! # Configuration
//!
//! SubX supports dependency injection-based configuration:
//!
//! ```rust,no_run
//! use subx_cli::config::{TestConfigService, Config};
//!
//! // Create configuration service with AI settings
//! let config_service = TestConfigService::with_ai_settings("openai", "gpt-4.1");
//! let config = config_service.config();
//!
//! // Access configuration values
//! println!("AI Provider: {}", config.ai.provider);
//! println!("AI Model: {}", config.ai.model);
//! ```
//!
//! # Performance Considerations
//!
//! - Use [`core::parallel`] for batch operations on large file sets
//! - Configure appropriate cache settings for repeated operations
//! - Consider memory usage when processing large audio files
//!
//! # Thread Safety
//!
//! The library is designed to be thread-safe where appropriate:
//! - Configuration manager uses `Arc<RwLock<T>>` for shared state
//! - File operations include rollback capabilities for atomicity
//! - Parallel processing uses safe concurrency patterns
//!
//! # Feature Flags
//!
//! SubX supports several optional features:
//! ```text
//! - ai - AI service integrations (default)
//! - audio - Audio processing capabilities (default)  
//! - parallel - Parallel processing support (default)
//! ```

#![allow(
    clippy::new_without_default,
    clippy::manual_clamp,
    clippy::useless_vec,
    clippy::items_after_test_module,
    clippy::needless_borrow,
    clippy::uninlined_format_args,
    clippy::collapsible_if
)]
#![warn(missing_docs)]
#![warn(rustdoc::missing_crate_level_docs)]

/// Library version string.
///
/// This constant provides the current version of the SubX library,
/// automatically populated from `Cargo.toml` at compile time.
///
/// # Examples
///
/// ```rust
/// use subx_cli::VERSION;
///
/// println!("SubX version: {}", VERSION);
/// ```
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

pub mod cli;
pub mod commands;
pub mod config;
pub use config::Config;
// Re-export new configuration service system
pub use config::{
    ConfigService, EnvironmentProvider, ProductionConfigService, SystemEnvironmentProvider,
    TestConfigBuilder, TestConfigService, TestEnvironmentProvider,
};
pub mod core;
pub mod error;
/// Convenient type alias for `Result<T, SubXError>`.
///
/// This type alias simplifies error handling throughout the SubX library
/// by providing a default error type for all fallible operations.
pub type Result<T> = error::SubXResult<T>;

pub mod services;

/// Main application structure with dependency injection support.
///
/// The `App` struct provides a programmatic interface to SubX functionality,
/// designed for embedding SubX in other Rust applications or for advanced
/// use cases requiring fine-grained control over configuration and execution.
///
/// # Use Cases
///
/// - **Embedding**: Use SubX as a library component in larger applications
/// - **Testing**: Programmatic testing of SubX functionality with custom configurations
/// - **Automation**: Scripted execution of SubX operations without shell commands
/// - **Custom Workflows**: Building complex workflows that combine multiple SubX operations
///
/// # vs CLI Interface
///
/// | Feature | CLI (`subx` command) | App (Library API) |
/// |---------|---------------------|-------------------|
/// | Usage | Command line tool | Embedded in Rust code |
/// | Config | Files + Environment | Programmatic injection |
/// | Output | Terminal/stdout | Programmatic control |
/// | Error Handling | Exit codes | Result types |
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust,no_run
/// use subx_cli::{App, config::ProductionConfigService};
/// use std::sync::Arc;
///
/// # async fn example() -> subx_cli::Result<()> {
/// let config_service = Arc::new(ProductionConfigService::new()?);
/// let app = App::new(config_service);
///
/// // Execute operations programmatically
/// app.match_files("/movies", true).await?; // dry run
/// app.convert_files("/subs", "srt", Some("/output")).await?;
/// # Ok(())
/// # }
/// ```
///
/// ## With Custom Configuration
///
/// ```rust,no_run
/// use subx_cli::{App, config::{TestConfigService, Config}};
/// use std::sync::Arc;
///
/// # async fn example() -> subx_cli::Result<()> {
/// let mut config_service = TestConfigService::with_ai_settings("openai", "gpt-4");
///
/// let app = App::new(Arc::new(config_service));
/// app.match_files("/path", false).await?;
/// # Ok(())
/// # }
/// ```
pub struct App {
    config_service: std::sync::Arc<dyn config::ConfigService>,
}

impl App {
    /// Create a new application instance with the provided configuration service.
    ///
    /// # Arguments
    ///
    /// * `config_service` - The configuration service to use
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use subx_cli::{App, config::TestConfigService};
    /// use std::sync::Arc;
    ///
    /// let config_service = Arc::new(TestConfigService::with_defaults());
    /// let app = App::new(config_service);
    /// ```
    pub fn new(config_service: std::sync::Arc<dyn config::ConfigService>) -> Self {
        Self { config_service }
    }

    /// Create a new application instance with the production configuration service.
    ///
    /// This is the default way to create an application instance for production use.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use subx_cli::App;
    ///
    /// # async fn example() -> subx_cli::Result<()> {
    /// let app = App::new_with_production_config()?;
    /// // Ready to use with production configuration
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the production configuration service cannot be created.
    pub fn new_with_production_config() -> Result<Self> {
        let config_service = std::sync::Arc::new(config::ProductionConfigService::new()?);
        Ok(Self::new(config_service))
    }

    /// Run the application with command-line argument parsing.
    ///
    /// This method provides a programmatic way to run SubX with CLI-style
    /// arguments, useful for embedding SubX in other Rust applications.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use subx_cli::{App, config::ProductionConfigService};
    /// use std::sync::Arc;
    ///
    /// # async fn example() -> subx_cli::Result<()> {
    /// let config_service = Arc::new(ProductionConfigService::new()?);
    /// let app = App::new(config_service);
    ///
    /// // This parses std::env::args() just like the CLI
    /// app.run().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if command execution fails.
    pub async fn run(&self) -> Result<()> {
        let cli = <cli::Cli as clap::Parser>::parse();
        self.handle_command(cli.command).await
    }

    /// Handle a specific command with the current configuration.
    ///
    /// This method allows programmatic execution of specific SubX commands
    /// without parsing command-line arguments.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use subx_cli::{App, cli::{Commands, MatchArgs}, config::TestConfigService};
    /// use std::sync::Arc;
    ///
    /// # async fn example() -> subx_cli::Result<()> {
    /// let config_service = Arc::new(TestConfigService::with_defaults());
    /// let app = App::new(config_service);
    ///
    /// let match_args = MatchArgs {
    ///     path: Some("/path/to/files".into()),
    ///     input_paths: vec![],
    ///     dry_run: true,
    ///     confidence: 80,
    ///     recursive: false,
    ///     backup: false,
    ///     copy: false,
    ///     move_files: false,
    ///     no_extract: false,
    /// };
    ///
    /// app.handle_command(Commands::Match(match_args)).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `command` - The command to execute
    ///
    /// # Errors
    ///
    /// Returns an error if command execution fails.
    pub async fn handle_command(&self, command: cli::Commands) -> Result<()> {
        // Use the centralized dispatcher to eliminate code duplication
        crate::commands::dispatcher::dispatch_command(command, self.config_service.clone()).await
    }

    /// Execute a match operation programmatically.
    ///
    /// This is a convenience method for programmatic usage without
    /// needing to construct the Commands enum manually.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use subx_cli::{App, config::TestConfigService};
    /// use std::sync::Arc;
    ///
    /// # async fn example() -> subx_cli::Result<()> {
    /// let config_service = Arc::new(TestConfigService::with_defaults());
    /// let app = App::new(config_service);
    ///
    /// // Match files programmatically
    /// app.match_files("/path/to/files", true).await?; // dry_run = true
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `input_path` - Path to the directory or file to process
    /// * `dry_run` - Whether to perform a dry run (no actual changes)
    ///
    /// # Errors
    ///
    /// Returns an error if the match operation fails.
    pub async fn match_files(&self, input_path: &str, dry_run: bool) -> Result<()> {
        let args = cli::MatchArgs {
            path: Some(input_path.into()),
            input_paths: vec![],
            dry_run,
            confidence: 80,
            recursive: false,
            backup: false,
            copy: false,
            move_files: false,
            no_extract: false,
        };
        self.handle_command(cli::Commands::Match(args)).await
    }

    /// Convert subtitle files programmatically.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use subx_cli::{App, config::TestConfigService};
    /// use std::sync::Arc;
    ///
    /// # async fn example() -> subx_cli::Result<()> {
    /// let config_service = Arc::new(TestConfigService::with_defaults());
    /// let app = App::new(config_service);
    ///
    /// // Convert to SRT format
    /// app.convert_files("/path/to/subtitles", "srt", Some("/output/path")).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `input_path` - Path to subtitle files to convert
    /// * `output_format` - Target format ("srt", "ass", "vtt", etc.)
    /// * `output_path` - Optional output directory path
    ///
    /// # Errors
    ///
    /// Returns an error if the conversion fails.
    pub async fn convert_files(
        &self,
        input_path: &str,
        output_format: &str,
        output_path: Option<&str>,
    ) -> Result<()> {
        let format = match output_format.to_lowercase().as_str() {
            "srt" => cli::OutputSubtitleFormat::Srt,
            "ass" => cli::OutputSubtitleFormat::Ass,
            "vtt" => cli::OutputSubtitleFormat::Vtt,
            "sub" => cli::OutputSubtitleFormat::Sub,
            _ => {
                return Err(error::SubXError::CommandExecution(format!(
                    "Unsupported output format: {output_format}. Supported formats: srt, ass, vtt, sub"
                )));
            }
        };

        let args = cli::ConvertArgs {
            input: Some(input_path.into()),
            input_paths: vec![],
            recursive: false,
            format: Some(format),
            output: output_path.map(Into::into),
            keep_original: false,
            encoding: "utf-8".to_string(),
            no_extract: false,
        };
        self.handle_command(cli::Commands::Convert(args)).await
    }

    /// Synchronize subtitle files programmatically.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use subx_cli::{App, config::TestConfigService};
    /// use std::sync::Arc;
    ///
    /// # async fn example() -> subx_cli::Result<()> {
    /// let config_service = Arc::new(TestConfigService::with_defaults());
    /// let app = App::new(config_service);
    ///
    /// // Synchronize using VAD method
    /// app.sync_files("/path/to/video.mp4", "/path/to/subtitle.srt", "vad").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `video_path` - Path to video file for audio analysis
    /// * `subtitle_path` - Path to subtitle file to synchronize
    /// * `method` - Synchronization method ("vad", "manual")
    ///
    /// # Errors
    ///
    /// Returns an error if synchronization fails.
    pub async fn sync_files(
        &self,
        video_path: &str,
        subtitle_path: &str,
        method: &str,
    ) -> Result<()> {
        let sync_method = match method.to_lowercase().as_str() {
            "vad" => Some(cli::SyncMethodArg::Vad),
            "manual" => Some(cli::SyncMethodArg::Manual),
            _ => {
                return Err(error::SubXError::CommandExecution(format!(
                    "Unsupported sync method: {method}. Supported methods: vad, manual"
                )));
            }
        };

        let args = cli::SyncArgs {
            positional_paths: Vec::new(),
            video: Some(video_path.into()),
            subtitle: Some(subtitle_path.into()),
            input_paths: vec![],
            recursive: false,
            offset: None,
            method: sync_method,
            window: 30,
            vad_sensitivity: None,
            output: None,
            verbose: false,
            dry_run: false,
            force: false,
            batch: None,
            no_extract: false,
        };
        self.handle_command(cli::Commands::Sync(args)).await
    }

    /// Synchronize subtitle files with manual offset.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use subx_cli::{App, config::TestConfigService};
    /// use std::sync::Arc;
    ///
    /// # async fn example() -> subx_cli::Result<()> {
    /// let config_service = Arc::new(TestConfigService::with_defaults());
    /// let app = App::new(config_service);
    ///
    /// // Apply +2.5 second offset to subtitles
    /// app.sync_files_with_offset("/path/to/subtitle.srt", 2.5).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `subtitle_path` - Path to subtitle file to synchronize
    /// * `offset` - Time offset in seconds (positive delays, negative advances)
    ///
    /// # Errors
    ///
    /// Returns an error if synchronization fails.
    pub async fn sync_files_with_offset(&self, subtitle_path: &str, offset: f32) -> Result<()> {
        let args = cli::SyncArgs {
            positional_paths: Vec::new(),
            video: None,
            subtitle: Some(subtitle_path.into()),
            input_paths: vec![],
            recursive: false,
            offset: Some(offset),
            method: None,
            window: 30,
            vad_sensitivity: None,
            output: None,
            verbose: false,
            dry_run: false,
            force: false,
            batch: None,
            no_extract: false,
        };
        self.handle_command(cli::Commands::Sync(args)).await
    }

    /// Get a reference to the configuration service.
    ///
    /// This allows access to the configuration service for testing or
    /// advanced use cases.
    pub fn config_service(&self) -> &std::sync::Arc<dyn config::ConfigService> {
        &self.config_service
    }

    /// Get the current configuration.
    ///
    /// This is a convenience method that retrieves the configuration
    /// from the configured service.
    ///
    /// # Errors
    ///
    /// Returns an error if configuration loading fails.
    pub fn get_config(&self) -> Result<config::Config> {
        self.config_service.get_config()
    }
}

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

    fn is_expected_test_error(e: &error::SubXError) -> bool {
        let msg = format!("{e:?}");
        msg.contains("NotFound")
            || msg.contains("No subtitle files found")
            || msg.contains("No video files found")
            || msg.contains("Config")
            || msg.contains("no such file")
            || msg.contains("cannot find")
            || msg.contains("No input")
            || msg.contains("No files")
            || msg.contains("FileNotFound")
            || msg.contains("IoError")
            || msg.contains("PathNotFound")
            || msg.contains("InvalidInput")
            || msg.contains("CommandExecution")
            || msg.contains("NoInputSpecified")
    }

    #[test]
    fn test_version_is_not_empty() {
        assert!(!VERSION.is_empty());
    }

    #[test]
    fn test_version_matches_cargo_pkg_version() {
        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
    }

    #[test]
    fn test_app_new_stores_config_service() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service.clone());
        // Verify config_service() returns a valid Arc
        let _ = app.config_service();
    }

    #[test]
    fn test_app_get_config_returns_config() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let config = app.get_config().expect("get_config should succeed");
        // Just verify we got a config object with a valid AI provider field
        let _ = config.ai.provider;
    }

    #[test]
    fn test_app_get_config_with_ai_settings() {
        let config_service = Arc::new(TestConfigService::with_ai_settings("openai", "gpt-4.1"));
        let app = App::new(config_service);
        let config = app.get_config().expect("get_config should succeed");
        assert_eq!(config.ai.provider, "openai");
        assert_eq!(config.ai.model, "gpt-4.1");
    }

    #[test]
    fn test_app_config_service_getter() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        // The returned Arc should be usable (get_config succeeds)
        let svc = app.config_service();
        assert!(svc.get_config().is_ok());
    }

    #[tokio::test]
    async fn test_convert_files_unknown_format_returns_error() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app.convert_files("/nonexistent", "xyz_unknown", None).await;
        assert!(result.is_err());
        let err_msg = format!("{:?}", result.unwrap_err());
        assert!(
            err_msg.contains("Unsupported output format"),
            "Error should mention unsupported format, got: {err_msg}"
        );
    }

    #[tokio::test]
    async fn test_convert_files_srt_format_accepted() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app.convert_files("/nonexistent_path", "srt", None).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for srt format: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_convert_files_ass_format_accepted() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app.convert_files("/nonexistent_path", "ass", None).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for ass format: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_convert_files_vtt_format_accepted() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app.convert_files("/nonexistent_path", "vtt", None).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for vtt format: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_convert_files_sub_format_accepted() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app.convert_files("/nonexistent_path", "sub", None).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for sub format: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_convert_files_format_case_insensitive() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        // Uppercase format should be treated the same as lowercase
        let result = app.convert_files("/nonexistent_path", "SRT", None).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for uppercase SRT: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_sync_files_unknown_method_returns_error() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app
            .sync_files("/video.mp4", "/subtitle.srt", "unknown_method")
            .await;
        assert!(result.is_err());
        let err_msg = format!("{:?}", result.unwrap_err());
        assert!(
            err_msg.contains("Unsupported sync method"),
            "Error should mention unsupported method, got: {err_msg}"
        );
    }

    #[tokio::test]
    async fn test_sync_files_vad_method_accepted() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app
            .sync_files("/nonexistent_video.mp4", "/nonexistent_sub.srt", "vad")
            .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for vad method: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_sync_files_manual_method_accepted() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app
            .sync_files("/nonexistent_video.mp4", "/nonexistent_sub.srt", "manual")
            .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for manual method: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_sync_files_method_case_insensitive() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app
            .sync_files("/nonexistent_video.mp4", "/nonexistent_sub.srt", "VAD")
            .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Uppercase VAD should not give format error, got: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_sync_files_with_offset_accepted() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app
            .sync_files_with_offset("/nonexistent_sub.srt", 2.5)
            .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for sync with offset: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_sync_files_with_negative_offset() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let app = App::new(config_service);
        let result = app
            .sync_files_with_offset("/nonexistent_sub.srt", -1.5)
            .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for sync with negative offset: {e:?}"
            ),
        }
    }

    #[tokio::test]
    async fn test_match_files_dry_run() {
        let config_service = Arc::new(TestConfigService::with_ai_settings(
            "test_provider",
            "test_model",
        ));
        let app = App::new(config_service);
        let result = app.match_files("/nonexistent_subx_test_path", true).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(
                is_expected_test_error(&e),
                "Unexpected error for match dry run: {e:?}"
            ),
        }
    }

    #[test]
    fn test_result_type_alias_ok() {
        let r: Result<i32> = Ok(42);
        assert_eq!(r.unwrap(), 42);
    }

    #[test]
    fn test_result_type_alias_err() {
        let r: Result<i32> = Err(error::SubXError::config("test error"));
        assert!(r.is_err());
    }
}