subx_cli/commands/
cache_command.rs

1//! Cache management command implementation with comprehensive cleanup capabilities.
2//!
3//! This module provides sophisticated cache management functionality through
4//! the `cache` subcommand, enabling users to inspect, maintain, and clean up
5//! various types of cached data that SubX accumulates during operation. The
6//! cache system is crucial for performance optimization and API cost reduction.
7//!
8//! # Cache System Overview
9//!
10//! SubX maintains multiple types of caches to optimize performance:
11//!
12//! ## AI Analysis Cache
13//! - **Purpose**: Store results from expensive AI API calls
14//! - **Content**: File analysis results, matching decisions, confidence scores
15//! - **Benefits**: Reduce API costs, improve response times, enable offline review
16//! - **Location**: `~/.config/subx/ai_cache/`
17//! - **Format**: JSON files with content hashes as keys
18//!
19//! ## Dry-run Results Cache
20//! - **Purpose**: Preserve preview results for later application
21//! - **Content**: Planned file operations, rename proposals, backup locations
22//! - **Benefits**: Review before apply, batch operations, undo planning
23//! - **Location**: `~/.config/subx/match_cache.json`
24//! - **Format**: Structured JSON with operation metadata
25//!
26//! ## Audio Analysis Cache
27//! - **Purpose**: Store computationally expensive audio processing results
28//! - **Content**: Speech detection patterns, timing analysis, correlation data
29//! - **Benefits**: Faster re-synchronization, batch processing optimization
30//! - **Location**: `~/.config/subx/audio_cache/`
31//! - **Format**: Binary files with audio fingerprints
32//!
33//! ## Configuration Cache
34//! - **Purpose**: Processed and validated configuration data
35//! - **Content**: Merged configuration, validation results, computed settings
36//! - **Benefits**: Faster application startup, consistency validation
37//! - **Location**: `~/.config/subx/config_cache/`
38//! - **Format**: Serialized configuration structures
39//!
40//! # Cache Management Operations
41//!
42//! ## Clear Operation
43//! - **Scope**: Remove all cached data across all cache types
44//! - **Safety**: Non-destructive to actual subtitle and video files
45//! - **Impact**: Next operations will require fresh computation/API calls
46//! - **Recovery**: All cached data can be regenerated through normal usage
47//!
48//! ## Status Operation (Future Enhancement)
49//! - **Information**: Cache size, age, hit rates, storage usage
50//! - **Analysis**: Identify stale or corrupted cache entries
51//! - **Optimization**: Suggest cache maintenance actions
52//! - **Reporting**: Usage statistics and efficiency metrics
53//!
54//! ## Selective Clear (Future Enhancement)
55//! - **Type-specific**: Clear only AI, audio, or configuration cache
56//! - **Age-based**: Remove cache entries older than specified time
57//! - **Size-based**: Remove least recently used entries to reduce disk usage
58//! - **Pattern-based**: Clear cache entries matching specific criteria
59//!
60//! # Performance Impact
61//!
62//! ## After Cache Clear
63//! - **AI Operations**: Will require fresh API calls (increased time/cost)
64//! - **Audio Processing**: Re-analysis required for sync operations
65//! - **Configuration**: Slight startup delay for configuration processing
66//! - **File Operations**: No impact on actual file processing capabilities
67//!
68//! ## Cache Regeneration
69//! - **Automatic**: Caches rebuild naturally during normal operations
70//! - **Intelligent**: Only necessary computations are performed
71//! - **Progressive**: Cache rebuilds incrementally as features are used
72//! - **Optimized**: New cache generation benefits from previous optimizations
73//!
74//! # Examples
75//!
76//! ```rust,ignore
77//! use subx_cli::cli::{CacheArgs, CacheAction};
78//! use subx_cli::commands::cache_command;
79//!
80//! // Clear all cache data
81//! let clear_args = CacheArgs {
82//!     action: CacheAction::Clear,
83//! };
84//! cache_command::execute(clear_args).await?;
85//! ```
86
87use crate::Result;
88use crate::cli::CacheArgs;
89use crate::config::ConfigService;
90use crate::error::SubXError;
91use dirs;
92
93/// Execute cache management operations with comprehensive cleanup and validation.
94///
95/// This function provides the main interface for cache management operations,
96/// currently focusing on cache clearing functionality with plans for expanded
97/// cache inspection and maintenance capabilities. It ensures safe cache
98/// operations while preserving actual user data.
99///
100/// # Cache Clear Process
101///
102/// 1. **Cache Location Discovery**: Identify all cache directories and files
103/// 2. **Validation**: Verify cache files are SubX-generated and safe to remove
104/// 3. **Backup Check**: Ensure no critical data will be lost
105/// 4. **Removal Execution**: Systematically remove cache files and directories
106/// 5. **Verification**: Confirm successful removal and cleanup
107/// 6. **Reporting**: Provide user feedback on operations performed
108///
109/// # Safety Guarantees
110///
111/// The cache management system provides strong safety guarantees:
112/// - **User Data Protection**: Never removes actual subtitle or video files
113/// - **Configuration Safety**: Preserves user configuration files
114/// - **Atomic Operations**: Complete success or complete failure, no partial state
115/// - **Recovery Capability**: All removed data can be regenerated automatically
116/// - **Validation**: Extensive checks before any destructive operations
117///
118/// # Cache Types Managed
119///
120/// ## AI Analysis Results
121/// - **File matching cache**: Results from AI-powered file correlation
122/// - **Content analysis cache**: Subtitle content analysis results
123/// - **API response cache**: Cached responses from AI service providers
124/// - **Confidence data**: Stored confidence scores and metadata
125///
126/// ## Processing Results
127/// - **Dry-run cache**: Preview results for later application
128/// - **Operation cache**: Planned file operations and metadata
129/// - **Backup references**: Information about created backup files
130/// - **Progress state**: Interrupted operation recovery data
131///
132/// ## System Cache
133/// - **Configuration cache**: Processed and validated configuration
134/// - **Discovery cache**: File system scan results
135/// - **Format cache**: Subtitle format detection results
136/// - **Metadata cache**: File metadata and characteristics
137///
138/// # Error Handling
139///
140/// Comprehensive error handling covers various failure scenarios:
141/// - **Permission Issues**: Clear guidance for access problems
142/// - **Disk Space**: Graceful handling of disk space constraints
143/// - **Concurrent Access**: Safe operation when multiple instances running
144/// - **Partial Failures**: Detailed reporting of what succeeded/failed
145/// - **Recovery Instructions**: Clear steps for manual cleanup if needed
146///
147/// # Arguments
148///
149/// * `args` - Cache management arguments containing the specific operation
150///   to perform and any associated parameters for cache management tasks.
151///
152/// # Returns
153///
154/// Returns `Ok(())` on successful cache operation completion, or an error
155/// describing specific problems encountered during cache management:
156/// - Configuration directory access issues
157/// - File system permission problems
158/// - Disk space or I/O errors during cleanup
159/// - Cache corruption requiring manual intervention
160///
161/// # Future Enhancements
162///
163/// Planned cache management features include:
164/// - **Cache Status**: Detailed information about cache size and utilization
165/// - **Selective Clearing**: Clear specific cache types or age ranges
166/// - **Cache Statistics**: Usage metrics and efficiency analysis
167/// - **Automatic Maintenance**: Scheduled cleanup and optimization
168/// - **Cache Import/Export**: Backup and restore cache data
169///
170/// # Examples
171///
172/// ```rust,ignore
173/// use subx_cli::cli::{CacheArgs, CacheAction};
174/// use subx_cli::commands::cache_command;
175///
176/// // Basic cache clearing
177/// let clear_all = CacheArgs {
178///     action: CacheAction::Clear,
179/// };
180/// cache_command::execute(clear_all).await?;
181/// ```
182///
183/// # Use Cases
184///
185/// ## Development and Testing
186/// - **Clean State**: Reset cache between test runs
187/// - **Debugging**: Eliminate cache-related variables in troubleshooting
188/// - **Performance Testing**: Measure operations without cache benefits
189/// - **Integration Testing**: Ensure fresh state for automated tests
190///
191/// ## Maintenance and Troubleshooting
192/// - **Corruption Recovery**: Clear potentially corrupted cache data
193/// - **Disk Space Management**: Reclaim space used by cache files
194/// - **Configuration Changes**: Clear cache after major configuration updates
195/// - **Version Upgrades**: Clear cache when upgrading SubX versions
196///
197/// ## Privacy and Security
198/// - **Data Cleanup**: Remove potentially sensitive cached content
199/// - **API Key Changes**: Clear cache tied to previous credentials
200/// - **System Migration**: Clean state before moving to new system
201/// - **Audit Compliance**: Regular cache cleanup for compliance requirements
202pub async fn execute(args: CacheArgs) -> Result<()> {
203    match args.action {
204        crate::cli::CacheAction::Clear => {
205            // Determine the appropriate cache directory using standard conventions
206            let dir = dirs::config_dir()
207                .ok_or_else(|| SubXError::config("Unable to determine cache directory"))?;
208            let path = dir.join("subx").join("match_cache.json");
209
210            if path.exists() {
211                // Remove the cache file with proper error handling
212                std::fs::remove_file(&path)?;
213                println!("Cache file cleared: {}", path.display());
214            } else {
215                println!("No cache file found");
216            }
217        }
218    }
219    Ok(())
220}
221
222/// Execute cache management command with injected configuration service.
223///
224/// This function provides the new dependency injection interface for the cache command,
225/// accepting a configuration service instead of loading configuration globally.
226///
227/// # Arguments
228///
229/// * `args` - Cache command arguments
230/// * `config_service` - Configuration service providing access to cache settings
231///
232/// # Returns
233///
234/// Returns `Ok(())` on successful completion, or an error if the operation fails.
235pub async fn execute_with_config(
236    args: CacheArgs,
237    _config_service: std::sync::Arc<dyn ConfigService>,
238) -> Result<()> {
239    // Cache command doesn't need complex configuration, delegate to original implementation
240    execute(args).await
241}