subx-core 1.0.0

Core subtitle processing library for SubX: matching, format conversion, synchronization, and AI service integrations.
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
//! Isolated test workspace builder for integration tests.
//!
//! Formerly the CLI crate's `common::cli_helpers::TestWorkspace`. The
//! test-suite split broke that type in two: this workspace/fixture half
//! lives here so both crates' tests build on it, and the binary-spawning
//! half (`run_command_*`, `CommandResult`) lives on the command-line side as
//! the `CliRun` extension trait.
//! The embedded unit tests below previously lived in the old test-crate
//! module, where an accidental relative `mod` reference meant they were never
//! compiled; moving them here is what finally makes them run.

use crate::Result;
use crate::config::{ConfigService, TestConfigService};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tempfile::TempDir;
use tokio::fs;

/// Isolated test workspace with dependency injection support.
///
/// This builder provides a complete testing environment with isolated
/// configuration, temporary directories, and utilities for creating test
/// fixtures. Command spawning lives in the command-line repository's
/// `common::cli_helpers` as the `CliRun` extension trait
/// (`CliRun::run_command_with_config`).
pub struct TestWorkspace {
    temp_dir: TempDir,
    test_files: Vec<PathBuf>,
    config_service: Arc<dyn ConfigService>,
}

impl TestWorkspace {
    /// Create a new CLI test helper with default test configuration.
    pub fn new() -> Self {
        let temp_dir = TempDir::new().expect("Failed to create temporary directory");
        let config_service = Arc::new(TestConfigService::with_defaults());

        Self {
            temp_dir,
            test_files: Vec::new(),
            config_service,
        }
    }

    /// Create a CLI test helper with custom configuration service.
    #[allow(dead_code)]
    pub fn with_config_service(config_service: Arc<dyn ConfigService>) -> Self {
        let temp_dir = TempDir::new().expect("Failed to create temporary directory");

        Self {
            temp_dir,
            test_files: Vec::new(),
            config_service,
        }
    }

    /// Create a CLI test helper with AI settings.
    pub fn with_ai_settings(provider: &str, model: &str) -> Self {
        let temp_dir = TempDir::new().expect("Failed to create temporary directory");
        let config_service = Arc::new(TestConfigService::with_ai_settings(provider, model));

        Self {
            temp_dir,
            test_files: Vec::new(),
            config_service,
        }
    }

    /// Create a CLI test helper with sync settings.
    #[allow(dead_code)]
    pub fn with_sync_settings(correlation_threshold: f32, max_offset: f32) -> Self {
        let temp_dir = TempDir::new().expect("Failed to create temporary directory");
        let config_service = Arc::new(TestConfigService::with_sync_settings(
            correlation_threshold,
            max_offset,
        ));

        Self {
            temp_dir,
            test_files: Vec::new(),
            config_service,
        }
    }

    /// Get the temporary directory path.
    pub fn temp_dir_path(&self) -> &Path {
        self.temp_dir.path()
    }

    /// Get a reference to the configuration service.
    pub fn config_service(&self) -> Arc<dyn ConfigService> {
        self.config_service.clone()
    }

    /// Create an isolated test workspace with standard test files.
    pub async fn create_isolated_test_workspace(&mut self) -> Result<PathBuf> {
        let workspace = self.temp_dir.path().to_path_buf();

        // Create standard test file structure
        self.create_media_files(&workspace).await?;
        self.create_subtitle_files(&workspace).await?;
        self.create_config_file(&workspace).await?;

        Ok(workspace)
    }

    /// Create test media files for testing.
    async fn create_media_files(&mut self, workspace: &Path) -> Result<()> {
        let media_dir = workspace.join("media");
        fs::create_dir_all(&media_dir).await?;

        // Create dummy video files
        let video_files = [
            "movie1.mp4",
            "movie2.avi",
            "series_s01e01.mkv",
            "series_s01e02.mkv",
        ];

        for filename in &video_files {
            let file_path = media_dir.join(filename);
            fs::write(&file_path, b"dummy video content").await?;
            self.test_files.push(file_path);
        }

        Ok(())
    }

    /// Create test subtitle files for testing.
    async fn create_subtitle_files(&mut self, workspace: &Path) -> Result<()> {
        let subtitle_dir = workspace.join("subtitles");
        fs::create_dir_all(&subtitle_dir).await?;

        // Create SRT subtitle files
        let srt_content = r#"1
00:00:01,000 --> 00:00:03,000
Hello, this is a test subtitle.

2
00:00:04,000 --> 00:00:06,000
This is the second subtitle entry.
"#;

        let subtitle_files = [
            "subtitle1.srt",
            "subtitle2.srt",
            "series_s01e01.srt",
            "series_s01e02.srt",
        ];

        for filename in &subtitle_files {
            let file_path = subtitle_dir.join(filename);
            fs::write(&file_path, srt_content).await?;
            self.test_files.push(file_path);
        }

        Ok(())
    }

    /// Create a test configuration file.
    async fn create_config_file(&mut self, workspace: &Path) -> Result<()> {
        let config_content = format!(
            r#"
[general]
workspace = "{}"
log_level = "debug"
enable_progress_bar = false

[test]
isolated = true
parallel_safe = true
timestamp = "{}"

[ai]
provider = "test"
model = "test-model"

[sync]
correlation_threshold = 0.8
max_offset_seconds = 30.0

[formats]
default_output = "srt"
preserve_styling = false
"#,
            workspace.display(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_millis()
        );

        let config_path = workspace.join("test_config.toml");
        fs::write(&config_path, config_content).await?;
        self.test_files.push(config_path);

        Ok(())
    }

    /// Create a test subtitle file with specific content.
    #[allow(dead_code)]
    pub async fn create_subtitle_file(&mut self, filename: &str, content: &str) -> Result<PathBuf> {
        let file_path = self.temp_dir.path().join(filename);
        fs::write(&file_path, content).await?;
        self.test_files.push(file_path.clone());
        Ok(file_path)
    }

    /// Create a test video file.
    #[allow(dead_code)]
    pub async fn create_video_file(&mut self, filename: &str) -> Result<PathBuf> {
        let file_path = self.temp_dir.path().join(filename);
        fs::write(&file_path, b"dummy video content").await?;
        self.test_files.push(file_path.clone());
        Ok(file_path)
    }

    /// Get a list of all created test files.
    pub fn test_files(&self) -> &[PathBuf] {
        &self.test_files
    }

    /// Clean up test files (called automatically on drop).
    pub fn cleanup(&mut self) {
        self.test_files.clear();
        // TempDir will handle cleanup automatically
    }
}
impl Default for TestWorkspace {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for TestWorkspace {
    fn drop(&mut self) {
        self.cleanup();
    }
}

/// Output validator for testing command outputs.
pub struct OutputValidator {
    patterns: Vec<regex::Regex>,
    anti_patterns: Vec<regex::Regex>,
}

impl OutputValidator {
    /// Create a new output validator.
    pub fn new() -> Self {
        Self {
            patterns: Vec::new(),
            anti_patterns: Vec::new(),
        }
    }

    /// Add a pattern that should be found in the output.
    pub fn expect_pattern(mut self, pattern: &str) -> Self {
        self.patterns
            .push(regex::Regex::new(pattern).expect("Invalid regex pattern"));
        self
    }

    /// Add a pattern that should NOT be found in the output.
    pub fn reject_pattern(mut self, pattern: &str) -> Self {
        self.anti_patterns
            .push(regex::Regex::new(pattern).expect("Invalid regex pattern"));
        self
    }

    /// Validate the output against all patterns.
    pub fn validate(&self, output: &str) -> ValidationResult {
        let mut result = ValidationResult::new();

        // Check expected patterns
        for pattern in &self.patterns {
            if pattern.is_match(output) {
                result.add_success(format!("Pattern found: {}", pattern.as_str()));
            } else {
                result.add_failure(format!("Pattern not found: {}", pattern.as_str()));
            }
        }

        // Check anti-patterns
        for pattern in &self.anti_patterns {
            if pattern.is_match(output) {
                result.add_failure(format!("Forbidden pattern found: {}", pattern.as_str()));
            } else {
                result.add_success(format!(
                    "Forbidden pattern correctly absent: {}",
                    pattern.as_str()
                ));
            }
        }

        result
    }
}

impl Default for OutputValidator {
    fn default() -> Self {
        Self::new()
    }
}

/// Result of output validation.
#[derive(Debug)]
pub struct ValidationResult {
    successes: Vec<String>,
    failures: Vec<String>,
}

impl ValidationResult {
    fn new() -> Self {
        Self {
            successes: Vec::new(),
            failures: Vec::new(),
        }
    }

    fn add_success(&mut self, message: String) {
        self.successes.push(message);
    }

    fn add_failure(&mut self, message: String) {
        self.failures.push(message);
    }

    /// Check if validation passed (no failures).
    pub fn is_valid(&self) -> bool {
        self.failures.is_empty()
    }

    /// Get the list of validation failures.
    pub fn failures(&self) -> &[String] {
        &self.failures
    }

    /// Get the list of validation successes.
    pub fn successes(&self) -> &[String] {
        &self.successes
    }

    /// Get a summary of the validation result.
    #[allow(dead_code)]
    pub fn summary(&self) -> String {
        format!(
            "Validation: {} successes, {} failures",
            self.successes.len(),
            self.failures.len()
        )
    }
}

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

    #[tokio::test]
    async fn test_cli_helper_creation() {
        let helper = TestWorkspace::new();
        assert!(helper.temp_dir_path().exists());
        assert!(helper.test_files().is_empty());
    }

    #[tokio::test]
    async fn test_cli_helper_with_ai_settings() {
        let helper = TestWorkspace::with_ai_settings("openai", "gpt-4.1");
        let config = helper.config_service().get_config().unwrap();
        assert_eq!(config.ai.provider, "openai");
        assert_eq!(config.ai.model, "gpt-4.1");
    }

    #[tokio::test]
    async fn test_cli_helper_workspace_creation() {
        let mut helper = TestWorkspace::new();
        let workspace = helper.create_isolated_test_workspace().await.unwrap();

        assert!(workspace.join("media").exists());
        assert!(workspace.join("subtitles").exists());
        assert!(workspace.join("test_config.toml").exists());
        assert!(!helper.test_files().is_empty());
    }

    #[tokio::test]
    async fn test_output_validator() {
        let validator = OutputValidator::new()
            .expect_pattern(r"✓.*success")
            .reject_pattern(r"✗.*error");

        let output = "✓ Operation completed successfully";
        let result = validator.validate(output);

        assert!(result.is_valid());
        assert_eq!(result.successes().len(), 2);
        assert_eq!(result.failures().len(), 0);
    }

    #[tokio::test]
    async fn test_output_validator_failure() {
        let validator = OutputValidator::new()
            .expect_pattern(r"✓.*success")
            .reject_pattern(r"✗.*error");

        let output = "✗ Operation failed with error";
        let result = validator.validate(output);

        assert!(!result.is_valid());
        assert_eq!(result.failures().len(), 2); // missing success pattern + forbidden error pattern
    }
}