bckplayer 0.1.0

A cross-platform CLI media player interface for VLC
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use sha2::{Sha256, Digest};

use crate::config_manager::{ConfigManager, ConfigModule};
use crate::config_modules::YoutubeConfig;
use crate::types::{MediaSource, TuiLogger};
use crate::utils;

/// Cached file metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheEntry {
    pub url: String,
    pub file_path: String,
    pub title: Option<String>,
    pub duration: Option<f64>,
    pub file_size: u64,
    pub download_time: u64,
    pub last_accessed: u64,
    pub format: String,
    pub checksum: String,
}

/// YouTube downloader and cache manager
pub struct YoutubeManager {
    config: YoutubeConfig,
    cache_index: HashMap<String, CacheEntry>,
    cache_index_path: PathBuf,
    logger: Option<TuiLogger>,
}

impl YoutubeManager {
    /// Create a new YouTube manager
    pub fn new() -> Result<Self> {
        Self::new_with_logger(None)
    }

    /// Create a new YouTube manager with a logger
    pub fn new_with_logger(logger: Option<TuiLogger>) -> Result<Self> {
        let config_manager = ConfigManager::new()?;
        let mut config = config_manager.get::<YoutubeConfig>();
        config.on_load()?;
        
        if let Some(ref log) = logger {
            log.info("Initializing YouTube manager");
            log.debug(&format!("Cache directory: {}", config.cache_directory.display()));
        }
        
        let cache_path = &config.cache_directory;
        let cache_index_path = cache_path.join("index.json");
        
        let cache_index = if cache_index_path.exists() {
            let content = fs::read_to_string(&cache_index_path)?;
            let cache_data = serde_json::from_str(&content).unwrap_or_default();
            if let Some(ref log) = logger {
                log.debug(&format!("Loaded cache index with {} entries", 
                    if let Ok(map) = serde_json::from_str::<HashMap<String, CacheEntry>>(&content) {
                        map.len()
                    } else {
                        0
                    }));
            }
            cache_data
        } else {
            if let Some(ref log) = logger {
                log.debug("No existing cache index found, creating new one");
            }
            HashMap::new()
        };
        
        let manager = Self {
            config,
            cache_index,
            cache_index_path,
            logger,
        };
        
        Ok(manager)
    }

    /// Check if yt-dlp is installed and available
    pub fn check_ytdlp_availability(&self) -> Result<()> {
        if let Some(ref logger) = self.logger {
            logger.debug("Checking yt-dlp availability");
        }
        
        let output = Command::new("yt-dlp")
            .arg("--version")
            .output();
            
        match output {
            Ok(output) if output.status.success() => {
                let version = String::from_utf8_lossy(&output.stdout);
                let message = format!("Found yt-dlp version: {}", version.trim());
                if let Some(ref logger) = self.logger {
                    logger.info(&message);
                } else {
                    println!("{}", message);
                }
                Ok(())
            }
            Ok(_) => {
                let error_msg = "yt-dlp is installed but returned an error. Please check your installation.";
                if let Some(ref logger) = self.logger {
                    logger.error(error_msg);
                }
                Err(anyhow::anyhow!(error_msg))
            }
            Err(_) => {
                let error_msg = "yt-dlp is not installed or not in PATH. Please install yt-dlp first.\n\
                     Installation instructions:\n\
                     - Windows: Download from https://github.com/yt-dlp/yt-dlp/releases\n\
                     - Linux: sudo apt install yt-dlp (or your package manager)\n\
                     - macOS: brew install yt-dlp\n\
                     - Python: pip install yt-dlp";
                if let Some(ref logger) = self.logger {
                    logger.error(error_msg);
                }
                Err(anyhow::anyhow!(error_msg))
            }
        }
    }

    /// Download a YouTube video/audio and cache it
    pub fn download_and_cache(&mut self, url: &str) -> Result<MediaSource> {
        if let Some(ref logger) = self.logger {
            logger.info(&format!("Processing YouTube URL: {}", url));
        }
        
        // Check if yt-dlp is available
        self.check_ytdlp_availability()?;
        
        // Generate cache key from URL
        let cache_key = self.generate_cache_key(url);
        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Generated cache key: {}", cache_key));
        }
        
        // Check if already cached and valid
        if self.config.enabled {
            if let Some(entry) = self.cache_index.get(&cache_key).cloned() {
                if let Some(ref logger) = self.logger {
                    logger.debug(&format!("Found cached entry for URL: {}", entry.file_path));
                }
                if self.is_cache_entry_valid(&entry)? {
                    if let Some(ref logger) = self.logger {
                        logger.info(&format!("Using cached file: {}", entry.file_path));
                    }
                    self.update_access_time(&cache_key)?;
                    return Ok(MediaSource::LocalFile(entry.file_path.clone()));
                } else {
                    if let Some(ref logger) = self.logger {
                        logger.warn(&format!("Cache entry invalid, removing: {}", entry.file_path));
                    }
                    // Remove invalid cache entry
                    self.remove_cache_entry(&cache_key)?;
                }
            } else if let Some(ref logger) = self.logger {
                logger.debug("No cached entry found for URL");
            }
        } else if let Some(ref logger) = self.logger {
            logger.debug("Caching is disabled");
        }
        
        // Download the media
        if let Some(ref logger) = self.logger {
            logger.info("Starting download...");
        }
        let downloaded_path = self.download_media(url)?;
        
        // Cache the downloaded file
        if self.config.enabled {
            if let Some(ref logger) = self.logger {
                logger.debug("Adding downloaded file to cache");
            }
            self.add_to_cache(url, &downloaded_path, &cache_key)?;
        }
        
        if let Some(ref logger) = self.logger {
            logger.info(&format!("Download completed: {}", downloaded_path));
        }
        
        Ok(MediaSource::LocalFile(downloaded_path))
    }

    /// Download media using yt-dlp
    fn download_media(&self, url: &str) -> Result<String> {
        let output_dir = if self.config.enabled {
            &self.config.cache_directory
        } else {
            // Use temporary directory if caching is disabled
            Path::new("./temp_downloads")
        };
        
        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Output directory: {}", output_dir.display()));
        }
        
        // Ensure output directory exists
        fs::create_dir_all(output_dir)?;
        
        // Generate hash-based filename
        let cache_key = self.generate_cache_key(url);
        
        // Build yt-dlp command
        let mut cmd = Command::new("yt-dlp");
        
        // Basic options
        cmd.arg("--no-playlist"); // Only download single video, not playlist
        
        // Quality and format selection
        if self.config.audio_only {
            cmd.arg("-x"); // Extract audio
            if !self.config.preferred_quality.is_empty() {
                cmd.arg("--audio-format").arg("mp3"); // Default to mp3 for audio
            }
            if let Some(ref logger) = self.logger {
                logger.debug("Downloading audio only (mp3 format)");
            }
        } else if !self.config.preferred_quality.is_empty() {
            cmd.arg("-f").arg(&self.config.preferred_quality);
            if let Some(ref logger) = self.logger {
                logger.debug(&format!("Using quality setting: {}", self.config.preferred_quality));
            }
        }
        
        // Output template using hash as filename, let yt-dlp decide extension
        let output_template = output_dir.join(format!("{}.%(ext)s", cache_key));
        cmd.arg("-o").arg(output_template.to_string_lossy().as_ref());
        
        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Using hash-based filename: {}", cache_key));
        }
        
        // Timeout and retry settings
        cmd.arg("--socket-timeout").arg("30"); // Default timeout
        cmd.arg("--retries").arg(self.config.retry_attempts.to_string());
        
        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Retry attempts: {}", self.config.retry_attempts));
        }
        
        // Add URL
        cmd.arg(url);
        
        // Execute command
        let download_msg = format!("Downloading: {}", url);
        if let Some(ref logger) = self.logger {
            logger.info(&download_msg);
        } else {
            println!("{}", download_msg);
        }

        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Executing command: {:?}", cmd));
        }
        
        let output = cmd.output()?;
        
        if !output.status.success() {
            let error_msg = String::from_utf8_lossy(&output.stderr);
            let full_error = format!("yt-dlp failed: {}", error_msg);
            if let Some(ref logger) = self.logger {
                logger.error(&full_error);
            }
            return Err(anyhow::anyhow!(full_error));
        }
        
        if let Some(ref logger) = self.logger {
            logger.debug("yt-dlp command completed successfully");
        }
        
        // Find the downloaded file using hash-based filename
        self.find_downloaded_file(output_dir, &cache_key)
    }

    /// Find the downloaded file in the output directory using hash-based filename
    fn find_downloaded_file(&self, output_dir: &Path, cache_key: &str) -> Result<String> {
        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Locating downloaded file with hash: {}", cache_key));
        }
        
        // Look for files that start with the cache key (hash)
        let entries = fs::read_dir(output_dir)?;
        for entry in entries {
            let entry = entry?;
            let file_name = entry.file_name().to_string_lossy().to_string();
            
            // Check if filename starts with our cache key
            if file_name.starts_with(cache_key) {
                let file_path = entry.path();
                if file_path.is_file() {
                    let result = file_path.to_string_lossy().to_string();
                    if let Some(ref logger) = self.logger {
                        logger.debug(&format!("Found downloaded file: {}", result));
                    }
                    return Ok(result);
                }
            }
        }
        
        let error_msg = format!("Downloaded file not found with hash: {}", cache_key);
        if let Some(ref logger) = self.logger {
            logger.error(&error_msg);
        }
        Err(anyhow::anyhow!(error_msg))
    }

    /// Generate cache key from URL
    fn generate_cache_key(&self, url: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(url.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// Check if cache entry is valid
    fn is_cache_entry_valid(&self, entry: &CacheEntry) -> Result<bool> {
        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Validating cache entry: {}", entry.file_path));
        }
        
        // Check if file exists
        let file_path = Path::new(&entry.file_path);
        if !file_path.exists() {
            if let Some(ref logger) = self.logger {
                logger.debug("Cache validation failed: file does not exist");
            }
            return Ok(false);
        }
        
        // Check file size
        let metadata = fs::metadata(file_path)?;
        if metadata.len() != entry.file_size {
            if let Some(ref logger) = self.logger {
                logger.debug(&format!("Cache validation failed: file size mismatch (expected {}, got {})", 
                    entry.file_size, metadata.len()));
            }
            return Ok(false);
        }
        
        // Check expiry
        let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
        let expiry_time = entry.download_time + (self.config.max_cache_age_days * 24 * 3600);
        if current_time > expiry_time {
            if let Some(ref logger) = self.logger {
                logger.debug("Cache validation failed: entry expired");
            }
            return Ok(false);
        }
        
        // Optionally verify checksum for important files (always enabled for simplicity)
        let current_checksum = self.calculate_file_checksum(file_path)?;
        if current_checksum != entry.checksum {
            if let Some(ref logger) = self.logger {
                logger.debug("Cache validation failed: checksum mismatch");
            }
            return Ok(false);
        }
        
        if let Some(ref logger) = self.logger {
            logger.debug("Cache entry validation successful");
        }
        
        Ok(true)
    }

    /// Calculate file checksum
    fn calculate_file_checksum(&self, file_path: &Path) -> Result<String> {
        let content = fs::read(file_path)?;
        let mut hasher = Sha256::new();
        hasher.update(&content);
        Ok(format!("{:x}", hasher.finalize()))
    }

    /// Add file to cache
    fn add_to_cache(&mut self, url: &str, file_path: &str, cache_key: &str) -> Result<()> {
        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Adding file to cache: {}", file_path));
        }
        
        let file_path_obj = Path::new(file_path);
        let metadata = fs::metadata(file_path_obj)?;
        let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
        
        // Get video info
        let (title, duration) = self.get_video_info(url)?;
        
        if let Some(ref logger) = self.logger {
            if let Some(ref title) = title {
                logger.debug(&format!("Video title: {}", title));
            }
            if let Some(duration) = duration {
                logger.debug(&format!("Video duration: {:.2}s", duration));
            }
        }
        
        let entry = CacheEntry {
            url: url.to_string(),
            file_path: file_path.to_string(),
            title,
            duration,
            file_size: metadata.len(),
            download_time: current_time,
            last_accessed: current_time,
            format: self.config.preferred_quality.clone(),
            checksum: self.calculate_file_checksum(file_path_obj)?,
        };
        
        self.cache_index.insert(cache_key.to_string(), entry);
        self.save_cache_index()?;
        
        if let Some(ref logger) = self.logger {
            logger.info(&format!("File cached successfully: {} ({} bytes)", 
                file_path, metadata.len()));
        }
        
        // Clean up cache if necessary
        self.cleanup_cache()?;
        
        Ok(())
    }

    /// Get video information using yt-dlp
    fn get_video_info(&self, url: &str) -> Result<(Option<String>, Option<f64>)> {
        let mut cmd = Command::new("yt-dlp");
        cmd.arg("--get-title")
           .arg("--get-duration")
           .arg("--no-playlist")
           .arg(url);
           
        let output = cmd.output()?;
        if !output.status.success() {
            return Ok((None, None));
        }
        
        let output_str = String::from_utf8_lossy(&output.stdout);
        let lines: Vec<&str> = output_str.trim().split('\n').collect();
        
        let title = if !lines.is_empty() && !lines[0].is_empty() {
            Some(lines[0].to_string())
        } else {
            None
        };
        
        let duration = if lines.len() >= 2 {
            lines[1].parse::<f64>().ok()
        } else {
            None
        };
        
        Ok((title, duration))
    }

    /// Update access time for cache entry
    fn update_access_time(&mut self, cache_key: &str) -> Result<()> {
        if let Some(entry) = self.cache_index.get_mut(cache_key) {
            let file_path = entry.file_path.clone(); // Clone before borrowing
            entry.last_accessed = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
            self.save_cache_index()?;
            if let Some(ref logger) = self.logger {
                logger.debug(&format!("Updated access time for cache entry: {}", file_path));
            }
        }
        Ok(())
    }

    /// Remove cache entry
    fn remove_cache_entry(&mut self, cache_key: &str) -> Result<()> {
        if let Some(entry) = self.cache_index.remove(cache_key) {
            if let Some(ref logger) = self.logger {
                logger.debug(&format!("Removing cache entry: {}", entry.file_path));
            }
            
            // Remove the actual file
            let file_path = Path::new(&entry.file_path);
            if file_path.exists() {
                fs::remove_file(file_path)?;
                if let Some(ref logger) = self.logger {
                    logger.debug(&format!("Deleted file: {}", entry.file_path));
                }
            }
            
            // Remove associated files (subtitles, thumbnails, info)
            if let Some(stem) = file_path.file_stem() {
                if let Some(parent) = file_path.parent() {
                    if let Ok(entries) = fs::read_dir(parent) {
                        for entry_dir in entries.flatten() {
                            let name = entry_dir.file_name().to_string_lossy().to_string();
                            if name.starts_with(&stem.to_string_lossy().to_string()) && 
                               name != file_path.file_name().unwrap().to_string_lossy() {
                                let _ = fs::remove_file(entry_dir.path());
                                if let Some(ref logger) = self.logger {
                                    logger.debug(&format!("Deleted associated file: {}", name));
                                }
                            }
                        }
                    }
                }
            }
            
            self.save_cache_index()?;
            
            if let Some(ref logger) = self.logger {
                logger.info(&format!("Cache entry removed: {}", entry.file_path));
            }
        }
        Ok(())
    }

    /// Clean up cache based on size and age limits
    fn cleanup_cache(&mut self) -> Result<()> {
        // Calculate total cache size
        let total_size = self.calculate_total_cache_size()?;
        let max_size_bytes = self.config.max_cache_size_mb * 1024 * 1024;
        
        if let Some(ref logger) = self.logger {
            logger.debug(&format!("Cache size: {:.2} MB / {:.2} MB", 
                total_size as f64 / (1024.0 * 1024.0),
                self.config.max_cache_size_mb as f64));
        }
        
        if total_size <= max_size_bytes {
            return Ok(());
        }
        
        if let Some(ref logger) = self.logger {
            logger.info("Cache size limit exceeded, cleaning up old entries");
        }
        
        // Sort entries by last accessed time (oldest first)
        let mut entries: Vec<_> = self.cache_index.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
        entries.sort_by_key(|(_, entry)| entry.last_accessed);
        
        // Remove oldest entries until we're under the size limit
        let mut current_size = total_size;
        for (key, entry) in entries {
            if current_size <= max_size_bytes {
                break;
            }
            
            current_size -= entry.file_size;
            self.remove_cache_entry(&key)?;
            
            let message = format!("Removed cached file: {} (freed {} bytes)", entry.file_path, entry.file_size);
            if let Some(ref logger) = self.logger {
                logger.info(&message);
            } else {
                println!("{}", message);
            }
        }
        
        Ok(())
    }

    /// Calculate total cache size
    fn calculate_total_cache_size(&self) -> Result<u64> {
        Ok(self.cache_index.values().map(|entry| entry.file_size).sum())
    }

    /// Save cache index to disk
    fn save_cache_index(&self) -> Result<()> {
        let content = serde_json::to_string_pretty(&self.cache_index)?;
        fs::write(&self.cache_index_path, content)?;
        Ok(())
    }

    /// Get cache statistics
    pub fn get_cache_stats(&self) -> Result<CacheStats> {
        let total_files = self.cache_index.len();
        let total_size = self.calculate_total_cache_size()?;
        let max_size_bytes = self.config.max_cache_size_mb * 1024 * 1024;
        
        Ok(CacheStats {
            total_files,
            total_size_bytes: total_size,
            total_size_mb: total_size as f64 / (1024.0 * 1024.0),
            max_size_mb: self.config.max_cache_size_mb as f64,
            usage_percentage: (total_size as f64 / max_size_bytes as f64) * 100.0,
        })
    }

    /// Clear entire cache
    pub fn clear_cache(&mut self) -> Result<()> {
        if let Some(ref logger) = self.logger {
            logger.info("Clearing entire YouTube cache");
        }
        
        let cache_path = &self.config.cache_directory;
        if cache_path.exists() {
            fs::remove_dir_all(cache_path)?;
            fs::create_dir_all(cache_path)?;
            if let Some(ref logger) = self.logger {
                logger.debug(&format!("Removed cache directory: {}", cache_path.display()));
            }
        }
        
        self.cache_index.clear();
        self.save_cache_index()?;
        
        if let Some(ref logger) = self.logger {
            logger.info("YouTube cache cleared successfully");
        }
        
        Ok(())
    }

    /// List cached entries
    pub fn list_cached_entries(&self) -> Vec<&CacheEntry> {
        self.cache_index.values().collect()
    }
}

/// Cache statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub total_files: usize,
    pub total_size_bytes: u64,
    pub total_size_mb: f64,
    pub max_size_mb: f64,
    pub usage_percentage: f64,
}

/// Check if URL is a YouTube URL
pub fn is_youtube_url(url: &str) -> bool {
    utils::is_url(url) && (
        url.contains("youtube.com") ||
        url.contains("youtu.be") ||
        url.contains("youtube-nocookie.com") ||
        url.contains("www.youtube.com") ||
        url.contains("m.youtube.com")
    )
}

/// Download YouTube content and return appropriate MediaSource
pub fn download_youtube_content(url: &str) -> Result<MediaSource> {
    download_youtube_content_with_logger(url, None)
}

/// Download YouTube content with optional logger and return appropriate MediaSource
pub fn download_youtube_content_with_logger(url: &str, logger: Option<TuiLogger>) -> Result<MediaSource> {
    let mut manager = YoutubeManager::new_with_logger(logger)?;
    manager.download_and_cache(url)
}

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

    #[test]
    fn test_youtube_url_detection() {
        assert!(is_youtube_url("https://www.youtube.com/watch?v=dQw4w9WgXcQ"));
        assert!(is_youtube_url("https://youtu.be/dQw4w9WgXcQ"));
        assert!(is_youtube_url("https://youtube.com/watch?v=dQw4w9WgXcQ"));
        assert!(!is_youtube_url("https://example.com"));
        assert!(!is_youtube_url("not a url"));
    }

    #[test]
    fn test_cache_key_generation() {
        let manager = YoutubeManager::new_with_logger(None).unwrap();
        let key1 = manager.generate_cache_key("https://youtube.com/watch?v=test1");
        let key2 = manager.generate_cache_key("https://youtube.com/watch?v=test2");
        let key3 = manager.generate_cache_key("https://youtube.com/watch?v=test1");
        
        assert_ne!(key1, key2);
        assert_eq!(key1, key3);
        assert_eq!(key1.len(), 64); // SHA256 hex string length
    }

    #[test]
    fn test_config_validation() {
        let mut config = YoutubeConfig::default();
        assert!(config.validate().is_ok());
        
        config.max_cache_size_mb = 0; // Too small
        assert!(config.validate().is_err());
        
        config.max_cache_size_mb = 150000; // Too large
        assert!(config.validate().is_err());
    }
}