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
//! Component factory for creating configured instances of core components.
//!
//! This module provides a centralized factory for creating instances of core
//! components with proper configuration injection, eliminating the need for
//! global configuration access within individual components.

use crate::services::ai::openai::OpenAIClient;
use crate::services::ai::openrouter::OpenRouterClient;
use crate::services::vad::{LocalVadDetector, VadAudioProcessor, VadSyncDetector};
use crate::{
    Result,
    config::{Config, ConfigService},
    core::{file_manager::FileManager, matcher::engine::MatchEngine},
    error::SubXError,
    services::ai::AIProvider,
};

/// Component factory for creating configured instances.
///
/// This factory provides a centralized way to create core components
/// with proper configuration injection, ensuring consistent component
/// initialization across the application.
///
/// # Examples
///
/// ```rust
/// use subx_cli::core::ComponentFactory;
/// use subx_cli::config::ProductionConfigService;
/// use std::sync::Arc;
///
/// # async fn example() -> subx_cli::Result<()> {
/// let config_service = Arc::new(ProductionConfigService::new()?);
/// let factory = ComponentFactory::new(config_service.as_ref())?;
///
/// // Create components with proper configuration
/// let match_engine = factory.create_match_engine()?;
/// let file_manager = factory.create_file_manager();
/// let ai_provider = factory.create_ai_provider()?;
/// # Ok(())
/// # }
/// ```
pub struct ComponentFactory {
    config: Config,
}

impl ComponentFactory {
    /// Create a new component factory with the given configuration service.
    ///
    /// # Arguments
    ///
    /// * `config_service` - Configuration service to load configuration from
    ///
    /// # Errors
    ///
    /// Returns an error if configuration loading fails.
    pub fn new(config_service: &dyn ConfigService) -> Result<Self> {
        let config = config_service.get_config()?;
        Ok(Self { config })
    }

    /// Create a match engine with AI configuration.
    ///
    /// Returns a properly configured MatchEngine instance using
    /// the AI configuration section.
    ///
    /// # Errors
    ///
    /// Returns an error if AI provider creation fails.
    pub fn create_match_engine(&self) -> Result<MatchEngine> {
        let ai_provider = self.create_ai_provider()?;
        let match_config = crate::core::matcher::MatchConfig {
            confidence_threshold: 0.8, // Default value, can be configurable
            max_sample_length: self.config.ai.max_sample_length,
            enable_content_analysis: true,
            backup_enabled: self.config.general.backup_enabled,
            relocation_mode: crate::core::matcher::engine::FileRelocationMode::None,
            conflict_resolution: crate::core::matcher::engine::ConflictResolution::AutoRename,
            ai_model: self.config.ai.model.clone(),
            max_subtitle_bytes: self.config.general.max_subtitle_bytes,
        };
        Ok(MatchEngine::new(ai_provider, match_config))
    }

    /// Create a file manager with general configuration.
    ///
    /// Returns a properly configured FileManager instance using
    /// the general configuration section.
    pub fn create_file_manager(&self) -> FileManager {
        // For now, FileManager doesn't take configuration in its constructor
        // This will be updated when FileManager is refactored to accept config
        FileManager::new()
    }

    /// Create an AI provider with AI configuration.
    ///
    /// Returns a properly configured AI provider instance based on
    /// the provider type specified in the AI configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the provider type is unsupported or
    /// provider creation fails.
    pub fn create_ai_provider(&self) -> Result<Box<dyn AIProvider>> {
        create_ai_provider(&self.config.ai)
    }

    /// Get a reference to the current configuration.
    ///
    /// Returns a reference to the configuration used by this factory.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Create a VAD sync detector with VAD configuration.
    ///
    /// Returns a properly configured VadSyncDetector instance using the VAD settings.
    ///
    /// # Errors
    ///
    /// Returns an error if VAD sync detector creation fails.
    pub fn create_vad_sync_detector(&self) -> Result<VadSyncDetector> {
        VadSyncDetector::new(self.config.sync.vad.clone())
    }

    /// Create a local VAD detector for audio processing.
    ///
    /// Returns a properly configured LocalVadDetector instance.
    ///
    /// # Errors
    ///
    /// Returns an error if local VAD detector initialization fails.
    pub fn create_vad_detector(&self) -> Result<LocalVadDetector> {
        LocalVadDetector::new(self.config.sync.vad.clone())
    }

    /// Create an audio processor for VAD operations.
    ///
    /// Returns a properly configured VadAudioProcessor instance.
    ///
    /// # Errors
    ///
    /// Returns an error if audio processor initialization fails.
    pub fn create_audio_processor(&self) -> Result<VadAudioProcessor> {
        VadAudioProcessor::new()
    }

    /// Create a translation engine using the configured AI provider and
    /// translation settings.
    ///
    /// # Errors
    ///
    /// Returns an error when AI provider creation fails or the configured
    /// translation batch size is invalid.
    pub fn create_translation_engine(&self) -> Result<crate::core::translation::TranslationEngine> {
        let ai_provider: std::sync::Arc<dyn AIProvider> =
            std::sync::Arc::from(self.create_ai_provider()?);
        crate::core::translation::TranslationEngine::new(
            ai_provider,
            self.config.translation.batch_size,
        )
    }
}

/// Create an AI provider from AI configuration.
///
/// This function creates the appropriate AI provider based on the
/// provider type specified in the configuration.
///
/// # Arguments
///
/// * `ai_config` - AI configuration containing provider settings
///
/// # Errors
///
/// Returns an error if the provider type is unsupported or creation fails.
/// Validate AI configuration parameters.
fn validate_ai_config(ai_config: &crate::config::AIConfig) -> Result<()> {
    let canonical = crate::config::field_validator::normalize_ai_provider(&ai_config.provider);
    let is_local = canonical == "local";

    // The `local` provider treats `api_key` as optional because most local
    // OpenAI-compatible runtimes (Ollama, LM Studio, llama.cpp `llama-server`)
    // accept unauthenticated requests. All hosted providers still require
    // an api_key.
    if !is_local && ai_config.api_key.as_deref().unwrap_or("").trim().is_empty() {
        return Err(SubXError::config(
            "AI API key is required. Set ai.api_key in configuration or use environment variable."
                .to_string(),
        ));
    }
    if ai_config.model.trim().is_empty() {
        return Err(SubXError::config(
            "AI model is required. Set ai.model in configuration.".to_string(),
        ));
    }
    if ai_config.temperature < 0.0 || ai_config.temperature > 2.0 {
        return Err(SubXError::config(
            "AI temperature must be between 0.0 and 2.0.".to_string(),
        ));
    }
    if ai_config.max_tokens == 0 {
        return Err(SubXError::config(
            "AI max_tokens must be greater than 0.".to_string(),
        ));
    }
    Ok(())
}

/// Create an AI provider from AI configuration.
///
/// This function creates the appropriate AI provider based on the
/// provider type specified in the configuration.
pub fn create_ai_provider(ai_config: &crate::config::AIConfig) -> Result<Box<dyn AIProvider>> {
    let canonical = crate::config::field_validator::normalize_ai_provider(&ai_config.provider);
    match canonical.as_str() {
        "openai" => {
            validate_ai_config(ai_config)?;
            let client = OpenAIClient::from_config(ai_config)?;
            Ok(Box::new(client))
        }
        "openrouter" => {
            validate_ai_config(ai_config)?;
            let client = OpenRouterClient::from_config(ai_config)?;
            Ok(Box::new(client))
        }
        "azure-openai" => {
            validate_ai_config(ai_config)?;
            let client =
                crate::services::ai::azure_openai::AzureOpenAIClient::from_config(ai_config)?;
            Ok(Box::new(client))
        }
        "local" => {
            validate_ai_config(ai_config)?;
            let client = crate::services::ai::local::LocalLLMClient::from_config(ai_config)?;
            Ok(Box::new(client))
        }
        other => Err(SubXError::config(format!(
            "Unsupported AI provider: {}. Supported providers: openai, openrouter, anthropic, azure-openai, local",
            other
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::test_service::TestConfigService;

    #[test]
    fn test_component_factory_creation() {
        let config_service = TestConfigService::default();
        let factory = ComponentFactory::new(&config_service);
        assert!(factory.is_ok());
    }

    #[test]
    fn test_factory_creation() {
        let config_service = TestConfigService::default();
        let factory = ComponentFactory::new(&config_service);
        assert!(factory.is_ok());
    }

    #[test]
    fn test_create_file_manager() {
        let config_service = TestConfigService::default();
        let factory = ComponentFactory::new(&config_service).unwrap();

        let _file_manager = factory.create_file_manager();
        // Basic validation that file manager was created
        // FileManager doesn't expose config yet, so just verify creation succeeds
    }

    #[test]
    fn test_unsupported_ai_provider() {
        let mut config = crate::config::Config::default();
        config.ai.provider = "unsupported".to_string();

        let result: Result<Box<dyn AIProvider>> = create_ai_provider(&config.ai);
        assert!(result.is_err());

        match result {
            Err(e) => {
                let error_msg = e.to_string();
                assert!(error_msg.contains("Unsupported AI provider"));
                // The error message must enumerate all supported providers,
                // including the new `local` provider added by the
                // add-local-llm-provider change.
                assert!(error_msg.contains("openai"), "missing openai: {error_msg}");
                assert!(
                    error_msg.contains("openrouter"),
                    "missing openrouter: {error_msg}"
                );
                assert!(
                    error_msg.contains("azure-openai"),
                    "missing azure-openai: {error_msg}"
                );
                assert!(error_msg.contains("local"), "missing local: {error_msg}");
            }
            Ok(_) => panic!("Expected error for unsupported provider"),
        }
    }

    #[test]
    fn test_create_vad_sync_detector() {
        let config_service = TestConfigService::default();
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_vad_sync_detector();
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_vad_detector() {
        let config_service = TestConfigService::default();
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_vad_detector();
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_audio_processor() {
        let config_service = TestConfigService::default();
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_audio_processor();
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_ai_provider_openai_success() {
        let config_service = TestConfigService::default();
        config_service.set_ai_settings_and_key("openai", "gpt-4.1-mini", "test-api-key");
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_ai_provider();
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_ai_provider_missing_api_key() {
        let config_service = TestConfigService::default();
        config_service.set_ai_settings_and_key("openai", "gpt-4.1-mini", "");
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_ai_provider();
        assert!(result.is_err());
        let error_msg = result.err().unwrap().to_string();
        assert!(error_msg.contains("API key is required"));
    }

    #[test]
    fn test_create_ai_provider_unsupported_provider() {
        let config_service = TestConfigService::default();
        config_service.set_ai_settings_and_key("unsupported-provider", "model", "key");
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_ai_provider();
        assert!(result.is_err());
        let error_msg = result.err().unwrap().to_string();
        assert!(error_msg.contains("Unsupported AI provider"));
    }

    #[test]
    fn test_create_ai_provider_with_custom_base_url() {
        let config_service = TestConfigService::default();
        config_service.set_ai_settings_and_key("openai", "gpt-4.1-mini", "test-api-key");
        config_service.config_mut().ai.base_url = "https://custom-api.com/v1".to_string();
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_ai_provider();
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_ai_provider_openrouter_success() {
        let config_service = TestConfigService::default();
        config_service.set_ai_settings_and_key(
            "openrouter",
            "deepseek/deepseek-r1-0528:free",
            "test-openrouter-key",
        );
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_ai_provider();
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_ai_provider_azure_openai_success() {
        let mut config = crate::config::Config::default();
        config.ai.provider = "azure-openai".to_string();
        config.ai.api_key = Some("azure-key-123".to_string());
        config.ai.model = "dep123".to_string();
        config.ai.api_version = Some("2025-04-01-preview".to_string());
        config.ai.base_url = "https://example.openai.azure.com".to_string();
        let result = create_ai_provider(&config.ai);
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_ai_provider_local_success() {
        // Mirror `test_create_ai_provider_openai_success`: build a
        // `TestConfigService` via `TestConfigBuilder` configured for the
        // local provider, with NO api_key (intentionally absent) and an
        // OpenAI-compatible Ollama-style base URL. The factory must accept
        // this and return a working AI provider.
        use crate::config::builder::TestConfigBuilder;
        let config_service = TestConfigBuilder::new()
            .with_ai_provider("local")
            .with_ai_model("llama3.1")
            .with_ai_base_url("http://localhost:11434/v1")
            .build_service();
        let factory = ComponentFactory::new(&config_service).unwrap();
        let result = factory.create_ai_provider();
        assert!(
            result.is_ok(),
            "local provider must construct without api_key: {:?}",
            result.err()
        );

        // The `ollama` alias normalizes to `local` and must take the same
        // factory path.
        let alias_service = TestConfigBuilder::new()
            .with_ai_provider("ollama")
            .with_ai_model("llama3.1")
            .with_ai_base_url("http://localhost:11434/v1")
            .build_service();
        let alias_factory = ComponentFactory::new(&alias_service).unwrap();
        assert!(
            alias_factory.create_ai_provider().is_ok(),
            "`ollama` alias must reach the local arm"
        );
    }
}