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
//! Test configuration service for isolated testing.
//!
//! This module provides a configuration service implementation specifically
//! designed for testing environments, offering complete isolation and
//! predictable configuration states.

use crate::config::service::ConfigService;
use crate::{Result, config::Config};
use std::path::{Path, PathBuf};
use std::sync::Mutex;

/// Test configuration service implementation.
///
/// This service provides a fixed configuration for testing purposes,
/// ensuring complete isolation between tests and predictable behavior.
/// It does not load from external sources or cache.
pub struct TestConfigService {
    config: Mutex<Config>,
}

impl TestConfigService {
    /// Set AI provider, model, and API key for testing.
    pub fn set_ai_settings_and_key(&self, provider: &str, model: &str, api_key: &str) {
        let mut cfg = self.config.lock().unwrap();
        cfg.ai.provider = provider.to_string();
        cfg.ai.model = model.to_string();
        cfg.ai.api_key = if api_key.is_empty() {
            None
        } else {
            Some(api_key.to_string())
        };
    }

    /// Set AI provider, model, API key, and custom base URL for testing.
    pub fn set_ai_settings_with_base_url(
        &self,
        provider: &str,
        model: &str,
        api_key: &str,
        base_url: &str,
    ) {
        self.set_ai_settings_and_key(provider, model, api_key);
        let mut cfg = self.config.lock().unwrap();
        cfg.ai.base_url = base_url.to_string();
    }
    /// Create a new test configuration service with the provided configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - The fixed configuration to use
    pub fn new(config: Config) -> Self {
        Self {
            config: Mutex::new(config),
        }
    }

    /// Create a test configuration service with default settings.
    ///
    /// This is useful for tests that don't need specific configuration values.
    pub fn with_defaults() -> Self {
        Self::new(Config::default())
    }

    /// Create a test configuration service with specific AI settings.
    ///
    /// # Arguments
    ///
    /// * `provider` - AI provider name
    /// * `model` - AI model name
    pub fn with_ai_settings(provider: &str, model: &str) -> Self {
        let mut config = Config::default();
        config.ai.provider = provider.to_string();
        config.ai.model = model.to_string();
        Self::new(config)
    }

    /// Create a test configuration service with specific AI settings including API key.
    ///
    /// # Arguments
    ///
    /// * `provider` - AI provider name
    /// * `model` - AI model name
    /// * `api_key` - API key for the provider
    pub fn with_ai_settings_and_key(provider: &str, model: &str, api_key: &str) -> Self {
        let mut config = Config::default();
        config.ai.provider = provider.to_string();
        config.ai.model = model.to_string();
        config.ai.api_key = Some(api_key.to_string());
        Self::new(config)
    }

    /// Create a test configuration service with specific sync settings.
    ///
    /// # Arguments
    ///
    /// * `correlation_threshold` - Correlation threshold for synchronization
    /// * `max_offset` - Maximum time offset in seconds
    pub fn with_sync_settings(correlation_threshold: f32, max_offset: f32) -> Self {
        let mut config = Config::default();
        config.sync.correlation_threshold = correlation_threshold;
        config.sync.max_offset_seconds = max_offset;
        Self::new(config)
    }

    /// Create a test configuration service with specific parallel processing settings.
    ///
    /// # Arguments
    ///
    /// * `max_workers` - Maximum number of parallel workers
    /// * `queue_size` - Task queue size
    pub fn with_parallel_settings(max_workers: usize, queue_size: usize) -> Self {
        let mut config = Config::default();
        config.general.max_concurrent_jobs = max_workers;
        config.parallel.task_queue_size = queue_size;
        Self::new(config)
    }

    /// Get the underlying configuration.
    ///
    /// This is useful for tests that need direct access to the configuration object.
    pub fn config(&self) -> std::sync::MutexGuard<'_, Config> {
        self.config.lock().unwrap()
    }

    /// Get a mutable reference to the underlying configuration.
    ///
    /// This allows tests to modify the configuration after creation.
    pub fn config_mut(&self) -> std::sync::MutexGuard<'_, Config> {
        self.config.lock().unwrap()
    }
}

impl ConfigService for TestConfigService {
    fn get_config(&self) -> Result<Config> {
        Ok(self.config.lock().unwrap().clone())
    }

    fn reload(&self) -> Result<()> {
        // Test configuration doesn't need reloading since it's fixed
        Ok(())
    }

    fn save_config(&self) -> Result<()> {
        // Test environment does not perform actual file I/O
        Ok(())
    }

    fn save_config_to_file(&self, _path: &Path) -> Result<()> {
        // Test environment does not perform actual file I/O
        Ok(())
    }

    fn get_config_file_path(&self) -> Result<PathBuf> {
        // Return a dummy path to avoid conflicts in test environment
        Ok(PathBuf::from("/tmp/subx_test_config.toml"))
    }

    fn get_config_value(&self, key: &str) -> Result<String> {
        let config = self.config.lock().unwrap();
        crate::config::service::read_config_value_from(&config, key)
    }

    fn reset_to_defaults(&self) -> Result<()> {
        // Reset the configuration to default values
        *self.config.lock().unwrap() = Config::default();
        Ok(())
    }

    fn set_config_value(&self, key: &str, value: &str) -> Result<()> {
        // Load current configuration via the tolerant path (which for
        // tests is equivalent to the strict path because in-memory
        // test configs are validated by construction).
        let mut cfg = self.load_for_repair()?;
        // Validate and set the value using the same logic as
        // ProductionConfigService. `validate_and_set_value` already
        // runs cross-section validation on the post-mutation config,
        // so we MUST NOT duplicate that call here.
        self.validate_and_set_value(&mut cfg, key, value)?;
        // Update the internal configuration
        *self.config.lock().unwrap() = cfg;
        Ok(())
    }

    fn load_for_repair(&self) -> Result<Config> {
        // Test configurations live in memory and are validated by
        // construction; tolerant load is equivalent to strict load.
        Ok(self.config.lock().unwrap().clone())
    }
}

impl TestConfigService {
    /// Validate and set a configuration value (same logic as ProductionConfigService).
    fn validate_and_set_value(&self, config: &mut Config, key: &str, value: &str) -> Result<()> {
        use crate::config::OverflowStrategy;
        use crate::config::validation::*;
        use crate::error::SubXError;

        let parts: Vec<&str> = key.split('.').collect();
        match parts.as_slice() {
            ["ai", "provider"] => {
                validate_enum(
                    value,
                    &[
                        "openai",
                        "anthropic",
                        "local",
                        "ollama",
                        "openrouter",
                        "azure-openai",
                    ],
                )?;
                config.ai.provider = crate::config::field_validator::normalize_ai_provider(value);
            }
            ["ai", "api_key"] => {
                if !value.is_empty() {
                    validate_api_key(value)?;
                    config.ai.api_key = Some(value.to_string());
                } else {
                    config.ai.api_key = None;
                }
            }
            ["ai", "model"] => {
                config.ai.model = value.to_string();
            }
            ["ai", "base_url"] => {
                validate_url(value)?;
                config.ai.base_url = value.to_string();
            }
            ["ai", "max_sample_length"] => {
                let v = validate_usize_range(value, 100, 10000)?;
                config.ai.max_sample_length = v;
            }
            ["ai", "temperature"] => {
                let v = validate_float_range(value, 0.0, 1.0)?;
                config.ai.temperature = v;
            }
            ["ai", "max_tokens"] => {
                let v = validate_uint_range(value, 1, 100_000)?;
                config.ai.max_tokens = v;
            }
            ["ai", "retry_attempts"] => {
                let v = validate_uint_range(value, 1, 10)?;
                config.ai.retry_attempts = v;
            }
            ["ai", "retry_delay_ms"] => {
                let v = validate_u64_range(value, 100, 30000)?;
                config.ai.retry_delay_ms = v;
            }
            ["ai", "request_timeout_seconds"] => {
                let v = validate_u64_range(value, 10, 600)?;
                config.ai.request_timeout_seconds = v;
            }
            ["formats", "default_output"] => {
                validate_enum(value, &["srt", "ass", "vtt", "webvtt"])?;
                config.formats.default_output = value.to_string();
            }
            ["formats", "preserve_styling"] => {
                let v = parse_bool(value)?;
                config.formats.preserve_styling = v;
            }
            ["formats", "default_encoding"] => {
                validate_enum(value, &["utf-8", "gbk", "big5", "shift_jis"])?;
                config.formats.default_encoding = value.to_string();
            }
            ["formats", "encoding_detection_confidence"] => {
                let v = validate_float_range(value, 0.0, 1.0)?;
                config.formats.encoding_detection_confidence = v;
            }
            ["sync", "max_offset_seconds"] => {
                let v = validate_float_range(value, 0.0, 300.0)?;
                config.sync.max_offset_seconds = v;
            }
            ["sync", "default_method"] => {
                validate_enum(value, &["auto", "vad"])?;
                config.sync.default_method = value.to_string();
            }
            ["sync", "vad", "enabled"] => {
                let v = parse_bool(value)?;
                config.sync.vad.enabled = v;
            }
            ["sync", "vad", "sensitivity"] => {
                let v = validate_float_range(value, 0.0, 1.0)?;
                config.sync.vad.sensitivity = v;
            }
            ["sync", "vad", "padding_chunks"] => {
                let v = validate_uint_range(value, 0, u32::MAX)?;
                config.sync.vad.padding_chunks = v;
            }
            ["sync", "vad", "min_speech_duration_ms"] => {
                let v = validate_uint_range(value, 0, u32::MAX)?;
                config.sync.vad.min_speech_duration_ms = v;
            }
            ["sync", "correlation_threshold"] => {
                let v = validate_float_range(value, 0.0, 1.0)?;
                config.sync.correlation_threshold = v;
            }
            ["sync", "dialogue_detection_threshold"] => {
                let v = validate_float_range(value, 0.0, 1.0)?;
                config.sync.dialogue_detection_threshold = v;
            }
            ["sync", "min_dialogue_duration_ms"] => {
                let v = validate_uint_range(value, 100, 5000)?;
                config.sync.min_dialogue_duration_ms = v;
            }
            ["sync", "dialogue_merge_gap_ms"] => {
                let v = validate_uint_range(value, 50, 2000)?;
                config.sync.dialogue_merge_gap_ms = v;
            }
            ["sync", "enable_dialogue_detection"] => {
                let v = parse_bool(value)?;
                config.sync.enable_dialogue_detection = v;
            }
            ["sync", "audio_sample_rate"] => {
                let v = validate_uint_range(value, 8000, 192000)?;
                config.sync.audio_sample_rate = v;
            }
            ["sync", "auto_detect_sample_rate"] => {
                let v = parse_bool(value)?;
                config.sync.auto_detect_sample_rate = v;
            }
            ["general", "backup_enabled"] => {
                let v = parse_bool(value)?;
                config.general.backup_enabled = v;
            }
            ["general", "max_concurrent_jobs"] => {
                let v = validate_usize_range(value, 1, 64)?;
                config.general.max_concurrent_jobs = v;
            }
            ["general", "task_timeout_seconds"] => {
                let v = validate_u64_range(value, 30, 3600)?;
                config.general.task_timeout_seconds = v;
            }
            ["general", "enable_progress_bar"] => {
                let v = parse_bool(value)?;
                config.general.enable_progress_bar = v;
            }
            ["general", "worker_idle_timeout_seconds"] => {
                let v = validate_u64_range(value, 10, 3600)?;
                config.general.worker_idle_timeout_seconds = v;
            }
            ["general", "max_subtitle_bytes"] => {
                let v = validate_u64_range(value, 1024, 1_073_741_824)?;
                config.general.max_subtitle_bytes = v;
            }
            ["general", "max_audio_bytes"] => {
                let v = validate_u64_range(value, 1024, 10_737_418_240)?;
                config.general.max_audio_bytes = v;
            }
            ["parallel", "max_workers"] => {
                let v = validate_usize_range(value, 1, 64)?;
                config.parallel.max_workers = v;
            }
            ["parallel", "task_queue_size"] => {
                let v = validate_usize_range(value, 100, 10000)?;
                config.parallel.task_queue_size = v;
            }
            ["parallel", "enable_task_priorities"] => {
                let v = parse_bool(value)?;
                config.parallel.enable_task_priorities = v;
            }
            ["parallel", "auto_balance_workers"] => {
                let v = parse_bool(value)?;
                config.parallel.auto_balance_workers = v;
            }
            ["parallel", "overflow_strategy"] => {
                validate_enum(value, &["Block", "Drop", "Expand"])?;
                config.parallel.overflow_strategy = match value {
                    "Block" => OverflowStrategy::Block,
                    "Drop" => OverflowStrategy::Drop,
                    "Expand" => OverflowStrategy::Expand,
                    _ => unreachable!(),
                };
            }
            _ => {
                return Err(SubXError::config(format!(
                    "Unknown configuration key: {key}"
                )));
            }
        }
        Ok(())
    }
}

impl Default for TestConfigService {
    fn default() -> Self {
        Self::with_defaults()
    }
}

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

    #[test]
    fn test_config_service_with_defaults() {
        let service = TestConfigService::with_defaults();
        let config = service.get_config().unwrap();

        assert_eq!(config.ai.provider, "openai");
        assert_eq!(config.ai.model, "gpt-4.1-mini");
    }

    #[test]
    fn test_config_service_with_ai_settings() {
        let service = TestConfigService::with_ai_settings("anthropic", "claude-3");
        let config = service.get_config().unwrap();

        assert_eq!(config.ai.provider, "anthropic");
        assert_eq!(config.ai.model, "claude-3");
    }

    #[test]
    fn test_config_service_with_ai_settings_and_key() {
        let service =
            TestConfigService::with_ai_settings_and_key("openai", "gpt-4.1", "test-api-key");
        let config = service.get_config().unwrap();

        assert_eq!(config.ai.provider, "openai");
        assert_eq!(config.ai.model, "gpt-4.1");
        assert_eq!(config.ai.api_key, Some("test-api-key".to_string()));
    }

    #[test]
    fn test_config_service_with_ai_settings_and_key_openrouter() {
        let service = TestConfigService::with_ai_settings_and_key(
            "openrouter",
            "deepseek/deepseek-r1-0528:free",
            "test-openrouter-key",
        );
        let config = service.get_config().unwrap();
        assert_eq!(config.ai.provider, "openrouter");
        assert_eq!(config.ai.model, "deepseek/deepseek-r1-0528:free");
        assert_eq!(config.ai.api_key, Some("test-openrouter-key".to_string()));
    }

    #[test]
    fn test_config_service_with_sync_settings() {
        let service = TestConfigService::with_sync_settings(0.8, 45.0);
        let config = service.get_config().unwrap();

        assert_eq!(config.sync.correlation_threshold, 0.8);
        assert_eq!(config.sync.max_offset_seconds, 45.0);
    }

    #[test]
    fn test_config_service_with_parallel_settings() {
        let service = TestConfigService::with_parallel_settings(8, 200);
        let config = service.get_config().unwrap();

        assert_eq!(config.general.max_concurrent_jobs, 8);
        assert_eq!(config.parallel.task_queue_size, 200);
    }

    #[test]
    fn test_config_service_reload() {
        let service = TestConfigService::with_defaults();

        // Reload should always succeed for test service
        assert!(service.reload().is_ok());
    }

    #[test]
    fn test_config_service_direct_access() {
        let service = TestConfigService::with_defaults();

        // Test direct read access
        assert_eq!(service.config().ai.provider, "openai");

        // Test mutable access
        service.config_mut().ai.provider = "modified".to_string();
        assert_eq!(service.config().ai.provider, "modified");

        let config = service.get_config().unwrap();
        assert_eq!(config.ai.provider, "modified");
    }
}